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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
2ed87959b281d4969c7caaaff46ba23e10fea19e | PHP | VenszY/school_upr1 | /index(old).php | UTF-8 | 1,622 | 3.234375 | 3 | [] | no_license | <?php
// echo "Hello World ! <br>";
// $username = "Vnesz";
// echo $username."<br>";
// $age = 22;
// echo $age."<br>";
// $bool = 1123;
// print_r($bool."<br><br>");
// $array = [true, false, 3689, "true"];
// foreach ($array as $arrval)
// {
// echo $arrval." | ";
// }
// $classStartAt = 420;
// $classStartAt2 = 500;
// if($classStartAt > $classStartAt2)
// {
// echo "Its too early anyway, I am not coming";
// }
// else
// {
// echo "WTF ?!";
// }
// switch($classStartAt){
// case $classStartAt > $classStartAt2 :
// echo "case 1";
// break;
// case $classStartAt < $classStartAt2:
// echo "case 2";
// break;
// default :
// echo "else text";
// }
// if (isset($_POST) && !empty($_POST)) {
// if ($_POST["username"] === "Venzy" && $_POST["password"] == "1234") {
// echo "Logged in";
// } else {
// echo "Unauthorized";
// }
// }
$adminUsername = "petko";
$adminPassword = "1234";
if(isset($_POST) && !empty($_POST)) {
if (isset($_POST["username"]) && !empty($_POST["username"]) &&
isset($_POST["username"]) && !empty($_POST["username"])
) {
if ($_POST["username"] === $adminUsername &&
$_POST["password"] === $adminPassword
) {
header("Location: welcome.html");
}else{
header("Location: index.html");
}
}else {
echo "Missing data";
}
}
| true |
d2a7f5220ffbcf40af604ea532ce3db6367a097d | PHP | y-67/simpleFramework | /Core/Config/LoadConfigFiles.php | UTF-8 | 963 | 2.8125 | 3 | [] | no_license | <?php
namespace Core\Config;
class LoadConfigFiles
{
protected string $path = '';
protected array $configs = [];
/**
* LoadConfigFiles constructor.
* @param string $path
*/
public function __construct(string $path)
{
$this->path = $path;
}
/**
* @return array
*/
public function loadFiles(): array
{
if (is_readable_dir($this->path) && is_writable_dir($this->path)) {
$configFiles = array_diff(scandir($this->path), ['.', '..']);
foreach ($configFiles as $configFile) {
$fileName = pathinfo($configFile, PATHINFO_FILENAME);
$fileContent = require_once($this->path . '/' . $configFile);
$this->configs[$fileName] = $fileContent;
}
} else {
dump("[Config::path] {$this->path} okuma ve yazma izni olan bir dizin belirtin.");
}
return $this->configs;
}
}
| true |
680945e52b28fb0ce5afde0d6a9568e8a12a25e1 | PHP | pyrello/migrate_preservation | /documents.inc | UTF-8 | 6,472 | 2.5625 | 3 | [] | no_license | <?php
/**
* @file
* Advanced migration examples. These serve two purposes:
*
* 1. To demonstrate some of the more advanced usages of the Migrate module.
* Search for "TIP:" below for features not found in the basic example.
* 2. To provide thorough test cases for the simpletest suite.
*
*/
class DocumentMigration extends XMLMigration {
//private $sourceid;
public function __construct() {
parent::__construct();
$this->description = t('XML feed (multi items) of roles (positions)');
// There isn't a consistent way to automatically identify appropriate "fields"
// from an XML feed, so we pass an explicit list of source fields
$fields = array(
'filename' => t('File name'),
'title' => t('Publication title'),
'country' => t('Publication country'),
'state' => t('Publication state'),
'city' => t('Publication city'),
'date' => t('Publication date'),
'lang' => t('Language'),
'pagenum' => t('Page number'),
'exceptions' => t('Exceptions'),
'id' => t('Image ID'),
);
// The source ID here is the one retrieved from the XML listing file, and
// used to identify the specific item's file
$this->map = new MigrateSQLMap($this->machineName,
array(
'id' => array(
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'description' => 'The Image ID',
)
),
MigrateDestinationNode::getKeySchema()
);
// This can also be an URL instead of a file path.
$xml_folder = variable_get('migrate_preservation_document_path_absolute', DRUPAL_ROOT);
$files = file_scan_directory($xml_folder, '/\.xml$/', array('recurse' => FALSE));
$items_url = array_keys($files);
$item_xpath = '/reel/image'; // relative to document
$item_ID_xpath = 'id'; // relative to item_xpath
$this->source = new MigrateSourceXML($items_url, $item_xpath, $item_ID_xpath, $fields);
$this->destination = new MigrateDestinationNode('document');
$this->addFieldMapping('id');
$this->addFieldMapping('sourceid');
$this->addFieldMapping('field_document_docid', 'docid')
->description('Populated by prepareRow');
$this->addFieldMapping('title', 'full_title')
->description('Populated by prepareRow');
$this->addFieldMapping('field_document_country', 'country')
->xpath('country');
$this->addFieldMapping('field_document_state', 'state')
->xpath('state');
$this->addFieldMapping('field_document_city', 'city')
->xpath('city');
$this->addFieldMapping('field_document_pubtitle', 'title')
->xpath('title');
$this->addFieldMapping('field_document_pagenum', 'pagenum')
->xpath('pagenum');
$this->addFieldMapping('field_document_text_raw', 'raw_text') // works!
->description('Populated by prepareRow from a text file');
$this->addFieldMapping('field_document_dirid', 'directory_id')
->description('Populated by prepareRow');
$this->addFieldMapping('field_document_collection', 'collection')
->description('Populated by prepareRow');
$this->addFieldMapping('field_document_filename', 'filename')
->xpath('filename');
$this->addFieldMapping('field_document_pdf', 'pdf');
// Date handled as separate fields because of limitations on php dates.
$this->addFieldMapping('field_document_year', 'year');
$this->addFieldMapping('field_document_month', 'month');
$this->addFieldMapping('field_document_day', 'day');
}
public function prepareRow($row) {
$filename = (string) $row->xml->filename;
$path = $this->source->activeUrl();
$row->docid = $this->getDocId($path, $filename);
$row->raw_text = $this->getTextFile($path, $filename);
$row->directory_id = $this->getDirectoryId($path);
$row->collection = $this->getCollection($path);
$row->full_title = $this->getFullTitle($row);
$row->pdf = $this->getFilePath($path, $filename, '.pdf');
if ((string) $row->xml->pagenum == '') {
$row->pagenum = 0;
}
$dateArr = explode('-', (string) $row->xml->date);
$row->year = $dateArr[0];
$row->month = $dateArr[1];
$row->day = $dateArr[2];
}
public function getFullTitle($row) {
return (string) $row->xml->title . ' ' . (string) $row->xml->date . ' - Page ' . (string) $row->xml->pagenum;
}
public function getDocId($xmlpath, $scanfilename) {
$file = basename($xmlpath);
$filename = substr($file, 0, strrpos($file, '.'));
$parts = explode('@#@', $filename);
$docid = $parts[0] . '--' . $parts[1] . '--' . $scanfilename;
return $docid;
}
public function getTextFile($xmlpath, $scanfilename) {
$path = $this->getFilePath($xmlpath, $scanfilename, '.txt');
$data = file_exists($path) ? utf8_encode(file_get_contents($path)) : '';
return $data;
}
public function getPDF($xmlpath, $scanfilename) {
$path = $this->getFilePath($xmlpath, $scanfilename, '.pdf');
$pdf = array();
$pdf['path'] = $path;
$pdf = drupal_json_encode($pdf);
return $pdf;
}
public function getFilePath($xmlpath, $filename, $ext) {
$xmlfile = basename($xmlpath);
$xmlname = substr($xmlfile, 0, strrpos($xmlfile, '.'));
$parts = explode('@#@', $xmlname);
$path = variable_get('migrate_preservation_document_path_absolute', DRUPAL_ROOT) . '/' . $parts[0] . '/';
if (file_exists($path . $parts[1] . '/' . $parts[1] . '/' . $filename . $ext)) { // Example: /Collection/Dates/Dates/File.ext
$path = $path . $parts[1] . '/' . $parts[1] . '/' . $filename . $ext;
} else if (file_exists($path . $parts[1] . '/' . $filename . $ext)) { // Example: /Collection/Dates/File.ext
$path = $path . $parts[1] . '/' . $filename . $ext;
} else if (file_exists($path . $filename . $ext)) { // Example: /Collection/File.ext
$path = $path . $filename . $ext;
} else { // Can't find the file
return FALSE;
}
return $path;
}
public function getDirectoryId($xmlpath) {
$file = basename($xmlpath);
$filename = substr($file, 0, strrpos($file, '.'));
$parts = explode('@#@', $filename);
return $parts[1];
}
public function getCollection($xmlpath) {
$file = basename($xmlpath);
$filename = substr($file, 0, strrpos($file, '.'));
$parts = explode('@#@', $filename);
return $parts[0];
}
} | true |
e3ece5ec63f8c2b04592fbe99889b63fcf922a08 | PHP | gustavomontiel/cademis | /api/app/Http/Controllers/UserController.php | UTF-8 | 3,566 | 2.640625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Validator;
use App\User;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::all();
return response()->json(['error' => 'false', 'data' => $users, 'message' => 'Usuarios enviados correctamente.']);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$input = $request->all();
$validator = Validator::make($input, [
'email' => 'required|email|unique:users,email',
'password' => 'required',
'name' => 'string',
'username' => 'required|unique:users,username'
]);
if ($validator->fails()) {
return response()->json(['error' => 'true', 'data' => $validator->errors(), 'message' => 'Error en la validación de datos.'], 400);
}
$input['password'] = Hash::make($input['password']);
$input['verified'] = 1;
$user = User::create($input);
return response()->json(['error' => 'false', 'data' => $user, 'message' => 'Usuario creado correctamente.']);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::where('id', $id)->first();
if (is_null($user)) {
return response()->json(['error' => 'true', 'message' => 'Usuario no encontrado.']);
}
return response()->json(['error' => 'false', 'data' => $user, 'message' => 'Usuario enviado correctamente.']);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$input = $request->all();
$user = User::find($id);
if (is_null($user)) {
return response()->json(['error' => 'true', 'message' => 'Usuario no encontrado.'], 404);
}
$validator = Validator::make($input, [
'email' => 'required|email|unique:users,email,' . $user->id,
'name' => 'string',
'username' => 'required|unique:users,username,' . $user->id
]);
if ($validator->fails()) {
return response()->json(['error' => 'true', 'data' => $validator->errors(), 'message' => 'Error en la validación de datos.'], 400);
}
$user->email = $input['email'];
$user->name = $input['name'];
$user->username = $input['username'];
$user->save();
return response()->json(['error' => 'false', 'data' => $user, 'message' => 'Usuario actualizado correctamente.']);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::find($id);
if (is_null($user)) {
return response()->json(['error' => 'true', 'message' => 'Usuario no encontrado.'], 404);
}
$user->delete();
return response()->json(['error' => 'false', 'message' => 'Usuario eliminado correctamente.']);
}
}
| true |
7f64ac72c0cf93fe1fb593d0480bd288f048435b | PHP | CemilSamli/satranc | /web/app/controller/pvpjson.php | UTF-8 | 2,829 | 2.5625 | 3 | [] | no_license | <?php
include_once("../model/utils.php");
loadModel("DBOnline.php");
loadModel("DBOyun.php");
// How often to poll, in microseconds (1,000,000 μs equals 1 s)
define('MESSAGE_POLL_MICROSECONDS', 1000000);
// How long to keep the Long Poll open, in seconds
define('MESSAGE_TIMEOUT_SECONDS', 25);
// Timeout padding in seconds, to avoid a premature timeout in case the last call in the loop is taking a while
define('MESSAGE_TIMEOUT_SECONDS_BUFFER', 5);
// Automatically die after timeout (plus buffer)
set_time_limit(MESSAGE_TIMEOUT_SECONDS+MESSAGE_TIMEOUT_SECONDS_BUFFER);
// Counter to manually keep track of time elapsed (PHP's set_time_limit() is unrealiable while sleeping)
$counter = MESSAGE_TIMEOUT_SECONDS;
$oyun = new DBOnline();
$db = new DBOyun();
session_start();
$fenString = $oyun->fenStringCek($_GET["id"]);
$parca = explode(" ",$fenString);
$sonRenk = $parca[1];
$renk = $oyun->renkBul($_GET["id"]);
session_write_close();
while($counter > 0)
{
session_start();
$fenString = $oyun->fenStringCek($_GET["id"]);
$parca = explode(" ",$fenString);
$sonRenk = $parca[1];
$renk = $oyun->renkBul($_GET["id"]);
// Check for new data (not illustrated)
//header('Content-Type: application/json');
//echo json_encode(array("pvpData" => $_GET['renk'].",".$sonRenk));
//exit();
if($_GET['renk'] != $sonRenk)
{
// Break out of while loop if new data is populated
break;
}
else
{
// Close the session prematurely to avoid usleep() from locking other requests
session_write_close();
// Otherwise, sleep for the specified time, after which the loop runs again
usleep(MESSAGE_POLL_MICROSECONDS);
// Decrement seconds from counter (the interval was set in μs, see above)
$counter -= MESSAGE_POLL_MICROSECONDS / 1000000;
}
}
$fen = rawurlencode ($fenString);
$oyuncuisimleri = $oyun->oyuncuIsimGetir($_GET["id"]);
$sonRenk = "Beyaz";
if($fenString != ""){
$parca = explode(" ",$fenString);
$sonRenk = $parca[1];
}
$dizi = $oyun->oyunHamleleri($_GET["id"]);
$kazananID = $db->oyunuKazanan($_GET["id"]);
$macBilgileri = $oyun->eskiMaclar($_SESSION["id"],$_GET["id"]);
$obj = new stdClass();
$obj->fen = $fen;
$obj->kullanici_renk = $renk;
$obj->oynayacak_renk = $sonRenk;
$obj->meydanOkuyanIsim = $oyuncuisimleri[0];
$obj->meydanOkunanIsim = $oyuncuisimleri[1];
$obj->meydanOkuyanID = $oyuncuisimleri[2];
$obj->meydanOkunanID = $oyuncuisimleri[3];
$obj->kazananID = $kazananID;
$obj->puanBeyaz = $macBilgileri[0]["puanBeyaz"];
$obj->puanSiyah = $macBilgileri[0]["puanSiyah"];
$obj->sureBeyaz = $macBilgileri[0]["sureBeyaz"];
$obj->sureSiyah = $macBilgileri[0]["sureSiyah"];
$obj->hamleler = $oyun->oyunHamleleriString($_GET["id"]);
header('Content-Type: application/json');
echo json_encode(array("pvpData" => $obj));
exit();
?>
| true |
3f7fd22727fbc6d586c32ce1ca364c609ab66dc2 | PHP | jinbonetwork/jinbo.net.2015 | /classes/Section.class.php | UTF-8 | 5,847 | 2.578125 | 3 | [] | no_license | <?php
class Section extends Objects {
public $section;
public $items;
private $index;
private $tabs;
private $mode;
public static function instance() {
return self::_instance(__CLASS__);
}
public function readSectionJson($app) {
$cacheFile = JFE_CACHE_PATH."/".$app."_section.json";
if(file_exists($cacheFile)) {
$fp = fopen($cacheFile,"r");
$this->section[$app] = json_decode(fread($fp,filesize($cacheFile)),true);
fclose($fp);
}
return $this->section[$app];
}
public function readItemsJson($app) {
$cacheFile = JFE_CACHE_PATH."/".$app."_items.json";
if(file_exists($cacheFile)) {
$fp = fopen($cacheFile,"r");
$this->items[$app] = $this->fetchUrlRecursive(json_decode(fread($fp,filesize($cacheFile)),true));
fclose($fp);
}
return $this->items[$app];
}
public function readJson($app) {
$this->readSectionJson($app);
$this->readItemsJson($app);
}
public function buildPage($app,$tabs,$mode='') {
$this->readJson($app);
$this->tabs = $tabs;
$this->mode = $mode;
if($this->section[$app] && is_array($this->section[$app])) {
foreach($this->section[$app] as $s => $data) {
$markup .= $this->buildSection($app,$s);
}
}
return $markup;
}
public function buildSection($app,$section) {
$s = $this->section[$app][$section];
$data['id'] = $app."-".$section;
$data['title'] = $s['title'];
$data['description'] = $s['description'];
$data['class'] = 'section';
$data['max-width'] = $s['max-width'];
if($this->mode) $data['class'] .= ' section-'.$this->mode;
if($s['class'] && is_array($s['class'])) {
$data['class'] .= ' '.implode(" ",$s['class']);
}
if($s['style'] && is_array($s['style'])) {
$data['style'] .= '';
foreach($s['style'] as $k=>$v) {
$data['style'] .= $k.":".$v.";";
}
}
if($s['attr'] && is_array($s['attr'])) {
foreach($s['attr'] as $k=>$v) {
$data['attr'] .= ' '.$k.'="'.$v.'"';
}
}
if($this->mode) {
$data['attr'] .= ($data['attr'] ? ' ' : '').'data-layout="'.$s['layout'].'"';
}
$data['content'] = $this->buildBlock($app,$section,$s['data'],$this->tabs);
$component = strtok($app,'.');
$markup = Component::get($component.'/section/'.$s['layout'],array('section'=>$data),1000);
if($this->tabs) {
$markup = rtrim(str_repeat("\t",$this->tabs).preg_replace("/\n/i","\n".str_repeat("\t",$this->tabs),$markup),"\t");
}
return $markup;
}
public function buildBlock($app,$section,$item,$tabs) {
$markup = '';
if($this->mode) $class = " row-".$this->mode;
if($item['class']) {
for($i=0; $i<@count($item['class']); $i++) {
if(preg_match("/^col\-/i",$item['class'][$i])) continue;
$class .= " ".$item['class'][$i];
}
}
if($item['type'] == 'item') $class .= ' column-item';
if($tabs == $this->tabs) {
$wrap_header = str_repeat("\t",($tabs ? $tabs : 0)).'<div class="row'.$class.'">'."\n";
$wrap_footer = str_repeat("\t",($tabs ? $tabs : 0)).'</div>'."\n";
}
if($item['type'] == 'division' && @count($item['data'])) {
$markup .= $wrap_header;
foreach($item['data'] as $i => $g) {
$markup .= $this->buildCol($app,$section,$g,($tabs+1),$item['template']);
}
$markup .= $wrap_footer;
} else if($item['type'] == 'item') {
$markup .= $this->buildItem($app,$section,($tabs+1));
}
return $markup;
}
private function buildCol($app,$section,$col,$tabs,$template="col") {
$tab = $tabs;
$markup = '';
if($template == 'rows') {
$markup .= str_repeat("\t",$tabs).'<div class="row'.($this->mode ? ' row-'.$this->mode : '').'">'."\n";
$tab = $tabs+1;
}
if($col['class'] && is_array($col['class'])) $col['class'][] = 'column';
else $col['class'] = array('column');
if($col['type'] == 'item') $col['class'][] = 'column-item';
$markup .= str_repeat("\t",$tab).'<div'.$this->buildAttr($col).">\n";
switch($col['type']) {
case 'division':
$markup .= $this->buildBlock($app,$section,$col,($tab+1));
break;
case 'item':
default:
$markup .= $this->buildItem($app,$section,($tabs+1));
break;
}
$markup .= str_repeat("\t",$tab)."</div>\n";
if($template == 'rows') {
$markup .= str_repeat("\t",$tabs).'</div>'."\n";
}
return $markup;
}
private function buildAttr($g) {
if($g['class'] && is_array($g['class'])) {
$markup .= ' class="'.implode(" ",$g['class']).($this->mode ? ' col-'.$this->mode : '').'"';
} else if($this->mode) {
$markup .= ' class="col-'.$this->mode.'"';
}
if($g['style'] && is_array($g['style'])) {
$markup .= ' style="';
foreach($g['style'] as $k=>$v) {
$markup .= $k.":".$v.";";
}
$markup .= '"';
}
if($g['attr'] && is_array($g['attr'])) {
foreach($g['attr'] as $k=>$v) {
$markup .= ' '.$k.'="'.$v.'"';
}
}
return $markup;
}
private function buildItem($app,$section,$tabs=0) {
if(!$this->index[$app][$section])
$this->index[$app][$section] = 0;
$item = $this->items[$app][$section][$this->index[$app][$section]];
if($item) {
// if($item['media']['url'] && !preg_match("/^</i",$item['media']['url'])) $item['media']['url'] = url($item['media']['url']);
$component = strtok($app,'.');
$markup = Component::get($component."/items/".$item['component'],array('data'=>$item,'classes'=>$item['class'],"styles"=>$item['style']),1001);
$this->index[$app][$section]++;
}
$markup = rtrim(str_repeat("\t",$tabs).preg_replace("/\n/i","\n".str_repeat("\t",$tabs),$markup),"\t");
return $markup;
}
private function fetchUrlRecursive($json) {
if($_SERVER['HTTPS'] != 'on') return $json;
if( is_array($json) ) {
foreach($json as $k => $v) {
$json[$k] = $this->fetchUrlRecursive($v);
}
return $json;
} else {
if(preg_match("/^http:\/\/(.*)\.(jpg|jpeg|gif|bmp|png)$/i",$json)) {
return preg_replace("/^http:\/\//i","https://",$json);
} else {
return $json;
}
}
}
}
?>
| true |
8f38a9eb1fca76e72615b2a4b1c3e8a7dc80f436 | PHP | himanshi1107/Basic_Banking_System | /transaction.php | UTF-8 | 1,634 | 2.625 | 3 | [] | no_license | <?php
session_start();
include 'connection.php';
if(isset($_post['submit'])){
$to = $_POST['to'];
$amount = $_POST['balance'];
$from = $_GET['id'];
}
$sql1 = mysqli_query($conn, " select * from userdetails where id='$to'");
if(!$sql1){
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($res = mysqli_fetch_array($sql1)){
$a = " update userdetails set ";
$a .= "amount = amount + '$amount' where id='$to'";
mysqli_query($conn, $a);
}
$sql2 = mysqli_query($conn, " select * from userdetails where id='$from'");
if(!$sql2){
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($res = mysqli_fetch_array($sql2)){
$b = " update userdetails set ";
$b .= "amount = amount - '$amount' where id='$from'";
mysqli_query($conn, $b);
}
$sql3 = mysqli_query($conn, " select * from userdetails where id='$to'");
if(!$sql3){
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($res = mysqli_fetch_array($sql3)){
$c = " insert into transferhistory (sender, receiver, amount) values ('".$from."', '".$to."', '".$amount."')";
mysqli_query($conn, $c);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
alert("Your Transaction has been Successful");
window.location.href="transactionHistory.php";
</script>
</body>
</html> | true |
e0020dcc8862ba71fd32317199cffd0e49183100 | PHP | franzbertazzo/PHPpiscine | /Day01/ex10/do_op.php | UTF-8 | 535 | 3.21875 | 3 | [] | no_license | #!/usr/bin/php
<?php
array_shift($argv);
if ($argc == 4)
{
$ops = array();
foreach ($argv as $param)
foreach (preg_split('/\s+/', trim($param)) as $op)
array_push($ops, $op);
if ($ops[1] == '+')
echo $ops[0] + $ops[2] . "\n";
else if ($ops[1] == '-')
echo $ops[0] - $ops[2] . "\n";
else if ($ops[1] == '*')
echo $ops[0] * $ops[2] . "\n";
else if ($ops[1] == '/')
echo $ops[0] / $ops[2] . "\n";
else if ($ops[1] == '%')
echo $ops[0] % $ops[2] . "\n";
}
else
print("Incorrect Parameters\n");
?> | true |
04f032f40f18ee020bc0c5df9f485321121b90c1 | PHP | MrKrzYch00/Abandoned-PHP-Scripts | /Recover files from CD/recovercd2.php | UTF-8 | 2,688 | 2.734375 | 3 | [] | no_license | <?php
class getsec extends Thread {
public $id2;
public $done;
public $offset;
public $file;
public $data;
public function __construct($id,$offset,$file) {
$this->id2 = (int)$id;
$this->done = false;
$this->offset = $offset;
$this->file = $file;
}
public function run() {
$input = fopen($this->file,"r");
if(is_resource($input)) {
stream_set_blocking($input, 0);
stream_set_read_buffer($input, 0);
fseek($input, $this->offset);
$this->data = fread($input, 2048);
fclose($input);
$this->done = true;
} else {
echo "Error opening {$this->file} \r\n";
exit;
}
}
}
function readline($prompt = null){
if($prompt){
echo $prompt;
}
$fp = fopen("php://stdin","r");
$line = rtrim(fgets($fp, 1024));
return $line;
}
if(!isset($argv[1]) || !isset($argv[2])) {
echo "php ",__FILE__," inputonCD outputonHD\r\n";
exit;
}
$failed = array();
$buffer = 2048;
$tries = 1;
$src = $argv[1];
$des = $argv[2];
$desstats = $des.".stats";
$input = fopen($src,"r");
if(is_resource($input)) {
fclose($input);
if(file_exists($des)) {
$output = fopen($des, "a");
fseek($output,0,SEEK_END);
$x = ftell($output);
} else {
$x = 0;
$output = fopen($des, "w");
}
if(is_resource($output)) {
if(!file_exists($desstats)) {
$outputstats = fopen($desstats, "w");
fclose($outputstats);
}
$outputstats = fopen($desstats, "a");
fseek($outputstats,0,SEEK_END);
$size = filesize($src);
for(;;) {
echo "Reading: {$x} / {$size} \r";
if($x >= $size) break;
unset($thread);
$thread = new getsec(0,$x,$src);
$thread->start();
$z = 0;
for(;;) {
USleep(100000);
++$z;
if($thread->done === true) {
$data = $thread->data;
break;
} else {
echo "Waiting for offset: {$x} [$z] \r";
if($z > 1800) {
$failed[] = $x;
echo "Fail reading at offset: {$x}. Autofill 2048 NULL bytes \r\n";
if($buffer > ($size - $x)) $buffer2 = $size - $x; else $buffer2 = $buffer;
$data = str_pad("", $buffer2, chr(0));
$thread->kill();
break;
}
}
}
fwrite($output, $data);
if($z > 600) {
fwrite($outputstats,"{$x},");
echo "If it doesn't exit, press CTRL+C\r\n";
exit;
}
$x += 2048;
}
} else {
echo "Can't open output file! \r\n";
exit;
}
} else {
echo "Can't open input file! \r\n";
exit;
}
var_dump($x);
echo "Finished! \r\n";
fclose($output);
?> | true |
eebb25bb768d629cacef9bd97baf7896e0910a24 | PHP | LesJudge/ekarrier | /library/uniweb/interface/UpdateableByResourceInterface.php | UTF-8 | 585 | 2.515625 | 3 | [] | no_license | <?php
/**
* Interface azokhoz az ActiveRecord modellekhez, amelyek valamilyen erőforrás által (ügyfél, munkáltató)
* módosíthatóak adatbázisban.
*
* @author Balázs Máté Petró <balazs@uniweb.hu>
*/
interface UpdateableByResourceInterface extends \ResourcableInterface
{
/**
* Objektum létrehozása az UPDATE queryhez.
* @param \ResourceInterface $ri Resource objektum.
* @param array $attributes Attribútumok.
* @return \UpdateableByResourceInterface
*/
public static function createUpdateInstance(\ResourceInterface $ri, array $attributes = array());
} | true |
20b0104d3805e3e8b64c8552c6ae6a229120b944 | PHP | kalimatas/zbook | /library/ZFExt/Controller/Helper/Acl.php | UTF-8 | 2,176 | 2.515625 | 3 | [] | no_license | <?php
/*
* Acl helper
*/
class ZFExt_Controller_Helper_Acl extends Zend_Controller_Action_Helper_Abstract
{
protected $_action;
protected $_acl;
protected $_auth;
protected $_controllerName;
public function __construct(Zend_View_Interface $view = null, array $options = array())
{
$this->_auth = Zend_Auth::getInstance();
$this->_acl = new ZFExt_Acl();
}
public function init()
{
$this->_action = $this->getActionController();
$controller = $this->_action->getRequest()->getControllerName();
if (!$this->_acl->has($controller)) {
$this->_acl->add(new Zend_Acl_Resource($controller));
}
}
public function preDispatch()
{
$role = ($this->_auth->hasIdentity() && !empty($this->_auth->getIdentity()->role)) ? $this->_auth->getIdentity()->role : 'guest';
$request = $this->_action->getRequest();
$controller = $request->getControllerName();
$action = $request->getActionName();
$module = $request->getModuleName();
$this->_controllerName = $controller;
$resource = $controller;
$privilege = $action;
if (!$this->_acl->has($resource)) {
$resource = null;
}
if (!$this->_acl->isAllowed($role, $resource, $privilege)) {
$request->setControllerName('auth');
$request->setActionName('login');
$request->setDispatched(false);
}
}
/*
* Allow actions to roles
* @param mixed $roles Roles
* @param mixed $actions Actions
*/
public function allow($roles = null, $actions = null)
{
$resource = $this->_controllerName;
$this->_acl->allow($roles, $resource, $actions);
return $this;
}
/*
* Deny actions to roles
* @param mixed $roles Roles
* @param mixed $actions Actions
*/
public function deny($roles = null, $actions = null)
{
$resource = $this->_controllerName;
$this->_acl->deny($roles, $resource, $actions);
return $this;
}
public function direct($a)
{
return $a * 2;
}
}
?>
| true |
133831d3fc66284187d3d80fd458a0d855733440 | PHP | dumpk/esetres | /tests/EsetresTest.php | UTF-8 | 2,594 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author Nicolás Bistolfi <nbistolfi@gmail.com>
* @license MIT
* @copyright 2015, Nicolás Bistolfi
*
* @link http://github.com/dumpk/esetres
*/
use Dumpk\Esetres\EsetresAWS;
use PHPUnit\Framework\TestCase;
class ElastcoderTest extends TestCase
{
public function tearDown()
{
}
public function testConnection()
{
$destination_key = getenv('KEY');
if (EsetresAWS::fileExists($destination_key, getenv('BUCKET'))) {
EsetresAWS::deleteFile($destination_key, getenv('BUCKET'));
}
$uploadResult = EsetresAWS::uploadFile(getenv('LOCAL_FILE'), getenv('KEY'), getenv('BUCKET'));
$this->assertTrue(isset($uploadResult['ObjectURL']), 'Upload file object URL result');
$objectURL = $uploadResult['ObjectURL'];
$object = EsetresAWS::getObject($destination_key, getenv('BUCKET'));
EsetresAWS::makeFilePublic($destination_key, getenv('BUCKET'));
$this->assertTrue(is_string(file_get_contents($object['@metadata']['effectiveUri'])));
echo $object['@metadata']['effectiveUri'];
$this->assertTrue(EsetresAWS::fileExists($destination_key, getenv('BUCKET')));
EsetresAWS::deleteObject($destination_key, getenv('BUCKET'));
}
public function testEncription()
{
$destination_key = 'enc'.getenv('KEY');
if (EsetresAWS::fileExists($destination_key, getenv('BUCKET'))) {
EsetresAWS::deleteFile($destination_key, getenv('BUCKET'));
}
$encription_key = '1231affd2950a1ab06a21137f54bd648';
$aditional_options = [
'SSECustomerAlgorithm' => 'AES256',
'SSECustomerKey' => $encription_key,
'SSECustomerKeyMD5' => md5($encription_key, true),
];
$uploadResult = EsetresAWS::uploadFile(
getenv('LOCAL_FILE'),
$destination_key,
getenv('BUCKET'),
'public-read',
array(),
'max-age=3600',
$aditional_options
);
$this->assertTrue(isset($uploadResult['ObjectURL']), 'Upload file object URL result');
$objectURL = $uploadResult['ObjectURL'];
$this->assertTrue(EsetresAWS::fileExists($destination_key, getenv('BUCKET'), $aditional_options));
$object = EsetresAWS::getObject($destination_key, getenv('BUCKET'), null, $aditional_options);
EsetresAWS::deleteObject($destination_key, getenv('BUCKET'));
}
}
| true |
9268a4cee3c3a94c93d54488bc45d45d00d2142d | PHP | vesparny/silex-simple-rest | /src/App/RoutesLoader.php | UTF-8 | 925 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace App;
use Silex\Application;
class RoutesLoader
{
private $app;
public function __construct(Application $app)
{
$this->app = $app;
$this->instantiateControllers();
}
private function instantiateControllers()
{
$this->app['notes.controller'] = function() {
return new Controllers\NotesController($this->app['notes.service']);
};
}
public function bindRoutesToControllers()
{
$api = $this->app["controllers_factory"];
$api->get('/notes', "notes.controller:getAll");
$api->get('/notes/{id}', "notes.controller:getOne");
$api->post('/notes', "notes.controller:save");
$api->put('/notes/{id}', "notes.controller:update");
$api->delete('/notes/{id}', "notes.controller:delete");
$this->app->mount($this->app["api.endpoint"].'/'.$this->app["api.version"], $api);
}
}
| true |
4d535c9fdc2d87aa05bc739f3aeb7bdfe1920bb7 | PHP | hoaaah/simoku-renbang | /modules/laporan/views/pelaporanunit/cetaklaporan2.php | UTF-8 | 4,369 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
Use app\itbz\fpdf\src\fpdf\fpdf;
use yii\db\Expression;
class PDF extends \fpdf\FPDF
{
function Footer()
{
//ambil link
$link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// $this->Image("http://api.qrserver.com/v1/create-qr-code/?size=150x150&data=$link", 280, 203 ,5,0,'PNG');
// Go to 1.5 cm from bottom
$this->SetY(-15);
// Select Arial italic 8
$this->SetFont('Arial','I',8);
// Print centered page number
$this->Cell(0,10,'Printed By BosSTAN | '.$this->PageNo().'/{nb}',0,0,'R');
}
}
//menugaskan variabel $pdf pada function fpdf().
$pdf = new PDF('L','mm',array(216,330));
$link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
function bulan($bulan){
Switch ($bulan){
case 1 : $bulan="Januari";
Break;
case 2 : $bulan="Februari";
Break;
case 3 : $bulan="Maret";
Break;
case 4 : $bulan="April";
Break;
case 5 : $bulan="Mei";
Break;
case 6 : $bulan="Juni";
Break;
case 7 : $bulan="Juli";
Break;
case 8 : $bulan="Agustus";
Break;
case 9 : $bulan="September";
Break;
case 10 : $bulan="Oktober";
Break;
case 11 : $bulan="November";
Break;
case 12 : $bulan="Desember";
Break;
}
return $bulan;
}
function kekata($x) {
$x = abs($x);
$angka = array("", "satu", "dua", "tiga", "empat", "lima",
"enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
$temp = "";
if ($x <12) {
$temp = " ". $angka[$x];
} else if ($x <20) {
$temp = kekata($x - 10). " belas";
} else if ($x <100) {
$temp = kekata($x/10)." puluh". kekata($x % 10);
} else if ($x <200) {
$temp = " seratus" . kekata($x - 100);
} else if ($x <1000) {
$temp = kekata($x/100) . " ratus" . kekata($x % 100);
} else if ($x <2000) {
$temp = " seribu" . kekata($x - 1000);
} else if ($x <1000000) {
$temp = kekata($x/1000) . " ribu" . kekata($x % 1000);
} else if ($x <1000000000) {
$temp = kekata($x/1000000) . " juta" . kekata($x % 1000000);
} else if ($x <1000000000000) {
$temp = kekata($x/1000000000) . " milyar" . kekata(fmod($x,1000000000));
} else if ($x <1000000000000000) {
$temp = kekata($x/1000000000000) . " trilyun" . kekata(fmod($x,1000000000000));
}
return $temp;
}
function terbilang($x, $style) {
// function ini berfungsi untuk membuat angka terbilang.
// untuk menggunakan gunakan cara berikut
// terbilang('your_number', 'style_number')
// style_number [1=> Untuk huruf terbilang besar seluruhnya, 2 => untuk huruf kecil seluruhnya, 3 => untuk huruf awal besar, 4 => untuk huruf pertama besar]
if($x<0) {
$hasil = "minus ". trim(kekata($x));
} else {
$hasil = trim(kekata($x));
}
switch ($style) {
case 1:
$hasil = strtoupper($hasil);
break;
case 2:
$hasil = strtolower($hasil);
break;
case 3:
$hasil = ucwords($hasil);
break;
default:
$hasil = ucfirst($hasil);
break;
}
return $hasil;
}
//cara menambahkan image dalam dokumen.
//Urutan data-> alamat file-posisi X- posisi Y-ukuran width - ukuran high -
//menambahkan link bila perlu
//Menambahkan halaman, untuk menambahkan halaman tambahkan command ini.
//P artinya potrait dan L artinya Landscape
$pdf->AddPage();
$pdf->SetAutoPageBreak(true,10);
$pdf->AliasNbPages();
$left = 25;
// Your Code GOES HERE -----------------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------------------------------------------------------
$pdf->Cell(40,5,'Data anda disini','',0,'L');
// End of your code --------------------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------------------------------------------------------
//Untuk mengakhiri dokumen pdf, dan mengirim dokumen ke output
$pdf->Output();
exit;
?> | true |
c7d427df7b51a4618ab4e38a548bdab3655884c0 | PHP | ViacheslavKurch/test_uplata | /src/Parser/Domain/Entity/ParsedEntity.php | UTF-8 | 1,601 | 3.15625 | 3 | [] | no_license | <?php
namespace App\Parser\Domain\Entity;
use DateTime;
use App\Parser\Domain\ValueObject\ParsedId;
/**
* Class ParseEntity
* @package App\Parser\Domain\Entity
*/
class ParsedEntity
{
/**
* @var ParsedId
*/
private ParsedId $id;
/**
* @var string
*/
private string $title;
/**
* @var string
*/
private string $author;
/**
* @var string
*/
private string $text;
/**
* @var DateTime
*/
private DateTime $date;
/**
* ParseEntity constructor.
* @param ParsedId $id
* @param string $title
* @param string $author
* @param string $text
* @param DateTime $date
*/
public function __construct(
ParsedId $id,
string $title,
string $author,
string $text,
DateTime $date
) {
$this->id = $id;
$this->title = $title;
$this->author = $author;
$this->text = $text;
$this->date = $date;
}
/**
* @return ParsedId
*/
public function getId(): ParsedId
{
return $this->id;
}
/**
* @return string
*/
public function getTitle(): string
{
return $this->title;
}
/**
* @return string
*/
public function getAuthor(): string
{
return $this->author;
}
/**
* @return string
*/
public function getText(): string
{
return $this->text;
}
/**
* @return DateTime
*/
public function getDate(): DateTime
{
return $this->date;
}
} | true |
755695934225f2f6ce4916e79da31f0e31a5031b | PHP | FastyPHP/fasty | /app/Core/Http/Request.php | UTF-8 | 2,027 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace App\Http;
class Request
{
public function __construct() {
extract($_GET);
extract($_POST);
extract($_SERVER);
extract($_FILES);
extract($_ENV);
extract($_COOKIE);
extract($_SESSION);
extract($_FILES);
}
public function get(?string $key = null, $val = null) {
if($val == null){
if($key == null) return $_GET;
else if(isset($_GET[$key])) return $_GET[$key];
else return false;
} else
return $_GET[$key] = $val;
}
public function post(?string $key = null, $val = null) {
if($val == null){
if($key == null) return $_POST;
else if(isset($_POST[$key])) return $_POST[$key];
else return false;
} else
return $_POST[$key] = $val;
}
public function files(?string $key = null, $val = null) {
if($val == null){
if($key == null) return $_FILES;
else if(isset($_FILES[$key])) return $_FILES[$key];
else return false;
} else
return $_FILES[$key] = $val;
}
public function cookie(?string $key = null, $val = null, ?int $expiry = 0) {
if($val == null){
if($key == null) return $_COOKIE;
else if(isset($_COOKIE[$key])) return $_COOKIE[$key];
else return false;
} else
return setcookie($key, $val, $expiry, "/", NULL, NULL, TRUE);
}
public function session(?string $key = null, $val = null) {
if($val == null){
if($key == null) return $_SESSION;
else if(isset($_SESSION[$key])) return $_SESSION[$key];
else return false;
} else
return $_SESSION[$key] = $val;
}
public function server(?string $key = null, $val = null) {
if($val == null){
if($key == null) return $_SERVER;
else if(isset($_SERVER[$key])) return $_SERVER[$key];
else return false;
} else
return $_SERVER[$key] = $val;
}
public function redirect(string $location) : void {
if(!headers_sent()) header('Location: '. $location);
else echo '<meta http-equiv="refresh" content="0; url='. $location .'">';
exit();
}
public function showError(int $errorCode) : void {
$this->Redirect('/error/'. $errorCode);
}
}
?>
| true |
6489482296290a356af92a45718a464ec67e94d6 | PHP | psquirrel2018/PlumbK2018 | /wp-content/themes/one-confluence/templates/team-fluid.php | UTF-8 | 2,380 | 2.53125 | 3 | [] | no_license | <?php
/**
*This is a template part if the admin wants to use a fluid layout for the team section
*/
global $post;
//Team Variables
//$teamLayout = get_post_meta($post->ID, 'team_layout', true);
$team_id = get_post_meta($post->ID, '_one_front_team_id', true);
$dataTitleTeam = get_post_meta($post->ID, '_one_front_team_title', true);
$team_bg = get_post_meta($post->ID, '_one_front_team_background_image', true);
?>
<section id="team" class="row" data-title="<?= $dataTitleTeam; ?>">
<div class="col-xs-12 team_div" style="background-image: url('<?= $team_bg; ?>');">
<div class="row">
<div class="col-xs-10 col-xs-push-1">
<div class="owl-carousel owl-theme">
<?php
$team2 = get_post_meta( $team_id, 'pks_team_group', true ); // this particular instance spits out 33 which is entered into a field in wp-admin
foreach( (array) $team2 as $team ){
// Default all variables in case they are not defined in the dataset.
$name = '';
$title = '';
$bio = '';
$img = '';
if ( isset( $team['name'] ) )
$name = esc_html( $team['name'] );
if ( isset( $team['title'] ) )
$title = esc_html( $team['title'] );
if ( isset( $team['bio'] ) )
$bio = esc_html( $team['bio'] );
if ( isset( $team['image_id'] ) ) {
$img = wp_get_attachment_image($team['image_id'], 'share-pick', null, array(
'class' => 'thumb img-responsive grayscale',
));
} ?>
<div class="team-member">
<div class="col-xs-12 col-sm-4 col-md-5 team-photo"><?= $img; ?></div>
<div class="col-xs-12 col-sm-8 col-md-7 details">
<h3><?= $name; ?></h3>
<h4><?= $title; ?></h4>
<p><?= $bio; ?></p>
</div>
</div>
<?php } // END foreach ?>
</div>
</div>
</div>
</div>
</section> | true |
6290a6a78f94d4531f7692181d23803ca9a172e0 | PHP | ikool-cn/phalcon-note | /Phalcon笔记/0-Phalcon创建查询的N种方式.php | GB18030 | 1,790 | 2.875 | 3 | [] | no_license | <?php
$phql = 'SELECT id,username FROM Users WHERE username like :username:';
//1
$users = $this->modelsManager->executeQuery($phql, array('username' => '%demo%'));
//2
$users = $this->modelsManager->createQuery($phql)->execute(array('username' => '%demo%'));
//3
$users = $this->modelsManager->createBuilder()->from('Users')->columns(array('id', 'username'))->where('username like :username:')->getQuery()->execute(array('username' => '%demo%'));
//4
$query = new Phalcon\Mvc\Model\Query($phql, $this->getDI());
$users = $query->execute(array('username like' => '%demo%'));
//5
$criteria = new Phalcon\Mvc\Model\Criteria();
$users = $criteria->setModelName('Users')->columns(array('id', 'username'))->where('username like :username:')->bind(array('username' => '%demo%'))->execute();
//6
$users = Users::find(array('columns' => 'id,username', 'conditions' => 'username like :username:', 'bind' => array('username' => '%demo%')));
//7
$users = Users::query()->where('username like :username:')->columns(array('id', 'username'))->bind(array('username' => '%demo%'))->execute();
//8 ݿ㣨Database Abstraction Layer
//http://docs.phalconphp.com/zh/latest/reference/db.html
$sql = "SELECT id,username FROM Users WHERE username like '%demo%'";
$query = $this->db->query($sql);
// Get all rows in an array
$robots = $this->db->fetchAll($sql);
foreach ($robots as $robot) {
print_r($robot);exit;
}
// SQL䵽ݿ
$result = $connection->query($sql);
// ӡÿrobot
while ($robot = $result->fetch()) {
echo $robot["name"];
}
// һؽ
$robots = $connection->fetchAll($sql);
foreach ($robots as $robot) {
echo $robot["name"];
}
鿴ĵ | true |
52a7ce263632a4b10d15e8b4c304c13d0c2fc06b | PHP | lDmitriyl/My_PHP | /application/models/Orders.php | UTF-8 | 1,184 | 2.734375 | 3 | [] | no_license | <?php
namespace application\models;
use application\core\Model;
class Orders extends Model {
function makeNewOrder($name,$phone,$address){
$userId=$_SESSION['user']['id'];
$comment="id пользователя {$userId}</br>
Имя:{$name}</br>
Телефон:{$phone}</br>
Адрес:{$address}</br>";
$dataCreated=date('Y.m.d H:i:s');
$user_ip=$_SERVER['REMOTE_ADDR'];
$sql="INSERT INTO `orders` (`user_id`,`date_created`,`date_payment`,`status`,`comment`,`user_ip`)
VALUES (:userId,:dataCreated,null,0,:comment,:user_ip)";
$stmt=$this->db->prepare($sql);
$stmt->bindParam(':userId',$userId);
$stmt->bindParam(':dataCreated',$dataCreated);
$stmt->bindParam(':comment',$comment);
$stmt->bindParam(':user_ip',$user_ip);
if($stmt->execute()){
$statement = $this->db->query("SELECT `id` FROM `orders` ORDER BY id DESC LIMIT 1");
$result=$statement->fetchAll();
if(isset($result[0])){
return $result['0']['id'];
}
}
return false;
}
}
| true |
789f01e8e7e8c9b90470ba367ef8861955fa6e9f | PHP | safra-silvania/safra-gp | /src/Policy/SketchPolicy.php | UTF-8 | 1,478 | 2.625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace App\Policy;
use App\Model\Entity\sketch;
use Authorization\IdentityInterface;
/**
* sketch policy
*/
class sketchPolicy extends Base\BasePolicy
{
public function canAccess(IdentityInterface $user, sketch $sketch)
{
return true;
}
/**
* Check if $user can create sketch
*
* @param Authorization\IdentityInterface $user The user.
* @param App\Model\Entity\sketch $sketch
* @return bool
*/
public function canCreate(IdentityInterface $user, sketch $sketch)
{
return true;
}
/**
* Check if $user can update sketch
*
* @param Authorization\IdentityInterface $user The user.
* @param App\Model\Entity\sketch $sketch
* @return bool
*/
public function canUpdate(IdentityInterface $user, sketch $sketch)
{
return true;
}
/**
* Check if $user can delete sketch
*
* @param Authorization\IdentityInterface $user The user.
* @param App\Model\Entity\sketch $sketch
* @return bool
*/
public function canDelete(IdentityInterface $user, sketch $sketch)
{
return true;
}
/**
* Check if $user can view sketch
*
* @param Authorization\IdentityInterface $user The user.
* @param App\Model\Entity\sketch $sketch
* @return bool
*/
public function canView(IdentityInterface $user, sketch $sketch)
{
return true;
}
}
| true |
97d7066935bbfd005871cfcb44296fe43f1c0e2c | PHP | amphp/parallel | /test/Context/AbstractContextTest.php | UTF-8 | 5,848 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php declare(strict_types=1);
namespace Amp\Parallel\Test\Context;
use Amp\CancelledException;
use Amp\Parallel\Context\Context;
use Amp\Parallel\Context\ContextException;
use Amp\PHPUnit\AsyncTestCase;
use Amp\TimeoutCancellation;
use function Amp\async;
use function Amp\delay;
abstract class AbstractContextTest extends AsyncTestCase
{
abstract public function createContext(string|array $script): Context;
public function testBasicProcess(): void
{
$context = $this->createContext([
__DIR__ . "/Fixtures/test-process.php",
"Test"
]);
self::assertSame("Test", $context->join());
}
public function testFailingProcess(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('No string provided');
$context = $this->createContext(__DIR__ . "/Fixtures/test-process.php");
$context->join();
}
public function testThrowingProcessOnReceive(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('The context stopped responding');
$context = $this->createContext(__DIR__ . "/Fixtures/throwing-process.php");
$cancellation = new TimeoutCancellation(0.1);
$context->receive($cancellation);
self::fail('Receiving should have failed');
}
public function testThrowingProcessOnSend(): void
{
$this->expectException(ContextException::class);
$context = $this->createContext(__DIR__ . "/Fixtures/throwing-process.php");
delay(1); // Give process time to start.
$context->send(1);
delay(1); // await TCP RST
$context->send(1);
self::fail('Sending should have failed');
}
public function testInvalidScriptPath(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage("No script found at '../test-process.php'");
$context = $this->createContext("../test-process.php");
$context->join();
}
public function testInvalidResult(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('The given data could not be serialized');
$context = $this->createContext(__DIR__ . "/Fixtures/invalid-result-process.php");
$context->join();
}
public function testNoCallbackReturned(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('did not return a callable function');
$context = $this->createContext(__DIR__ . "/Fixtures/no-callback-process.php");
$context->join();
}
public function testParseError(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('contains a parse error');
$context = $this->createContext(__DIR__ . "/Fixtures/parse-error-process.inc");
$context->join();
}
public function testCloseWhenJoining(): void
{
$this->setTimeout(3);
$this->expectException(ContextException::class);
$this->expectExceptionMessage('Failed to receive result from context');
$context = $this->createContext([
__DIR__ . "/Fixtures/delayed-process.php",
5,
]);
$future = async($context->join(...));
$context->close();
$future->await();
}
public function testCloseBusyContext(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('Failed to receive result');
$context = $this->createContext([__DIR__ . "/Fixtures/sleep-process.php"]);
$future = async($context->join(...));
async($context->close(...));
$future->await();
}
public function testExitingProcess(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('Failed to receive result');
$context = $this->createContext([__DIR__ . "/Fixtures/exiting-process.php"]);
$context->join();
}
public function testExitingProcessOnReceive(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('stopped responding');
$context = $this->createContext(__DIR__ . "/Fixtures/exiting-process.php");
$context->receive();
}
public function testExitingProcessOnSend(): void
{
$this->expectException(ContextException::class);
$this->expectExceptionMessage('stopped responding');
$context = $this->createContext(__DIR__ . "/Fixtures/exiting-process.php");
delay(1);
$context->send(1);
delay(1); // Await TCP RST
$context->send(1);
}
public function testCancelJoin(): void
{
$this->setTimeout(2);
$context = $this->createContext([
__DIR__ . "/Fixtures/delayed-process.php",
1,
]);
try {
$context->join(new TimeoutCancellation(0.1));
self::fail('Joining should have been cancelled');
} catch (CancelledException $exception) {
// Expected
}
self::assertSame(1, $context->join(new TimeoutCancellation(1)));
}
public function testImmediateJoin(): void
{
$context = $this->createContext([
__DIR__ . "/Fixtures/channel-process.php",
1,
]);
$cancellation = new TimeoutCancellation(1);
$exitValue = async($context->join(...));
$receivedValue = async($context->receive(...));
$value = 'value';
$context->send($value);
self::assertSame($value, $receivedValue->await($cancellation));
self::assertSame($value, $exitValue->await($cancellation));
}
}
| true |
b4cd4901fe2e47fd8e4340bd244bccff5ad5a7fc | PHP | samhemelryk/css_theme_tool | /colourpicker_image.php | UTF-8 | 2,473 | 3.015625 | 3 | [] | no_license | <?php
/**
* Generates the colour picker image in for use with the colour picker
* component in module.js
*
* This is the coolest file in this block, it mathematically generates a PNG image
* in such a way that given XY coordinates JavaScript can work out what colour was
* clicked.
*
* @package block_css_theme_tool
* @copyright 2012 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* Generates and sends the colour picker image
*/
function produce_colorpicker() {
$width = 384;
$height = 128;
$factor = 4;
$colour = array(255, 0, 0);
$matrices = array();//R, G, B
$matrices[] = array( 0, 1, 0);
$matrices[] = array( -1, 0, 0);
$matrices[] = array( 0, 0, 1);
$matrices[] = array( 0, -1, 0);
$matrices[] = array( 1, 0, 0);
$matrices[] = array( 0, 0, -1);
$matrixcount = count($matrices);
$limit = ceil($width/$matrixcount);
$heightbreak = floor($height/2);
header("Content-type: image/png");
$image = imagecreatetruecolor($width, $height);
imagecolorallocate($image, 0, 0, 0);
for ($x = 0; $x < $width; $x++) {
$divisor = floor($x / $limit);
$matrix = $matrices[$divisor];
$colour[0] += $matrix[0]*$factor;
$colour[1] += $matrix[1]*$factor;
$colour[2] += $matrix[2]*$factor;
for ($y=0;$y<$height;$y++) {
$pixel = $colour;
if ($y < $heightbreak) {
$pixel[0] += ((255-$pixel[0])/$heightbreak)*($heightbreak-$y);
$pixel[1] += ((255-$pixel[1])/$heightbreak)*($heightbreak-$y);
$pixel[2] += ((255-$pixel[2])/$heightbreak)*($heightbreak-$y);
} else if ($y > $heightbreak) {
$pixel[0] = ($height-$y)*($pixel[0]/$heightbreak);
$pixel[1] = ($height-$y)*($pixel[1]/$heightbreak);
$pixel[2] = ($height-$y)*($pixel[2]/$heightbreak);
}
if ($pixel[0] < 0) $pixel[0] = 0;
else if ($pixel[0] > 255) $pixel[0] = 255;
if ($pixel[1] < 0) $pixel[1] = 0;
else if ($pixel[1] > 255) $pixel[1] = 255;
if ($pixel[2] < 0) $pixel[2] = 0;
else if ($pixel[2] > 255) $pixel[2] = 255;
imagesetpixel($image, $x, $y, imagecolorallocate($image, $pixel[0], $pixel[1], $pixel[2]));
}
}
imagepng($image);
imagedestroy($image);
}
produce_colorpicker(); | true |
f837275a8836ce192028ac37e54a3681500bc80c | PHP | danyalSh/employeeSystem | /app/UserProjectTasks.php | UTF-8 | 1,083 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserProjectTasks extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'user_id', 'project_id', 'task_id'
];
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user_project_tasks';
public function assignTaskToEmployee($request){
// dd($request);
$array = [
'user_id' => $request->employees,
'project_id' => $request->projects,
'task_id' => $request->tasks
];
$result = $this->create($array);
return $result;
}
public function updateUserProjectTask($request){
$record = $this->where('task_id', '=', $request->tasks)->first();
$array = [
'user_id' => $request->employees,
'project_id' => $request->projects,
'task_id' => $request->tasks
];
$result = $record->update($array);
return $result;
}
}
| true |
603d9231e23762e507abad9ca28c60c4b3e18158 | PHP | ahmadrivaldi-arv/php-native- | /lib/function.php | UTF-8 | 2,376 | 2.71875 | 3 | [] | no_license | <?php
session_start();
$db = new mysqli("localhost","superadmin","super","db_login");
if($db -> connect_errno){
echo("failed to connect to databse!");
exit();
}
function generate_random_session(){
$random_str = rand();
$random_session = hash('sha256',$random_str);
return $random_session;
}
function get_data_login($user_email,$password){
global $db;
$result = $db->query("select * from tbl_users where email='$user_email'");
foreach ($result as $user_data) {
if(!password_verify($password,$user_data['password'])){
return false;
}else {
$_SESSION['session_id'] = generate_random_session();
$_SESSION['name'] = $user_data['name'];
$_SESSION['email'] = $user_data['email'];
$_SESSION['role'] = $user_data['role'];
return TRUE;
}
}
}
function get_data_users(){
global $db;
$sql = "select id,name,email,role from tbl_users";
$result = $db->query($sql);
$rows = [];
if(mysqli_num_rows($result) > 0){
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
return $rows;
}
function register_new_user($full_name,$user_email,$user_password){
global $db;
$password_hash = password_hash($password,PASSWORD_DEFAULT);
$sql = "INSERT INTO tbl_users VALUES(null,'$full_name','$user_email','$password_hash','user')";
if($db->query($sql)){ // jika data berhasil disimpan
// header("location:../register/index.php?pesan=success");
// kembalikan nilai true
return TRUE;
}
else {
// header("location:../register/index.php?pesan=gagal");
return FALSE;
}
}
function if_user_exist($user_email){
global $db;
}
function delete_user($userid){
global $db;
$sql = "delete from tbl_users where id='$userid'";
if($db->query($sql)){
return TRUE;
}else {
return FALSE;
}
}
function add_new_user($full_name,$email,$password,$role){
global $db;
$password_hash = password_hash($password,PASSWORD_DEFAULT);
$sql = "INSERT INTO tbl_users VALUES(null,'$full_name','$email','$password_hash','$role')";
if($db->query($sql)){
return TRUE;
}
else {
// $_SESSION['sql_status'] = "Error: " . $sql . "<br>" . $conn->error;
}
}
?> | true |
aa7fa67b98eea35e105914d610f0ef9b438417df | PHP | oat-sa/jig | /Utils/ServerUtils.php | UTF-8 | 4,649 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
/**
* This file is part of the Jig package.
*
* Copyright (c) 04-Mar-2013 Dieter Raber <me@dieterraber.net>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Jig\Utils;
use Exception;
/**
* ServerUtils
*/
class ServerUtils
{
/**
* Determine whether a request has been made with AJAX
*
* @return bool
*/
public static function requestIsXhr()
{
return !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
$_SERVER['HTTP_X_REQUESTED_WITH']
) === 'xmlhttprequest';
}
/**
* Make an educated guess on the URI that called the current script
*
* @param bool $qualified
* @return string
*/
public static function getScriptUri($qualified = false)
{
if (!empty($_SERVER['REQUEST_URI'])) {
return $qualified ? self::getBaseUri() . '/' . ltrim(
$_SERVER['REQUEST_URI'],
'/'
) : $_SERVER['REQUEST_URI'];
}
if (!empty($_SERVER['REDIRECT_URL'])) {
return $qualified ? self::getBaseUri() . '/' . ltrim(
$_SERVER['REDIRECT_URL'],
'/'
) : $_SERVER['REDIRECT_URL'];
}
$queryString = '';
if (!empty($_SERVER['QUERY_STRING'])) {
$queryString = $_SERVER['QUERY_STRING'];
} else if (!empty($_SERVER['REDIRECT_QUERY_STRING'])) {
$queryString = $_SERVER['REDIRECT_QUERY_STRING'];
}
$queryString = '?' . htmlspecialchars($queryString);
$phpSelf = '';
if (!empty($_SERVER['PHP_SELF'])) {
$phpSelf = $_SERVER['PHP_SELF'];
} else if (!empty($_SERVER['SCRIPT_NAME'])) {
$phpSelf = $_SERVER['SCRIPT_NAME'];
}
if ($phpSelf) {
return $qualified ? self::getBaseUri() . '/' . ltrim(
$phpSelf . $queryString,
'/'
) : $phpSelf . $queryString;
}
return '';
}
/**
* Get base uri (protocol + domain)
*
* @return string
*/
public static function getBaseUri()
{
$server = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME'];
return rtrim(self::getProtocol() . '://' . $server, '/');
}
/**
* Get protocol
*
* @return string
*/
public static function getProtocol()
{
return 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "s" : "");
}
/**
* Redirect to a different resource
*
* @param string $path to the resource without protocol and without host
* @return bool|void
*/
public static function redirect($path = '')
{
$redirection = self::getProtocol() . '://' . $_SERVER['HTTP_HOST'] . '/' . ltrim($path, '/');
if (self::getScriptUri(true) === $redirection) {
return false;
}
if ($redirection !== self::getScriptUri(true)) {
header('Location: ' . $redirection, true, 301);
exit(-1);
}
return false;
}
/**
* Force a file to download
*
* @param $path
* @param null $dwlFilename
* @throws Exception
*/
public static function forceDownload($path, $dwlFilename = null)
{
if (!is_file($path)) {
throw new Exception(__METHOD__ . '() File ' . $path . ' doesn\'t exist!');
}
if (!$dwlFilename) {
$dwlFilename = basename($path);
}
$content = file_get_contents($path);
// initialize download
header('Expires: Fri, 16 Sep 1983 00:00:01 GMT');
header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Cache-control: private');
header('Content-type: application/octet-stream');
header('Content-Length: ' . strlen($content));
header('Content-Disposition: ' . $dwlFilename);
print($content);
exit(-1);
}
public static function clientIpIs($ip)
{
return !empty($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] === $ip;
}
public static function protocolizeUri($uri)
{
$uri = ltrim($uri, '/');
if (strpos($uri, '://') === false) {
$uri = self::getServerProtocol() . '://' . $uri;
}
return $uri;
}
}
| true |
ba7faafcc744ee7676981bac487de9313626c826 | PHP | genkgo/api | /src/StringStream.php | UTF-8 | 2,072 | 2.828125 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace Genkgo\Api;
use Psr\Http\Message\StreamInterface;
final class StringStream implements StreamInterface
{
private int $position = 0;
public function __construct(private string $content)
{
}
public function __toString()
{
return $this->content;
}
public function close()
{
}
public function detach()
{
$handle = \fopen('php://memory', 'r+');
if ($handle === false) {
throw new \UnexpectedValueException('Cannot open php://memory for writing');
}
\fwrite($handle, $this->content);
return $handle;
}
public function getSize()
{
return \strlen($this->content);
}
public function tell()
{
return $this->position;
}
public function eof()
{
return $this->position >= \strlen($this->content);
}
public function isSeekable()
{
return true;
}
public function seek($offset, $whence = SEEK_SET)
{
$length = \strlen($this->content);
if ($length < $offset) {
$offset = $length;
}
$this->position = $offset;
return 0;
}
public function rewind()
{
$this->position = 0;
return true;
}
public function isWritable()
{
return true;
}
public function write($string)
{
$this->content = \substr_replace($this->content, $string, $this->position, \strlen($string));
$bytesWritten = \strlen($string);
$this->content += $bytesWritten;
return $bytesWritten;
}
public function isReadable()
{
return true;
}
public function read($length)
{
$result = \substr($this->content, $this->position, $length);
$this->position += \strlen($result);
return $result;
}
public function getContents()
{
return \substr($this->content, $this->position);
}
public function getMetadata($key = null)
{
return [];
}
}
| true |
ec5f8d10fb626b000ce2aa28dbf453ff98a60546 | PHP | ionutmilica/ionix-framework | /src/Validation/Rules/UrlRule.php | UTF-8 | 523 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php namespace Ionix\Validation\Rules;
use Ionix\Validation\Rule;
class UrlRule extends Rule {
/**
* Validate the rule against the value
*
* @return mixed
*/
public function validate()
{
return filter_var($this->getValue(), FILTER_VALIDATE_URL) !== false;
}
/**
* Get error message in case of fail
*
* @return string
*/
public function getMessage()
{
return sprintf('The field `%s` should be a valid url!', $this->inputName);
}
} | true |
4de52116602e1c7eece43aceccf68dfd04c3121d | PHP | XenosEleatikos/MusicBrainz | /src/Relation/Type/Artist/Artist/MusicalRelationships/IsComposerInResidenceAt.php | UTF-8 | 682 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace MusicBrainz\Relation\Type\Artist\Artist\MusicalRelationships;
use MusicBrainz\Value\Name;
use MusicBrainz\Relation\Type\Artist\Artist\MusicalRelationships;
/**
* An "is composer-in-residence at" relation
* This links a group (often an orchestra) to a composer who has a composer-in-residence position with the group.
*
* https://musicbrainz.org/relationship/094b1ddf-3df3-4fb9-8b01-cfd28e45da80
*/
class IsComposerInResidenceAt extends MusicalRelationships
{
/**
* Returns the name of the relation.
*
* @return Name
*/
public static function getRelationName(): Name
{
return new Name('composer-in-residence');
}
}
| true |
b2051197b562bc2c14d7adff1655414444826280 | PHP | cazunigag/reabastecimiento | /assets/telerik/wrappers/php/lib/Kendo/UI/UploadAsync.php | UTF-8 | 4,824 | 2.546875 | 3 | [
"LicenseRef-scancode-free-unknown",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
namespace Kendo\UI;
class UploadAsync extends \Kendo\SerializableObject {
//>> Properties
/**
* By default, the selected files are uploaded immediately. To change this behavior, set autoUpload to false.
* @param boolean $value
* @return \Kendo\UI\UploadAsync
*/
public function autoUpload($value) {
return $this->setProperty('autoUpload', $value);
}
/**
* By default and if supported by the browser, the selected files are uploaded in separate requests. To change this behavior, set batch to true. As a result, all selected files are uploaded in one request.The batch mode applies to multiple files which are selected simultaneously. Files that are selected one after the other are uploaded in separate requests.
* @param boolean $value
* @return \Kendo\UI\UploadAsync
*/
public function batch($value) {
return $this->setProperty('batch', $value);
}
/**
* When async.chunkSize is set, the selected files are uploaded chunk by chunk with the declared size. Each request sends a separate file blob and additional string metadata to the server. This metadata is in a stringified JSON format and contains the fileName, relativePath, chunkIndex, contentType, totalFileSize, totalChunks, and uploadUid properties. These properties enable the validation and combination of the file on the server side. The response also returns a JSON object with the uploaded and fileUid properties, which notifies the client what the next chunk is.
* @param float $value
* @return \Kendo\UI\UploadAsync
*/
public function chunkSize($value) {
return $this->setProperty('chunkSize', $value);
}
/**
* By default, the selected files are uploaded one after the other. When async.concurrent is set to true, all selected files start to upload simultaneously.
* @param boolean $value
* @return \Kendo\UI\UploadAsync
*/
public function concurrent($value) {
return $this->setProperty('concurrent', $value);
}
/**
* If async.autoRetryAfter is set, the failed upload request is repeated after the declared amount of time in miliseconds.
* @param float $value
* @return \Kendo\UI\UploadAsync
*/
public function autoRetryAfter($value) {
return $this->setProperty('autoRetryAfter', $value);
}
/**
* Sets the maximum number of attempts that are performed if an upload fails.
* @param float $value
* @return \Kendo\UI\UploadAsync
*/
public function maxAutoRetries($value) {
return $this->setProperty('maxAutoRetries', $value);
}
/**
* The name of the form field that is submitted to removeUrl.
* @param string $value
* @return \Kendo\UI\UploadAsync
*/
public function removeField($value) {
return $this->setProperty('removeField', $value);
}
/**
* The URL of the handler which is responsible for the removal of the uploaded files (if any). The handler must accept POST requests with one or more "fileNames" fields which specify the files that will be deleted.
* @param string $value
* @return \Kendo\UI\UploadAsync
*/
public function removeUrl($value) {
return $this->setProperty('removeUrl', $value);
}
/**
* The HTTP verb that will be used by the remove action.
* @param string $value
* @return \Kendo\UI\UploadAsync
*/
public function removeVerb($value) {
return $this->setProperty('removeVerb', $value);
}
/**
* The name of the form field which is submitted to saveUrl. The default value is the input name.
* @param string $value
* @return \Kendo\UI\UploadAsync
*/
public function saveField($value) {
return $this->setProperty('saveField', $value);
}
/**
* The URL of the handler that will receive the submitted files. The handler must accept POST requests which contain one or more fields with the same name as the original input name.
* @param string $value
* @return \Kendo\UI\UploadAsync
*/
public function saveUrl($value) {
return $this->setProperty('saveUrl', $value);
}
/**
* By default, the files are uploaded as file data. When set to true, the files are read as a file buffer by using FileReader. This buffer is sent in the request body.
* @param boolean $value
* @return \Kendo\UI\UploadAsync
*/
public function useArrayBuffer($value) {
return $this->setProperty('useArrayBuffer', $value);
}
/**
* Controls whether to send credentials (cookies, headers) for cross-site requests.
* @param boolean $value
* @return \Kendo\UI\UploadAsync
*/
public function withCredentials($value) {
return $this->setProperty('withCredentials', $value);
}
//<< Properties
}
?>
| true |
afb6c60a93c7c191997b3caaa713c7ebb59e97bb | PHP | swarnalats/php-sgt-rest-api | /api/add_grade.php | UTF-8 | 1,666 | 2.734375 | 3 | [] | no_license | <?php
//print_r($_POST);
$output = [
'message' => 'testing add record',
'record' => null
];
$course = null;
$grade = null;
$name = null;
$errors = [];
if(isset($_POST['course'])){
$course = $_POST['course'];
}else {
$errors[] = 'No course name received';
}
if(isset($_POST['grade'])){
$grade = (int) $_POST['grade'];
if($grade <0 || $grade > 100){
$errors[] = "Grade must be between 1 and 100: $grade is invalid";
}
}else {
$errors[] = 'No grade received';
}
if(isset($_POST['name'])){
$name = $_POST['name'];
}else {
$errors[] = 'No name received';
}
if(count($errors) > 0){
http_response_code(422);
echo json_encode([
'errors' => $errors,
'message' => "Unable tp add new grade"
]);
exit;
}
//$sql = "INSERT INTO grades (pid, course, grade, name) VALUES (UUID(), '$course', $grade, '$name'";
$result = mysqli_query($conn,"INSERT INTO grades (pid, course, grade, name) VALUES (UUID(), '$course', $grade, '$name')");
if(mysqli_affected_rows($conn) >0){
$record_id = mysqli_insert_id($conn);
$result = mysqli_query($conn, "
SELECT pid, course, grade, name, updated AS lastUpdated
FROM grades WHERE id=$record_id");
if(mysqli_num_rows($result)){
$output['message'] = "Successfully added new record for $name";
$output['record'] = mysqli_fetch_assoc($result);
echo json_encode($output);
exit;
}
}
http_response_code(500);
echo json_encode([
'errors' => ['Error adding grade record']
]);
| true |
12e592713e349fe1a6c9d141f7b9395c41808da5 | PHP | olivier8573/blog | /admin/addUser.php | UTF-8 | 4,095 | 3.1875 | 3 | [] | no_license | <?php
// Le fichier config.php contient les identifiants de connexion à la base de données sous forme de variables
include('../config/config.php');
// Le fichier bdd.lib.php contient la fonction connexion qui permet de générer un nouveau PDO (PHP Data Object) et se connecter en utilisant les identifiants de config.php
include('../lib/bdd.lib.php');
// On inclut dans une variable la vue du fichier qui sera affiché si tout fonctionne
$vue = 'addUser.phtml';
$erreur = false;
// On prépare un tableau vide (cela permet d'alimenter les value du formulaire)
$resultats = [
'aut_name' => '',
'aut_firstname' => '',
'aut_email' => '',
'aut_password' => '',
'aut_password2' => ''
];
// Tentative d'exécution 'try' qui sous-entend qu'une alternative 'catch' peut être précisée (afin notamment d'éviter d'afficher le mot de passe en clair en cas d'échec) / La flèche correspond à l'équivalent du "." de Javascript suivie d'une fonction qui est propre à l'objet PDO
try {
// Vérification de la présence d'un nom rempli dans le formulaire
if (array_key_exists('aut_name',$_POST)) {
// Alimentation du tableau des résultats même s'il y a des erreurs dans les données saisies
$resultats = [
'aut_name' => $_POST['aut_name'],
'aut_firstname' => $_POST['aut_firstname'],
'aut_email' => $_POST['aut_email'],
'aut_password' => $_POST['aut_password'],
'aut_password2' => $_POST['aut_password2']
];
// Vérification de l'email
$email = $_POST['aut_email'];
if (filter_var($email,FILTER_VALIDATE_EMAIL) == false) {
$erreur = 'Email invalide';
}
else {
// Vérification de la cohérence du mot de passe
$password = $_POST['aut_password'];
$password2 = $_POST['aut_password2'];
if ($password != $password2) {
$erreur = 'Mots de passe non identiques';
}
else {
// Hashage du mot de passe
$passwordHash = password_hash($password,PASSWORD_DEFAULT);
// Modification du tableau des résultats en précisant le mot de passe haché
$resultats = [
'aut_name' => $_POST['aut_name'],
'aut_firstname' => $_POST['aut_firstname'],
'aut_email' => $email,
'aut_password' => $password
];
// Etape 1 : connexion à la base de données à partir de la fonction connexion du fichier bdd.lib.php
$dbh = connexion();
// Etape 2 : préparation de la requête sachant que le NULL correspond à la colonne aut_id qui nécessite une auto-incrémentation (obligatoire) / Tous les champs qui ont une spécificité "not null" doivent impérativement être pris en compte dans la requête (équivalent de champs obligatoires) / C'est à l'étape suivante que l'on indiquera qu'il faut utiliser le tableau $resultats : utilisation des index de ce tableau en les précédant de ":"
$sth = $dbh->prepare('INSERT INTO auteur (aut_id,aut_name,aut_firstname,aut_email,aut_password) VALUES (NULL,:aut_name,:aut_firstname,:aut_email,:aut_password)');
// Etape 3 : exécution de la requête (pas de paramètres supplémentaires à transmettre dans les parenthèses)
$sth->execute($resultats);
// L'étape 4 prévoit habituellement le stockage des résultats des requêtes dans une variable mais ce n'est pas nécessaire puisque l'on ne récupère pas de données de la requête SQL
}
}
}
}
// Alternative en cas d'échec au 'try'
catch(PDOException $e) {
$vue = 'erreur.phtml';
//Si une exception est envoyée par PDO (exemple : serveur de BDD innaccessible) on arrive ici
$messageErreur = 'Une erreur de connexion a eu lieu :'.$e->getMessage();
}
include('tpl/layout.phtml'); | true |
f42a3a0b5fbe8222f805a7d41c17538500c4ed8c | PHP | eljam/cqrs-example | /src/Domain/Exception/Command/AccommodationNotFoundException.php | UTF-8 | 509 | 2.6875 | 3 | [] | no_license | <?php
declare(strict_types=1);
/*
* Have fun !
*/
namespace App\Domain\Exception\Command;
use App\Domain\Shared\Command\NotFoundException;
/**
* Class AccommodationNotFoundException.
*/
class AccommodationNotFoundException extends NotFoundException
{
/**
* @param string $id
*
* @return AccommodationNotFoundException
*/
public static function withId(string $id): self
{
return new self(\sprintf('An accommodation with Id "%s" does not exist.', $id));
}
}
| true |
373f13dd2ef56ca4c4a9bf7d828da8d8c74a622c | PHP | AlexMaybee/first_one | /application/models/users_details.php | UTF-8 | 5,902 | 2.546875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
class Users_details extends CI_Model
{
/* public function get_user_details()
{
$this->load->database();
$query=$this->db->get('users_details');
return $query->result_array();
}*/
public function insert_users_details($formData1) //Уже не нужна, все сделал из users
{
$this->load->database();
if($query=$this->db->insert('users_details', $formData1) === true): return true;
endif;
}
public function ava_upload() //Сюда все перенесено из контроллера admin_contr->upload_avatar()
{
$userId = $_SESSION['userData']['id'];
if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/upload/'.$userId))
{
mkdir($_SERVER['DOCUMENT_ROOT'].'/upload/'.$userId);
mkdir($_SERVER['DOCUMENT_ROOT'].'/upload/'.$userId.'/thumbs'); //Создал папку колхозно, т.к. местная ф-я не хочет этого делать.
}
$config= array(
'upload_path' => './upload/'.$userId, //Путь к папке для загрузки
'allowed_types' => 'gif|jpg|png|jpeg', //Разрешенные расширения файлов.
'max_size' => '0', // ограничение в килобайтах
'encrypt_name' => true , //изменяет стоковое имя файла на шифр
'remove_spaces' => true, //del spaces from name
);
//load library
$this->load->library('upload',$config);
if($this->upload->do_upload('fileToUpload') === FALSE)
{
return false;
//На странице ошибка выводится, если $this->input->post('fileToUpload') === FALSE
}
else
{
$image_info=$this->upload->data(); // Вызываем массив информации о загруженном файле.
$this->load->library('image_lib'); //Вызываем библиотеку.
//Watermark on original foto
$config = array(
'source_image' => $image_info['full_path'], //картинка, кот. берется за основу.
'wm_text' => 'Copyright 2017, by Alex Mayboroda', //текст, кот. будет печататься.
'wm_type' => 'text',
'wm_padding' => '10',
'wm_vrt_alignment' => 'top', //расположение по вертикали
'wm_hor_alignment' => 'left', //расположение печати по горизонтали
'wm_font_color' => 'fff', //цыет печати.
'wm_font_size' => '25', //размер шрифта печати зависит от разрешения картинки: чем больше разрешение, тем мельче шрифт!!!
);
$this->image_lib->initialize($config);
$this->image_lib->watermark(); //НЕ получается, чтобы сначала делало копию в миниатюры, а потом ставило знак.
//Watermark on original foto
//Image resize
$config = array(
'image_library' => 'gd2',
'source_image' => $image_info['full_path'],
'maintain_ratio' => true,
'create_thumb' => true, // Должно, кажется, быть в связве с путем через строку выше, иначе будеи изменять название
'new_image' => APPPATH.'../upload/'.$userId.'/thumbs', //была здесь ошибка в точках, поэтому не грузоло в папку.
'width' => 100,
'height' => 100,
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
//Image resize
//Вносим в массив имя поля-значение
$avatar=array(
'image' => $image_info['file_name']
);
$this->load->database();
$this->db->where('id_users',$userId);
$this->db->update('users_details', $avatar);
// Session refresh
$this->load->model('users');
$userData=$this->users->allUserDataLoad($userId);
foreach ($userData as $column)
{
$add_userdata=$column;
}
$addSession=array(
'logged_In' => 'true',
'first_name' => $add_userdata['first_name'],
'last_name' => $add_userdata['last_name'],
'id' => $add_userdata['id'],
'email' => $add_userdata['email'],
'image' => $add_userdata['image']
);
$this->session->set_userdata('userData', $addSession);
// Session refresh
// return true;
}
}
public function avarge_salary()
{
$this->load->database();
$this->db->select_avg('salary');
$this->db->from('users_details');
$query=$this->db->get();
return $query->row_array();
}
public function countOld() //функция вычисления полных лет для страницы админа
{
$userId=$_SESSION['userData']['id'];
$time = date('Y-m-d',time());
$this->load->database();
$this->db->select('birthdate');
$this->db->from('users_details');
$this->db->where('id_users',$userId);
$query= $this->db->get();
$row=$query->row_array();
$date1 = str_replace('-','',$row['birthdate']);
$date2 = str_replace('-','',$time);
$v = abs($date1-$date2);
return substr($v,0,-4);
}
} | true |
101eb0ad09c2b9a83be8405880ea2bd5450308f8 | PHP | eridiumdev/e-shop | /src/Controller/BaseController.php | UTF-8 | 15,289 | 2.75 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use App\Model\Database\Reader;
use App\Model\Data\Cart;
use App\Model\Data\CartItem;
const TEMPLATES_DIR = __DIR__ . '/../View/templates';
/**
* Basic template for all page controllers
* Loads twig, wraps all needed variables via render()
* and transfers response via Router
*
* Interfaces: replacing template, replacing http response code,
* adding variables to twig, adding flash messages to twig,
* cleaning up input variables
*/
class BaseController
{
protected $twig;
protected $template = 'home.twig';
protected $httpCode = Response::HTTP_FOUND;
protected $vars = [];
protected $logger;
protected $uid; // current session user
public function __construct()
{
global $logger;
$this->logger = $logger;
$this->loadTwig();
}
public function showHomepage()
{
$this->render();
}
/**
* Init current session user id (using auth token)
* No effect if noone has logged in
*/
public function getCurrentUser()
{
$userId = Security::getUserId();
if (!empty($userId)) {
$this->uid = $userId;
}
}
/**
* Prepares twig environment and loads default functions
* and variables to twig, e.g. auth functions or cart contents
*/
public function loadTwig()
{
$loader = new \Twig_Loader_Filesystem(TEMPLATES_DIR);
$this->twig = new \Twig_Environment($loader);
$this->addTwigFunc('authenticated', 'isAuthenticated', 'App\Controller\Security');
$this->addTwigFunc('admin', 'isAdmin', 'App\Controller\Security');
$this->addTwigFunc('short', 'short', $this);
$this->addTwigFunc('activeSection', 'activeSection', $this);
$this->addTwigFunc('activeAction', 'activeAction', $this);
$this->twig->addFilter(new \Twig_Filter('name', [$this, 'name']));
// Catalog pages require cart, categories, sections always
// (to at least display in the header nav)
// Admin pages don't require these however
if (!($this instanceOf AdminController)) {
// Initialize current session user, if it exists
if ($user = $this->getCurrentUser()) {
$this->addTwigVar('user', $user);
}
// Populate nav with sections and categories
try {
$dbReader = new Reader();
$categories = $dbReader->getAllCategories();
$sections = $dbReader->getAllSections();
} catch (\Exception $e) {
Logger::log(
'db', 'error',
"Failed to get categories/sections from database",
$e
);
}
if (!empty($categories)) {
$this->addTwigVar('categories', $categories);
}
if (!empty($sections)) {
$this->addTwigVar('sections', $sections);
}
// Initialize cart (get from database/cookie)
$cart = $this->initCart();
if (!empty($cart)) {
$this->addTwigVar('cart', $cart);
}
}
}
public function initCart()
{
try {
$dbReader = new Reader();
$userId = $this->uid;
$cart = new Cart();
if (!empty($userId)) {
// User is not a guest, get cart from database
$cart = $dbReader->getUserCart($userId);
} elseif (!empty($cartProducts = Router::getCookie('cart'))) {
// User is a guest, get cart from cookie
foreach ($cartProducts as $prodId => $qty) {
if ($product = $dbReader->getProductById($prodId)) {
$cart->addItem(new CartItem($product, $qty));
}
}
}
} catch (\Exception $e) {
Logger::log('db', 'error', "Failed to initialize cart", $e);
}
return $cart;
}
/**
* Renders current template, wraps variables for twig and sends response
*/
public function render()
{
$page = $this->twig->load($this->template);
$this->prepareFlashMessages();
$html = $page->render($this->vars);
Router::sendResponse($html);
}
public function setTemplate(string $template)
{
$this->template = $template;
}
public function setHttpCode(int $httpCode)
{
$this->httpCode = $httpCode;
}
/**
* Adds a key-value pair for use in a twig template
* @param string $varName
* @param any $varValue
*/
public function addTwigVar(string $varName, $varValue)
{
$this->vars[$varName] = $varValue;
}
/**
* Load function for use in twig template
* @param string $twigFuncName - how to refer inside twig
* @param string $funcName - real function name
* @param $handle
* class name if using static function
* item instance if using non static function
* null if using standalone function
*/
public function addTwigFunc(
string $twigFuncName,
string $funcName,
$handle = null)
{
if ($handle) {
$this->twig->addFunction(new \Twig_Function(
$twigFuncName, [$handle, $funcName]
));
} else {
$this->twig->addFunction(new \Twig_Function(
$twigFuncName, $funcName
));
}
}
/**
* Shortcut for adding flash messages to
* the session's flashBag
* @param string $msgType - 'success', 'fail'
* @param string $msg
*/
public function flash(string $msgType, string $msg)
{
global $session;
$session->getFlashBag()->add($msgType, $msg);
}
/**
* Extracts and prepares flash messages for future use in a twig template
*/
public function prepareFlashMessages()
{
global $session;
$messages = [];
foreach ($session->getFlashBag()->all() as $msgType => $msg) {
$messages[$msgType] = $msg;
}
//print_r($messages);
//exit;
$this->addTwigVar('messages', $messages);
}
/**
* Returns first $limit characters of a string
* @param string full
* @param int limit
* @return string
*/
public function short(string $full, $limit = 30) : string
{
preg_match(PATTERN_CHINESE, $full, $matches);
if (!empty($matches)) {
if (mb_strlen($full) >= $limit) {
return mb_substr($full, 0, $limit-1) . "...";
} else {
return mb_substr($full, 0, $limit);
}
} else {
if (strlen($full) >= $limit) {
return substr($full, 0, $limit-1) . "...";
} else {
return substr($full, 0, $limit);
}
}
}
/**
* Returns only the filename in the path
* @param string $path - full path
* @return string
*/
public function name(string $path) : string
{
$arr = explode('/', $path);
return $arr[count($arr) - 1];
}
public function activeSection(string $section)
{
if ($section == Router::$route['section']) {
return 'active';
} else {
return '';
}
}
public function activeAction(string $action)
{
if ($action == Router::$route['action']) {
return 'active';
} else {
return '';
}
}
/**
* Processes and adds to flashes successful batch action results
* @param array $good - succeeded entries
* @param array $data - all entries
* @param array $fields - column headers
* @param string $msg - e.g. Successful:
* @return void
*/
public function prepareGoodBatchResults(
array $good, array $data, array $fields, $msg = "Successful: "
) {
$total = count($data);
// p($data);pe($good);
if (!empty($good)) {
$goodOut = $msg . count($good) . "/$total\n\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $goodOut .= " - ";
$goodOut .= "[" . $fields[$i] . "]";
}
foreach ($good as $item) {
$goodOut .= $this->getBatchResultsRow($item, $fields);
}
$this->flash('success', $goodOut);
}
}
/**
* Processes and adds to flashes failed batch action results
* @param array $bad - failed entries
* @param array $data - all entries
* @param array $fields - column headers
* @param string $msg - e.g. Failed:
* @return void
*/
public function prepareBadBatchResults(
array $bad, array $data, array $fields, $msg = "Failed: "
) {
$total = count($data);
// p($data);pe($bad);
if (!empty($bad)) {
$badCount = 0;
foreach ($bad as $reason) {
foreach ($reason as $item) {
$badCount++;
}
}
$badOut = $msg . $badCount . "/$total";
foreach ($bad as $reason => $items) {
switch ($reason) {
case 'data' :
$badOut .= "\n\nBad input data:\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $badOut .= " - ";
$badOut .= "[" . $fields[$i] . "]";
}
foreach ($items as $item) {
$badOut .= $this->getBatchResultsRow($item, $fields);
}
break;
case 'duplicate' :
$badOut .= "\n\nDuplicates:\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $badOut .= " - ";
$badOut .= "[" . $fields[$i] . "]";
}
foreach ($items as $item) {
$badOut .= $this->getBatchResultsRow($item, $fields);
}
break;
case 'db' :
$badOut .= "\n\nDatabase failure:\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $badOut .= " - ";
$badOut .= "[" . $fields[$i] . "]";
}
foreach ($items as $item) {
$badOut .= $this->getBatchResultsRow($item, $fields);
}
break;
case 'fs' :
$badOut .= "\n\nFile System failure:\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $badOut .= " - ";
$badOut .= "[" . $fields[$i] . "]";
}
foreach ($items as $item) {
$badOut .= $this->getBatchResultsRow($item, $fields);
}
break;
case 'ext' :
$badOut .= "\n\nWrong file extension\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $badOut .= " - ";
$badOut .= "[" . $fields[$i] . "]";
}
foreach ($items as $item) {
$badOut .= $this->getBatchResultsRow($item, $fields);
}
break;
}
}
$this->flash('warning', $badOut);
}
}
/**
* Returns results entry output, used both for bad and goor results
* @param array OR object OR scalar $item - entry
* @param array $fields - array values OR class properties
* @return string
*/
public function getBatchResultsRow($item, array $fields) : string
{
$out = "\n";
for ($i = 0; $i < count($fields); $i++) {
if ($i != 0) $out .= " - ";
if (is_array($item)) {
// if item is array, output uses array fields values
$out .= $item[$fields[$i]];
} elseif (is_object($item)) {
// if item is object, output uses class getters
$getter = 'get' . ucfirst($fields[$i]);
$out .= $item->$getter();
} else {
// if item is scalar type, just print it out
$out .= $item;
}
}
return $out;
}
/**
* Cleans up input data and returns true if it has not changed
* @param array $vars - by reference -> possibly changed after cleanup
* @return bool
*/
public function isClean(array &$vars) : bool
{
$beforeCleanup = $vars;
$this->cleanupVars($vars);
// pe($vars);
return $beforeCleanup == $vars;
}
public function cleanupVars(array &$vars)
{
foreach ($vars as $key => &$val) {
if (is_array($val)) {
// p($val);
$this->cleanupVars($val);
} else {
// p($val); n();
switch (strtolower($key)) {
case 'password' :
$val = trim(filter_var($val, FILTER_SANITIZE_STRING));
$vars[$key] = str_replace(' ', '', $val);
break;
case 'email' :
$val = trim(filter_var($val, FILTER_SANITIZE_EMAIL));
if (!filter_var($val, FILTER_VALIDATE_EMAIL)) {
$val = '';
}
break;
case 'input' :
case 'username' :
$val = trim(filter_var($val, FILTER_SANITIZE_STRING));
$vars[$key] = str_replace(' ', '', $val);
break;
case 'text' :
case 'description' :
$val = trim(filter_var($val, FILTER_SANITIZE_STRING));
break;
case 'id' :
case 'number' :
$val = trim(filter_var($val, FILTER_SANITIZE_NUMBER_INT));
break;
case 'price' :
$val = trim(filter_var($val, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
break;
case 'uri' :
$val = trim(filter_var($val, FILTER_SANITIZE_URL));
break;
default :
$vars[$key] = trim(filter_var($val, FILTER_SANITIZE_STRING));
}
}
}
}
}
| true |
314567331f40518c7925ed96ddba3436a06ca89f | PHP | wilcarjose/werp | /app/Builders/Inputs/AddressInput.php | UTF-8 | 2,309 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Werp\Builders\Inputs;
class AddressInput extends TextInput
{
protected $addressName1;
protected $addressName2;
protected $addressValue1;
protected $addressValue2;
/**
* InputBuilder constructor.
* @param $name
* @param $type
* @param $icon
* @param $text
* @param $value
*/
public function __construct($value = null, $disabled = false, $icon = null)
{
$this->name = 'address';
$this->type = 'address';
$this->icon = $icon;
$this->text = trans('view.address');
$this->value = $value;
$this->disabled = $disabled;
$this->addressName1 = 'address_1';
$this->addressName2 = 'address_2';
}
public function setValue($value)
{
$this->addressValue1 = isset($value['address_1']) ? $value['address_1'] : null;
$this->addressValue2 = isset($value['address_2']) ? $value['address_2'] : null;
}
/**
* @return mixed
*/
public function getAddressName1()
{
return $this->addressName1;
}
/**
* @param mixed $addressName1
* @return InputBuilder
*/
public function setAddressName1($addressName1)
{
$this->addressName1 = $addressName1;
return $this;
}
/**
* @return mixed
*/
public function getAddressName2()
{
return $this->addressName2;
}
/**
* @param mixed $addressName2
* @return InputBuilder
*/
public function setAddressName2($addressName2)
{
$this->addressName2 = $addressName2;
return $this;
}
/**
* @return mixed
*/
public function getAddressValue1()
{
return $this->addressValue1;
}
/**
* @param mixed $addressValue1
* @return InputBuilder
*/
public function setAddressValue1($addressValue1)
{
$this->addressValue1 = $addressValue1;
return $this;
}
/**
* @return mixed
*/
public function getAddressValue2()
{
return $this->addressValue2;
}
/**
* @param mixed $addressValue2
* @return InputBuilder
*/
public function setAddressValue2($addressValue2)
{
$this->addressValue2 = $addressValue2;
return $this;
}
} | true |
c58c7dcbd8e260df2ef2805acd498dcf14830a90 | PHP | Guikingone/SchedulerBundle | /src/Task/FailedTask.php | UTF-8 | 730 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace SchedulerBundle\Task;
use DateTimeImmutable;
use function sprintf;
/**
* @author Guillaume Loulier <contact@guillaumeloulier.fr>
*/
final class FailedTask extends AbstractTask
{
private DateTimeImmutable $failedAt;
public function __construct(private TaskInterface $task, private string $reason)
{
$this->failedAt = new DateTimeImmutable();
parent::__construct(name: sprintf('%s.failed', $task->getName()));
}
public function getTask(): TaskInterface
{
return $this->task;
}
public function getReason(): string
{
return $this->reason;
}
public function getFailedAt(): DateTimeImmutable
{
return $this->failedAt;
}
}
| true |
bb3cbb2e43c6bbe420d1697eb5c44a062c0daed2 | PHP | tvs-laravel-pkgs/gigo-pkg | /src/database/migrations/2020_05_15_122950_gate_pass_details_c.php | UTF-8 | 1,844 | 2.515625 | 3 | [
"Unlicense"
] | permissive | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class GatePassDetailsC extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up() {
if (!Schema::hasTable('gate_pass_details')) {
Schema::create('gate_pass_details', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('gate_pass_id');
$table->unsignedInteger('vendor_type_id');
$table->unsignedInteger('vendor_id');
$table->string('work_order_no', 64)->nullable();
$table->string('work_order_description', 191)->nullable();
$table->string('vendor_contact_no', 64)->nullable();
$table->unsignedInteger("created_by_id")->nullable();
$table->unsignedInteger("updated_by_id")->nullable();
$table->unsignedInteger("deleted_by_id")->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign("gate_pass_id")->references("id")->on("gate_passes")->onDelete("CASCADE")->onUpdate("CASCADE");
$table->foreign("vendor_type_id")->references("id")->on("configs")->onDelete("CASCADE")->onUpdate("CASCADE");
$table->foreign("vendor_id")->references("id")->on("vendors")->onDelete("CASCADE")->onUpdate("CASCADE");
$table->foreign("created_by_id")->references("id")->on("users")->onDelete("SET NULL")->onUpdate("cascade");
$table->foreign("updated_by_id")->references("id")->on("users")->onDelete("SET NULL")->onUpdate("cascade");
$table->foreign("deleted_by_id")->references("id")->on("users")->onDelete("SET NULL")->onUpdate("cascade");
$table->unique(["gate_pass_id"]);
$table->unique(["work_order_no"]);
});
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down() {
Schema::dropIfExists('gate_pass_details');
}
}
| true |
c83bff0388c4c3debbd46da6e0eeed9ee4f82071 | PHP | Zenat0r/hexacore | /System/Core/Model/Manager/ModelManager.php | UTF-8 | 3,873 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: christophe
* Date: 17/03/19
* Time: 21:02
*/
namespace Hexacore\Core\Model\Manager;
use Hexacore\Core\Exception\Model\IdentificatorModelException;
use Hexacore\Core\Exception\Model\MissingGetterModelException;
use Hexacore\Core\Exception\Model\PopulatedModelException;
use Hexacore\Core\Model\AbstractQueryBuilder;
use Hexacore\Core\Model\ManageableModelInterface;
/**
* Class ModelManager
* @package Hexacore\Core\Model\ModelManager
*/
class ModelManager implements ModelManagerInterface
{
/**
* @var AbstractQueryBuilder
*/
private $queryBuilder;
/**
* ModelManager constructor.
* @param AbstractQueryBuilder $qb
*/
public function __construct(AbstractQueryBuilder $qb)
{
$this->queryBuilder = $qb;
}
/**
* @param ManageableModelInterface $model
* @return AbstractQueryBuilder
* @throws \ReflectionException
* @throws \Exception
*/
private function populateQueryBuilder(ManageableModelInterface $model): AbstractQueryBuilder
{
$namespace = get_class($model);
$reflection = new \ReflectionClass($namespace);
$reflexionProperties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
$qb = $this->queryBuilder->model($namespace);
foreach ($reflexionProperties as $property) {
$propertyName = $property->getName();
$getterName = "get" . ucfirst($propertyName);
if (method_exists($model, $getterName)) {
if (!is_null($value = $model->$getterName())) {
$qb->set($propertyName, $value);
}
} else {
throw new MissingGetterModelException("Getter for $propertyName doesn't exist");
}
}
return $qb;
}
/**
* @param ManageableModelInterface $model
* @return string
* @throws \ReflectionException
* @throws \Exception
*/
private function getIdentificator(ManageableModelInterface $model): string
{
$reflection = new \ReflectionClass(get_class($model));
$reflexionProperties = $reflection->getProperties(\ReflectionProperty::IS_PRIVATE);
foreach ($reflexionProperties as $property) {
if (preg_match("/id$/", $property->getName())) {
return $property->getName();
}
}
throw new IdentificatorModelException("Missing ManagableModel identificator");
}
/**
* @param ManageableModelInterface $model
* @throws \ReflectionException
* @throws \Exception
*/
private function update(ManageableModelInterface $model)
{
$this->populateQueryBuilder($model)
->where($this->getIdentificator($model), $model->getId())
->update();
}
/**
* @param ManageableModelInterface $model
* @throws \Exception
*/
private function create(ManageableModelInterface $model)
{
$this->populateQueryBuilder($model)
->insert();
}
/**
* @inheritdoc
* @throws \ReflectionException
* @throws \Exception
*/
public function delete(ManageableModelInterface $model)
{
if (empty($model->getId())) {
throw new PopulatedModelException("Can not delete this model, not a populated ManageableModel");
}
$this->queryBuilder
->model(get_class($model))
->where($this->getIdentificator($model), $model->getId())
->delete();
}
/**
* @inheritdoc
* @throws \ReflectionException
* @throws \Exception
*/
public function persist(ManageableModelInterface $model)
{
if (!empty($model->getId())) {
$this->update($model);
} else {
$this->create($model);
}
}
} | true |
92dfbaa6d25c296416cb69b861f2d2ead2fb8c33 | PHP | alexandreamormino/worksena | /wsSystem/Controller/AbstractActionController.php | UTF-8 | 5,482 | 3.09375 | 3 | [
"MIT"
] | permissive | <?php
/**
* --- WorkSena - Micro Framework ---
* Classe abstrata responsável por renderizar o layout
* Caso o mesmo exista e seja setando no controller. Também a definição de configurações
* das views da aplicação...
* @license https://github.com/WalderlanSena/worksena/blob/master/LICENSE (MIT License)
*
* @copyright © 2013-2017 - @author Walderlan Sena <walderlan@worksena.xyz>
*
*/
namespace WsSystem\Controller;
use WsSystem\Components\Sessions\Session;
use WsSystem\Authentication\AuthUser;
abstract class AbstractActionController
{
protected $view; // Recebe o objeto padrão stdClass
protected $success; // Flash messages de sucesso
protected $errors; // Flash messages de erro
protected $info; // Flash messages de informação
protected $inputs; // Armazena os dados dos inputs temporariamente
protected $action; // Recebe o nome da action setada
protected $auth; // Recebe um objeto com os dados do usuário logado
private $pageDescription = null; // Recebe a descrição da meta tags description
private $pageTitle = null; // Recebe o titulo da página
private $config;
public function __construct()
{
// Criando e inicializando um objeto view
$this->view = new \stdClass();
$this->auth = new AuthUser();
// Variável que recebe as configurações padrões da aplicação
$this->config = self::findDataSettings();
// Inicializando flash mensagem da aplicação
// Mensagem padrão para operações de sucesso
if (Session::getSession('success')) {
$this->success = Session::getSession('success');
Session::destroySession('success');
}//end if
// Mensagem padrão para operações de erros
if (Session::getSession('errors')) {
$this->errors = Session::getSession('errors');
Session::destroySession('errors');
}//end if
// Mensagem padrão para operações de info
if (Session::getSession('info')) {
$this->info = Session::getSession('info');
Session::destroySession('info');
}//end if
// Captura padrão de dados inseridos nos campos dos formulários
if (Session::getSession('inputs')) {
$this->inputs = Session::getSession('inputs');
Session::destroySession('inputs');
}//endif
}//end construct
/**
* Método que retorna as configurações padrão de localização de layout e mensagem
* @return bool|mixed
*/
private function findDataSettings()
{
if(file_exists("../wsSystem/Config/GeneralSettings.php")) {
return require "../wsSystem/Config/GeneralSettings.php";
}
return false;
}//end findDataSettings
/**
* @param $action
* @param bool $layout
* @return mixed|void
*/
public function render($action, $layout = true)
{
// Passando o nome da view que foi solicitada
$this->action = $action;
// Verifica se o layout existe. E Se caso o mesmo exista será incluido
if ($layout == true && file_exists($this->config['layoutLocation'])) {
include_once $this->config['layoutLocation'];
} else {
// Caso não aja um layout existente, ou não seja solicitado, e carregado o content
$this->content();
}//end if
}//end function render
/**
* Renderizando as flash mensagens
* @param $layoutLocation
*/
public function renderNotify($layoutLocation)
{
if (file_exists($this->config['notifyMessage'].$layoutLocation.".php"))
include_once $this->config['notifyMessage'].$layoutLocation.".php";
else
echo "Erro: Layout de notificação padrão não encontrado !";
}//end renderNotify
/**
* Renderiza o content da Aplicação
*/
public function content()
{
// Captura o nome da class atual
$current = get_class($this);
// Remove o caminho desnecessários somente o nome do controller
$ClassName = strtolower(str_replace("App\\Controllers\\", "", $current));
// Remove a palavra Controller, para corrigir o nome do diretório da view
$filterFolder = explode('\\', $ClassName);
// Inclui a view referente ao nome filtrado acima
include_once '../app/Views/'.$filterFolder[0].'/'.$this->action.'.phtml';
}//end function content
/**
* Configurando titulo dinâmico para as views
* @param $pageTitle
*/
protected function setPageTitle($pageTitle)
{
$this->pageTitle = $pageTitle;
}//end function setPageTitle
/**
* Adiciona separador no titulo da página
* @param null $separator
* @return null|string
*/
protected function getPageTitle($separator = null)
{
if ($separator)
return $this->pageTitle. " " . $separator. " ";
else
return $this->pageTitle;
}//end function getPageTitle
/**
* @param $description
*/
protected function setDescription($description)
{
$this->pageDescription = $description;
}
/**
* @return null
*/
protected function getDescription()
{
return $this->pageDescription;
}
}// end class AbstractActionController
| true |
54065ead941c7f786fa226d1a390fb972899da15 | PHP | saeed-ghasemi/hypertext_add_sales | /sales_add.php | UTF-8 | 1,324 | 2.578125 | 3 | [] | no_license | <?php
require_once '_includes/connect.php';
//echo("sales_insert.php");
//get JSON info
//$jsonData = json_decode(file_get_contents('php://input'));
//echo($jsonData);
$itemID = $_REQUEST["itemID"];
$customerID = $_REQUEST["customerID"];
$pricePaid = $_REQUEST["pricePaid"];
//define table
//echo("sales_insert.php: $itemID, $customerID, $pricePaid")
$tbl = "sales";//change to your table i.e. John_app
$insertArray = [];
//write query
$query = "INSERT INTO $tbl (itemID, customerID, pricePaid) VALUES (?,?,?)";
//prepare statement, execute, store_result
if($insertStmt = $mysqli->prepare($query)){
$insertStmt->bind_param("sss", $itemID, $customerID, $pricePaid);
$insertStmt->execute();
$insertStmt->insert_id;
$insertRows = $insertStmt->affected_rows;
}else{
//echo("<br>Oops there was an error: $insertStmt->error");
//echo("<br>$mysqli->error");
$insertArray[] = ["error", $insertStmt->error, $mysqli->error];
}
//if the info got inserted
if($insertRows > 0){
$insertArray[] = ["success", $insertStmt->affected_rows, $insertStmt->insert_id];
}else{
$insertArray[] = ["error", "Sorry, there was a problem saving your info."];
}
echo(json_encode($insertArray));
$insertStmt->close();
$mysqli->close();
?> | true |
4b757f702b3e562fee8d8f1a91b8138232998434 | PHP | Heres-A-Hand/Heres-A-Hand-Web | /src/DBMigrationManager.class.php | UTF-8 | 3,183 | 2.90625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Copyright 2011-2013 Here's A Hand Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @copyright 2011-2013 Here's A Hand Limited
* @license Apache License, Version 2.0
**/
class DBMigrationManager {
public static function upgrade($verbose = false) {
$db = getDB();
// First, the migrations table.
$stat = $db->query("SELECT true FROM pg_tables WHERE tablename = 'migration';");
$tableExists = ($stat->rowCount() == 1);
if ($tableExists) {
if ($verbose) print "Migrations table exists.\n";
} else {
if ($verbose) print "Creating migration table.\n";
$db->query("CREATE TABLE migration ( id VARCHAR(255) NOT NULL, installed_at TIMESTAMP WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id) )");
}
// Now load all possible migrations from disk & sort them
$migrations = array();
$dir = dirname(__FILE__).'/../sql/migrations/';
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
if ($verbose) echo "Loading ".$file."\n";
if (substr($file, -4) == '.sql') {
$migrations[] = new DBMigration(substr($file, 0, -4), file_get_contents($dir.$file));
}
}
}
closedir($handle);
usort($migrations, "DBMigrationManager::compareMigrations");
// Now see what is already applied
// ... in an O(N^2) loop inside a loop, performance could be better but doesn't matter here for now.
$stat = $db->query("SELECT id FROM migration");
while($result = $stat->fetch()) {
foreach($migrations as $migration) {
if ($migration->getId() == $result['id']) {
$migration->setIsApplied();
}
}
}
// Finally apply the new ones!
if ($verbose) {
foreach($migrations as $migration) {
if (!$migration->getApplied()) {
print "Will apply ".$migration->getId()."\n";
} else {
print "Already Applied ".$migration->getId()."\n";
}
}
}
$stat = $db->prepare("INSERT INTO migration (id, installed_at) VALUES (:id, :at)");
foreach($migrations as $migration) {
if (!$migration->getApplied()) {
if ($verbose) print "Applying ".$migration->getId()."\n";
$db->beginTransaction();
$migration->performMigration($db);
$stat->execute(array('id'=>$migration->getId(),'at'=>date('Y-m-h H:i:s')));
$db->commit();
if ($verbose) print "Applied ".$migration->getId()."\n";
}
}
if ($verbose) print "Done\n";
}
private static function compareMigrations(DBMigration $a, DBMigration $b) {
if ($a->getIdAsUnixTimeStamp() == $b->getIdAsUnixTimeStamp()) return 0;
return ($a->getIdAsUnixTimeStamp() < $b->getIdAsUnixTimeStamp()) ? -1 : 1;
}
} | true |
ad329d707224f79e888586dee37bce8caf261a0e | PHP | abler98/php-huawei-pushkit | /src/Contracts/Sender.php | UTF-8 | 609 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace MegaKit\Huawei\PushKit\Contracts;
use MegaKit\Huawei\PushKit\Data\Destination\Destination;
use MegaKit\Huawei\PushKit\Data\Message\Message;
use MegaKit\Huawei\PushKit\Data\SendResult;
use MegaKit\Huawei\PushKit\Exceptions\HuaweiException;
use MegaKit\Huawei\PushKit\HuaweiConfig;
interface Sender
{
/**
* @param HuaweiConfig $config
* @param Message $message
* @param Destination $destination
* @return SendResult
* @throws HuaweiException
*/
public function sendMessage(HuaweiConfig $config, Message $message, Destination $destination): SendResult;
}
| true |
d06df8568f3ac04f056e1ef918ddbb1df91951a0 | PHP | shin1127/todoByPHP | /csstest/index.php | UTF-8 | 1,224 | 2.609375 | 3 | [] | no_license | <?php
require_once("functions.php");
addTodo();
updateDone();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="hoge.css" />
<title>PHP TODO</title>
</head>
<body>
<h1>TO DO by PHP</h1>
<form action="index.php" method="post">
<span>Task Name</span>
<input type="text" name="name">
<br>
<span>Priority</span>
<select name="priority">
<option value="high">High</option>
<option value="middle">Middle</option>
<option value="low">Low</option>
</select>
<br>
<button type="submit" name="submit">ADD</button>
</form>
<div class="compare-box">
<div class="compare-left-wrap">
<div class="compare-left-head">Do</div>
<div class="compare-left">
<ul class="list">
<?php showDo(); ?>
</ul>
</div>
</div>
<div class="compare-right-wrap">
<div class="compare-right-head">Done</div>
<div class="compare-right">
<ul class="list">
<?php showDone(); ?>
</ul>
</div>
</div>
</div>
</body>
</html>
| true |
e0ac3c95e236243b34f19e2d5aa465e2568323bb | PHP | jasonbdaro/php_design_pattern_app | /app/AbstractPizzaStore/Eggplant.php | UTF-8 | 329 | 2.75 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: JASONBDARO
* Date: 10/8/2018
* Time: 12:11 AM
*/
namespace AbstractPizzaStore;
/**
* Class Eggplant
* @package AbstractPizzaStore
*/
class Eggplant
{
/**
* Eggplant constructor.
*/
public function __construct()
{
echo 'Eggplant' . PHP_EOL;
}
}
| true |
639a304d5a820015047eb9f30918863a60989138 | PHP | ansendu/ansio | /app/socket/server/debugWS.php | UTF-8 | 2,236 | 2.734375 | 3 | [] | no_license | <?php
/**
* User: ansen.du
* Date: 15-12-4
*/
namespace socket\server;
use ANSIO\Config;
use ANSIO\Debug;
use ANSIO\WebSocketServer;
use ANSIO\WebSocketHandle;
use ANSIO\TimerEvent;
class debugWS extends WebSocketServer
{
public $handle;
public function __construct($addr = null, $port = null)
{
parent::__construct($name = '-');
$this->bindSocket($addr, $port);
}
public function init()
{
$this->addPathHandle('debug', array($this, 'handleDebug'));
TimerEvent::add('test', function () {
debugWSHandle::sendDebugData('test broadcast after 10 sec.');
});
TimerEvent::setTimeout('test', 10);
}
public function bindSocket($addr = null, $port = null)
{
if ($addr === null && $port === null) {
$addr = Config::get('host');
$port = Config::get('port');
}
parent::bindSocket($addr, $port);
}
public function handleDebug($sess)
{
return new debugWSHandle($sess, $this);
}
}
class debugWSHandle extends WebSocketHandle
{
public static $clientPool = array();
public function onFrame($data, $type)
{
self::sendDebugData('receice frame:[' . $data . '] type:[' . $type . ']');
// $this->sendDebugDataToClient('receice frame:[' . $data . '] type:[' . $type . ']');
}
public function __construct($client, $appInstance = NULL)
{
parent::__construct($client, $appInstance);
self::$clientPool[$client->getConnId()] = $client;
}
public function sendDebugDataToClient($s)
{
$this->client->sendFrame($s);
}
public static function sendDebugData($s)
{
foreach (self::$clientPool as $client) {
/* @var $client webSocketSession */
if (!$client->isAlive()) {
unset(self::$clientPool[$client->getConnId()]);
continue;
}
$client->sendFrame($s);
}
}
public function onClose()
{
Debug::log(get_class($this) . '::' . __METHOD__ . ' : webSocketSession onClose id[' . $this->client->getConnId() . ']');
unset(self::$clientPool[$this->client->getConnId()]);
}
} | true |
581c5178c0309622e42e3175f45f9a117d7127b2 | PHP | philippvlasov/wonde | /app/Http/Controllers/ContactController.php | UTF-8 | 1,205 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Validator;
use Illuminate\Support\Facades\DB;
class ContactController extends Controller
{
public function index() {
return view('contacts');
}
public function validateMessage(Request $request) {
$rules = [
'name' => 'required',
'email' => 'required|email',
'phone' => 'required|numeric',
'message' => 'required',
];
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
return $this->insertMessageInTable($request);
} else {
return redirect()->route('contacts')->withErrors($validator)->withInput();
}
}
public function insertMessageInTable(Request $request) {
DB::table('messages')->insert([
[
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'message' => $request->message
]
]);
return redirect()->back()->with('message', 'Ваше сообщение успешно отправлено');
}
}
| true |
05ca4de2814c9d95f6b159c1fe4215c926bc791d | PHP | Relihazard/vva | /recherche.php | UTF-8 | 1,734 | 2.703125 | 3 | [] | no_license | <?php
include 'modele/connexionSQL.php';
include 'modele/session.php';
//récupération des critères de recherches spécifiés par l'utilisateur
$nbPlaces = filter_input(INPUT_GET, 'nbPlaces');
if (isset($nbPlaces)) {
$critere1 = 'AND NBPLACEHEB=' . $nbPlaces . '';
} else {
$critere1 = ' ';
}
$orientation = filter_input(INPUT_GET, 'orientation');
if (isset($orientation)) {
$critere2 = 'AND ORIENTATIONHEB=\'' . $orientation . '\'';
} else {
$critere2 = ' ';
}
$internet = filter_input(INPUT_GET, 'internet');
if ($internet == "Oui") {
$critere3 = 'AND INTERNET=1';
} else if ($internet == "Non") {
$critere3 = 'AND INTERNET=0';
} else {
$critere3 = ' ';
}
//construction de la requête SQL suivant les critères
$requete = 'SELECT * FROM HEBERGEMENT WHERE NOHEB!=0 ' . $critere1 . ' ' . $critere2 . ' ' . $critere3 . ';';
$sql = $link->query($requete);
$data = $sql->fetch();
include '/vue/partage/header.php';
?>
Résultat de votre recherche :<br><br>
<?php
if ($sql == true) {
if (count($data['NOHEB']) != 0) {
for ($i = 0; $i < count($data['NOHEB']); $i++) {
echo '<form method=\'get\' action=\' affichageOffre.php\'>';
echo '<input type=\'hidden\' name=\'nomHebergement\' value=\'' . $data['NOMHEB'] . '\'>', $data['NOMHEB'], ' ';
echo '<input type=\'submit\' value=\'Aficher les détails\'>';
echo '</form><br><br>';
}
} else {
echo 'Désolé, aucune offre ne correspond à vos critères.';
}
} else {
echo 'Erreur SQL, veuillez réessayer.';
}
?>
</body>
</html>
| true |
cc485be9bd5496835da7fddff6386ca59a24ef46 | PHP | pronamic/wp-softwear | /classes/Pronamic/Softwear/WooCommerce/Product.php | UTF-8 | 3,772 | 2.875 | 3 | [] | no_license | <?php
/**
* Title: Product
* Description:
* Copyright: Copyright (c) 2005 - 2011
* Company: Pronamic
* @author Remco Tolsma
* @version 1.0
*/
class Pronamic_Softwear_WooCommerce_Product {
/**
* WordPress post ID
*
* @var string
*/
public $id;
/**
* WordPress post title
*
* @var string
*/
public $title;
/**
* WooCommerce product SKU
*
* @var string
*/
public $sku;
/**
* WooCommerce product price
*
* @var int
*/
public $price;
/**
* WooCommerce product stock
*
* @var int
*/
public $stock;
//////////////////////////////////////////////////
/**
* Taxonomies
*
* @var array
*/
public $taxonomies;
/**
* Attributes
*
* @var array
*/
public $attributes;
/**
* Variations
*
* @var array
*/
public $variations;
//////////////////////////////////////////////////
/**
* Constructs and initialize an product
*/
public function __construct() {
$this->taxonomies = array();
$this->attributes = array();
$this->variations = array();
}
//////////////////////////////////////////////////
public function get_title() {
return $this->title;
}
//////////////////////////////////////////////////
// Taxonomies
//////////////////////////////////////////////////
public function add_terms( $taxonmy, $terms ) {
if ( ! isset( $this->taxonomies[$taxonmy] ) ) {
$this->taxonomies[$taxonmy] = array();
}
if ( ! is_array( $terms ) ) {
$terms = array_map( 'trim', explode( ',', $terms ) );
}
$this->taxonomies[$taxonmy] += $terms;
}
public function get_taxonomies() {
$taxonomies = $this->taxonomies;
// Type
$taxonomies['product_type'] = array( 'variable' );
// Variations taxonomies
foreach ( $this->variations as $variation ) {
foreach ( $variation->attributes as $key => $value ) {
if ( ! isset( $taxonomies[$key] ) ) {
$taxonomies[$key] = array();
}
$taxonomies[$key][] = $value;
}
}
return $taxonomies;
}
//////////////////////////////////////////////////
// Attributes
//////////////////////////////////////////////////
public function set_attribute( $key, $value ) {
$this->attributes[$key] = $value;
}
//////////////////////////////////////////////////
// Variations
//////////////////////////////////////////////////
public function add_variation( Pronamic_Softwear_WooCommerce_ProductVariation $variation ) {
$variation->parent = $this;
$this->variations[] = $variation;
}
//////////////////////////////////////////////////
public function get_post() {
$post = array();
$post['post_type'] = 'product';
$post['post_status'] = 'publish';
$post['post_title'] = $this->title;
return $post;
}
public function get_meta() {
$meta = array();
$meta['_sku'] = $this->sku;
$meta['_backorders'] = 'yes';
$meta['_manage_stock'] = 'yes';
$meta['_visibility'] = 'visible';
$meta['_product_attributes'] = array();
// Normal attributes
$position = 0;
foreach ( $this->attributes as $key => $value ) {
$meta['_product_attributes'][$key] = array(
'name' => $key ,
'value' => '' ,
'position' => $position ,
'is_visible' => true ,
'is_variation' => false ,
'is_taxonomy' => true
);
$position++;
}
// Variations attributes
$position = 0;
foreach ( $this->variations as $variation ) {
foreach ( $variation->attributes as $key => $value ) {
if ( ! isset( $meta['_product_attributes'][$key] ) ) {
$meta['_product_attributes'][$key] = array(
'name' => $key ,
'value' => '',
'position' => $position ,
'is_visible' => false ,
'is_variation' => true ,
'is_taxonomy' => true
);
$position++;
}
}
}
return $meta;
}
}
| true |
1dbf08cbe213e4973f6d2d911dbeee4c05a09690 | PHP | johnvandeweghe/php-api-library-core | /src/CacheControlInterface.php | UTF-8 | 487 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace PHPAPILibrary\Core;
/**
* Interface CacheControlInterface
* @package PHPAPILibrary\Core
*/
interface CacheControlInterface
{
/**
* Whether to consider the cache item private (for a specific user) or public (so a shared cache can use it).
* @return bool
*/
public function isPrivate(): bool;
/**
* How long the cache item is valid for.
* @return \DateInterval
*/
public function getRelativeExpiration(): \DateInterval;
}
| true |
2e488d919b73791e2e86fa358b30d52468bf848c | PHP | PatTelnetCmd/Entomology-Database | /admin/add_order.php | UTF-8 | 3,930 | 2.5625 | 3 | [] | no_license | <?php
session_start();
require_once '../libs/config.php';
require_once '../libs/database.php';
require 'includes/functions.php';
$db = new database(); //instantiating database object
/* inserting insect order */
if(isset($_POST['submit'])) {
$order = $_POST['insect_order'];
$order = ucfirst(strtolower($db->escape_string($order)));
$msg = '';
if(empty($order)){
$msg = 'Please insert order field!';
//echo $msg;
}
else{
$sql_select = "SELECT * FROM `Order` WHERE order_name = '{$order}'";
$run_query = $db->select($sql_select);
if($run_query){
$msg = "{$order} already exists";
}else {
$message = '';
$sql_insert = "INSERT INTO `Order`(order_name) VALUES('{$order}')";
$run_query = $db->insert($sql_insert);
if($run_query) {
$message = 'Order successfully added';
redirect_to('order_list.php', $message);
}
}
}
}
?>
<!-- header -->
<?php include 'includes/header.php'; ?>
<!-- =============================================== -->
<!-- siderbar navigation -->
<?php include 'includes/sidebar_nav.php'; ?>
<!-- =============================================== -->
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Order
<small>Describe order of species</small>
</h1>
<ol class="breadcrumb">
<li><a href="#"><i class="fa fa-dashboard"></i> Insects</a></li>
<li><a href="#">Order</a></li>
<li class="active">Add</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<div class='row'>
<div class='col-md-12'>
<fieldset>
<legend>Add New Insect Order</legend>
<form action='add_order.php' method='post' role='form'>
<div class='box box-primary'>
<div class='box-body'>
<?php if(!empty($msg)): ?>
<div class='alert alert-warning'>
<?php echo $msg; ?>
</div>
<?php endif; ?>
<div class='form-group'>
<label class='control-label' for='insect_order'>Insect Order</label>
<input type='text' class='form-control' id='insect_order' name='insect_order' placeholder='Enter Insect Order'>
</div>
<div class='form-group'>
<input type='submit' name='submit' class='btn btn-success' value='SAVE'>
<input type='reset' name='cancel' class='btn btn-danger' value='CANCEL'>
</div>
</div>
</div>
</form>
</fieldset>
</div>
</div>
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<!-- footer -->
<!-- =================================================================== -->
<?php include 'includes/footer.php'; ?>
| true |
c375b49a9d9cbcac8dce58de793b2db4d7841f39 | PHP | artemypolenko/AnimalShelter | /Entities/Owners/Person.php | UTF-8 | 444 | 3.21875 | 3 | [] | no_license | <?php
namespace App\Entities\Owners;
use App\Contracts\OwnerInterface;
/**
* @author Artemy Polenko
*/
class Person implements OwnerInterface
{
/**
* @var string Имя владельца.
*/
private $name;
public function __construct($name)
{
$this->name = $name;
}
/**
* @return string Имя владельца.
*/
public function getOwnerName()
{
return $this->name;
}
}
| true |
8c2bc6e3124dd1805c281174380454b012d575c5 | PHP | jeanray/Oblig-2-EJ | /switchFunksjon.php | UTF-8 | 2,331 | 2.625 | 3 | [] | no_license | <?php
if (isset($_GET["funksjon"])) {
$valgtFunksjon = $_GET["funksjon"];
// merk ":" i stedet for curly brackets. Les mer om det i slutten av switchen
// Motmerk: man blir ser svært mange flere {} og venner seg til betydningen
// i motsetning til : og "endswitch". Ser argumentet, men er dog uenig da
// krølleparentes er langt mer "lesbart" for _meg_ (og sannsynlig de fleste programmerere)
// Kan gjøre et eksperiment og se på eksempler med bruk av switch, og se hva som er mest brukt?
switch($valgtFunksjon) {
case "forside":
include("forside.php");
break;
case "registrer_klasse":
include("registrer_klasse.php");
break;
case "registrer_student":
include("registrer_student.php");
break;
case "registrer_bilde":
include("registrer_bilde.php");
break;
case "vis_alle_klasser":
include("vis_klasser.php");
break;
case "vis_alle_studenter":
include("vis_studenter.php");
break;
case "vis_alle_bilder":
include("vis_bilder.php");
break;
case "endre_klasser":
include("endre_klasser.php");
break;
case "endre_studenter":
include("endre_studenter.php");
break;
case "endre_bilder":
include("endre_bilder.php");
break;
case "slette_klasse":
include("slette_klasse.php");
break;
case "slette_student":
include("slette_student.php");
break;
case "slette_bilde":
include("slette_bilde.php");
break;
case "sok":
include("sok_i_database.php");
break;
case "logg_ut":
include("logg_ut.php");
break;
default: // Inntreffer kun hvis man skriver inn URL manuelt og da med ?funksjon=noe_annet_enn_i_switchen
print("Funksjonen du har valgt er ugyldig, vennligst bruk menyen over for å velge funksjon.");
// endswitch istede for curly brackets. Gjør koden mer human readable og kalles for syntactic sugar
// kan ta diskusjonen siden -jean - per nå så fucker det opp editoren min, og jeg velger brackets
}
// Her "mangler" det nå en krølleparentes sier magefølelsen min :D Men mange veier til capt. morgan!
} else { // Slutt på $GET_["funksjon"]
include("forside.php"); // Skriv ut en standard forside siden ingen funksjon er valgt.
}
?>
| true |
9193dc6984c0f35ac6280778d802e8f8d58cc39c | PHP | padraic/Stickler | /library/Stickler/Scanner.php | UTF-8 | 1,405 | 2.90625 | 3 | [] | no_license | <?php
namespace Stickler;
class Scanner
{
protected $detectors = array();
protected $log = array();
public function scan(FileTokens $tokens)
{
foreach($tokens as $index=>$token) {
$this->notify($token, $index, $tokens); // notify all (limit by config later)
}
}
public function attach(Detector\DetectorInterface $detector)
{
$this->detectors[get_class($detector)] = $detector;
}
public function detach(Detector\DetectorInterface $detecter)
{
unset($this->detectors[get_class($detector)]);
}
public function notify($token, $index, FileTokens $tokens)
{
foreach ($this->detectors as $detector) {
$result = $detector->notify($token, $index, $tokens);
if ($result === true) {
$this->log[] = array(
'detector' => get_class($detector),
'line' => Token::getLine($token)
);
}
}
}
public function getTriggered()
{
$return = array();
foreach ($this->detectors as $detector) {
if ($detector->isTriggered()) {
$return[] = $detector;
}
}
return $return;
}
public function getLog()
{
return $this->log;
}
public function resetLog()
{
$this->log = array();
}
} | true |
8dcec2669b6775bab17614a156a897e221e6f1d3 | PHP | moodleou/moodle-filter_embedquestion | /classes/attempt_storage.php | UTF-8 | 5,467 | 2.59375 | 3 | [] | no_license | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
namespace filter_embedquestion;
/**
* Deals with finding or creating the usages to store question attempts.
*
* This default implementation does not keep attempts long term. If you
* install report_embedquestion then there is an alternative implementation
* which does keep the data.
*
* @package filter_embedquestion
* @copyright 2019 The Open University
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class attempt_storage {
/**
* Private constructor. Use {@link instance()} to get an instance.
*/
protected function __construct() {
}
/**
* Static factory: get the most appropriate attempt_manager to use.
*
* If report_embedquestion is installed, then we use its implementation,
* which stores the attempts long-term. Otherwise we use our own, which
* does not keep data long term.
*
* @return attempt_storage
*/
public static function instance(): attempt_storage {
if (class_exists('\report_embedquestion\attempt_storage')) {
return new \report_embedquestion\attempt_storage();
} else {
return new self();
}
}
/**
* Is there already an attempt at this question in this location?
*
* @param embed_id $embedid identity of the question(s) being embedded in this place.
* @param embed_location $embedlocation where the question(s) are being embedded.
* @param \stdClass $user The user who is attempting the question (defaults to $USER).
* @return array [question_usage, int slot number], or [null, 0] if not found.
*/
public function find_existing_attempt(embed_id $embedid, embed_location $embedlocation,
\stdClass $user): array {
return [null, 0];
}
/**
* Update the timemodified time associated with this attempt.
*
* @param int $qubaid usage id for the attempt to update.
*/
public function update_timemodified(int $qubaid): void {
}
/**
* Make a new usage. Will only be called if find_existing_attempt has not found anything.
*
* Do not try to save the new usage yet. That won't work until MDL-66685 is fixed.
* {@link new_usage_saved()} will be called once the usage id is known.
*
* @param embed_id $embedid identity of the question(s) being embedded in this place.
* @param embed_location $embedlocation where the question(s) are being embedded.
* @param \stdClass $user the user who is attempting the question (defaults to $USER).
* @return \question_usage_by_activity usage to use.
*/
public function make_new_usage(embed_id $embedid, embed_location $embedlocation,
\stdClass $user): \question_usage_by_activity {
$quba = \question_engine::make_questions_usage_by_activity(
'filter_embedquestion', \context_user::instance($user->id));
return $quba;
}
/**
* New usage has been saved so we now know its id.
*
* Called after {@link make_new_usage()} and after the at least one
* question_attempt has been added.
*
* @param \question_usage_by_activity $quba the usage that has just been saved.
* @param embed_id $embedid identity of the question(s) being embedded in this place.
* @param embed_location $embedlocation where the question(s) are being embedded.
* @param \stdClass $user the user who is attempting the question (defaults to $USER).
*/
public function new_usage_saved(\question_usage_by_activity $quba,
embed_id $embedid, embed_location $embedlocation, \stdClass $user): void {
}
/**
* Checks to verify that a given usage is one we should be using.
*
* Throws an exception if not OK to continue.
*
* @param \question_usage_by_activity $quba the usage to check.
* @param \context $context the context we are in.
*/
public function verify_usage(\question_usage_by_activity $quba, \context $context): void {
global $USER;
if ($quba->get_owning_component() != 'filter_embedquestion') {
throw new \moodle_exception('notyourattempt', 'filter_embedquestion');
}
// Since responses are not stored long term, users can only access their own attempts.
if ($quba->get_owning_context()->instanceid !== $USER->id) {
throw new \moodle_exception('notyourattempt', 'filter_embedquestion');
}
}
/**
* Completely delete the attempt corresponding to this usage.
*
* This includes deleting the usage.
*
* @param \question_usage_by_activity $quba
*/
public function delete_attempt(\question_usage_by_activity $quba) {
// Do nothing here. Use by subclasses.
}
}
| true |
bb191ead6a13c082deee5e17ea87519da8210ad3 | PHP | Dev91100/NouPartazer | /NouPartazer_App/lib/php/BusinessRegistration.php | UTF-8 | 3,383 | 2.609375 | 3 | [] | no_license | <?php
require_once("Connection.php");
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$brn = test_input($_POST["brn"]);
$companyName = test_input($_POST["companyName"]);
$businessName = test_input($_POST["businessName"]);
$website = test_input($_POST["website"]);
$contactNumber = test_input($_POST["contactNumber"]);
$email = test_input($_POST["email"]);
$password = trim($_POST["password"]);
/*
select brn and put result in a variable
select email and put result in a variable
compare both variables if they are the same as entered in the text fields
*/
$query = "SELECT brn FROM BUSINESS WHERE brn='$brn'";
$res = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($res);
$brnToBeChecked = $row['brn'];
$query = "SELECT email FROM PROFILE WHERE email='$email'";
$res = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($res);
$emailToBeChecked = $row['email'];
if ($brn == $brnToBeChecked || $email == $emailToBeChecked)
{
echo json_encode("account already exists");
}
else
{ //Insert most of the data retrieved in business table
$query = "INSERT INTO BUSINESS (brn, companyName, businessName, website, contactNumber) VALUES ('$brn', '$companyName', '$businessName', '$website', '$contactNumber')";
$res = mysqli_query($conn, $query);
if($res)
{
$query = "SELECT businessID FROM BUSINESS WHERE brn='$brn'";
$res = mysqli_query($conn, $query);
if($res)
{
//Insert remaining data into profile table
$row = mysqli_fetch_assoc($res);
$businessID = $row['businessID'];
$query = "INSERT INTO PROFILE (businessID, email, password) VALUES ('$businessID', '$email', '$password')";
$res = mysqli_query($conn, $query);
if ($res)
{
$mainDirectory = 'uploads/' . 'business/' . $brn;
$directory = $mainDirectory . '/banner';
if(!file_exists($directory))
{
mkdir($directory, 0777, true);
}
$directory = $mainDirectory . '/profile';
if(!file_exists($directory))
{
mkdir($directory, 0777, true);
}
$directory = $mainDirectory . '/event';
if(!file_exists($directory))
{
mkdir($directory, 0777, true);
}
$directory = $mainDirectory . '/tmp';
if(!file_exists($directory))
{
mkdir($directory, 0777, true);
}
echo json_encode("true");
}
else
{
echo json_encode("false");
}
}
else
{
echo json_encode("false");
}
}
else
{
echo json_encode("false");
}
}
?> | true |
b8287c118bd1d59899063309fce647a80f913d29 | PHP | Arthur1/abc | /abc133/c/abc133_c.php | UTF-8 | 431 | 3.53125 | 4 | [] | no_license | <?php
/**
* ABC133
* C - Remainder Minimization 2019
*/
// $s = trim(fgets(STDIN));
// fscanf(STDIN, "%d %d", $a, $b);
// $n = array_map('intval', explode(' ', trim(fgets(STDIN))));
fscanf(STDIN, "%d %d", $L, $R);
$result = PHP_INT_MAX - 1;
for ($l = $L; $l <= $R; $l++) {
for ($r = $l; $r <= $R; $r++) {
$result = min($result, $l * $r % 2019);
if ($result === 0) break 2;
}
}
echo $result, PHP_EOL;
| true |
1bfb349098e7d12dd88d23a783a60b7c050efe4d | PHP | YRYcom/Harmony2 | /Tools/CliProgressBar.php | UTF-8 | 750 | 3.03125 | 3 | [] | no_license | <?php
namespace Harmony2\Tools;
/**
* Created by Yannick LALLEAU.
* Date: 09/02/2017
* Time: 15:01
*/
class CliProgressBar
{
static $oldDisplayValue;
static $maxLengthDisplay=0;
public static function display($done, $total, $info = "", $width = 50)
{
$perc = round(($done * 100) / $total);
if($perc != self::$oldDisplayValue) {
self::$oldDisplayValue = $perc;
$bar = round(($width * $perc) / 100);
$display = sprintf("%s%%[%s>%s]%s\r", $perc, str_repeat("=", $bar), str_repeat(" ", $width - $bar), $info);
if(self::$maxLengthDisplay < strlen($display))
self::$maxLengthDisplay = strlen($display);
echo $display;
}
}
public static function reset()
{
echo sprintf("%s\r",str_repeat(" ", self::$maxLengthDisplay));
}
} | true |
0c93445a71ade69b35bda8badb23e66c24b84a67 | PHP | robertux/apollouesfmo | /clases/cusuario.php | UTF-8 | 5,724 | 3.234375 | 3 | [] | no_license | <?php
//include_once("cconexion.php");
/*!
* \brief Clase que representa a los registros de la tabla docentes en la base de datos de Apollo
* Los usuarios son capaces de iniciar y cerrar sesion dentro del sitio para obtener privilegios administrativos y agregar/editar/eliminar elementos
*/
class cUsuario
{
/*!
* Objeto conexion, para hacer las consultas a la base de datos
*/
private $con;
/*!
* Reprsenta al id del usuario
*/
public $id;
//private $consulta;
/*!
* Represenat el nombre del usuario
*/
public $nombre;
/*!
* Representa la clave de acceso encriptada del usuario
*/
public $clave;
/*!
* Representa el tipo de privilegio que posee este usuario
*/
public $privilegio;
/*!
* Variable utilizada para saber la tabla que representa esta clase
*/
public $tabla;
/*!
* Variable utilizada para almacenar el mensaje de error producido por alguna consulta
*/
public $error;
/*!
* Constructor de la clase
* Instancia el objeto Conexion y asigna el nombre de la tabla que esta clase representa
*/
public function __construct()
{
$this->id = 0;
$this->nombre = "";
$this->clave = "";
$this->privilegio = "";
$this->con = new cConexion();
$this->tabla = "usuario";
//$this->con->Conectar();
}
/*!
* Destructor de la clase
*/
public function __destruct()
{
//..
}
/*!
* Obtenemos una lista de los docentes de la base de datos
* \param $cond Parametro opcional que define una condicion WHERE a incluir en la consulta de seleccion de los usuarios
*/
public function GetLista($cond = "")
{
return($this->Consultar("SELECT * FROM usuario" . ($cond == ""? " ": " WHERE $cond ") . " ORDER BY id DESC;", true));
}
/*!
* Obtenemos una lista filtrada de los usuarios de la base de datos
* El filtro se hace para poder paginar los resultados mediante la clausula LIMIT en la consulta de seleccion
* \param $ini El numero del registro inicial a incluir en el rango de los resultados
* \param $len Cantidad de registros a incluir en el rango de los resultados
* \param $cond Parametro opcional que define una condicion WHERE a incluir en la consulta de seleccion de los usuarios
*/
public function GetListaFiltrada($ini=0, $len=10, $cond="")
{
return($this->Consultar("SELECT * FROM usuario" . ($cond == ""? " ": " WHERE $cond ") . "ORDER BY id DESC limit $ini, $len;", true));
}
/*!
* Rellenamos los datos de esta clase con el registro de la tabla docentes que coincida con el nombre y clave pasados como parametros
* \param $pNombre El nombre del usuario a obtener
* \param $pClave La clave del usuario a obtener
*/
public function GetPorNombreClave($pNombre, $pClave)
{
return $this->Consultar("SELECT * FROM usuario WHERE nombre = '$pNombre' AND clave = '$pClave';", false);
}
/*!
* Rellenamos los datos de esta clase con el registro de la tabla procesos que coincida con el ID pasado como parametro
* \param $pId el ID del registro con el cual rellenar esta clase
*/
public function GetPorId($pId)
{
return $this->Consultar("SELECT * FROM usuario WHERE id = '$pId';", false);
}
/*
public function Insert()
{
$this->Consultar("INSERT INTO usuario(id, clave, nombre) VALUES ('$this->id', '$this->nombre','$this->clave');", false);
}
//?
/*public function Insert($pNombre, $pClave)
{
$this->Consultar("INSERT INTO usuario(clave,nombre) VALUES ('$pNombre','$pClave');");
}*/
/*
public function Update()
{
$this->Consultar("UPDATE usuario SET clave = '$this->clave', nombre = '$this->nombre' WHERE id = $this->id;", false);
}
public function Delete()
{
$this->Consultar("DELETE FROM usuario WHERE id = $this->id;", false);
}*/
/*!
* Realiza la llamada a la clase conexion para realizar las consultas respectivas
* \param $Consulta La cadena que contiene la consulta SQL a ejecutar
* \param $GetLista Valor booleano que define si la consulta rellenara este usuario o devolvera una lista de resultados
*/
function Consultar($Consulta, $GetLista)
{
@$this->con->Conectar();
$resultConsulta = false;
// ejecutar la consulta
if ($resultado = @$this->con->mysqli->query($Consulta))
{
// hay registros?
if ($resultado->num_rows > 0)
{
// si
if ($GetLista)
{
return ($resultado);
}
else
{
while($row = @$resultado->fetch_array())
{
$this->id = $row[0];
$this->clave = $row[1];
$this->nombre = $row[2];
$conTemp = new cConexion();
$conTemp->Conectar();
$resPriv = $conTemp->mysqli->query("SELECT p.nombre FROM privilegio p INNER JOIN asignacion a ON p.id = a.privilegio INNER JOIN usuario u ON a.usuario = u.id WHERE u.id=$this->id;");
if($resRow = $resPriv->fetch_array())
$this->privilegio = $resRow[0];
$conTemp->mysqli->close();
}
// liberar la memoria
$resultado->close();
}
$resultConsulta = true;
}
else
{
// no
$this->error .= "No hay resultados para mostrar!";
return false;
}
}
else
{
// tiremos el error (si hay)... ojala que no :P
//echo "Error en la consulta: $this->consulta. ".$this->con->mysqli->error;
}
// cerrar la conexion
@$this->con->mysqli->close();
return $resultConsulta;
}
}
?> | true |
d3c28ebce3af6309812337fd4666afa4f778438b | PHP | eguvenc/framework_old | /app/folders/examples/forms/Element.php | UTF-8 | 900 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace Examples\Forms;
use Obullo\Http\Controller;
class Element extends Controller
{
/**
* Index
*
* @return void
*/
public function index()
{
if ($this->request->isPost()) {
$this->validator->setRules('name', 'Name', 'required');
$this->validator->setRules('email', 'Email', 'required|email');
$this->validator->setRules('message', 'Your Message', 'required|max(800)');
$this->validator->setRules('hear', 'Last', 'required');
$this->validator->setRules('communicate', 'Communicate', 'required|max(5)');
if ($this->validator->isValid()) {
$this->form->success('Form validation success.');
} else {
$this->form->error('Form validation failed.');
}
}
$this->view->load('element');
}
} | true |
e62e3ae381447fe2b2f18abd3f7bb09f5812b72d | PHP | Przemar5/HTML-CSS-Javascript-and-PHP-tutorial-projects | /mmtuts/AJAX/AJAX 4/suggestions.php | UTF-8 | 290 | 2.796875 | 3 | [] | no_license | <?php
$names = array('Przemek', 'Piotr', 'Jan', 'Daniel');
if(isset($_POST['suggestion'])) {
$name = $_POST['suggestion'];
if(!empty($name)) {
foreach($names as $existingName) {
if(strpos($existingName, $name) !== false) {
echo $existingName;
}
}
}
}
?> | true |
0c3615f2baf41a364563beed0604c67be905d6dc | PHP | dominuskernel/school-environment | /backend/getdata.php | UTF-8 | 262 | 2.828125 | 3 | [] | no_license | <?php
header('Access-Control-Allow-Origin: *');
if(isset($_POST['num1']) && isset($_POST['num2'])){
$num1 = $_POST['num1'];
$num2 = $_POST['num2'];
echo "numero 1: ".$num1."<br>numero 2: ".$num2;
}else{
echo "Erro al recibir los datos";
}
?> | true |
b23142fb65d74db5d23c6900e53d4974f8444a5b | PHP | Yukun76/Projet5-DWJ | /src/Entity/Region.php | UTF-8 | 1,149 | 2.6875 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Animal;
/**
* @ORM\Entity(repositoryClass="App\Repository\RegionRepository")
*/
class Region
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* One Region has Many Animal.
* @OneToMany(targetEntity="Animal", mappedBy="region")
*/
private $animal;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getAnimal(): string
{
return $this->animal;
}
public function setAnimal(string $name): self
{
$this->animal = $animal;
return $this;
}
public function __toString()
{
return (string) $this->name;
}
}
| true |
76105a3614cc2a8b68de4155bbcc9429f9d1e0aa | PHP | cympak56/loftschool | /DM-3/src/AbstractController.php | UTF-8 | 443 | 3.015625 | 3 | [] | no_license | <?php
namespace Base;
use App\Model\User;
abstract class AbstractController
{
/** @var View */
protected $view;
/** @var User */
protected $user;
protected function redirect(string $url)
{
throw new RedirectException($url);
}
public function setView(View $view): void
{
$this->view = $view;
}
public function setUser(User $user): void
{
$this->user = $user;
}
} | true |
c65f54adba34dd61995738e1d74a599f90a84f9f | PHP | johndavedecano/Hello-API | /src/Modules/Core/Seeders/DatabaseSeeder.php | UTF-8 | 722 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Hello\Modules\Core\Seeders;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Seeder;
use Hello\Services\Authorization\Seeders\SeedRolesAndPermissions;
/**
* Class DatabaseSeeder.
*
* @author Mahmoud Zalt <mahmoud@zalt.me>
*/
class DatabaseSeeder extends Seeder
{
/**
* The application Seeders that needs to be registered.
*
* @var array
*/
protected $seeders = [
SeedRolesAndPermissions::class,
];
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Model::unguard();
foreach ($this->seeders as $seeder) {
$this->call($seeder);
}
Model::reguard();
}
}
| true |
51b45c6f92d6faaed59bc9c173ffd804dd0277ac | PHP | dwilbourne/pvcInterfaces | /src/struct/range_collection/RangeElementDateTimeInterface.php | UTF-8 | 769 | 2.765625 | 3 | [
"MIT"
] | permissive | <?php
/**
* @author: Doug Wilbourne (dougwilbourne@gmail.com)
*/
declare(strict_types=1);
namespace pvc\interfaces\struct\range_collection;
use DateTime;
use DateTimeImmutable;
/**
* @interface RangeElementDateTimeInterface is the DateTime-based interface for a RangeElement.
* @extends RangeElementInterface<RangeElementDateTimeInterface, DateTime|DateTimeImmutable>
*/
interface RangeElementDateTimeInterface extends RangeElementInterface
{
/**
* @return array<DateTime|DateTimeImmutable>
*/
public function getRange(): array;
/**
* @return DateTime|DateTimeImmutable
*/
public function getMin(): DateTime|DateTimeImmutable;
/**
* @return DateTime|DateTimeImmutable
*/
public function getMax(): DateTime|DateTimeImmutable;
}
| true |
9bc7dba4d6b3d8d26a70b71177f5a95d43dc1b82 | PHP | Zhuravleva08062005/Mutate | /src/AC/Mutate/Application/Application.php | UTF-8 | 4,844 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
namespace AC\Mutate\Application;
use AC\Mutate\Transcoder;
use AC\Mutate\TranscodeLogSubscriber;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
/**
* Main CLI Aplication class which builds a shared instance of the Transcoder and automatically registers commands, adapters, presets and jobs provided with the library.
*/
class Application extends BaseApplication
{
const VERSION = '0.8.0';
private $transcoder = false;
/**
* Construct app, build the Transcoder, register error handler.
*
* @param array $config - array of configuration passed to Transcoder
*/
public function __construct($config = array())
{
set_error_handler(array($this, 'handleError'));
parent::__construct("Mutate File Transcoder", self::VERSION);
//set default internal config
$defaults = array(
'mutate.log.enabled' => false,
'mutate.log.path' => '/var/log/mutate.log',
'mutate.log.level' => Logger::ERROR
);
$this->config = array_merge($defaults, $config);
//build transcoder
$this->transcoder = new Transcoder($config);
//register log subscriber, if logging is enabled
if ($this->config['mutate.log.enabled']) {
$logger = new Logger('mutate');
$logger->pushHandler(new StreamHandler($this->config['mutate.log.path'], $this->config['mutate.log.level']));
$this->transcoder->addSubscriber(new TranscodeLogSubscriber($logger));
}
}
/**
* Convert PHP errors to exceptions for consistency
*
* @param string $no
* @param string $str
* @param string $file
* @param string $line
* @return void
* @throws ErrorException
*/
public function handleError($no, $str, $file, $line)
{
throw new \ErrorException($str, $no, 0, $file, $line);
}
/**
* Run a command from string input. By default will not catch exceptions when run in this manner.
*
* This is provided as a convenient way to run commands with the stand-alone application from within another
* framework or application, if need-be.
*
* @param string $string
* @param string $catch
* @return \AC\Mutate\Application\ArrayOutput
* @author Evan Villemez
*/
public function runCommand($string, $catch = false)
{
$this->setCatchExceptions($catch);
$input = new \Symfony\Component\Console\Input\StringInput($string);
$output = new ArrayOutput;
$result = $this->run($input, $output);
$output->writeln("Finished with status: ".$result);
return $output;
}
/**
* Add commands in /Commands directory to default commands
*
* @return array
*/
protected function getDefaultCommands()
{
$commands = parent::getDefaultCommands();
$dir = __DIR__."/../Commands";
if (file_exists($dir)) {
foreach (scandir($dir) as $item) {
if (!in_array($item, array('.','..'))) {
$class = substr("AC\\Mutate\\Commands\\".$item, 0, -4); //get rid of ".php"
$commands[] = new $class;
}
}
}
return $commands;
}
/**
* Check for whether or not to run interactive shell
*
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
public function doRun(InputInterface $input, OutputInterface $output)
{
//setup and register transcoder listener to give user feedback during any transcode events
$listener = new CliOutputSubscriber;
$listener->setOutput($output);
$listener->setHelperSet($this->getHelperSet());
$this->getTranscoder()->addSubscriber($listener);
return parent::doRun($input, $output);
}
/**
* Return shared Transcoder instance
*
* @return AC\Mutate\Transcoder
*/
public function getTranscoder()
{
return $this->transcoder;
}
/**
* Set shared transcoder instance
*
* @param AC\Mutate\Transcoder $t
*/
public function setTranscoder(Transcoder $t)
{
$this->transcoder = $t;
}
/**
* Returns the long version of the application.
*
* @return string The long application version
*/
public function getLongVersion()
{
return sprintf('<info>%s</info> version <comment>%s</comment> by <comment>Evan Villemez</comment>', $this->getName(), $this->getVersion());
}
}
| true |
cf2ba5ae6a968f21c5c44d35f35c330459c8ae21 | PHP | pgrimaud/cheetahmail-sdk | /src/Campaigns/Content/CorrespondanceMTODeleteResponse.php | UTF-8 | 942 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace Cheetahmail\Campaigns\Content;
class CorrespondanceMTODeleteResponse
{
/**
* @var boolean $CorrespondanceMTODeleteResult
*/
protected $CorrespondanceMTODeleteResult = null;
/**
* @param boolean $CorrespondanceMTODeleteResult
*/
public function __construct($CorrespondanceMTODeleteResult)
{
$this->CorrespondanceMTODeleteResult = $CorrespondanceMTODeleteResult;
}
/**
* @return boolean
*/
public function getCorrespondanceMTODeleteResult()
{
return $this->CorrespondanceMTODeleteResult;
}
/**
* @param boolean $CorrespondanceMTODeleteResult
* @return \Cheetahmail\Campaigns\Content\CorrespondanceMTODeleteResponse
*/
public function setCorrespondanceMTODeleteResult($CorrespondanceMTODeleteResult)
{
$this->CorrespondanceMTODeleteResult = $CorrespondanceMTODeleteResult;
return $this;
}
}
| true |
753b26a6032a38f4c92e3b71c2284ec70afc1a9b | PHP | hivepress/hivepress-updates | /includes/components/class-updater.php | UTF-8 | 5,983 | 2.78125 | 3 | [] | no_license | <?php
/**
* Updater component.
*
* @package HivePress\Components
*/
namespace HivePress\Components;
use HivePress\Helpers as hp;
// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;
/**
* Updater component class.
*
* @class Updater
*/
final class Updater extends Component {
/**
* Class constructor.
*
* @param array $args Component arguments.
*/
public function __construct( $args = [] ) {
// Check license key.
if ( ! get_option( 'hp_hivepress_license_key' ) ) {
return;
}
// Check theme updates.
add_filter( 'pre_set_site_transient_update_themes', [ $this, 'check_theme_updates' ] );
// Check plugin updates.
add_filter( 'pre_set_site_transient_update_plugins', [ $this, 'check_plugin_updates' ] );
// Set plugin details.
add_filter( 'plugins_api', [ $this, 'set_plugin_details' ], 10, 3 );
parent::__construct( $args );
}
/**
* Gets license key.
*
* @return string
*/
protected function get_license_key() {
return implode( ',', explode( "\n", get_option( 'hp_hivepress_license_key' ) ) );
}
/**
* Gets themes.
*
* @return array
*/
protected function get_themes() {
// Get license key.
$license_key = $this->get_license_key();
// Get cache key.
$cache_key = 'themes_' . md5( $license_key );
// Get cached themes.
$themes = hivepress()->cache->get_cache( $cache_key );
if ( is_null( $themes ) ) {
$themes = [];
// Get API response.
$response = json_decode(
wp_remote_retrieve_body(
wp_remote_get(
'https://store.hivepress.io/api/v1/products?' . http_build_query(
[
'type' => 'theme',
'license_key' => $license_key,
]
)
)
),
true
);
if ( is_array( $response ) && isset( $response['data'] ) ) {
foreach ( $response['data'] as $theme ) {
// Add theme.
$themes[ $theme['slug'] ] = [
'theme' => $theme['slug'],
'new_version' => $theme['version'],
'requires' => $theme['wp_min_version'],
'requires_php' => $theme['php_version'],
'url' => $theme['buy_url'],
'package' => $theme['download_url'],
];
}
// Cache themes.
hivepress()->cache->set_cache( $cache_key, null, $themes, HOUR_IN_SECONDS );
}
}
return $themes;
}
/**
* Gets plugins.
*
* @return array
*/
protected function get_plugins() {
// Get license key.
$license_key = $this->get_license_key();
// Get cache key.
$cache_key = 'plugins_' . md5( $license_key );
// Get cached plugins.
$plugins = hivepress()->cache->get_cache( $cache_key );
if ( is_null( $plugins ) ) {
$plugins = [];
// Get API response.
$response = json_decode(
wp_remote_retrieve_body(
wp_remote_get(
'https://store.hivepress.io/api/v1/products?' . http_build_query(
[
'type' => 'extension',
'license_key' => $license_key,
]
)
)
),
true
);
if ( is_array( $response ) && isset( $response['data'] ) ) {
foreach ( $response['data'] as $extension ) {
// Add plugin.
$plugins[ $extension['slug'] ] = (object) [
'name' => $extension['name'],
'slug' => $extension['slug'],
'version' => $extension['version'],
'new_version' => $extension['version'],
'tested' => $extension['wp_max_version'],
'requires' => $extension['wp_min_version'],
'requires_php' => $extension['php_version'],
'id' => $extension['buy_url'],
'url' => $extension['buy_url'],
'package' => $extension['download_url'],
'download_link' => $extension['download_url'],
'plugin' => $extension['slug'] . '/' . $extension['slug'] . '.php',
'author' => '<a href="https://hivepress.io/" target="_blank">HivePress</a>',
'banners' => [],
'banners_rtl' => [],
'compatibility' => (object) [],
'icons' => [
'1x' => $extension['image_url'],
'2x' => $extension['image_url'],
],
'sections' => [
'description' => $extension['description'],
],
];
}
// Cache plugins.
hivepress()->cache->set_cache( $cache_key, null, $plugins, HOUR_IN_SECONDS );
}
}
return $plugins;
}
/**
* Checks theme updates.
*
* @param object $transient Transient object.
* @return object
*/
public function check_theme_updates( $transient ) {
if ( ! empty( $transient->checked ) ) {
// Get themes.
$themes = $this->get_themes();
foreach ( $themes as $theme ) {
// Get version.
$version = hp\get_array_value( $transient->checked, $theme['theme'] );
if ( $version && version_compare( $version, $theme['new_version'], '<' ) ) {
// Add update.
$transient->response[ $theme['theme'] ] = $theme;
}
}
}
return $transient;
}
/**
* Checks plugin updates.
*
* @param object $transient Transient object.
* @return object
*/
public function check_plugin_updates( $transient ) {
if ( ! empty( $transient->checked ) ) {
// Get plugins.
$plugins = $this->get_plugins();
foreach ( $plugins as $plugin ) {
// Get version.
$version = hp\get_array_value( $transient->checked, $plugin->plugin );
if ( $version && version_compare( $version, $plugin->version, '<' ) ) {
// Add update.
$transient->response[ $plugin->plugin ] = $plugin;
}
}
}
return $transient;
}
/**
* Sets plugin details.
*
* @param object $response API response.
* @param string $action API action.
* @param array $args Request arguments.
* @return object
*/
public function set_plugin_details( $response, $action, $args ) {
if ( 'plugin_information' === $action ) {
// Get plugin.
$plugin = hp\get_array_value( $this->get_plugins(), $args->slug );
if ( $plugin ) {
// Set details.
$response = $plugin;
}
}
return $response;
}
}
| true |
f411602d001f805d88835618f345450d47b62703 | PHP | SadowyKinga/WDPAI | /src/Repository/ICrudRepository.php | UTF-8 | 188 | 2.609375 | 3 | [] | no_license | <?php
interface ICrudRepository
{
public function findById($id);
public function findAll($id);
public function delete($id);
public function save($entity);
}
?>
| true |
3b32ff673cc6db9005c17929d8aa67398a0e8969 | PHP | tipui/Tipui-PHP | /Builtin/Libs/Request.php | UTF-8 | 2,453 | 2.75 | 3 | [] | no_license | <?php
/**
* @class Request
* @file Request.php
* @brief URL and CLI parameters abstraction.
* @date 2013-06-22 14:50:00
* @license http://opensource.org/licenses/GPL-3.0 GNU Public License
* @company: Tipui Co. Ltda.
* @author: Daniel Omine <omine@tipui.com>
* @updated: 2014-01-23 12:50:00
*/
namespace Tipui\Builtin\Libs;
use Tipui\Builtin\Libs\Strings as Strings;
class Request
{
/**
* Constants that defines valid methods
*/
const METHOD_GET = 'GET';
const METHOD_POST = 'POST';
const METHOD_FILES = 'FILES';
const METHOD_PUT = 'PUT';
const METHOD_DELETE = 'DELETE';
/**
* Parameter defined by model/user config settings
*/
protected static $rq_parameter;
/**
* (boolean) Handles the Core IsModeCli method
*/
protected static $sapi_is_cli;
/**
* Handles URL base path
*/
protected static $url_href_base;
/**
* Handles URL folder separator path
*/
protected static $url_pfs;
/**
* Handles URL parameter argument
*/
protected static $url_param_argumentor;
/**
* Method defined by model/user
*/
protected static $rq_method;
/**
* Real method received
*/
protected static $method;
/**
* Handles the server URI (Entire URL or CLI parameters)
*/
protected static $uri;
/**
* handles the server URI (HTTP only)
*/
protected static $request_uri;
/**
* (boolean) true: on, false: off
*/
protected static $mod_rewrite;
/**
* Handles all parameters extracted from URL or CLI
*/
protected static $parameters;
/**
* (boolean) true: enables magic quotes checking, false: disable it
*/
protected static $check_magic_quotes;
public function SetDefaults()
{
$this -> SetSapiMode();
$this -> SetURLParts();
self::$rq_method = null;
self::$rq_parameter = null;
self::$uri = null;
self::$request_uri = null;
self::$parameters = null;
self::$method = self::GetMethod();
self::$mod_rewrite = true;
self::$check_magic_quotes = false;
return null;
}
/**
* Instance.
*
* sample
* [code]
* $c = new Libs\Request;
* $c -> MethodName();
* [/code]
*/
public function __call( $name, $arguments )
{
return Factory::Exec( 'Request', $name, $arguments );
}
/**
* Statically.
*
* sample
* [code]
* Request::MethodName();
* [/code]
*/
public static function __callStatic( $name, $arguments )
{
return Factory::Exec( 'Request', $name, $arguments );
}
} | true |
257e125a7dca1878de364b35ae88c2917d0c8458 | PHP | masitings/lavender | /app/Http/Composers/Partials/MessageComposer.php | UTF-8 | 408 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Composers\Partials;
use App\Support\Facades\Message;
class MessageComposer
{
public function compose($view)
{
$messages = [];
foreach(config('store.message_types') as $type){
$message = Message::get($type);
if($message->getMessages()) $messages[$type] = $message;
}
$view->with('messages', $messages);
}
} | true |
9b5b6510b19eb13d4ad849073b4d6af0787c7b4f | PHP | laravel/telescope | /src/Watchers/EventWatcher.php | UTF-8 | 4,998 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Laravel\Telescope\Watchers;
use Closure;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Str;
use Laravel\Telescope\ExtractProperties;
use Laravel\Telescope\ExtractTags;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use ReflectionFunction;
class EventWatcher extends Watcher
{
use FormatsClosure;
/**
* Register the watcher.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function register($app)
{
$app['events']->listen('*', [$this, 'recordEvent']);
}
/**
* Record an event was fired.
*
* @param string $eventName
* @param array $payload
* @return void
*/
public function recordEvent($eventName, $payload)
{
if (! Telescope::isRecording() || $this->shouldIgnore($eventName)) {
return;
}
$formattedPayload = $this->extractPayload($eventName, $payload);
Telescope::recordEvent(IncomingEntry::make([
'name' => $eventName,
'payload' => empty($formattedPayload) ? null : $formattedPayload,
'listeners' => $this->formatListeners($eventName),
'broadcast' => class_exists($eventName)
? in_array(ShouldBroadcast::class, (array) class_implements($eventName))
: false,
])->tags(class_exists($eventName) && isset($payload[0]) ? ExtractTags::from($payload[0]) : []));
}
/**
* Extract the payload and tags from the event.
*
* @param string $eventName
* @param array $payload
* @return array
*/
protected function extractPayload($eventName, $payload)
{
if (class_exists($eventName) && isset($payload[0]) && is_object($payload[0])) {
return ExtractProperties::from($payload[0]);
}
return collect($payload)->map(function ($value) {
return is_object($value) ? [
'class' => get_class($value),
'properties' => json_decode(json_encode($value), true),
] : $value;
})->toArray();
}
/**
* Format list of event listeners.
*
* @param string $eventName
* @return array
*/
protected function formatListeners($eventName)
{
return collect(app('events')->getListeners($eventName))
->map(function ($listener) {
$listener = (new ReflectionFunction($listener))
->getStaticVariables()['listener'];
if (is_string($listener)) {
return Str::contains($listener, '@') ? $listener : $listener.'@handle';
} elseif (is_array($listener) && is_string($listener[0])) {
return $listener[0].'@'.$listener[1];
} elseif (is_array($listener) && is_object($listener[0])) {
return get_class($listener[0]).'@'.$listener[1];
} elseif (is_object($listener) && is_callable($listener) && ! $listener instanceof Closure) {
return get_class($listener).'@__invoke';
}
return $this->formatClosureListener($listener);
})->reject(function ($listener) {
return Str::contains($listener, 'Laravel\\Telescope');
})->map(function ($listener) {
if (Str::contains($listener, '@')) {
$queued = in_array(ShouldQueue::class, class_implements(Str::beforeLast($listener, '@')));
}
return [
'name' => $listener,
'queued' => $queued ?? false,
];
})->values()->toArray();
}
/**
* Determine if the event should be ignored.
*
* @param string $eventName
* @return bool
*/
protected function shouldIgnore($eventName)
{
return $this->eventIsIgnored($eventName) ||
(Telescope::$ignoreFrameworkEvents && $this->eventIsFiredByTheFramework($eventName));
}
/**
* Determine if the event was fired internally by Laravel.
*
* @param string $eventName
* @return bool
*/
protected function eventIsFiredByTheFramework($eventName)
{
return Str::is(
[
'Illuminate\*',
'Laravel\Octane\*',
'Laravel\Scout\Events\ModelsImported',
'eloquent*',
'bootstrapped*',
'bootstrapping*',
'creating*',
'composing*',
],
$eventName
);
}
/**
* Determine if the event is ignored manually.
*
* @param string $eventName
* @return bool
*/
protected function eventIsIgnored($eventName)
{
return Str::is($this->options['ignore'] ?? [], $eventName);
}
}
| true |
d27d77053b085d6d815cec38179fd62f22126877 | PHP | morrizon/ToDDDoList | /src/Context/Task/Domain/Task.php | UTF-8 | 364 | 3.0625 | 3 | [] | no_license | <?php
namespace ToDDDoList\Context\Task\Domain;
class Task
{
private $title;
private $done;
public function __construct($title, $done)
{
$this->title = $title;
$this->done = $done;
}
public function getTitle()
{
return $this->title;
}
public function done()
{
return $this->done;
}
}
| true |
b8aff5027f1cf201fa52059e3f80136bc3f0d78d | PHP | kelkel17/skilltest1 | /addstudent.php | UTF-8 | 1,949 | 2.875 | 3 | [] | no_license | <?php
require_once("dbconn.php");
$view = viewAllDepartments();
if(isset($_POST['submit'])){
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$year = $_POST['year'];
$dept = $_POST['department'];
$data = array($fname,$lname,$age,$gender,$year,$dept);
addStudent($data);
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<center>
<h1>Add Student</h1>
<br /><br /><br />
</center>
<table>
<form method="post">
<tr>
<td>
Student First Name:
<input type="text" name="fname" required>
</td>
</tr>
<tr>
<td>
Student Last Name:
<input type="text" name="lname" required>
</td>
</tr>
<tr>
<td>
Student Age:
<input type="number" name="age" required>
</td>
</tr>
<tr>
<td>
Student Gender:
<input type="radio" name="gender" value="Male" required>Male
<input type="radio" name="gender" value="Female" required>Female
</td>
</tr>
<tr>
<td>
Student Year:
<select name="year" required>
<option value="">---Year Level---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
</tr>
<tr>
<td>
Department:
<select name="department" required>
<option value="">---Select Department---</option>
<?php
if(count($view) > 0){
foreach ($view as $row) {
$id = $row['dept_id'];
$name = $row['dept_name'];
$schoolname = $row['school_name'];
//echo '<option value="'.$row['school_id'].'">'.$row['school_name'].'</option>';
?>
<option value="<?php echo $id; ?>"><?php echo $name."(".$schoolname.")"; ?></option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" class="buttons" value="Add Student">
</form>
<a href="managestudent.php"><button class="buttons">Cancel</button></a>
</td>
</tr>
</table>
</body>
</html>
| true |
f67b45991232e5f37b0d78912cd9089f874cfdf8 | PHP | lamine87/Exercices2-php-poo | /liste_produits.php | UTF-8 | 1,737 | 2.78125 | 3 | [] | no_license | <?php
require 'Product.php';
$basket = new Product('Nike');
$basket->setNom('Nike AirMax');
$basket->setPrixHT(120);
$basket->setQteStock(8);
$basket->setPhoto('nike_airmax.png');
$sweat = new Product('Adidas');
$sweat->setNom("sweat capuche");
$sweat->setQteStock(6);
$sweat->setPhoto('kangol.jpg');
$casquette = new Product("kangol");
$casquette->setNom('kangol 504');
$casquette->setPrixHT(70);
$casquette->setQteStock(0);
$casquette->setPhoto('kangol.jpg');
$produits = [$basket,$sweat,$casquette];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Marque</th>
<th>Nom</th>
<th>Prix HT</th>
<th>Prix TTC</th>
<th>Qte Stock</th>
<th>Photo</th>
</tr>
</thead>
<tbody>
<?php foreach ($produits as $p) :?>
<tr>
<td><?= $p->getMarque() ?></td>
<td><?= $p->getNom() ?></td>
<td><?= $p->getPrixHT() ?></td>
<td><?= $p->getPrixTTC() ?></td>
<td>
<?= $p->getQteStock() ?>
<?php if($p->getIsDispo()) :?>
<span style="background: green;color: #fff;padding: 3px">Dispo</span>
<?php else:?>
<span style="background: red;color: #fff;padding: 3px">Indispo</span>
<?php endif?>
</td>
<td>
<img src="img/<?=$p->getPhoto(); ?>" width="50" alt="">
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html> | true |
dc38a4d0431c3e8d0a459dfd3fdedc9085558d15 | PHP | Chivan/Dirigendo | /src/Dirigendo/FrontEndBundle/MysqlSpatial/tests/CrEOF/Tests/ORM/Functions/NumPointsTest.php | UTF-8 | 3,124 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Copyright (C) 2012 Derek J. Lambert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace CrEOF\Tests\ORM\Types;
use Doctrine\ORM\Query;
use CrEOF\PHP\Types\LineString;
use CrEOF\PHP\Types\Point;
use CrEOF\Tests\OrmTest;
use CrEOF\Tests\Fixtures\LineStringEntity;
/**
* NumPoints DQL function tests
*
* @author Derek J. Lambert <dlambert@dereklambert.com>
* @license http://dlambert.mit-license.org MIT
*/
class NumPointsTest extends OrmTest
{
public function testNumPoints()
{
$entity1 = new LineStringEntity();
$entity1->setLineString(new LineString(
array(
new Point(42.6525793, -73.7562317),
new Point(48.5793, 34.034),
new Point(-75.371, 87.90424)
))
);
$this->_em->persist($entity1);
$entity2 = new LineStringEntity();
$entity2->setLineString(new LineString(
array(
new Point(42.6525793, -73.7562317),
new Point(48.5793, 34.034),
new Point(-75.371, 87.90424),
new Point(56.74, 2.053)
))
);
$this->_em->persist($entity2);
$entity3 = new LineStringEntity();
$entity3->setLineString(new LineString(
array(
new Point(42.6525793, -73.7562317),
new Point(56.74, 2.053)
))
);
$this->_em->persist($entity3);
$this->_em->flush();
$this->_em->clear();
$query = $this->_em->createQuery('SELECT NumPoints(l.lineString) FROM CrEOF\Tests\Fixtures\LineStringEntity l');
$result = $query->getResult();
$this->assertEquals(3, $result[0][1]);
$this->assertEquals(4, $result[1][1]);
$this->assertEquals(2, $result[2][1]);
$this->_em->clear();
$query = $this->_em->createQuery('SELECT l FROM CrEOF\Tests\Fixtures\LineStringEntity l WHERE NumPoints(l.lineString) = 4');
$result = $query->getResult();
$this->assertCount(1, $result);
$this->assertEquals($entity2, $result[0]);
}
}
| true |
5c34d41d145ead8ce87ead91ecd0535eba0e4034 | PHP | GDIBass/movie-collection-app | /src/Traits/LoggerTrait.php | UTF-8 | 456 | 2.796875 | 3 | [] | no_license | <?php
/**
* @author Matt Johnson <matt@gdibass.com>
*/
namespace App\Traits;
use Psr\Log\LoggerInterface;
/**
* Trait LoggerTrait
* Adds auto-wired logging to a class
*
* @package App\Traits
*/
trait LoggerTrait
{
/**
* @var LoggerInterface
*/
protected $logger;
/**
* @param LoggerInterface $logger
*
* @required
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
} | true |
65d4f464c4d7ad30fe5189d918d14427985d15b4 | PHP | Muqeet1/PHP-Admin-Control-Panel | /admin/adduser.php | UTF-8 | 1,396 | 3.3125 | 3 | [] | no_license | <?php
/*
file: adduser.php
desc: Adds the user into database with generated password
if the username does not already exist
*/
function genRndString($length = 10, $chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
if($length > 0)
{
$len_chars = (strlen($chars) - 1);
$the_chars = $chars{rand(0, $len_chars)};
for ($i = 1; $i < $length; $i = strlen($the_chars))
{
$r = $chars{rand(0, $len_chars)};
if ($r != $the_chars{$i - 1}) $the_chars .= $r;
}
return $the_chars;
}
}
if(empty($_POST)) header('location:users.php');
else{
include('../db.php');
$username=$_POST['username'];
//check that username does not exist
$sql="select username from user where username='$username' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//username is already in use
header("location:users.php?error=true");
}else{
//username available, insert into table user
$username=mysql_real_escape_string($username);
$password=genRndString(); //generates a random string
$sql="insert into user(username,password) ";
$sql.="values('$username','$password')";
if($conn->query($sql)===TRUE){
//insert was successful!
header("location:users.php?insert=ok");
}else header("location:users.php?insert=error");
}
}
?>
| true |
7bbfcea1b2521a85fb4fb8fd65828027bff56d0a | PHP | jeevitha-gv/freshgrc | /php/common/saveChat.php | UTF-8 | 1,369 | 2.640625 | 3 | [] | no_license | <?php
require_once __DIR__.'/../common/constants.php';
require_once __DIR__.'/../common/dbOperations.php';
require_once __DIR__.'/../common/metaData.php';
class ChatManager {
public function saveChat($chatData){
$sql = 'INSERT INTO chat(sender_id, receiver_id, message, message_sent_time) VALUES (?, ?, ?, ?)';
$paramArray = array($chatData->senderId, $chatData->receiverId, $chatData->message, date("Y-m-d h:i:s"));
error_log("chat".print_r($paramArray,true));
$dbOps = new DBOperations();
return $dbOps->cudData($sql, 'iiss', $paramArray);
}
public function getAllChatHistory($chatData){
$sql = 'SELECT c.id,c.message as message, c.message_sent_time as message_sent_time,c.sender_id,c.receiver_id from chat c where (c.sender_id=? and c.receiver_id=?) or (c.sender_id=? and c.receiver_id=?)';
$paramArray = array($chatData->senderId,$chatData->receiverId,$chatData->receiverId,$chatData->senderId);
error_log("inside save Chat".print_r($paramArray,true));
$dbOps = new DBOperations();
return $dbOps->fetchData($sql, 'iiii', $paramArray);
}
public function getAllUsersForChat(){
$sql = 'SELECT last_name,id FROM user';
$dbOps = new DBOperations();
return $dbOps->fetchData($sql);
}
}
| true |
446f54600aef1dc41a932f3aa3cda0ad7e5af88d | PHP | redtagmobile/teste | /SDI - POO - PDO/source/Controllers/ControllerPdf.php | UTF-8 | 9,610 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Source\Controllers;
use Source\Database\Connect;
class ControllerPdf
{
public function read($id_destino_fk, $dia_passeio, $id_veiculo)
{
$dia_passeio = $dia_passeio;
$sql = "SELECT
DISTINCT(familia.codigo_familia) as codigoDasFamilia,
familia.id_destino_fk,
destinos.nome_destino
FROM familia
INNER JOIN destinos ON destinos.id_destino = familia.id_destino_fk
WHERE familia.id_destino_fk = ?
AND familia.viagem_finalizada = 'NAO'
AND familia.dia_viagem = ?
AND familia.id_veiculo_fk = ?
";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_destino_fk);
$stmt->bindValue(2, $dia_passeio);
$stmt->bindValue(3, $id_veiculo);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public function membrosFamilia($id_destino_fk, $codigo_familia)
{
// $sql = "SELECT * FROM `familia` WHERE familia.viagem_finalizada = 'NAO' AND
// familia.id_destino_fk = ? AND familia.codigo_familia = ? ORDER BY familia.email DESC";
$sql = "SELECT
familia.nome,
familia.rg,
familia.email,
familia.telefone1,
familia.telefone2,
familia.valor_na_epoca,
familia.valor_de_venda,
familia.id_vendedor_fk,
categoria.nome_categoria as categoriaPassagem,
login.nome as vendedor,
ponto_encontro.id_destino_fk,
ponto_de_encontro.descricao,
ponto_de_encontro.horario
FROM familia
INNER JOIN login ON login.id_login = familia.id_vendedor_fk
INNER JOIN passagem ON passagem.id_passagem = familia.id_passagem_fk
INNER JOIN categoria ON categoria.id_categoria = passagem.id_categoria_fk
INNER JOIN ponto_encontro ON ponto_encontro.codigo_familia = familia.codigo_familia
INNER JOIN ponto_de_encontro ON ponto_de_encontro.id_ponto_encontro = ponto_encontro.id_ponto_de_encontro_fk
WHERE familia.viagem_finalizada = 'NAO' AND
familia.id_destino_fk = ? AND familia.codigo_familia = ? ORDER BY familia.email DESC";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_destino_fk);
$stmt->bindValue(2, $codigo_familia);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public function categoria($id_destino_fk, $codigo_familia)
{
$sql2 = "SELECT
categoria.nome_categoria as nomecategoria,
COUNT(categoria.nome_categoria) as quantidade
FROM familia
INNER JOIN passagem ON passagem.id_passagem = familia.id_passagem_fk
INNER JOIN categoria ON categoria.id_categoria = passagem.id_categoria_fk
WHERE familia.id_destino_fk = ?
AND familia.codigo_familia = ?
GROUP BY categoria.id_categoria";
$stmt2 = Connect::getInstance()->prepare($sql2);
$stmt2->bindValue(1, $id_destino_fk);
$stmt2->bindValue(2, $codigo_familia);
$stmt2->execute();
if ($stmt2->rowCount() > 0) {
$resultado = $stmt2->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public static function getValoresFinaisPdf($id_destino_fk, $codigo_familia)
{
$sql = "SELECT
COUNT(familia.codigo_familia)as NumeroCodigos,
SUM(familia.valor_de_venda)+hotel_familia.valor as valorTotalFamilia,
SUM(familia.valor_na_epoca) as valorPassagens,
familia.codigo_familia,
familia.valor_de_venda,
familia.id_vendedor_fk,
login.nome as vendedor,
hotel_familia.valor,
hotel.nome_hotel,
vaucher.entrada,
vaucher.forma_de_pagamento,
ponto_encontro.id_destino_fk,
ponto_de_encontro.descricao,
ponto_de_encontro.horario
FROM familia
INNER JOIN hotel_familia ON hotel_familia.codigo_familia = familia.codigo_familia
INNER JOIN hotel ON hotel.id_hotel = hotel_familia.id_hotel_fk
INNER JOIN vaucher ON vaucher.codigo_familia = familia.codigo_familia
INNER JOIN login ON login.id_login = familia.id_vendedor_fk
INNER JOIN ponto_encontro ON ponto_encontro.codigo_familia = familia.codigo_familia
INNER JOIN ponto_de_encontro ON ponto_de_encontro.id_ponto_encontro = ponto_encontro.id_ponto_de_encontro_fk
WHERE familia.viagem_finalizada = 'NAO' AND familia.id_destino_fk = ? AND familia.codigo_familia = ?
GROUP BY familia.codigo_familia";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_destino_fk);
$stmt->bindValue(2, $codigo_familia);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public function pdfPontoEncontro($id_destino_fk, $data_passeio, $fk_login_loja)
{
$data_passeio = $data_passeio;
// $sql = "SELECT * FROM `ponto_encontro`
// INNER JOIN familia ON familia.codigo_familia = ponto_encontro.codigo_familia
// WHERE familia.id_destino_fk = ?
// AND familia.dia_viagem = ?
// AND familia.fk_login_familia_loja = ?
// GROUP BY ponto_encontro.endereco";
$sql = "SELECT * FROM ponto_encontro
INNER JOIN familia ON familia.codigo_familia = ponto_encontro.codigo_familia
INNER JOIN ponto_de_encontro ON ponto_de_encontro.id_ponto_encontro = ponto_encontro.id_ponto_de_encontro_fk
WHERE familia.id_destino_fk = ?
AND familia.dia_viagem = ?
AND familia.fk_login_familia_loja = ?
GROUP BY familia.codigo_familia";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_destino_fk);
$stmt->bindValue(2, $data_passeio);
$stmt->bindValue(3, $fk_login_loja);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public function infos($id_destino_fk, $data_passeio, $fk_login_loja, $id_veiculo_fk)
{
$data_passeio = $data_passeio;
// $sql = "SELECT COUNT(categoria.nome_categoria) as CandA FROM familia
// INNER JOIN passagem ON passagem.id_passagem = familia.id_passagem_fk
// INNER JOIN categoria ON categoria.id_categoria = passagem.id_categoria_fk
// WHERE familia.id_destino_fk = ? AND familia.dia_viagem = ? AND familia.fk_login_familia_loja = ?
// GROUP BY categoria.nome_categoria";
$sql = "SELECT
categoria.nome_categoria as nomecategoria,
COUNT(categoria.nome_categoria) as quantidade
FROM familia
INNER JOIN passagem ON passagem.id_passagem = familia.id_passagem_fk
INNER JOIN categoria ON categoria.id_categoria = passagem.id_categoria_fk
WHERE familia.id_destino_fk = ?
AND familia.dia_viagem = ?
AND familia.fk_login_familia_loja = ?
AND familia.id_veiculo_fk = ?
GROUP BY categoria.id_categoria
";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_destino_fk);
$stmt->bindValue(2, $data_passeio);
$stmt->bindValue(3, $fk_login_loja);
$stmt->bindValue(4, $id_veiculo_fk);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public function valoresCabecalho($destino, $id_veiculo, $dia_viagem, $categoria, $id_loja)
{
$dia_viagem = $dia_viagem;
$sql = "SELECT * FROM passeio
WHERE passeio.id_destino_fk = ?
AND passeio.id_veiculo_fk = ?
AND passeio.dia_viagem = ?
AND passeio.categoria = ?
AND passeio.fk_login_passeio_loja = ?";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $destino);
$stmt->bindValue(2, $id_veiculo);
$stmt->bindValue(3, $dia_viagem);
$stmt->bindValue(4, $categoria);
$stmt->bindValue(5, $id_loja);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
public static function placaVeiculo($id_veiculo){
$sql = "SELECT * FROM veiculo WHERE veiculo.id_veiculo = ?";
$stmt = Connect::getInstance()->prepare($sql);
$stmt->bindValue(1, $id_veiculo);
$stmt->execute();
if ($stmt->rowCount() > 0) {
$resultado = $stmt->fetchAll(\PDO::FETCH_ASSOC);
return $resultado;
} else {
return ["<h1>Foi não</h1>"];
}
}
}
| true |
d75f1c0ddc9a63624ac2e816120ae764c57318f8 | PHP | harukarist/thanks | /cardList_sent.php | UTF-8 | 6,285 | 2.59375 | 3 | [] | no_license | <?php
//共通ファイル読込み・デバッグスタート
require('function.php');
debugLogStart();
//ログイン認証
require('auth.php');
//-------------------------------------------------
// 画面処理
//-------------------------------------------------
// 一覧画面表示用データ取得
//-------------------------------------------------
// GETパラメータを取得
//----------------------------------
debug('GETパラメータ:' . print_r($_GET, true));
// カレントページのGETパラメータを取得(pagination()で付与)
$currentPageNum = (!empty($_GET['p'])) ? (int) $_GET['p'] : 1; //デフォルトは1ページ目
// GETパラメータを取得
$is_asc = (!empty($_GET['asc'])) ? $_GET['asc'] : '';
$is_fav = (!empty($_GET['fav'])) ? $_GET['fav'] : '';
$category = 'SENT';
// GETパラメータに不正な値が入っている場合はトップページへ
// int型にキャストしてからis_intで整数型かどうかをチェック
if (!is_int((int) $currentPageNum)) {
error_log('エラー発生:指定ページに不正な値が入りました');
header("Location:index.php");
exit();
}
// 1ページあたりの表示件数を指定
$listSpan = 12;
// スキップする件数を算出
$currentMinNum = (($currentPageNum - 1) * $listSpan);
// DBからメッセージデータを取得
$dbMessages = getMessageList($_SESSION['user_id'], $listSpan, $currentMinNum, $category, $is_asc, $is_fav);
// debug('現在のページ:'.$currentPageNum);
debug('$dbMessages:' . print_r($dbMessages, true));
debug(basename($_SERVER['PHP_SELF']) . '画面表示処理終了 --------------');
?>
<?php
$siteTitle = 'カード一覧';
require('head.php');
?>
<body>
<!-- ヘッダー -->
<?php
require('header.php');
?>
<main id="main" class="l-main--one-column">
<h1 class="c-title__top"><i class="fas fa-inbox"></i>カード一覧</h1>
<section class="p-card-list__menu">
<ul class="p-card-list__menu-list">
<li class="p-card-list__menu-item"><a href="cardList.php"><i class="fas fa-envelope-open-text"></i>届いたカード</a></li>
<li class="p-card-list__menu-item active"><a href="cardList_sent.php"><i class="fas fa-envelope"></i>贈ったカード</a></li>
<li class="p-card-list__menu-item"><a href="cardList_all.php"><i class="fas fa-share-alt-square"></i>みんなのカード</a></li>
</ul>
</section>
<section class="p-card-list__contents">
<h2 class="c-title__sub"><i class="fas fa-envelope"></i>あなたが贈ったカード</h2>
<div class="c-sort-menu">
<?php if (!$is_asc) { ?>
<a href="cardList_sent.php<?php echo (!empty(appendGetParam())) ? appendGetParam() . '&asc=1' : '?asc=1'; ?>"><i class="fas fa-sort-numeric-down c-sort-menu__icon"></i>日付の古い順に並べ替え</a>
<?php } else { ?>
<a href="cardList_sent.php<?php echo (!empty(appendGetParam())) ? appendGetParam(array('asc')) : '?asc=0'; ?>"><i class="fas fa-sort-numeric-down-alt c-sort-menu__icon"></i>日付の新しい順に並べ替え</a>
<?php } ?>
</div>
<div class="c-sort-menu">
<?php if (!$is_fav) { ?>
<a href="cardList_sent.php<?php echo (!empty(appendGetParam())) ? appendGetParam() . '&fav=1' : '?fav=1'; ?>"><i class="fab fa-gratipay c-sort-menu__icon"></i>お気に入りカードのみ表示</a>
<?php } else { ?>
<a href="cardList_sent.php<?php echo (!empty(appendGetParam())) ? appendGetParam(array('fav')) : '?fav=0'; ?>"><i class="fas fa-inbox c-sort-menu__icon"></i>すべてのカードを表示</a>
<?php } ?>
</div>
<div class="p-card-panel">
<?php
if (!empty($dbMessages)) foreach ($dbMessages['data'] as $key => $val) :
?>
<div class="p-card-panel__card-item">
<!-- カード詳細画面へのリンク -->
<a href="cardDetail.php<?php echo (!empty(appendGetParam())) ? appendGetParam() . '&m_id=' . $val['id'] : '?m_id=' . $val['id']; ?>" class="p-card-panel__card-link">
<!-- カード画像 -->
<img src="<?php echo (sanitize($val['card_id']) === '0') ? sanitize($val['pic']) : sanitize($val['card_pic']); ?>" alt="<?php echo sanitize($val['username']) . 'さんへのカード'; ?>" class="p-card-panel__card-img">
<!-- メッセージ -->
<p class="p-card-panel__card-message"><?php echo sanitize($val['msg'], true); ?></p>
</a>
<div class="p-card-panel__card-info">
<p class="p-card-panel__name">
<?php if ($val['to_user_deleted'] === '0') : ?>
<a href="profile.php?u_id=<?php echo sanitize($val['to_user']); ?>">
<?php echo sanitize($val['username']); ?></a>
<?php else : ?>
<?php echo sanitize($val['username']); ?>
<?php endif; ?>
<span class="u-font-size--s">さんへ</span>
<p class="p-card-panel__date"><?php echo date('Y-m-d H:i', strtotime(sanitize($val['created_at']))); ?></p>
<i class="fab fa-gratipay p-card-panel__icon c-icon c-icon-fav js-click-fav <?php if (isFavorite($_SESSION['user_id'], $val['id'])) echo 'active'; ?>" aria-hidden="true" data-messageid="<?php echo sanitize($val['id']); ?>"></i>
<a href="cardCreate.php?m_id=<?php echo sanitize($val['id']); ?>"><i class="fas fa-edit p-card-panel__icon c-icon c-icon-reply"></i></a>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="c-search-result">
<?php if ($dbMessages['total'] !== 0) { ?>
<?php echo (!empty($dbMessages['data'])) ? $currentMinNum + 1 : '0'; ?> - <?php echo (!empty($dbMessages['data'])) ? $currentMinNum + count($dbMessages['data']) : '0'; ?>枚目を表示(<?php echo sanitize($dbMessages['total']); ?>枚中)
<?php } else {
echo 'カードがまだありません';
} ?>
</div>
<!-- ページネーション -->
<?php
pagination($currentPageNum, (int) $dbMessages['total_page']);
?>
</section>
</main>
<!-- フッター -->
<?php
require('footer.php');
?>
| true |
752d640d0f754897510b7839ef0107dd52f324fe | PHP | oligus/schema | /src/Serializers/TypeSerializers/ObjectSerializer.php | UTF-8 | 2,198 | 2.9375 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types=1);
namespace GQLSchema\Serializers\TypeSerializers;
use GQLSchema\Field;
use GQLSchema\Serializers\Serializer;
use GQLSchema\Types\ObjectType;
use GQLSchema\Types\InterfaceType;
use GQLSchema\Exceptions\SchemaException;
use GQLSchema\Serializers\FieldSerializer;
use GQLSchema\Collections\InterfaceCollection;
use Exception;
use GQLSchema\Types\Type;
/**
* Class ObjectSerializer
* @package GQLSchema\Serializers\TypeSerializers
*/
class ObjectSerializer implements Serializer
{
/**
* @throws SchemaException
* @throws Exception
*/
public function serialize(Type $type): string
{
if (!$type instanceof ObjectType) {
throw new SchemaException('Type must be of type ObjectType');
}
$string = '';
if (!empty($type->getDescription())) {
$string .= '"""' . "\n";
$string .= $type->getDescription() . "\n";
$string .= '"""' . "\n";
}
$string .= $type->getType();
$string .= ' ' . $type->getName();
/** @var InterfaceCollection $interfaces */
$interfaces = $type->getInterfaces();
if ($interfaces instanceof InterfaceCollection && !$interfaces->isEmpty()) {
$string .= ' implements ';
/**
* @var int $index
* @var InterfaceType $interface
*/
foreach ($type->getInterfaces()->getCollection() as $index => $interface) {
$string .= $interface->getName();
if ((int) $index + 2 <= $type->getInterfaces()->getCollection()->count()) {
$string .= ', ';
}
}
}
$string .= " {\n";
if ($type->getFields()->isEmpty()) {
throw new SchemaException('An object type must define one or more fields.');
}
/** @var Field $field */
foreach ($type->getFields()->getIterator() as $field) {
$string .= ' ';
$string .= str_replace("\n", "\n ", (new FieldSerializer())->serialize($field));
$string .= "\n";
}
$string .= "}\n\n";
return $string;
}
}
| true |
8c87ee4f0fc4c7e666da756224095604f36ec0c5 | PHP | adamworks/laravel-movies | /app/Foundation/Validation/Form.php | UTF-8 | 2,373 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Foundation\Validation;
use Illuminate\Support\Facades\Validator;
use App\Foundation\Exceptions\NoValidationRulesFoundException;
class Form
{
protected $data;
protected $validationRules;
protected $validationMarkdowns;
protected $validationMessages = [];
protected $validator;
protected $valid = null;
public function __construct($data = null, $validationMarkdowns = [])
{
if (is_null($data)) {
$this->data = [];
} else {
$this->data = $data;
}
$this->validationMarkdowns = $validationMarkdowns;
}
public function getData()
{
return $this->data;
}
public function get($key, $default = null)
{
if (array_key_exists($key, $this->data)) {
return $this->data[$key];
}
return $default;
}
public function isValid()
{
if (!is_null($this->valid)) {
return $this->valid;
}
$this->beforeValidation();
if ( ! isset($this->validationRules)) {
throw new NoValidationRulesFoundException('no validation rules found in class ' . get_called_class());
}
$this->validator = Validator::make($this->getData(), $this->getPreparedRules(), $this->getPreparedMessages());
$valid = $this->validator->passes();
$this->valid = $valid;
return $valid;
}
public function validate()
{
if (!$this->isValid()) {
throw new FormValidationException($this->getErrors());
}
}
public function getValidData()
{
$this->validate();
return $this->getData();
}
public function getErrors()
{
return $this->validator->errors();
}
protected function getPreparedRules()
{
if (empty($this->validationMarkdowns)) {
return $this->validationRules;
}
$rules = $this->validationRules;
$markdowns = $this->validationMarkdowns;
foreach ($rules as &$rule) {
foreach ($markdowns as $key => $val) {
$rule = str_replace('{'.$key.'}', $val, $rule);
}
}
return $rules;
}
protected function getPreparedMessages()
{
return $this->validationMessages;
}
protected function beforeValidation() {}
} | true |
29ec1d15a60634b57c0d71413cba5655156e7566 | PHP | wxy000/Comment2Bark | /Plugin.php | UTF-8 | 5,003 | 2.5625 | 3 | [] | no_license | <?php
/**
* 推送评论通知
*
* @package Comment2Bark
* @author wxy
* @version 1.0.3
* @link http://118.178.241.13
*/
class Comment2Bark_Plugin implements Typecho_Plugin_Interface
{
/**
* 激活插件方法,如果激活失败,直接抛出异常
*
* @access public
* @return void
* @throws Typecho_Plugin_Exception
*/
public static function activate()
{
Typecho_Plugin::factory('Widget_Feedback')->comment = array('Comment2Bark_Plugin', 'sc_send');
Typecho_Plugin::factory('Widget_Feedback')->trackback = array('Comment2Bark_Plugin', 'sc_send');
Typecho_Plugin::factory('Widget_XmlRpc')->pingback = array('Comment2Bark_Plugin', 'sc_send');
return _t('请配置此插件的ip或域名地址, 以使您的bark推送生效');
}
/**
* 禁用插件方法,如果禁用失败,直接抛出异常
*
* @static
* @access public
* @return void
* @throws Typecho_Plugin_Exception
*/
public static function deactivate(){}
/**
* 获取插件配置面板
*
* @access public
* @param Typecho_Widget_Helper_Form $form 配置面板
* @return void
*/
public static function config(Typecho_Widget_Helper_Form $form)
{
$bark = new Typecho_Widget_Helper_Form_Element_Text('bark', NULL, NULL, _t('Bark服务地址'), _t('请在此处填入bark的服务地址,例如https://api.day.app/2432432432ewqeqeqw 注意地址后面的/不需要填'));
$form->addInput($bark->addRule('required', _t('您必须填写一个正确的bark服务地址')));
$title = new Typecho_Widget_Helper_Form_Element_Text('title', NULL, '博客', _t('推送信息的标题'), _t('在此输入推送信息的标题'));
$form->addInput($title);
$groupname = new Typecho_Widget_Helper_Form_Element_Text('groupname', NULL, '博客', _t('分组名称'), _t('输入分组名称,即在app的历史消息中按分组保存信息'));
$form->addInput($groupname);
$sound = new Typecho_Widget_Helper_Form_Element_Text('sound', NULL, NULL, _t('推送铃声'), _t('具体有哪些铃声可到app中查看'));
$form->addInput($sound);
$is_archive = new Typecho_Widget_Helper_Form_Element_Radio('is_archive', ['0' => _t('否'), '1' => _t('是')], '1', _t('是否自动保存通知消息'), _t('这里的设置高于app中的设置,若选择保存,则app端会将推送消息保存'));
$form->addInput($is_archive);
$author = new Typecho_Widget_Helper_Form_Element_Text('author', NULL, NULL, _t('作者名称'), _t('评论推送排除作者,若不填则全部都会推送'));
$form->addInput($author);
}
/**
* 个人用户的配置面板
*
* @access public
* @param Typecho_Widget_Helper_Form $form
* @return void
*/
public static function personalConfig(Typecho_Widget_Helper_Form $form){}
/**
* 微信推送
*
* @access public
* @param array $comment 评论结构
* @param Typecho_Widget $post 被评论的文章
* @return void
*/
public static function sc_send($comment, $post)
{
$options = Typecho_Widget::widget('Widget_Options');
$bark = $options->plugin('Comment2Bark')->bark;
$title = $options->plugin('Comment2Bark')->title;
$groupname = $options->plugin('Comment2Bark')->groupname;
$sound = $options->plugin('Comment2Bark')->sound;
$is_archive = $options->plugin('Comment2Bark')->is_archive;
$author = $options->plugin('Comment2Bark')->author;
if($comment['author']==trim($author)){
return $comment;
}
$desp = "**".$comment['author']."** 在「".$post->title."」中说到: > ".$comment['text'];
$desp = urlencode($desp);
$desp = $desp."?url=".$post->permalink;
$url = '';
if(trim($title)!=''){
$url = $bark.'/'.$title.'/'.$desp;
}else {
$url = $bark.'/'.$desp;
}
#分组
if(trim($groupname)!=''){
$url = $url.'&group='.$groupname;
}
#铃声
if(trim($sound)!=''){
$url = $url.'&sound='.$sound;
}
#是否自动保存通知消息
$url = $url.'&isArchive='.$is_archive;
/*$postdata = http_build_query(
array(
'text' => $text,
'desp' => $desp
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://sc.ftqq.com/'.$sckey.'.send', false, $context);*/
$result = file_get_contents($url);
return $comment;
}
}
| true |
0efbeeaa5320a93681ad93159e46d0f2ccc2368d | PHP | gurov-itstep-php/teach-assistant | /sys/core/form.php | UTF-8 | 2,573 | 2.59375 | 3 | [] | no_license | <?php
namespace sys\core;
use \sys\lib\Field as Field;
class Form {
public $name;
public $className;
public $methodName;
public $actionPath;
public $enctype;
public $fields;
public function generate() {
// <form
echo('<form');
echo(' id="'.$this->name.'"');
echo(' class="'.$this->className.'"');
echo(' method="'.$this->methodName.'"');
echo(' action="'.$this->actionPath.'"');
//
if($this->enctype !== '') {
echo(' enctype="'.$this->enctype.'"');
}
//*
if ($this->name === 'regform') {
echo(' onsubmit="return false"'); //валидация для регформ
}
echo('>');
//
if(is_array($this->fields) && count($this->fields) > 0) {
foreach ($this->fields as $field) {
if ($field instanceof Field) {
echo('<div class="form-group">');
if ($field->name !== 'stand') {
echo('<label for="'.$field->name.'">');
echo(ucfirst($field->name).':');
echo('</label>');
$field->generate();
} else {
echo('<p style="text-align: center; margin: 30px 0px -10px 0px">');
echo('<input type="checkbox" id="stand" name="stand" value="yes">');
echo(' ');
echo('<label for="stand">Оставаться в системе</label>');
echo('</p>');
}
echo('<div class="error"');
echo(' id="'.$field->name.'-error">');
echo('');
echo('</div>');
echo('</div>');
}
}
}
//
echo('<div class="btn-group">');
echo('<input type="submit" id="submit" name="submit" value="Отправить" class="btn-sm btn-success my-btn" />');
echo('<input type="reset" id="reset" name="reset" value="Очистить" class="btn-sm btn-danger my-btn" />');
echo('</div>');
//
echo('</form>'); // </form>
}
public function fill() {
if(is_array($this->fields) && count($this->fields) > 0) {
foreach ($this->fields as $field) {
if(isset($_POST[$field->name])) {
$field->fieldValue = $_POST[$field->name];
}
}
}
}
} | true |
697fbd94ca9784039b5fdd4f4dcdae6f442579ed | PHP | ludovicjj/glide | /src/Helper/StringHelper.php | UTF-8 | 689 | 3.21875 | 3 | [] | no_license | <?php
namespace App\Helper;
class StringHelper
{
/**
* Replace last middle dash to dot
*
* @param string|null $subject
* @param string $needle
* @param string $replacement
* @return string|null
*/
public static function replaceLastMiddleDashToDot(
?string $subject,
string $needle = '-',
string $replacement = '.'
): ?string
{
if ($subject === null) {
return null;
}
$start = strrpos($subject, $needle);
if (!$start) {
return null;
}
$end = strlen($needle);
return substr_replace($subject, $replacement, $start, $end);
}
} | true |
252e4f61eac6e24d40422563e949d73f2be6c7ec | PHP | qi500/rapid-php | /apps/core/classier/wrapper/OrderWrapper.php | UTF-8 | 2,053 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
namespace apps\core\classier\wrapper;
use apps\core\classier\config\OrderConfig;
use apps\core\classier\model\AppOrderModel;
use apps\core\classier\wrapper\user\AddressWrapper;
class OrderWrapper extends AppOrderModel
{
/**
* 订单状态文本
* @var string|null
*/
public $status_text;
/**
* 订单支付状态文本
* @var string|null
*/
public $pay_status_text;
/**
* @var AddressWrapper|null
*/
public $factory_detail;
/**
* @var AddressWrapper|null
*/
public $warehouse_detail;
/**
* @param int|null $status
*/
public function setStatus(?int $status)
{
$this->status_text = OrderConfig::getOrderStatusText($status);
parent::setStatus($status);
}
/**
* @param int|null $pay_status
*/
public function setPayStatus(?int $pay_status)
{
$this->pay_status_text = OrderConfig::getOrderPayStatusText($pay_status);
parent::setPayStatus($pay_status);
}
/**
* @return string|null
*/
public function getStatusText(): ?string
{
return $this->status_text;
}
/**
* @return string|null
*/
public function getPayStatusText(): ?string
{
return $this->pay_status_text;
}
/**
* @param AddressWrapper|null $factory_detail
*/
public function setFactoryDetail(?AddressWrapper $factory_detail): void
{
$this->factory_detail = $factory_detail;
}
/**
* @return AddressWrapper|null
*/
public function getFactoryDetail(): ?AddressWrapper
{
return $this->factory_detail;
}
/**
* @param AddressWrapper|null $warehouse_detail
*/
public function setWarehouseDetail(?AddressWrapper $warehouse_detail): void
{
$this->warehouse_detail = $warehouse_detail;
}
/**
* @return AddressWrapper|null
*/
public function getWarehouseDetail(): ?AddressWrapper
{
return $this->warehouse_detail;
}
} | true |
5cb370cfe9fc42f5dd3462047142ddc37d94697d | PHP | Ganeshnadar/inventroy_management | /app/Http/Controllers/CategoryController.php | UTF-8 | 2,931 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Category;
use App\Repositories\CategoryRepositoryInterface;
class CategoryController extends Controller
{
/**
* @var \App\Repositories\CategoryRepository.
*
*/
private $categoryRepository;
public function __construct(CategoryRepositoryInterface $categoryRepository){
$this->categoryRepository = $categoryRepository;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = $this->categoryRepository->allCategory();
return view('categoryIndex', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('categoryCreate');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'category_name' => 'required|min:3|max:255',
'category_slug' => 'required|min:3|max:255'
]);
$this->categoryRepository->save($request->all());
return redirect('Category')->with('success', 'Data Added successfully.');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$data = $this->categoryRepository->find($id);
return view('categoryView', compact('data'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$data = $this->categoryRepository->find($id);
return view('categoryEdit', compact('data'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'category_name' => 'required',
'category_slug' => 'required'
]);
$this->categoryRepository->update($id, $request->all());
return redirect('Category')->with('success', 'Data is successfully updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$this->categoryRepository->delete($id);
return redirect('Category')->with('success', 'Data is successfully deleted');
}
}
| true |
7491c3e807586ec820d640474dfa34d379f9ed3b | PHP | netz98/n98-magerun | /src/N98/Magento/Application/Console/EventSubscriber/CheckRootUser.php | UTF-8 | 1,573 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace N98\Magento\Application\Console\EventSubscriber;
use N98\Magento\Application\Console\Event;
use N98\Magento\Application\Console\Events;
use N98\Util\OperatingSystem;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CheckRootUser implements EventSubscriberInterface
{
/**
* @var string
*/
public const WARNING_ROOT_USER = '<error>It\'s not recommended to run n98-magerun as root user</error>';
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array The event names to listen to
*
* @api
*/
public static function getSubscribedEvents()
{
return [Events::RUN_BEFORE => 'checkRunningAsRootUser'];
}
/**
* Display a warning if a running n98-magerun as root user
*
* @param Event $event
* @return void
*/
public function checkRunningAsRootUser(Event $event)
{
if ($this->_isSkipRootCheck($event->getInput())) {
return;
}
$config = $event->getApplication()->getConfig();
if (!$config['application']['check-root-user']) {
return;
}
if (OperatingSystem::isRoot()) {
$output = $event->getOutput();
$output->writeln(['', self::WARNING_ROOT_USER, '']);
}
}
/**
* @return bool
*/
protected function _isSkipRootCheck(InputInterface $input)
{
return $input->hasParameterOption('--skip-root-check');
}
}
| true |
3affb9046b7456865a408612f8c2a4fe5cc3d1b9 | PHP | MartDevelopers-Inc/Order_Processing_MIS | /vendor/ruflin/elastica/src/Connection/Strategy/Simple.php | UTF-8 | 779 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This is the default license template.
*
* File: Simple.php
* Author: root
* Copyright (c) 2021 root
*
* To edit this license information: Press Ctrl+Shift+P and press 'Create new License Template...'.
*/
namespace Elastica\Connection\Strategy;
use Elastica\Connection;
use Elastica\Exception\ClientException;
/**
* Description of SimpleStrategy.
*
* @author chabior
*/
class Simple implements StrategyInterface
{
/**
* {@inheritdoc}
*/
public function getConnection(array $connections): Connection
{
foreach ($connections as $connection) {
if ($connection->isEnabled()) {
return $connection;
}
}
throw new ClientException('No enabled connection');
}
}
| true |
87c22823c369022211bdc2a0872aeeedf0912c44 | PHP | MirosTruckstop/mt_server_api | /src/api/admin/NewsGeneration.php | UTF-8 | 3,129 | 2.859375 | 3 | [] | no_license | <?php
/**
* Automatically generate news entries based on new photo uploads (and newly
* create galleries).
*
* @package api
* @subpackage admin
*/
class MT_Admin_NewsGeneration extends MT_Admin_Common {
/**
* Timestamp of the last news
*
* @var integer
*/
private $timestampLatestNews;
/**
*
* @return int HTTP status code
*/
public function action() {
$this->timestampLatestNews = parent::getAggregate('news', 'MAX', 'date');
$timestampLatestPhoto = parent::getAggregate('photo', 'MAX', 'date');
if ($this->timestampLatestNews < $timestampLatestPhoto) {
return parent::getList($this->getGeneratedNews());
} else {
return parent::getList(array());
}
}
/**
*
* @return array
*/
private function getGeneratedNews() {
$query = ORM::for_table('wp_mt_photo')
->select_many(array(
'galleryName' => 'wp_mt_gallery.name',
'categoryName' => 'wp_mt_category.name',
'subcategoryName' => 'wp_mt_subcategory.name'
))
->select_expr('COUNT(wp_mt_gallery.id)', 'numPhotos')
->inner_join('wp_mt_gallery', 'wp_mt_gallery.id = wp_mt_photo.gallery')
->inner_join('wp_mt_category', 'wp_mt_category.id = wp_mt_gallery.category')
->left_outer_join('wp_mt_subcategory', 'wp_mt_subcategory.id = wp_mt_gallery.subcategory')
->where_equal('wp_mt_photo.show', 1)
->where_gte('wp_mt_photo.date', $this->timestampLatestNews)
->group_by(array('wp_mt_category.name', 'wp_mt_subcategory.name', 'wp_mt_gallery.name'))
->order_by_desc('numPhotos');
$news = array();
foreach ($query->find_many() as $item) {
array_push($news, array(
'title' => self::generateTitle($item->categoryName, $item->subcategoryName, $item->galleryName, $item->date, $item->numPhotos),
'text' => self::generateText($item->numPhotos),
'gallery' => $item->id
));
}
return $news;
}
/**
* Generates the title of the news entry.
*
* @param string $catgegoryName Name of the category
* @param string|null $subcategoryName Name of the subcategory
* @param string $galleryName Name of the gallery
* @param int $galleryDate Date of the gallery as timestamp
* @param int $numPhotos Number of added photos
* @return string Title of the news
*/
private function generateTitle($catgegoryName, $subcategoryName = NULL, $galleryName, $galleryDate, $numPhotos) {
$title = $catgegoryName;
if( !empty($subcategoryName) ) {
$title .= ' > ' . $subcategoryName;
}
$title .= ': ';
// New gallery
if($galleryDate >= $this->timestampLatestNews) {
$title .= "Neue Galerie '" . $galleryName . "'";
}
// New photos only
else {
if($numPhotos != 1) {
$title .= 'Neue Bilder';
} else {
$title .= 'Neues Bild';
}
$title .= " in der Galerie '" . $galleryName . "'";
}
return $title;
}
/**
* Generates the text of the news entry.
*
* @param int $numPhotos Number of photos added
* @return string Text of the news
*/
private function generateText($numPhotos) {
$text = $numPhotos . ' ';
if($numPhotos > 1) {
$text .= 'neue Bilder';
} else {
$text .= 'neues Bild';
}
return $text;
}
}
| true |
4eb1462d0169c87033c6d7207dd4b47101e1aa25 | PHP | jmvedrine/moodle-qformat_imsqti21 | /moodle/serializer/calculated_formula_serializer.class.php | UTF-8 | 11,194 | 2.9375 | 3 | [] | no_license | <?php
/**
* Translate Moodle calculated formulas to QTI formulas.
*
* Tokens regex
*
* id = [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
* number = [0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?
* varref = \{[a-zA-Z_][a-zA-Z0-9_]*\}
*
* Grammar
*
* expression = ["+"|"-"] term {("+"|"-") term} .
* term = factor {("*"|"/") factor} .
* factor = varref | number | call | "(" expression ")".
* call = id "(" expression ")" | id "(" expression "," expression ")"
*
*
* University of Geneva
* @author laurent.opprecht@unige.ch
*
*/
class CalculatedFormulaSerializer {
private $map = array();
private $success = true;
private $message = '';
private $current = '';
private $text = '';
/**
* @var ImsQtiWriter
*/
private $writer = null;
public function get_success(){
return $this->success;
}
public function get_message(){
return $this->message;
}
public function parse($text){
try{
$this->init($text);
$result = $this->get_expression();
return $result;
}catch(Exception $e){
$this->success = false;
//throw $e;
return '';
}
}
protected function get_map(){
if(empty($this->map)){
$result = array();
$result['abs'] = 'customOperator';
$result['acos'] = 'customOperator';
$result['acosh'] = 'customOperator';
$result['asin'] = 'customOperator';
$result['atan'] = 'customOperator';
$result['ceil'] = 'ceiling';
$result['cos'] = 'customOperator';
$result['cosh'] = 'customOperator';
$result['deg2rad'] = 'customOperator';
$result['exp'] = 'exp';
$result['expm1'] = 'customOperator';
$result['floor'] = 'truncate';
$result['log'] = 'customOperator';
$result['log10'] = 'customOperator';
$result['log1p'] = 'customOperator';
$result['rad2deg'] = 'customOperator';
$result['round'] = 'round';
$result['sin'] = 'customOperator';
$result['sinh'] = 'customOperator';
$result['sqrt'] = 'customOperator';
$result['tan'] = 'customOperator';
$result['tanh'] = 'customOperator';
$result['atan2'] = 'customOperator';
$result['pow'] = 'power';
$result['pi'] = 3.1415927;
$result['e'] = 2.7182818;
$this->map = $result;
}
return $this->map;
}
protected function translate($key){
$map = $this->get_map();
return isset($map[$key]) ? $map[$key] : 'customOperator';
}
//GRAMMAR SPECIFIC
protected function expression(ImsQtiWriter $writer){
$base_writer = $writer;
$term_writer = new ImsQtiWriter();
$term_writer = $this->current == '-' ? $term_writer->add_minus() : $term_writer;
if($this->current == '-' || $this->current == '+'){
$this->move_next();
}
$noop = true;
$left = $this->get_term($term_writer);
while($this->current == '+' || $this->current == '-'){
if($noop){
$writer = $writer->add_sum();
$noop = false;
}
$writer->add_flow($left);
//$writer = $this->current == '-' ? $writer->add_subtract() : $writer->add_sum();
if($this->current == '-'){
$this->move_next();
$term_writer = new ImsQtiWriter();
$term_writer = $term_writer->add_minus();
$left = $this->get_term($term_writer);
}else{
$this->move_next();
$left = $this->get_term();
}
}
$writer->add_flow($left);
//debug($base_writer->get_doc());
return true;
}
protected function term(ImsQtiWriter $writer){
$left = $this->get_factor();
$noop = true;
while($this->current == '/' || $this->current == '*'){
if($noop){
$writer = $writer->add_product();
$noop = false;
}
$writer->add_flow($left);
if($this->current == '/'){
$this->move_next();
$term_writer = new ImsQtiWriter();
$term_writer = $term_writer->add_inverse();
$left = $this->get_factor($term_writer);
}else{
$this->move_next();
$left = $this->get_factor();
}
}
$writer->add_flow($left);
return true;
}
protected function factor(ImsQtiWriter $writer){
if($this->number($writer)){
return true;
}else if($this->varref($writer)){
return true;
}else if($this->call($writer)){
return true;
}else if($this->current == '('){
$this->expect('(');
$this->expression($writer);
$this->expect(')');
return true;
}else{
$this->error();
}
}
protected function call(ImsQtiWriter $writer){
if($this->is_id()){
$name = $this->translate($this->current);
if(empty($name)){
return $this->error();
}else if($name == 'customOperator'){
$writer = $writer->add_customOperator($this->current);
}else if(is_numeric($name)){
$writer = $writer->add_baseValue(ImsQtiWriter::BASETYPE_FLOAT, $name);
}
else{
$f = 'add_' . $name;
$writer = $writer->$f();
}
$this->move_next();
$this->expect('(');
if($this->current != ')'){
$first = $this->expression($writer);
}
while($this->current == ','){
$this->move_next();
$second = $this->expression($writer);
}
$this->expect(')');
return true;
}else{
return false;
}
}
protected function number(ImsQtiWriter $writer){
if($this->is_number()){
$value = $this->current;
$base_type = ((int)$value) == $value ? ImsQtiWriter::BASETYPE_INTEGER : ImsQtiWriter::BASETYPE_FLOAT;
$writer->add_baseValue($base_type, $value);
$this->move_next();
return true;
}else{
return false;
}
}
protected function varref(ImsQtiWriter $writer){
if($this->is_varref()){
$writer->add_variable(trim($this->current, '{}'));
$this->move_next();
return true;
}else{
return false;
}
}
// PARSER CORE
protected function init($text){
$this->writer = new ImsQtiWriter();
$this->success = true;
$this->message = '';
$this->text = $this->cleanup($text);
$this->move_next();
}
protected function cleanup($text){
return preg_replace('#\s+#', '', $text);
}
protected function error($token=null){
$token = empty($token) ? $this->current : $token;
$this->success = false;
$this->message = 'Unexpected token: ' . $token;
throw new Exception($this->message);
return false;
}
protected function accept($token){
if($this->current == $token){
$this->move_next();
return true;
}else{
return false;
}
}
protected function expect($token){
if($this->accept($token)){
return true;
}else{
$this->error($token);
return false;
}
}
protected function move_next(){
$token = $this->get_token();
if(empty($token)){
return false;
}else{
$this->current = $token;
$this->text = substr($this->text, strlen($token), strlen($this->text)-strlen($token));
return true;
}
}
//LEXER
protected function get_token(){
if($result = $this->get_number()){
return $result;
}else if($result = $this->get_id()){
return $result;
}else if($result = $this->get_special()){
return $result;
}else if($result = $this->get_varref()){
return $result;
}else{
return '';
}
}
protected function is_number(){
if(empty($this->current)){
return false;
}
$left = substr($this->current, 0, 1);
return is_number($left);
}
protected function is_varref(){
if(empty($this->current)){
return false;
}
$left = substr($this->current, 0, 1);
return $left =='{';
}
protected function is_id(){
if(empty($this->current)){
return false;
}
$left = substr($this->current, 0, 1);
$left = strtolower($left);
return strpos('abcdefghijklmnopqrstuvwxyz_', $left) !== false;
}
protected function is_special(){
if(empty($this->current)){
return false;
}
$left = substr($this->current, 0, 1);
return strpos('+-*/%)(,', strtolower($left)) !== false;
}
protected function get_special(){
$left = substr($this->text, 0, 1);
switch($left){
case '+':
case '-':
case '/':
case '*':
case '%':
case '(':
case ')':
//case '<':
//case '>':
case ',':
return $left;
default:
return '';
}
}
protected function get_number(){
$pattern = "/^[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/";
$matches = array();
if(preg_match($pattern, $this->text, $matches)){
return $matches[0];
}else{
return '';
}
}
protected function get_id(){
$pattern = "/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/";
$matches = array();
if(preg_match($pattern, $this->text, $matches)){
return $matches[0];
}else{
return '';
}
}
protected function get_varref(){
$pattern = "/^\{[a-zA-Z_][a-zA-Z0-9_]*\}/";
$matches = array();
if(preg_match($pattern, $this->text, $matches)){
return $matches[0];
}else{
return '';
}
}
// END LEXER
public function __call($name, $arguments){
$pieces = explode('_', $name);
if(count($pieces)>1 && $pieces[0] == 'get'){
$writer = isset($arguments[0]) ? $arguments[0] : new ImsQtiWriter();
$name = str_replace($pieces[0].'_', '', $name);
$f = array($this, $name);
if(call_user_func($f, $writer)){
$result = $writer->saveXML(false);
return $result;
}else{
return false;
}
}else{
return false;
}
}
}
| true |
398ed9f1bfb2b62843200804c413af67ae1ddae9 | PHP | TummanoonW/Proto-Framework | /@proto/library/api.php | UTF-8 | 3,369 | 3.15625 | 3 | [
"MIT"
] | permissive | <?php
class API{
private $apiKey = "null";
function __construct($apiKey){
if(isset($apiKey)){
$this->apiKey = $apiKey;
}
}
//build URL with custom path and all the parameters provided
public function getURL($path, $method, $query){
return $this->getURLCustom($path) . $this->getMethodParam($method) . $this->getQueryParam($query);
}
//build URL with custom path
private function getURLCustom($path){
return App::$apiURL . $path . $this->getAPIParam();
}
private function getURLRoot(){
return App::$apiURL . $this->getAPIParam();
}
private function getQueryParam($query){
$json = json_encode($query);
return '&q=' . $json;
}
private function getMethodParam($m){
return '&m=' . $m;
}
private function getAPIParam(){
return '?apiKey=' . $this->apiKey;
}
//return data from the given URL
public function get($url){
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, false);
$output = utf8_decode(curl_exec($curlSession));
$response = json_decode($output);
curl_close($curlSession);
return $response;
}
//post data then return data from the given URL
public function post($url, $objArr){
$json = json_encode($objArr);
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $json);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, false);
$output = utf8_decode(curl_exec($curlSession));
$response = json_decode($output);
curl_close($curlSession);
return $response;
}
//custom request then return data from the given URL
public function request($url, $method, $objArr){
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
if($objArr != NULL){
$json = json_encode($objArr);
curl_setopt($curlSession, CURLOPT_POSTFIELDS, $json);
}
curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, false);
$output = utf8_decode(curl_exec($curlSession));
$response = json_decode($output);
curl_close($curlSession);
return $response;
}
} | true |
aa3d1435804be04dd358741be6d838a88c888fa8 | PHP | isabella232/gedcomx-php-sample-app | /src/examples/CurrentUserPerson.php | UTF-8 | 548 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
include '../header.php';
include '../includes/prettyprint.php';
// First we make a request to the API for the current user's person and save the response
$response = $client->familytree()->readPersonForCurrentUser();
// Check for errors
if($response->hasError()){
handleErrors($response);
}
// No errors
else {
// Then we get the person from the response
$person = $response->getPerson();
// Display the person's information
printPerson($person);
}
include '../footer.php'; | true |
46d7d7729c8ffd79fccb6e22c24e511c7c4a901d | PHP | enerl/GSB-Report | /src/GSB/Domain/VisitReport.php | UTF-8 | 1,663 | 3.046875 | 3 | [] | no_license | <?php
namespace GSB\Domain;
class VisitReport
{
/**
* Visit Report id.
*
* @var integer
*/
private $id;
/**
* practitioner id.
*
* @var integer
*/
private $practitionerId;
/**
* Visit id.
*
* @var integer
*/
private $visitorId;
/**
* Visit Report date.
*
* @var date
*/
private $date;
/**
* Visit Report assessment.
*
* @var string
*/
private $assessment;
/**
* Visit Report purpose.
*
* @var string
*/
private $purpose;
public function getId() {
return $this->id;
}
public function getPractitionerId() {
return $this->practitionerId;
}
public function getVisitorId() {
return $this->visitorId;
}
public function getDate() {
return $this->date;
}
public function getAssessment() {
return $this->assessment;
}
public function getPurpose() {
return $this->purpose;
}
public function setId($id) {
$this->id = $id;
}
public function setPractitionerId($practitionerId) {
$this->practitionerId = $practitionerId;
}
public function setVisitorId($visitorId) {
$this->visitorId = $visitorId;
}
public function setDate($date) {
$this->date = $date;
}
public function setAssessment($assessment) {
$this->assessment = $assessment;
}
public function setPurpose($purpose) {
$this->purpose = $purpose;
}
} | true |
4e2d543323e4a5ffa310a0e158418140a760ed40 | PHP | haihai317/hcc | /database/migrations/2019_03_12_075047_create_role_table.php | UTF-8 | 1,303 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRoleTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
//生成角色表
Schema::create('role', function (Blueprint $table) {
//
$table->bigIncrements('role_id');
// varchar形态,职位名称
$table->string('role_name')->comment('职位名称')->default('');
// 职位代码
$table->string('role_code')->comment('职位代码')->default('')->nullable();
// 职位状态
$table->smallInteger('role_status')->comment('职位状态,1可用2禁用')->default(1);
// 职位等级
$table->smallInteger('role_level')->comment('职位等级')->default(1)->nullable();
// 创建和修改时间
$table->timestamp('role_addtime')->default(date("Y-m-d H:i:s"));
$table->timestamp('role_updatetime')->default(date("Y-m-d H:i:s"));
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//回滚迁移
Schema::drop('role');
}
}
| true |
bd1fc2e6486ad75332f1345223c47d2f53aa2205 | PHP | epsi-rns/AlumniBook-SF | /lib/filter/doctrine/AlumniFormFilter.class.php | UTF-8 | 4,051 | 2.59375 | 3 | [
"MIT",
"CC-BY-2.5",
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | <?php
/**
* Alumni filter form.
*
* @package alumni
* @subpackage filter
* @author E.R. Nurwijayadi
* @version 1.0
*/
class AlumniFormFilter extends BaseAlumniFormFilter
{
static protected $order_by_choices = array(
null => '',
1 => 'ID',
24 => 'Name',
11 => 'Created Time',
12 => 'Updated Time',
'' => '----------',
111 => 'Community',
112 => 'Department',
113 => 'Faculty',
114 => 'Program',
115 => 'Class of (year)'
);
public function configure()
{
$this->widgetSchema->setFormFormatterName('list');
$this->disableCSRFProtection();
$this->addAllCommunityFields($this);
$this->widgetSchema['name']->setLabel('Name Like %');
$this->widgetSchema['order_by'] = new sfWidgetFormChoice(array(
'choices' => self::$order_by_choices));
$this->validatorSchema['order_by'] = new sfValidatorPass();
$this->widgetSchema['update_st'] = new sfWidgetFormDatePicker(
array('theme'=>'dashboard'));
$this->widgetSchema['update_st']->setLabel('Update (start) Range');
$this->validatorSchema['update_st'] = new sfValidatorPass();
$this->widgetSchema['update_nd'] = new sfWidgetFormDatePicker(
array('theme'=>'dashboard'));
$this->widgetSchema['update_nd']->setLabel('Update (end) Range');
$this->validatorSchema['update_nd'] = new sfValidatorPass();
$this->widgetSchema['department_id'] = new sfWidgetFormChoice(array(
'choices' => array(null => '')
));
$this->useFields(array(
'department_id', 'faculty_id', 'program_id', 'class_year',
'order_by', 'name', 'update_st', 'update_nd'
));
$query = Doctrine_Core::getTable('Alumni')
->createQuery('a')
->select('a.*, ac.*, c.community')
->leftJoin('a.ACommunities ac')
->leftJoin('ac.Community c');
$this->setQuery($query);
}
public function addOrderByColumnQuery(Doctrine_Query $query, $field, $values)
{
$order_by_choices = array(
1 => 'a.aid',
24 => 'a.name',
11 => 'a.created_at',
12 => 'a.updated_at',
111 => 'ac.community, a.name',
112 => 'ac.department_id, ac.program_id, ac.class_year, a.name',
113 => 'ac.faculty_id, ac.department_id, ac.program_id, ac.class_year, a.Name',
114 => 'ac.program_id, ac.department_id, ac.class_year, a.name',
115 => 'ac.class_year, ac.department_id, a.name' // default
);
if ( array_key_exists($values, $order_by_choices) )
$query->orderBy( $order_by_choices[$values] );
$codes = array('department' => 112, 'faculty' => 113, 'program' => 114);
$this->addSelectCommunityFields($query, $values, $codes);
}
/* This parts might needs Trait in PHP 5.4 */
public function addDepartmentIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.department_id = ?', $values); }
public function addFacultyIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.faculty_id = ?', $values); }
public function addProgramIdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('ac.program_id = ?', $values); }
public function addClassYearColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values['text']) ) $query->andWhere('ac.class_year = ?', $values['text']); }
/* Manage Data Entry Filter Fields */
public function addNameColumnQuery(Doctrine_Query $query, $field, $values)
{
if ( !empty($values['text']) )
{
$driver = Doctrine_Manager::getInstance()
->getCurrentConnection()->getDriverName();
if ($driver=='Mysql')
$query->andWhere('LOWER(a.name) LIKE ?', strtolower($values['text']));
else
$query->andWhere('a.name LIKE ?', $values['text']);
}
}
public function addUpdateStColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('a.updated_at >= ?', $values); }
public function addUpdateNdColumnQuery(Doctrine_Query $query, $field, $values)
{ if (!empty($values) ) $query->andWhere('a.updated_at <= ?', $values); }
}
| true |
db274cda82f438bb82bdf2a40f986dfe11577744 | PHP | ekadesign/applesTestTask | /database/migrations/2018_01_06_014508_add_foreign_key_to_apples.php | UTF-8 | 780 | 2.515625 | 3 | [] | no_license | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddForeignKeyToApples extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('apples', function (Blueprint $table){
$table->integer('grabbed_by')->unsigned()->nullable();
$table->foreign('grabbed_by')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('apples', function (Blueprint $table){
$table->dropForeign(['grabbed_by']);
$table->drop('grabbed_by');
});
}
}
| true |
dbfd32216f1e91ddaf09c1a6f01886ed138b9bed | PHP | BeautifulStack/php-back | /src/Crud/Transfer.php | UTF-8 | 895 | 2.65625 | 3 | [] | no_license | <?php
class Transfer extends CrudClass implements CrudInterface
{
protected $name = "transfer";
protected $key = "idTransfer";
protected $attributes = [
"idTransfer",
"amount",
"transferDate",
"idUser",
"idProject"
];
protected $foreignKey = [
"idUser" => ["user", "lastName"],
"idProject" => ["project", "name"]
];
public function create(array $args)
{
$args = $this->check_attributes_create($args, $this->attributes, $this->key);
$query = $this->conn->prepare("INSERT INTO transfer(amount, idUser, idProject) VALUES (?, ?, ?)");
$query->execute([
$args["amount"],
$args["idUser"],
$args["idProject"]
]);
$query = $this->conn->query("SELECT LAST_INSERT_ID() as id");
return $query->fetch(PDO::FETCH_ASSOC);
}
}
| true |
bf172ac4232bc59a37b422a20cd5596fa8c3f274 | PHP | C4Chip/nov18 | /getdata2.php | UTF-8 | 893 | 3.328125 | 3 | [] | no_license | <?php
$query = "SELECT * FROM product ORDER BY costperiteam";
$result = mysqli_query($connection,$query);
if (!$result) {
die("databases query failed.");
}
echo "How to order? </br>";
echo "Choice only one between description and price !<br>";
echo '<input type="radio" name="description" value="Description"> Description';
echo '<input type="radio" name="price" value="costperiteam"> Price';
echo "<br>";
echo "Choice only one between ascending and descending! <br>";
echo '<input type="radio" name="ascending" value="ASC"> Ascending';
echo '<input type="radio" name="descending" value="DESC"> Descending';
while ($row = mysqli_fetch_assoc($result)) {
echo "<br>";
echo "".$row["productid"]. " " . $row["Description"] . " " . $row["costperiteam"] . " " . $row["quantity"] . "<br>";
}
mysqli_free_result($result);
?>
| true |