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
4a1db2e55d05692b2daf37bfc46f8be19a865ce1
PHP
exts/configured
/src/ConfigStorage.php
UTF-8
677
2.84375
3
[ "MIT" ]
permissive
<?php namespace Exts\Configured; use Exts\Configured\Storage\StorageInterface; /** * Class ConfigStorage * @package Exts\Configured */ class ConfigStorage { /** * @var StorageInterface */ private $storageInterface; /** * ConfigStorage constructor. * @param StorageInterface $storageInterface */ public function __construct(StorageInterface $storageInterface) { $this->storageInterface = $storageInterface; } /** * @param string $file * @param $data * @return mixed */ public function store(string $file, $data) { return $this->storageInterface->store($file, $data); } }
true
c8fe08aa64fc1b558430e2bbd6a7a75793dfbc0b
PHP
yannyesteban/sevian2019
/BK/class/Menu.php
UTF-8
4,176
2.546875
3
[]
no_license
<?php namespace Sevian; class MenuItem extends HTML implements \JsonSerializable{ public $tagName = "li"; public $caption = false; private $_menu = false; private $_submenu = false; public $action = false; public $events = array(); public $classImage = false; public $id = false; public $index = false; public $parent = false; public $icon = false; public function jsonSerialize(){ return array_filter((array)$this, function($value){ return ($value===false)? false: true; }); } public function __construct($opt){ foreach($opt as $k => $v){ $this->$k = $v; } $this->class = "item"; $option = $this->add("a"); $option->class = "option"; $option->id = $this->id; if($this->wIcon){ $icon = $option->add("div"); $icon->class = "icon"; if($this->classImage){ $icon->class .= " ".$this->classImage; } if($this->icon){ $img = $icon->add("img"); $img->src = $this->icon; } } $caption = $option->add("span"); $caption->class = "caption"; foreach($this->events as $k => $v){ $option->{"on$k"} = $v; } if($this->action){ if(!isset($option->onclick)){ $option->onclick = $this->action; }else{ $option->onclick .= $this->action; } } $caption->innerHTML = $this->caption; } public function getMenu(){ return $this->_menu; } public function createMenu(){ $this->_menu = $this->add("ul"); $this->_menu->class = "submenu"; /* if(!this._item.query(".ind")){ this._item.create("div").addClass("ind").ds("sgMenuType", "ind"); } this._menu.addClass("submenu"); if(classMenu){ this._menu.addClass(classMenu); } */ } public function _appendChild($child){ $this->_menu->appendChild($child); } public function renderX(){ return HTML::render(); } } class Menu implements \JsonSerializable{ public $main = ""; public $id = false; public $type = "normal"; public $mode = "default"; public $caption = false; private $dinamic = true; public $value = false; public $className = false; public $items = false; public $pullX = "front"; public $pullY = "top"; public $pullDeltaX = -3; public $pullDeltaY = 5; public $wCheck = true; public $item = false; private $_item = array(); private $_menu = []; public function jsonSerialize(){ return $this; return array_filter((array)$this, function($value){ return ($value===false)? false: true; }); /* $a = (array)$this; array_walk_recursive($a, function($v,$k) use (&$a) { if($v === false) unset($a[$k]); }); return $a; */ } public function __construct($opt = array()){ foreach($opt as $k => $v){ $this->$k = $v; } } public function add($opt){ $this->_item[$opt["index"]] = $opt; //$this->items[] = $opt; } public function render(){ $main = new HTML("div"); $main->id = $this->id; if($this->dinamic){ $this->target = $main->id; $this->items = &$this->_item; return $main->render(); } $this->main = $main->id; $main->class = "sg-menu"; if($this->caption !== false){ $caption = $main->add("header"); $caption->innerHTML = $this->caption; $caption->class = "caption"; } $menu = $main->add("ul"); $menu->class = "menu"; $items = array(); foreach($this->_item as $k => $item){ $_menu = $menu; if($this->wIcon){ $item["wIcon"] = true; } if($this->wCheck){ $item["wCheck"] = true; } $items[$k] = $_item = new MenuItem($item); if($_item->parent !== false){ $parent = $items[$_item->parent]; if(!isset($this->_menu[$_item->parent])){ $parent->createMenu(); $this->_menu[$_item->parent] = true; } $_menu = $parent->getMenu(); } //hr($k); $_menu->appendChild($_item); //hr($k, "red"); } return $main->render(); } public function getScript(){ $opt = json_encode($this, JSON_PRETTY_PRINT); return "\nvar menu = new Sevian.Menu($opt);"; } } ?>
true
2ca1e45fc58e870c294f601c11ff31fbe5bddec3
PHP
TsubasaReader/TsubasaServer
/rss.php
UTF-8
740
2.921875
3
[ "Apache-2.0" ]
permissive
<?php // atom encapsulation utilities. // (c) sebastian lin, 2018 function Feed($title, $link, $body) { return '<?xml version="1.0" encoding="UTF-8" ?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>'. $title . '</title> <link href="' . $link . '" /> ' . $body . ' </feed> '; } function Entry($title, $link, $date, $description) { return '<entry> <title>' . $title . '</title> <link href="' . $link . '" /> <updated>' . $date . '</updated> <content type="html"><![CDATA[' . $description . ']]></content> </entry>'; } function ItemList($itemlist) { $result = ''; for($len = count($itemlist), $i = 0; $i < $len; $i++) { $result = $result . $itemlist[$i]; } return $result; } ?>
true
703c237454e2ba3f796426c335fa194764b6133d
PHP
sumanrajinbox/malhipur2
/mark/config.php
UTF-8
656
2.671875
3
[]
no_license
<?php // function __autoload($class_name) // { // if (file_exists('../lib/classes/' . $class_name . '.php')) { // require_once('../lib/classes/' . $class_name . '.php'); // } else { // echo ("Unable to load or File Not exist $class_name.php"); // die(); // } // } spl_autoload_register('myAutoloader'); function myAutoloader($class_name) { if (file_exists('../lib/classes/' . $class_name . '.php')) { require_once('../lib/classes/' . $class_name . '.php'); } else { echo ("Unable to load or File Not exist $class_name.php"); die(); } } date_default_timezone_set('Asia/Kolkata');
true
2d510d049df5b106b1253b7c8fd56b800e605268
PHP
ganapathyhh/serendipity
/admin/customize.php
UTF-8
4,258
2.5625
3
[]
no_license
<?php $current = "Customize"; require_once 'header.php'; ?> <div class = "cell"> <h3>Customize</h3> </div> <div class = "cell"> <div class = "grid-x grid-margin-x"> <?php $themeDir = isset($_SESSION['theme-name'])?$_SESSION['theme-name']:themeName(); if(isset($_POST['theme-select'])){ $_SESSION['theme-name'] = $_POST['theme-name']; header('location:'.$_SERVER['REQUEST_URI']); } $array = glob('../themes/*', GLOB_ONLYDIR); ?> <?php $themeDirectory = '../themes/'.$themeDir.'/'; function listFolderFiles($dir){ $allowed = array('php', 'html', 'css'); $contents = array(); foreach(scandir($dir) as $file){ if($file == '.' || $file == '..') continue; $path = $dir.DIRECTORY_SEPARATOR.$file; if(is_dir($path)){ $contents = array_merge($contents, listFolderFiles($path)); } else { if(in_array(pathinfo($file, PATHINFO_EXTENSION), $allowed)) $contents[$file] = $path; } } return $contents; } $dirFileArr = array(); $contentFiles = listFolderFiles($themeDirectory); $first_key = key($contentFiles); if(isset($_POST['update-file'])){ $fileName = ''; if(isset($_GET['file_getter'])) $fileName = $_GET['file_getter']; else{ $temp = explode('/', $contentFiles[0]); $temp = explode('\\', $temp); $fileName = $temp[count($temp) - 1]; } file_put_contents($themeDirectory.$fileName, $_POST['custom-content']); header('location: '.$_SERVER['REQUEST_URI']); } ?> <div class = "small-12 medium-10 cell small-order-2"> <form action = "" method = "post"> <textarea class = "customise-content" name = "custom-content"><?php if(isset($_GET['file_getter'])) echo file_get_contents($contentFiles[$_GET['file_getter']]); else echo file_get_contents($contentFiles[$first_key]); ?></textarea> <input type = "submit" class = "button primary" value = "Save" name = "update-file"> </form> </div> <div class = "small-12 medium-2 cell small-order-1"> <form action = "" method = "post"> <select name = "theme-name"> <?php for($i = 0; $i < count($array); $i++){ ?> <option value = "<?php echo explode('/', $array[$i])[2]; ?>" <?php if(explode('/', $array[$i])[2] == $themeDir) echo 'selected'; ?>><?php echo explode('/', $array[$i])[2]; ?></option> <?php } ?> </select> <input type = "submit" name = "theme-select" class = "button primary" value = "Select"> <h5>File to edit</h5> <?php foreach($contentFiles as $fileShow){ $counter = explode('/', $fileShow); $counter = explode('\\', $fileShow); ?> <a href = "?file_getter=<?php echo $counter[count($counter) - 1]; ?>" title = "<?php echo $counter[count($counter) - 1]; ?>" style = "font-size: 1.2em; display: block; line-height: 2em"><?php echo $counter[count($counter) - 1];?></a> <?php } ?> </form> </div> </div> </div> <?php require_once 'footer.php'; ?>
true
3faf846a5997f4dad2349f73f823efc3012be549
PHP
make-it-all/website
/app/controllers/sessions_controller.php
UTF-8
1,097
2.5625
3
[]
no_license
<?php class SessionsController extends ApplicationController { public $layout = 'form_layout'; public function new() { // $user = User::new(['name'=>'Henry Morgan', 'email'=>'henry@cd2solutions.co.uk', 'password'=>'pass123', 'is_specialist'=>true]); // $user->save(); } public function create() { var_dump($this->params); $this->email = strtolower($this->params['session']['email']); $password = strtolower($this->params['session']['password']); $user = User::find_by(['email' => $this->email]); if ($user && $user->authenticate($password)) { # Log the user in and redirect to the user's show page. $_SESSION['user_id'] = $user->id(); $this->redirect_to('/', ['success'=>"Welcome, $user->name"]); } else { $this->error = 'Invalid email/password combination'; $this->render('new'); } } public function destroy() { $_SESSION['user_id'] = null; $this->redirect_to('/'); } public function admin_login() { $id = $this->params['id'] ?? User::first()->id(); $_SESSION['user_id'] = $id; $this->redirect_to('/'); } }
true
b9749b5bbb2037be1d1f7290fdfec28c5728dc21
PHP
SlawomirOlchawa/examples
/example2/classes/Tag/Form/Hidden.php
UTF-8
350
2.734375
3
[]
no_license
<?php /** * @author Sławomir Olchawa <slawooo@gmail.com> */ /** * HTML Input hidden * * @property string $type */ class Tag_Form_Hidden extends Tag_Form_Input { /** * @param string $name * @param null|string $value */ public function __construct($name, $value=null) { parent::__construct($name, $value); $this->type = 'hidden'; } }
true
2787682598c1587c3ddb275b962406083f1b15c0
PHP
liquiddesign/eshop
/src/DB/DeliveryDiscount.php
UTF-8
1,141
2.734375
3
[]
no_license
<?php declare(strict_types=1); namespace Eshop\DB; /** * Slevova dopravu * @table */ class DeliveryDiscount extends \StORM\Entity { /** * Sleva na dopravu v měně * @column */ public ?float $discountValue; /** * Sleva na dopravu v měně s DPH * @column */ public ?float $discountValueVat; /** * Sleva na dopravu * @column */ public ?float $discountPct; /** * Od jaké ceny košíku je sleva * @column */ public float $discountPriceFrom = 0.0; /** * Od jaké váhy objednávky platí * @column */ public ?float $weightFrom; /** * Do jaké váhy objednávky platí * @column */ public ?float $weightTo; /** * Minimální objednávka * @column */ public ?float $minimalOrderPrice; /** * Maximální objednávka * @column */ public ?float $maximalOrderPrice; /** * Typ * @column{"type":"enum","length":"'or','and'"} */ public string $conditionsType; /** * Měna * @relation * @constraint */ public Currency $currency; /** * Akce * @relation * @constraint{"onUpdate":"CASCADE","onDelete":"CASCADE"} */ public Discount $discount; }
true
521cd1a345933ce72908213b210201b8b1f47c95
PHP
JaniceStefa/proyecto-seguimiento
/Codigo Fuente/modelo/m_producto.php
UTF-8
1,135
2.796875
3
[]
no_license
<?php class M_Producto{ private $db; private $productos; // Conexion con Base de Datos public function __construct(){ require_once("conectar_bd.php"); $this->db=Conectar::conexion(); $this->productos=array(); } // Agregar Nuevo Producto public function Agregar_Producto($descripcion,$imagen,$precio,$categoria){ $sql="CALL SP_A_TABLA_PRODUCTO('".$descripcion."','".$imagen ."','".$precio."','".$categoria."')"; $this->db->query($sql); } // Actualizar datos del Producto public function Cambiar_Producto($descripcion,$imagen,$precio){ $sql="CALL SP_C_TABLA_PRODUCTO('".$descripcion."','".$imagen ."','".$precio."')"; $this->db->query($sql); } // Mostrar listado de Productos public function Mostrar_Producto(){ $sql=$this->db->query("CALL SP_M_TABLA_PRODUCTO"); while($filas=$sql->fetch(PDO::FETCH_ASSOC)){ $this->productos[]=$filas; } return $this->productos; } //Eliminar Producto public function Eliminar_Producto($cod_producto){ $sql="CALL SP_E_TABLA_PRODUCTO('".$cod_producto."')"; $this->db->query($sql); } } ?>
true
946ee751b4772d1d0b231e767cce40b65c345309
PHP
shomisha/stubless
/src/ImperativeCode/ControlBlocks/IfBlock.php
UTF-8
2,477
2.65625
3
[ "MIT" ]
permissive
<?php namespace Shomisha\Stubless\ImperativeCode\ControlBlocks; use PhpParser\Node\Stmt\Else_; use PhpParser\Node\Stmt\ElseIf_; use PhpParser\Node\Stmt\If_; use Shomisha\Stubless\Abstractions\ImperativeCode; use Shomisha\Stubless\Values\AssignableValue; class IfBlock extends ImperativeCode { private const ELSEIF_KEY_CONDITION = 'condition'; private const ELSEIF_KEY_BODY = 'body'; private AssignableValue $condition; private ?ImperativeCode $body = null; private array $elseIfs = []; private ?ImperativeCode $elseBlock = null; public function __construct(AssignableValue $condition, ?ImperativeCode $body = null) { $this->condition = $condition; $this->body = $body; } public function then(?ImperativeCode $body): self { $this->body = $body; return $this; } public function elseif($condition, ?ImperativeCode $body): self { $this->elseIfs[] = [ self::ELSEIF_KEY_CONDITION => AssignableValue::normalize($condition), self::ELSEIF_KEY_BODY => $body ]; return $this; } public function else(?ImperativeCode $body): self { $this->elseBlock = $body; return $this; } public function getPrintableNodes(): array { $elseIfs = array_map(function (array $elseIfConditionAndBody) { /** @var AssignableValue $condition */ $condition = $elseIfConditionAndBody[self::ELSEIF_KEY_CONDITION]; /** @var \Shomisha\Stubless\ImperativeCode\Block|null $block */ $block = $elseIfConditionAndBody[self::ELSEIF_KEY_BODY]; return new ElseIf_( $condition->getAssignableValueExpression(), $this->normalizeNodesToExpressions($block->getPrintableNodes()) ); }, $this->elseIfs); $body = []; if ($this->body) { $body = $this->normalizeNodesToExpressions($this->body->getPrintableNodes()); } $else = null; if ($this->elseBlock) { $else = new Else_( $this->normalizeNodesToExpressions($this->elseBlock->getPrintableNodes()) ); } return [ new If_( $this->condition->getAssignableValueExpression(), [ 'stmts' => $body, 'elseifs' => $elseIfs, 'else' => $else, ] ) ]; } protected function getImportSubDelegates(): array { $allElements = [ $this->condition, $this->body, $this->elseBlock, ]; foreach ($this->elseIfs as $conditionAndBody) { $allElements[] = $conditionAndBody[self::ELSEIF_KEY_CONDITION]; $allElements[] = $conditionAndBody[self::ELSEIF_KEY_BODY]; } return $this->extractImportDelegatesFromArray($allElements); } }
true
f7776e160e27aac908952ef878c08cb8777c2493
PHP
yangruofeng/wechat
/test/class/test_owen.class.php
UTF-8
2,806
2.75
3
[]
no_license
<?php /** * Created by PhpStorm. * User: owen * Date: 2018/9/26 * Time: 下午5:20 */ class test_owenClass { // static function getCODofTeller($teller_id) // { // return userClass::getPassbookBalanceOfUser($teller_id); // } /* * 新增用户 * $p 用户数据 //新增的时候直接操作database */ static function AddUser($param) { $user_name = $param['user_name']; $password = $param['password']; $gender = $param['gender']; if (!$user_name || !$password || !$gender) { return new result(false, 'IUsername or password cannot be empty', $param); } $m_test_user = M('test_user'); $conn = ormYo::Conn(); $conn->startTransaction(); try { $row = $m_test_user->newRow(); $row->user_name = $user_name; $row->password = md5($password); $row->gender = $gender; $rt = $row->insert(); if (!$rt->STS) { $conn->rollback(); return new result(false, 'Add failed'); } $conn->submitTransaction(); return new result(true, 'Add Successful'); } catch (Exception $ex) { $conn->rollback(); return new result(false, 'Add Failed'); } } /* * 查询用户列表 model中操作database */ public function getUserList($page_num,$page_size){ //还需要优化 $page_num = $page_num ?: 1; $page_size = $page_size ?: 20; //调用model查询 $m_user = new test_owenModel(); return $m_user->getUserList($page_num,$page_size); } /* * 删除用户 */ public function deleteOneUser($uid){ $m_test_user = M('test_user'); return $m_test_user->delete($uid); } /* * 修改用户信息 */ public function editUser($p){ $uid = $p['uid']; $m_um_user = M('test_user'); $row = $m_um_user->getRow(array('uid' => $uid)); if (empty($row)) { return new result(false, 'Invalid Id!'); } $row->user_name = $p['user_name']; $row->password = md5($p['password']); $row->gender = $p['gender']; $rt = $row->update(); if ($rt->STS) { return new result(true, 'Edit success'); }else{ return new result(false, 'Edit failed'); } } /* * 获取单个用户信息 */ public function getOneUser($uid){ $m_um_user = M('test_user'); $row = $m_um_user->getRow(array('uid' => $uid)); if (empty($row)) { return new result(false, 'Invalid Id!'); }else{ return new result(true, $row); } } }
true
fbc4cc646b872566847008e670108e0e9d838cac
PHP
MarinaMeza/Prog3_2018
/Clase12/prueba/clases/mediaApi.php
UTF-8
4,255
2.875
3
[]
no_license
<?php require_once 'media.php'; require_once 'IApiUsable.php'; class mediaApi extends Media implements IApiUsable{ public function CargarUno($request, $response, $args) { $objDelaRespuesta= new stdclass(); $ArrayDeParametros = $request->getParsedBody(); //var_dump($ArrayDeParametros); $color= $ArrayDeParametros['color']; $marca= $ArrayDeParametros['marca']; $precio= $ArrayDeParametros['precio']; $talle= $ArrayDeParametros['talle']; $miMedia = new Media(); $miMedia->color = $color; $miMedia->marca = $marca; $miMedia->precio = $precio; $miMedia->talle = $talle; $archivos = $request->getUploadedFiles(); if(!file_exists('fotos')) { mkdir('fotos', 0777, true); } $destino="./fotos/"; //var_dump($archivos); //var_dump($archivos['foto']); if(isset($archivos['foto'])){ $nombreAnterior=$archivos['foto']->getClientFilename(); $extension= explode(".", $nombreAnterior); //var_dump($nombreAnterior); $extension=array_reverse($extension); $archivos['foto']->moveTo($destino.$marca.$color.".".$extension[0]); $miMedia->foto = $destino.$marca.$color.".".$extension[0]; } $miMedia->InsertarMediaParametros(); //$response->getBody()->write("se guardo el cd"); $objDelaRespuesta->respuesta = "Se guardó la media."; return $response->withJson($objDelaRespuesta, 200); } public function TraerUno($request, $response, $args) { $id=$args['id']; $laMedia=Media::TraerUnaMedia($id); if(!$laMedia) { $objDelaRespuesta= new stdclass(); $objDelaRespuesta->error="No esta la media"; $NuevaRespuesta = $response->withJson($objDelaRespuesta, 500); } else { $NuevaRespuesta = $response->withJson($laMedia, 200); } return $NuevaRespuesta; } public function TraerTodos($request, $response, $args) { $todasLasMedias=Media::TraerTodasLasMedias(); $newresponse = $response->withJson($todasLasMedias, 200); return $newresponse; } public function TraerTodosFiltrado($request, $response, $args) { $todasLasMedias=Media::TraerTodasLasMediasFiltrado(); $todasLasMediasAux = array(); foreach ($todasLasMedias as $media) { $aux = (object) array_filter((array) $media); array_push($todasLasMediasAux,$aux); } $newresponse = $response->withJson($todasLasMediasAux, 200); return $newresponse; } public function BorrarUno($request, $response, $args) { $ArrayDeParametros = $request->getParsedBody(); $id=$ArrayDeParametros['id']; $media= new Media(); $media->id=$id; $cantidadDeBorrados=$media->BorrarMedia(); $objDelaRespuesta= new stdclass(); $objDelaRespuesta->cantidad=$cantidadDeBorrados; if($cantidadDeBorrados>0) { $objDelaRespuesta->resultado="algo borro!!!"; } else { $objDelaRespuesta->resultado="no Borro nada!!!<br>".$ArrayDeParametros; } $newResponse = $response->withJson($objDelaRespuesta, 200); return $newResponse; } public function ModificarUno($request, $response, $args) { //$response->getBody()->write("<h1>Modificar uno</h1>"); $ArrayDeParametros = $request->getParsedBody(); //var_dump($ArrayDeParametros); $miMedia = new Media(); $miMedia->id=$ArrayDeParametros['id']; $miMedia->color=$ArrayDeParametros['color']; $miMedia->marca=$ArrayDeParametros['marca']; $miMedia->precio=$ArrayDeParametros['precio']; $miMedia->talle=$ArrayDeParametros['talle']; $miMedia->foto=$ArrayDeParametros['foto']; $resultado =$miMedia->ModificarMediaParametros(); $objDelaRespuesta= new stdclass(); //var_dump($resultado); $objDelaRespuesta->resultado=$resultado; $objDelaRespuesta->tarea="modificar"; return $response->withJson($objDelaRespuesta, 200); } } ?>
true
b9c9b2e8164f2805fc9d1c586110e9570aa04acf
PHP
lcyoong/booqnow
/app/Booqnow/Filters/Addonfilter.php
UTF-8
2,815
2.609375
3
[ "MIT" ]
permissive
<?php namespace Filters; use Carbon\Carbon; class AddonFilter extends QueryFilter { /** * Resource type filter * @param string $value * @return Builder */ public function resourceType($value) { if (!empty($value)) { $this->joins[] = 'joinResources'; return $this->builder->where("rs_type", '=', $value); } } public function masterType($value = 0) { $this->joins[] = 'joinResources'; $this->joins[] = 'joinResourceTypes'; return $this->builder->where("rty_master", '=', $value); } /** * Date filter * @param string $value * @return Builder */ public function onDate($value) { if (!empty($value)) { return $this->builder->where("add_date", 'like', "%$value%"); } } /** * Date filter * @param string $value * @return Builder */ public function fromDate($value) { if (!empty($value)) { return $this->builder->where("add_date", '>=', date('YmdHis', strtotime($value))); } } /** * Date filter * @param string $value * @return Builder */ public function toDate($value) { if (!empty($value)) { return $this->builder->where("add_date", '<', Carbon::parse($value)->addDays(1)); // return $this->builder->where(DB::raw('DATE_ADD(add_date, 1)'), '<', $date) } } /** * Trancking no filter * @param string $value * @return Builder */ public function tracking($value = '') { if (!empty($value)) { return $this->builder->where("add_tracking", '=', $value); } } /** * Reference no filter * @param string $value * @return Builder */ public function reference($value = '') { if (!empty($value)) { return $this->builder->where("add_reference", '=', $value); } } /** * Join resources to query * @return Builder */ public function joinResources() { $this->builder->join('resources', 'rs_id', '=', 'add_resource'); } public function joinResourceTypes() { $this->builder->join('resource_types', 'rty_id', '=', 'rs_type'); } public function ofYear($value) { if (!empty($value)) { return $this->builder->whereYear('add_date', $value); } } public function notInStatus($value = []) { if (!empty($value)) { return $this->builder->whereNotIn('add_status', $value); } } public function ofStatus($value) { if (!empty($value)) { return $this->builder->where('add_status', '=', $value); } } }
true
b39ce1cd675fd42f53a7cb003a963f58380ea6b3
PHP
xylon1/Exam
/system/app/Http/Controllers/RoadAccessController.php
UTF-8
1,289
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\RoadAccess; use Illuminate\Http\Request; class RoadAccessController extends Controller { private $roadaccess; public function __construct(RoadAccess $roadaccess) { $this->roadaccess=$roadaccess; } public function index() { $data=$this->roadaccess->all(); return view('roadaccess.index')->with(compact('data')); } public function add() { return view('roadaccess.add'); } public function save(Request $request) { $data=[ 'name'=>$request->input('name'), ]; $this->roadaccess->create($data); return redirect()->route('roadaccess'); } public function edit($id) { $data= $this->roadaccess->find($id); return view('roadaccess.update')->with(compact('data')); } public function update($id,Request$request) { $old=$this->roadaccess->find($id); $data=[ 'name'=>$request->input('name'), ]; $old->update($data); return redirect()->route('roadaccess'); } public function delete($id) { $old=$this->roadaccess->find($id); $old->delete(); return redirect()->route('roadaccess'); } }
true
a00eb0a7c181ffceb9eb2d5a4da27a1c328f2207
PHP
betitoglez/itinerary
/tests/Itinerary/ItineraryTest.php
UTF-8
3,600
2.828125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: betit * Date: 29/05/2017 * Time: 16:15 */ use Itinerary\Cards\Card; use Itinerary\Places\Cities\{ Madrid, London, Barcelona, Dubai, Rome }; use Itinerary\Places\Sites\{ GreatWall, EmpireState }; use Itinerary\Transports\{ Airplane, Bus, Car, Ship }; use PHPUnit\Framework\TestCase; class ItineraryTest extends TestCase { private $itinerary; protected function setUp() { $this->itinerary = new \Itinerary\Itinerary(); } /** * Create unsorted Cards */ protected function mockItinerary() { $this->itinerary->add( new Card( new EmpireState(), new Barcelona(), new Airplane(), 'Come back to home!' ) ); $this->itinerary->add( new Card( new Dubai(), new GreatWall(), new Airplane() ) ); $this->itinerary->add( new Card( new London(), new Rome(), new Car(), 'Rent a car in Gatwick' ) ); $this->itinerary->add( new Card( new Rome(), new Dubai(), new Ship('305'), 'Royal Cruise' ) ); $this->itinerary->add( new Card( new Madrid(), new London(), new Bus('30B'), 'November 14th, 15:30. International Bus Station' ) ); $this->itinerary->add( new Card( new GreatWall(), new EmpireState(), new Airplane() ) ); } public function testItineraryFailsWhenWrongCardAdded(): void { $this->expectException(\Exception::class); $this->itinerary->add('expect error'); } public function testItineraryFailsWhenCardsAreMissing(): void { $this->expectException(\Exception::class); $this->mockItinerary(); $this->itinerary->add( new Card( new Rome(), new London(), new Airplane() ) ); $this->itinerary->create(); } public function testItineraryIsSorted(): void { $this->mockItinerary(); /** * @var \Itinerary\Cards\Collection */ $sortedCollection = $this->itinerary->create(); $this->assertEquals('MAD',$sortedCollection->first()->getDeparture()->getId()); $this->assertEquals('BAR',$sortedCollection->last()->getArrival()->getId()); $this->assertCount(6,$sortedCollection); } public function testGenerateItineraryFromArray() : void { $itinerary = \Itinerary\Itinerary::arrayToItinerary([ [ 'from' => 'Cities\Madrid', 'to' => 'Cities\London', 'transport' => 'Airplane' ] , [ 'from' => 'Cities\London', 'to' => 'Sites\EmpireState', 'transport' => 'Bus', 'seat' => '14D', 'comment' => 'It is a really long trip...' ] ]); $this->assertInstanceOf(\Itinerary\Itinerary::class,$itinerary); } }
true
70facbd5c7adfe2fd0571a91c6fe194962739bf5
PHP
rtmatt/csvimport
/src/CSVImportDirectoryReader.php
UTF-8
732
2.78125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: mattemrick * Date: 11/27/15 * Time: 1:24 PM */ namespace RTMatt\CSVImport; use RTMatt\CSVImport\Exceptions\CSVDirectoryNotFoundExcepton; class CSVImportDirectoryReader { public static function readDirectory($directory) { if ( ! realpath($directory)) { throw new CSVDirectoryNotFoundExcepton ('Import Directory Does Not Exist at ' . $directory); } $all_files = glob($directory . '/*.php'); $matches = [ ]; foreach ($all_files as $file) { if (preg_match("/\A.*\/{1}([a-zA-Z]*Importer.php\z)/", $file, $catch)) { $matches[] = $catch[1]; } } return $matches; } }
true
4f6cbd37d9b4e71d5bc9768233d52af44d365893
PHP
Gord80/Semaine4
/VerificationConnectionBack.php
UTF-8
2,951
2.734375
3
[]
no_license
<?php try { $db = new PDO('mysql:host=localhost;charset=utf8;dbname=jarditou', 'root', ''); } catch (Exception $e) { echo 'erreur : ' . $e->getMessage() . '<br>'; echo 'N° : ' . $e->getCode(); die('fin du script'); } /* Accès à la connexion */ if (isset($_POST['signIn'])) { // Vidage sessions session_unset(); // login if (!empty($_POST['login'])) { if (preg_match($namePattern, $_POST['login'])) { $login = htmlspecialchars($_POST['login']); } else { $connexionErreur['login'] = 'Veuillez renseigner un login valide!'; } } else { $$connexionErreur['login'] = 'Veuillez renseigner votre login!'; } // mot de passe if (!empty($_POST['motdepasse'])) { if (preg_match($namePattern, $_POST['motdepasse'])) { $motdepasse = htmlspecialchars($_POST['motdepasse']); } else { $connexionErreur['motdepasse'] = 'Veuillez renseigner un mot de passe valide!'; } } else { $connexionErreur['motdepasse'] = 'Veuillez renseigner votre mot de passe!'; } // Execution Script sans erreurs if (count($connexionErreur) == 0) { $state = false; $query = 'SELECT * FROM `user`' . 'WHERE `login_user` = :login'; $result = $db->prepare($query); $result->bindValue(':login', $login, PDO::PARAM_STR); // si la requète fonctionne correctement if ($result->execute()) { $selectResult = $result->fetch(PDO::FETCH_OBJ); // si présence de l'objet if (is_object($selectResult)) { // vérification du mot de passe if (password_verify($motdepasse, $selectResult-$motdepasse_user)) { // Enregistrement utilisateur if (isset($_POST['keepLog'])) { $_SESSION['login'] = $login; $_SESSION['motdepasse'] = $motdepasse; } $state = true; } else { // message d'erreur en cas d'erreur de mot de passe $connexionErreur['motdepasse'] = 'Erreur lors de la saisie. Veuillez reessayer.'; } } else { // message d'erreur en cas d'erreur de pseudo $connexionErreur['erreur'] = 'Erreur de login. Veuillez reessayer'; } } else { // message en cas mauvaise connexion à la BDD $connexionErreur['Erreur'] = 'Impossibilité de connexion à la base de données'; } return $state; } }
true
6dd65e5a023da943d704b0cad27d6e55bf2515b1
PHP
andrelins/yii2-application
/models/Ddd.php
UTF-8
1,129
2.65625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "ddd". * * @property integer $id * @property integer $ddd * @property string $name * * @property Calls[] $calls * @property Calls[] $calls0 */ class Ddd extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'ddd'; } /** * @inheritdoc */ public function rules() { return [ [['ddd', 'name'], 'required'], [['ddd'], 'integer'], [['name'], 'string'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'ddd' => 'Ddd', 'name' => 'Name', ]; } /** * @return \yii\db\ActiveQuery */ public function getCalls() { return $this->hasMany(Calls::className(), ['destiny' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getCalls0() { return $this->hasMany(Calls::className(), ['origin' => 'id']); } }
true
6d232880dc5a514a88b5d1b49126b2ec9402aed3
PHP
MusheAbdulHakim/CoinGeckoApi
/src/Api/Companies.php
UTF-8
487
2.65625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace MusheAbdulHakim\CoinGecko\Api; use MusheAbdulHakim\CoinGecko\Request; /** * Get public companies bitcoin or ethereum holdings */ class Companies extends Request { /** * Get public companies bitcoin or ethereum holdings * * @param string $coin_id * @return array */ public function getPublicTreasury(string $coin_id): array { return $this->get('companies/public_treasury/' . $coin_id); } }
true
5692b17eb8b6d91666b02cece9b6e73363d1cd81
PHP
MiguelScript/sistema_inventario_alquimista
/src/Sales/Services/GetProductsSoldBySale.php
UTF-8
373
2.71875
3
[ "MIT" ]
permissive
<?php namespace Src\Sales\Services; use Src\Sales\Repository\SaleRepository; class GetProductsSoldBySale { protected $repository; public function __construct(SaleRepository $repository) { $this->repository = $repository; } public function __invoke($sale_id) { return $this->repository->get_products_from_sale($sale_id); } }
true
fa2f6ef0da1d9efe67020abf8f72f7be0a85b3db
PHP
ChrisJim15/lala
/edit1.php
UTF-8
2,371
2.546875
3
[]
no_license
<?php session_start(); include_once("config.php"); if(isset($_POST['update'])){ $reservedate=mysqli_real_escape_string($db,$_POST['reservedate']); $restime=mysqli_real_escape_string($db,$_POST['restime']); $returndate=mysqli_real_escape_string($db,$_POST['returndate']); $studid=mysqli_real_escape_string($db,$_POST['studid']); $equipid=mysqli_real_escape_string($db,$_POST['equipid']); $issuedby=mysqli_real_escape_string($db,$_POST['issuedby']); $reserveid=mysqli_real_escape_string($db,$_POST['reserveid']); $result=mysqli_query($db,"UPDATE `reservation` SET reservedate='$reservedate',restime='$restime',returndate='$returndate',studid='$studid',equipid='$equipid',issuedby='$issuedby' WHERE reserveid=$reserveid"); header("Location: viewreservation.php"); } ?> <?php $reserveid=$_GET['reserveid']; $result=mysqli_query($db,"SELECT * FROM reservation WHERE reserveid=$reserveid"); while ($res=mysqli_fetch_array($result)) { $reservedate= $res['reservedate']; $restime= $res['restime']; $returndate= $res['returndate']; $studid= $res['studid']; $equipid= $res['equipid']; $issuedby= $res['issuedby']; } ?> <!DOCTYPE html> <html> <head> <title>Edit</title> </head> <body> <form action="edit.php" method="POST"> <table width="50%" border="0"> <tr> <td>Reservation Date: </td> <td><input type="Date" name="reservedate" value="<?php echo $reservedate; ?>"></td> </tr> <tr> <td>Reservation Time: </td> <td><input type="time" name="restime" value="<?php echo $restime; ?>" ></td> </tr> <tr> <td>Return Date: </td> <td><input type="Date" name="returndate" value="<?php echo $returndate; ?>"></td> </tr> <tr> <tr> <td>Student ID: </td> <td><input type="number" name="studid" value="<?php echo $studid; ?>"></td> </tr> <tr> <tr> <td>Equipment ID: </td> <td><input type="number" name="equipid" value="<?php echo $equipid; ?>"></td> </tr> <tr> <tr> <td>Issued by: </td> <td><input type="text" name="issuedby" value="<?php echo $issuedby; ?>"></td> </tr> <tr> <td></td> <br> <td><input type="hidden" name="reserveid" value=<?php echo $_GET['reserveid']; ?>></td> <td><input type="submit" name="update" value="Update"></td> </tr> </table> </form> </body>
true
9a68d88e779f2b37e545ea271e58c3c978e83301
PHP
CrisRubio/Lab
/P1/pdo2.php
UTF-8
1,459
2.65625
3
[]
no_license
<?php header('Content-Type: application/json'); /** The name of the database */ define('DB_NAME', 'ei1036_42'); /** MySQL database username */ define('DB_USER', '*****'); /** MySQL database password */ define('DB_PASSWORD', '*****'); /** MySQL hostname */ define('DB_HOST', 'db-aules.uji.es' ); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); $pdo = new PDO("pgsql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD); function ejecutarSQL($pdo,$table,$query,$valor) { var_dump($valor); try{ $consult = $pdo->prepare($query); $a=$consult->execute($valor); } catch (PDOException $e) { echo "Failed to get DB handle: " . $e->getMessage() . "\n"; exit; } return $a; } $table="a_cliente"; $query="CREATE TABLE IF NOT EXISTS $table (client_id SERIAL PRIMARY KEY, name CHAR(50) NOT NULL, surname CHAR(50) NOT NULL, address CHAR(50),city CHAR(50),zip_code CHAR(5),foto_file VARCHAR(25) );"; echo $query; $a=ejecutarSQL($pdo,$table,$query,[]); $query = "INSERT INTO $table (name,surname) VALUES (?,?)"; $a=ejecutarSQL($pdo,$table,$query,['user4','pp']); if (1>$a) {echo "InCorrecto1";} var_dump($a); $query = "SELECT * FROM $table "; $a=ejecutarSQL($pdo,$table,$query,NULL); var_dump($a); ?>
true
843aa0b483915962dfd99542c48add304f4f4dc0
PHP
ozgg/Brujo
/library/Brujo/Http/Router.php
UTF-8
3,935
2.890625
3
[]
no_license
<?php /** * Router * * @author Maxim Khan-Magomedov <maxim.km@gmail.com> * @package Brujo\Http */ namespace Brujo\Http; use Brujo\Http\Error\NotFound; /** * Router */ class Router { /** * Available routes * * @var Route[] */ protected $routes = []; /** * Add route * * @param Route $route */ public function addRoute(Route $route) { $this->routes[$route->getName()] = $route; } /** * Get route by name * * @param $name * @return Route * @throws \RuntimeException */ public function getRoute($name) { if (isset($this->routes[$name])) { $route = $this->routes[$name]; } else { throw new \RuntimeException("Cannot find route {$name}"); } return $route; } /** * Get all routes * * @return Route[] */ public function getRoutes() { return $this->routes; } public function loadCompacted($baseDir) { if (is_dir($baseDir)) { foreach (scandir($baseDir) as $file) { if ($file[0] == '.') { continue; } $type = pathinfo($file, PATHINFO_FILENAME); $data = include $baseDir . '/' . $file; switch ($type) { case Route::TYPE_REST: $this->decompressRestRoutes($data); break; default: $error = "Invalid route type {$type}"; throw new \RuntimeException($error); } } } } /** * Import routes from array * * @param array $routes */ public function import(array $routes) { foreach ($routes as $name => $data) { $type = isset($data['type']) ? $data['type'] : Route::TYPE_STATIC; $route = Route::factory($type); $route->setName($name); $route->initFromArray($data); $this->addRoute($route); } } /** * Match URI to routes and get according route * * @param string $uri * @return Route * @throws \Brujo\Http\Error\NotFound */ public function matchRequest($uri) { $match = null; $path = '/' . trim(strtolower(parse_url($uri, PHP_URL_PATH)), '/'); foreach ($this->routes as $route) { if ($route->isStatic()) { $found = $path == strtolower($route->getMatch()); } else { $found = (preg_match("#{$route->getMatch()}#i", $path) > 0); } if ($found) { $match = $route; break; } } if (!$match instanceof Route) { throw new NotFound("Cannot match URI {$uri} against any route"); } return $match; } protected function decompressRestRoutes(array $data) { foreach ($data as $uri => $routeInfo) { $prefix = ''; $scope = str_replace('/', '_', trim($uri, '/')); if ($scope != '') { $scope .= '_'; } if (($uri == '') || ($uri[0] != '/')) { $uri = '/' . $uri; } if (substr($uri, -1) != '/') { $uri .= '/'; } foreach ($routeInfo as $name => $resources) { if ($name == '_prefix') { $prefix = $resources; } else { $route = new Route\RestRoute; $route->setName($scope . $name); $route->setControllerName($prefix . ucfirst($name)); $route->setUri($uri . $name); $route->setResources($resources); $this->addRoute($route); } } } } }
true
73343c822b2f4c736e340f4eebb20c6a4057cc7c
PHP
Akhtar-18/LaravelCustComApp
/app/Console/Commands/UserCreate.php
UTF-8
1,301
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Hash; use App\Models\User; class UserCreate extends Command { /** * The name and signature of the console command. * * @var string */ //protected $signature = 'command:name'; protected $signature = 'user:create'; /** * The console command description. * * @var string */ //protected $description = 'Command description'; protected $description = 'This is the command asks for user information and create into database'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return int */ public function handle() { //return 0; $input['name'] = $this->ask('Enter your name:'); $input['email'] = $this->ask('Enter your email address:'); $input['password'] = $this->ask('Provide your secret password:'); $input['password'] = Hash::make($input['password']); $input['phone'] = $this->ask('Enter your phone no:'); User::create($input); $this->info("User created successfully"); } }
true
11c1820ed78faa46be49f8415670accf80cf1918
PHP
lloricode/apiato-audit
/Audit/Tasks/GetAllAuditsTask.php
UTF-8
727
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Containers\Audit\Tasks; use App\Containers\Audit\Data\Repositories\AuditRepository; use App\Ship\Parents\Tasks\Task; use App\Ship\Exceptions\NotFoundException; use App\Containers\Audit\Data\Criterias\OneInstanceCriteria; class GetAllAuditsTask extends Task { protected $repository; public function __construct(AuditRepository $repository) { $this->repository = $repository; } public function run($classModel, $id) { try { $this->repository->pushCriteria(new OneInstanceCriteria($classModel, $id)); return $this->repository->paginate(); } catch (Exception $exception) { throw new NotFoundException(); } } }
true
075795a9e76bbbca040b19de7ca6a92a8504ec74
PHP
MRLIXIANZHONG/tp_fancan
/application/home/model/CarKindTable.php
UTF-8
823
2.53125
3
[ "Apache-2.0" ]
permissive
<?php /** * Created by PhpStorm. * User: 吕卫萌 * Date: 2019/10/30/030 * Time: 15:46 */ namespace app\home\model; use think\exception\DbException; class CarKindTable extends Table { // 设置当前模型对应的完整数据表名称 protected $name = 'car_kind'; //没有使用id作为主键名 protected $pk = 'id'; /** * 获取站点类别 * @param int $fid 父ID * @return array */ public function getByFid(int $fid) { try{ $where = [ ['pid', '=', $fid] ]; $entityValue = $this->getReadDb()->field(['kindid', 'kindname'])->where($where)->order(['kindid'])->select(); return $entityValue; }catch (DbException $ex){ return json($ex->getMessage()); } } }
true
751c62a72b52267574d7e81cec0aa4ed637a489a
PHP
jcastell7/AsignacionDeSalones
/Objetos/Salon.php
UTF-8
1,251
3.453125
3
[]
no_license
<?php class Salon { /* * clase salon * contiene los atributos del objeto salon */ private $idSalon; private $numero; private $capacidad; private $info; /* * constructor del objeto * recibe el numero de salon (bloque-salon ej: 11-112) * la capacidad del salón (entero) * informacion extra(por defecto está vacío) * disponibilidad (booleano que por defecto será true (disponible) */ function __construct($numero, $capacidad, $idSalon, $info = null) { $this->numero = $numero; $this->capacidad = $capacidad; $this->info = $info; $this->idSalon = $idSalon; } /* * geters y seters del objeto */ function getNumero() { return $this->numero; } function getCapacidad() { return $this->capacidad; } function setNumero($numero) { $this->numero = $numero; } function setCapacidad($capacidad) { $this->capacidad = $capacidad; } function getIdSalon() { return $this->idSalon; } function getInfo() { return $this->info; } function setInfo($info) { $this->info = $info; } }
true
27b4832edeaec4b0e15233f79a10634aa53a11af
PHP
lesterpadul/FDCNydus
/inc/core/ErrorHandler.php
UTF-8
586
3
3
[]
no_license
<?php class ErrorHandler{ private $const = NULL; function __construct(){ $this->const = new ConstVars; } // write log file on error public function writeError($err = FALSE){ // check if err is valid if ($err == FALSE) { return false; } if (strpos($err['content'], "CONTENT") !== FALSE) { $filename = "error_log.txt"; $errMsg = "[".date('Y/m/d H:i:s')."] "; $errMsg .= "Subject: ".$err['subject']." "; $errMsg .= $err['content']; fopen($this->const->config['DIR'].$filename, "a"); file_put_contents($filename, $errMsg, FILE_APPEND); } } }
true
1e9e468a2f2a33a0be10449a3f4b730b55d8b6c0
PHP
cp3402-students/a2-cp3402-2019-team10
/wp-content/plugins/smart-slider-3/library/smartslider/libraries/slider/generator/generatorFactory.php
UTF-8
794
2.953125
3
[ "GPL-3.0-only", "GPL-3.0-or-later", "BSD-3-Clause" ]
permissive
<?php class N2SSGeneratorFactory { /** @var N2SliderGeneratorPluginAbstract[] */ private static $generators = array(); /** * @param N2SliderGeneratorPluginAbstract $generator */ public static function addGenerator($generator) { self::$generators[$generator->getName()] = $generator; } public static function getGenerators() { foreach (self::$generators AS $generator) { $generator->load(); } return self::$generators; } /** * @param $name * * @return N2SliderGeneratorPluginAbstract|false */ public static function getGenerator($name) { if (!isset(self::$generators[$name])) { return false; } return self::$generators[$name]->load(); } }
true
f73b76a0912b1d2bcea2703e4d7830d41dd77e4d
PHP
alejoto/permissions
/app/controllers/WebserviceController.php
UTF-8
1,698
2.765625
3
[]
no_license
<?php class WebservicesData{ public function all () { return Webservice::all(); } } class WebserviceController extends \BaseController { /** * Display a listing of the resource. * GET /webservice * * @return Response */ public function index() { $d=new WebservicesData; $data=array( 'webservices'=>$d->all() ) ; return View::make('webservices.index',$data); } /** * Show the form for creating a new resource. * GET /webservice/create * * @return Response */ public function create() { $data=array(); return View::make('webservices.create',$data); } /** * Store a newly created resource in storage. * POST /webservice * * @return Response */ public function store() { $n=new Webservice; $n->name=Input::get('name'); $n->url=Input::get('url'); $n->description=Input::get('description'); $n->save(); return 'success'; } /** * Display the specified resource. * GET /webservice/{id} * * @param int $id * @return Response */ public function show($id) { $data=array(); return View::make('webservices.show',$data); } /** * Show the form for editing the specified resource. * GET /webservice/{id}/edit * * @param int $id * @return Response */ public function edit($id) { $data=array(); return View::make('webservices.edit',$data); } /** * Update the specified resource in storage. * PUT /webservice/{id} * * @param int $id * @return Response */ public function update($id) { // } /** * Remove the specified resource from storage. * DELETE /webservice/{id} * * @param int $id * @return Response */ public function destroy($id) { // } }
true
d84b8d0c43e5f70f13472123885944fcd84197d6
PHP
neformalist/not
/common/models/Text.php
UTF-8
1,393
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use Yii; /** * This is the model class for table "{{%text}}". * * @property integer $id * @property integer $article_id * @property string $text_ru * @property string $text_en * * @property Article $article */ class Text extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%text}}'; } /** * @inheritdoc */ public function rules() { return [ [['article_id', 'number_page','visible'], 'integer'], ['number_page', 'unique', 'message' => 'Номер страницы уже существует'], [['text_ru', 'text_en'], 'string'], [['article_id'], 'exist', 'skipOnError' => true, 'targetClass' => Article::className(), 'targetAttribute' => ['article_id' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'article_id' => 'Article ID', 'text_ru' => 'Text Ru', 'text_en' => 'Text En', 'number_page' => 'number_page', 'visible' => 'Visible', ]; } /** * @return \yii\db\ActiveQuery */ public function getArticle() { return $this->hasOne(Article::className(), ['id' => 'article_id']); } }
true
b9ca261005a6deda469921a9c3f69943b42b6d2a
PHP
whosnext000/work-samples
/php-mysql/Profolio-wordpress-plugin/edit_client.php
UTF-8
950
2.625
3
[]
no_license
<?php /** The database needs to know what we're updating **/ if(isset($_POST['client_name'])) { $name=$_POST['client_name']; $title_=strtolower($name); $slug=str_replace(" ","_",$title_); $update="update $client_tbl set name='$name', slug='$slug' where id=".$edit_id; $wpdb->query($update); header("Location: ?page=profolio_manage_client"); } $qry="SELECT * from ".$client_tbl." where id=".$edit_id; $rows=$wpdb->get_results($qry,ARRAY_A); ?> <style type="text/css"> label{ display:block; } </style> <!-- Here's the form fo updating clients !--> <h2>Update Your Client Details:</h2> <table> <form action="" method="post"> <tr> <td><label for="item_type">Client Name: </label></td> <td><input type="text" value="<?php echo $rows[0][name];?>" name="client_name" id="client_name" /></td> </td> <tr> <td><input class="button-primary" type="submit" value="Update Client" /></td> <td></td> </tr> </form> </table>
true
2cdddccc7ab6b821f4678a8d2cd5a606070f93fd
PHP
taleksey/chat
/controllers/ChatController.php
UTF-8
3,046
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\controllers; use app\models\Chat; use app\models\User; use Yii; use yii\bootstrap\ActiveForm; use yii\filters\AccessControl; use yii\web\BadRequestHttpException; use yii\web\Controller; use yii\web\ForbiddenHttpException; use yii\web\Response; use yii\web\ErrorAction; class ChatController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['create'], 'rules' => [ // allow authenticated users [ 'allow' => true, 'roles' => ['@'], ], ], 'denyCallback' => function ($rule, $action) { throw new ForbiddenHttpException('You are not allowed to access this page'); } ], ]; } /** * @inheritdoc */ public function actions() { return [ 'error' => [ 'class' => ErrorAction::class, ], ]; } /** * Displays homepage. * * @return string * @throws \yii\base\InvalidParamException */ public function actionIndex() { $user = new User(); $chat = new Chat(); $createdUsers = User::getAllUsers(); $createdMessages = Chat::getAllMessages(); $currentUserId = Yii::$app->user->id; return $this->render('index', ['user' => $user, 'createdUsers' => $createdUsers, 'chat' => $chat, 'messages' => $createdMessages, 'currentUserId' => $currentUserId ] ); } public function actionCreate() { $chat = new Chat(); $request = \Yii::$app->getRequest(); if ($request->isPost && $request->isAjax && $chat->load(Yii::$app->request->post())) { \Yii::$app->response->format = Response::FORMAT_JSON; $userId = Yii::$app->user->id; $chat->user_id = $userId; $isSavedChat = $chat->save(); $user = User::findIdentity($userId); $chat->refresh(); return ['success' => $isSavedChat, 'chat' => [ 'message' => $chat->message, 'nick' => $user->nick, 'createdTime' => $chat->getDate() ] ]; } throw new BadRequestHttpException('Request is not correct.'); } /** * @return array */ public function actionValidate() { $model = new Chat(); $request = \Yii::$app->getRequest(); if ($request->isPost && $model->load($request->post())) { \Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } return []; } }
true
9be563527f1e910415e66df822cc50fcb5699a44
PHP
Iskandarcoder/consul
/backend/models/News.php
UTF-8
2,452
2.59375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace backend\models; use Yii; /** * This is the model class for table "news". * * @property integer $id * @property integer $id_category_news * @property string $uz_thema * @property string $ru_thema * @property string $en_thema * @property string $x_thema * @property string $uz_description * @property string $ru_description * @property string $en_description * @property string $x_description * @property string $uz_text * @property string $ru_text * @property string $en_text * @property string $x_text * @property string $date * @property string $img * @property integer $slider * @property integer $active * @property integer $show_n */ class News extends \yii\db\ActiveRecord { /** * @inheritdoc */ public $file; public static function tableName() { return 'news'; } /** * @inheritdoc */ public function rules() { return [ [['slider', 'active', 'show_n'], 'integer'], [['id_category_news','uz_thema', 'uz_description'], 'required'], [['uz_thema', 'ru_thema', 'en_thema', 'x_thema', 'uz_description', 'ru_description', 'en_description', 'x_description', 'uz_text', 'ru_text', 'en_text', 'x_text'], 'string'], [['file'],'file'], [['date'], 'safe'], [['img'], 'string', 'max' => 5000], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'id_category_news' => 'Категория', 'uz_thema' => 'Uz Thema', 'ru_thema' => 'Ru Thema', 'en_thema' => 'En Thema', 'x_thema' => 'X Thema', 'uz_description' => 'Uz Description', 'ru_description' => 'Ru Description', 'en_description' => 'En Description', 'x_description' => 'X Description', 'uz_text' => 'Uz Text', 'ru_text' => 'Ru Text', 'en_text' => 'En Text', 'x_text' => 'X Text', 'date' => 'Date', 'img' => 'Images (width=555px; height=416px)', 'slider' => 'Slider', 'active' => 'Active', 'show_n' => 'Show N', 'file' => 'Images (width=555px; height=416px)', ]; } public function getCategorNews(){ return $this->hasOne(CategorNews::className(),['id'=>'id_category_news']); } }
true
f9a0ac5692329e255a67710f352de93038c10595
PHP
Dry7/analytics-backend
/app/Models/Post.php
UTF-8
1,405
2.625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * Class Post * @package App\Models * * @property int $id * @property int $group_id * @property int $post_id * @property Carbon $date * @property int $likes * @property int $shares * @property int $views * @property int $comments * @property int $links * @property bool $is_pinned * @property bool $is_ad * @property bool $is_gif * @property bool $is_video * @property bool $video_group_id * @property bool $video_id * @property bool $shared_group_id * @property bool $shared_post_id * @property string $export_hash * * @property Group $group */ class Post extends Model { protected $fillable = [ 'group_id', 'post_id', 'date', 'likes', 'shares', 'views', 'comments', 'links', 'is_pinned', 'is_ad', 'is_gif', 'is_video', 'video_group_id', 'video_id', 'shared_group_id', 'shared_post_id', 'export_hash', ]; protected $dates = [ 'date', ]; /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function group(): BelongsTo { return $this->belongsTo(Group::class); } public function getUrlAttribute(): string { return 'https://vk.com/wall-' . $this->group->source_id . '_' . $this->post_id; } }
true
785a95ec0185ee390837357f8ebe53c778880fbf
PHP
hongzhangMu/webapp
/config.php
GB18030
1,460
2.546875
3
[ "Apache-2.0" ]
permissive
<?php var_dump(123); die(); //header("Content-Type:application/json; charset=UTF-8"); //ļ define("DBServer", "localhost"); //ݿIPַ define("DBUser", "sa"); //ݿ¼ sa define("DBPassword", "cai83114"); //ݿ¼ cai83114 define("DBName", "GPS"); //Ҫʹõݿ //tUser //id = 1 //name = test //password = test //MSSQL ת iconv('gb2312','utf-8', $resultArray['title']) //ͨóʼ function initialize() { header("Content-Type:application/json; charset=UTF-8"); } //ݿⲢѡݿ function connectDatabase() { $conn = sqlsrv_connect(DBServer, array( "Database"=>DBName, "UID"=>DBUser, "PWD"=>DBPassword)); return $conn; } //رݿ function closeDatabase($conn) { sqlsrv_close($conn); } //ͷż¼Դ function freeResult($result) { //mssql_free_result($result); } //ִвѯ //tCar, tUser, tSuperVision function executeQuery($sql) { global $conn; return sqlsrv_query($conn, $sql); } //ִSQL function executeSQL($sql) { global $conn; sqlsrv_query($conn, $sql); } //չ¼ function fetchArray($result) { return sqlsrv_fetch_array($result); } //ȡ¼ļ¼ function getResultCount($result) { return sqlsrv_num_rows($result); } ?>
true
079d6b71c8d5c58686d58c9482d4948b7048a410
PHP
shhphp/SHH
/src/SHH/TokenParser/Identifier.php
UTF-8
5,676
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace SHH\TokenParser; use SHH\TokenParser; use SHH\Node; use SHH\Parser; /* * This file is part of SHH. * (c) 2015 Dominique Schmitz <info@domizai.ch> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * Identifier TokenParser */ class Identifier extends TokenParser { const TYPE = IDENTIFIER_TYPE; public $respectIndent = true; protected static $autotagSelf = false; /** * Parse token. * * @param Parser $parser a Parser instance * * @return Node an Element, Attribute or Content Node */ public function parse(Parser &$parser) { # This order is crucial if( $node = $this->addCode($parser) ) return $node; if( $node = $this->addAutotag($parser) ) return $node; if( $node = $this->addAttribute($parser) ) return $node; if( $node = $this->addContent($parser) ) return $node; if( $node = $this->addElement($parser) ) return $node; } protected function addAutotag(Parser &$parser) { if( !$parser->directive->get(AUTOTAG) ){ return false; } if( self::$autotagSelf ){ self::$autotagSelf = false; return false; } if( array_key_exists($this->tok, $parser->autotags ) ){ if( $parser->parent && $parser->autotags[$this->tok][2] ){ if( !in_array(end($parser->parent)->tok, \SHH\Defaults::toArray($parser->autotags[$this->tok][2])) ){ return false; } } $p = $parser->p; $newName = $parser->autotags[$this->tok][0]; $toks = array(); $toks[] = new TokenParser\Identifier($newName, $this->line, $this->indent); if( is_callable($parser->autotags[$this->tok][1]) ){ if( $parser->nextIs(new TokenParser\Assign, null, true) ){ $arg = $parser->parseCurrent(); } foreach($parser->autotags[$this->tok][1]($arg->value) as $attr => $value) { if($value){ $toks[] = new TokenParser\Attribute('@', $this->line, $this->indent); $toks[] = new TokenParser\Identifier($attr, $this->line, $this->indent); $toks[] = new TokenParser\Assign('=', $this->line, $this->indent); $toks[] = new TokenParser\Identifier($value, $this->line, $this->indent); } } } $parser->removeToken($p, $parser->p); $parser->p = $p; $parser->injectToken($toks); if( $newName == $this->tok) self::$autotagSelf = true; return( $parser->parseCurrent() ); } } protected function addAttribute(Parser &$parser) { if( $parser->nextIs(new TokenParser\Assign) ){ if( $parser->prevIs(array(new TokenParser\EOL, new TokenParser\GroupOpen, new TokenParser\GroupClose, new TokenParser\Tail)) ){ $parser->injectToken(array( new TokenParser\Identifier($parser->defaultElement, $this->line, $this->indent), new TokenParser\Whitespace(' ', $this->line, $this->indent)) ); return( $parser->parseCurrent() ); } $parser->expect(new TokenParser\Assign); return new Node\Attribute( $this->tok, $parser->parseCurrent()->value ); } } protected function addCode(Parser &$parser) { if( $parser->nextIs(new TokenParser\Code) ){ $parser->expect(new TokenParser\Code); $parser->scope++; $code = $parser->parseCurrent(); $parser->scope--; if(array_key_exists($this->tok, $parser->filter) ){ # parseCurrent if( !(is_callable($parser->filter[$this->tok][2]) && $content = $parser->filter[$this->tok][2]( $code->value )) ){ $content = $code->value; } if($parser->filter[$this->tok][0]){ return new Node\Element( array($parser->filter[$this->tok][0], $parser->filter[$this->tok][1]), array( new Node\Content($content) )); } else { return new Node\Content( $parser->format($content) ); } } else { return new Node\Element( $this->tok, array(new Node\Content( $code->value ))); } } } protected function addContent(Parser &$parser) { if( $parser->prevIs( array(new TokenParser\Php, new TokenParser\Identifier, new TokenParser\Escape, new TokenParser\SingleQuote, new TokenParser\DoubleQuote) )){ $string = $parser->capture( array(new TokenParser\EOL, new TokenParser\GroupClose )); $parser->p--; return new Node\Content( $this->tok.$string ); } } protected function addElement(Parser &$parser) { if( $parser->directive->get(HTML) && !in_array($this->tok, $parser->htmlElements) ){ $string = $parser->capture( array(new TokenParser\PhpShorthand, new TokenParser\EOL, new TokenParser\GroupClose )); $parser->p--; return new Node\Content( trim($this->tok.$string) ); } if( preg_match('/^</', $this->tok) ){ $string = $parser->capture( array(new TokenParser\EOL)); return new Node\Content( $this->tok.$string ); } $parser->scope++; $parser->parent[] =& $this; # Scope/group counting is crucial $nodes = $parser->parseToks( function( &$parser, &$self ){ if( $parser->current()->respectIndent && $parser->current()->indent <= $self->indent && $parser->current()->line > $self->line ){ $parser->scope--; return true; } // div[eol](... if( ($parser->current() instanceof TokenParser\GroupOpen || $parser->current() instanceof TokenParser\Anchor ) && $parser->current()->indent > $self->indent && $parser->current()->line > $self->line ){ $parser->scope++; } if( $parser->current() instanceof TokenParser\GroupClose){ if( $self->group+1 == $parser->group && $self->scope == $parser->scope ) return true; if( $self->scope+1 == $parser->scope && $self->group == $parser->group){ $parser->scope--; return true; } } }); $parser->scope = max(0, $parser->scope); array_pop($parser->parent); return new Node\Element( $this->tok, $nodes ); } }
true
c1e1f61ccdda510cd38418df66bcdfeb5f3a81f0
PHP
kristapsmors/bitcoin-chart
/app/commands/ExchangeBitstampTickerCommand.php
UTF-8
939
2.90625
3
[ "MIT" ]
permissive
<?php class ExchangeBitstampTickerCommand extends ExchangeTickerCommandBase { /** * The console command name. * * @var string */ protected $name = 'bc:ticker:bitstamp'; /** * The console command description. * * @var string */ protected $description = 'Get Bitstamp Exchange Data'; /** * Execute the console command. * * @return mixed */ public function fire() { $response = file_get_contents('https://www.bitstamp.net/api/ticker/'); $result = json_decode($response, true); // Split the JSON into arrays. $amounts = [ 'low' => $result['low'], 'high' => $result['high'], 'last' => $result['last'], ]; $volumes = [ 'bitcoins' => $result['volume'], ]; $this->saveData(ExchangeData::MARKET_BITSTAMP, ExchangeData::CURRENCY_BTC, ExchangeData::CURRENCY_USD, $amounts, $volumes); $this->info('Ticker: bitstamp @ USD | Saved Exchange Data for ' . date('d.m.Y H:i:s')); } }
true
a1bb5110894e5f5cca6b4bc3bb33d78bb2523640
PHP
Dongs7/phpBoard
/application/controllers/Board.php
UTF-8
6,202
2.5625
3
[ "MIT" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Board extends CI_Controller { function __construct(){ parent::__construct(); date_default_timezone_set('America/Vancouver'); $this->load->database(); $this->load->model('board_m'); } public function index() { $this->lists(); } public function _remap($method){ $this->load->view('layout/header_v'); if(method_exists($this, $method)){ $this->{"{$method}"}(); } $this->load->view('layout/footer_v'); } /** * Main Page - Show full list of forum * */ public function lists(){ $table = $this->uri->segment(3); $q = $soption = $sterm =''; $uri_segment = 5; $uri_array = $this->segment_explode($this->uri->uri_string()); if(in_array('q', $uri_array)){ $soption = urldecode($this->url_exploded($uri_array, 'q')); $sterm = urldecode($this->url_exploded($uri_array, $soption)); $q = '/q/'.$soption.'/'.$sterm; $uri_segment = 8; } //Pagination $this->load->library('pagination'); $config['base_url'] = '/board/lists/ci_board'.$q.'/page/'; $config['total_rows'] = $this->board_m->get_list($table, 'count','','',$soption, $sterm); $config['per_page'] = 5; $config['uri_segment'] = $uri_segment; //Apply Twitter bootstrap style to pagination $config['full_tag_open'] = '<ul class="pagination">'; $config['full_tag_close'] = '</ul>'; $config['first_link'] = false; $config['last_link'] = false; $config['first_tag_open'] = '<li>'; $config['first_tag_close'] = '</li>'; $config['prev_link'] = '&laquo'; $config['prev_tag_open'] = '<li class="prev">'; $config['prev_tag_close'] = '</li>'; $config['next_link'] = '&raquo'; $config['next_tag_open'] = '<li>'; $config['next_tag_close'] = '</li>'; $config['last_tag_open'] = '<li>'; $config['last_tag_close'] = '</li>'; $config['cur_tag_open'] = '<li class="active"><a href="#">'; $config['cur_tag_close'] = '</a></li>'; $config['num_tag_open'] = '<li>'; $config['num_tag_close'] = '</li>'; //Dont forget to initialize pagination with $config value! $this->pagination->initialize($config); $data['pagination'] = $this->pagination->create_links(); //Set $pages variable to 1 if 5th segment does not have any value. $pages = $this->uri->segment($uri_segment,1); //Set start and limit for pagination if($pages > 1){ $start = ($pages/$config['per_page']) * $config['per_page']; }else{ $start = ($pages - 1) * $config['per_page']; } $limit = $config['per_page']; //Need to fix here array not working, need to make function instead. $data['search_result'] = array( 'soption' => $soption, 'sterm' => $sterm ); // $data['comments'] = $this->board_m->get_list($table,'comment',$start,$limit , $soption, $sterm); $data['lists'] = $this->board_m->get_list($table,'',$start,$limit, $soption, $sterm); // echo '<pre>'; // var_dump($data); // echo '</pre>'; $this->load->view('board/list_v', $data); } /** * View selected Post * @return [type] [description] */ public function view(){ $table = $this->uri->segment(3); $id = $this->uri->segment(5); $data['views'] = $this->board_m->get_view($table, $id); $data['comment_list'] = $this->board_m->get_comment($table, $id); $this->load->view('board/view_v', $data); } public function newpost(){ $this->form_validation->set_rules('title', 'TITLE', 'required'); $this->form_validation->set_rules('body', 'CONTENTS', 'required'); if($this->session->userdata('logged_in') == TRUE){ if($_POST){ if($this->form_validation->run() == TRUE){ $title = $this->input->post('title', TRUE); $body = $this->input->post('body', TRUE); $newdata = array( 'table' => $this->uri->segment(3), 'title' => $title, 'body' => $body, 'author' => $this->session->userdata('user_id') ); $result = $this->board_m->create_post($newdata); if($result){ alert('Post Created', '/board/lists/ci_board/page/1'); exit; }else{ alert('Post failed, Please try again', '/board/lists/ci_board/page/1'); exit; } }else{ $this->load->view('board/write_v'); } }else{ $this->load->view('board/write_v'); } }else{ alert('Please log in first', '/board/lists/ci_board/page/1'); exit; } } public function edit(){ $table = $this->uri->segment(3); $id = $this->uri->segment(5); if($this->session->userdata('logged_in') == TRUE){ if($_POST){ $edit_title = $this->input->post('title', TRUE); $edit_body = $this->input->post('body', TRUE); $editData = array( 'table' => $this->uri->segment(3), 'board_id' => $this->uri->segment(5), 'title' => $edit_title, 'body' => $edit_body, ); $result = $this->board_m->modify_post($editData); if($result){ alert('Post Edited', '/board/lists/ci_board/page/1'); }else{ alert('Post edit failed, Please try again', '/board/lists/ci_board/page/1'); } }else{ $data['views'] = $this->board_m->get_view($table, $id); $this->load->view('board/edit_v', $data); } }else{ alert('login first', '/board/lists/ci_board/page/1'); exit; } } public function delete(){ if($this->session->userdata('logged_in') == TRUE){ $table = $this->uri->segment(3); $id = $this->uri->segment(5); $return = $this->board_m->delete_post($table, $id); if($return){ alert('Post deleted', '/board/lists/ci_board/page/1'); } }else{ alert('login first', '/board/lists/ci_board/page/1'); exit; } } function segment_explode($uri){ //Get length of current uri $len = strlen($uri); //If there is a '/' at the first index, //Set new $uri starting from index 1. if(substr($uri, 0, 1) == '/'){ $uri = $substr($uri, 1, $len); } //If there is a '/' at the end, //Set new $uri from index 0 to length -1. if(substr($uri, -1) == '/'){ $uri = $substr($uri, 0, $len-1); } return explode('/', $uri); } function url_exploded($arrays, $key){ $cnt = count($arrays); for($i=0; $i < $cnt; $i++){ if($arrays[$i] == $key){ $target = $arrays[$i+1]; return $target; } } } }
true
93a6b21e93edc916610dc86ec6f1830661b8dbd8
PHP
wizyoua/Notes
/PHP/udemy/udemyoop/index.php
UTF-8
246
2.5625
3
[]
no_license
<?php error_reporting(E_ALL); ini_set('display_errors', 'On'); spl_autoload_register(function($class_name){ include $class_name . '.php'; }); // include 'foo.php'; // include 'bar.php'; $foo = new Foo; $bar = new Bar; $bar->sayHello(); ?>
true
be5ef96777a73aa883b4415493271c0e012ad0ee
PHP
phacility/phabricator
/src/applications/drydock/query/DrydockBlueprintQuery.php
UTF-8
5,561
2.65625
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php final class DrydockBlueprintQuery extends DrydockQuery { private $ids; private $phids; private $blueprintClasses; private $datasourceQuery; private $disabled; private $authorizedPHIDs; private $identifiers; private $identifierIDs; private $identifierPHIDs; private $identifierMap; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withBlueprintClasses(array $classes) { $this->blueprintClasses = $classes; return $this; } public function withDatasourceQuery($query) { $this->datasourceQuery = $query; return $this; } public function withDisabled($disabled) { $this->disabled = $disabled; return $this; } public function withAuthorizedPHIDs(array $phids) { $this->authorizedPHIDs = $phids; return $this; } public function withNameNgrams($ngrams) { return $this->withNgramsConstraint( new DrydockBlueprintNameNgrams(), $ngrams); } public function withIdentifiers(array $identifiers) { if (!$identifiers) { throw new Exception( pht( 'Can not issue a query with an empty identifier list.')); } $this->identifiers = $identifiers; $ids = array(); $phids = array(); foreach ($identifiers as $identifier) { if (ctype_digit($identifier)) { $ids[] = $identifier; } else { $phids[] = $identifier; } } $this->identifierIDs = $ids; $this->identifierPHIDs = $phids; return $this; } public function getIdentifierMap() { if ($this->identifierMap === null) { throw new Exception( pht( 'Execute a query with identifiers before getting the '. 'identifier map.')); } return $this->identifierMap; } public function newResultObject() { return new DrydockBlueprint(); } protected function getPrimaryTableAlias() { return 'blueprint'; } protected function willExecute() { if ($this->identifiers) { $this->identifierMap = array(); } else { $this->identifierMap = null; } } protected function willFilterPage(array $blueprints) { $impls = DrydockBlueprintImplementation::getAllBlueprintImplementations(); foreach ($blueprints as $key => $blueprint) { $impl = idx($impls, $blueprint->getClassName()); if (!$impl) { $this->didRejectResult($blueprint); unset($blueprints[$key]); continue; } $impl = clone $impl; $blueprint->attachImplementation($impl); } if ($this->identifiers) { $id_map = mpull($blueprints, null, 'getID'); $phid_map = mpull($blueprints, null, 'getPHID'); $map = $this->identifierMap; foreach ($this->identifierIDs as $id) { if (isset($id_map[$id])) { $map[$id] = $id_map[$id]; } } foreach ($this->identifierPHIDs as $phid) { if (isset($phid_map[$phid])) { $map[$phid] = $phid_map[$phid]; } } // Just for consistency, reorder the map to match input order. $map = array_select_keys($map, $this->identifiers); $this->identifierMap = $map; } return $blueprints; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'blueprint.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'blueprint.phid IN (%Ls)', $this->phids); } if ($this->datasourceQuery !== null) { $where[] = qsprintf( $conn, 'blueprint.blueprintName LIKE %>', $this->datasourceQuery); } if ($this->blueprintClasses !== null) { $where[] = qsprintf( $conn, 'blueprint.className IN (%Ls)', $this->blueprintClasses); } if ($this->disabled !== null) { $where[] = qsprintf( $conn, 'blueprint.isDisabled = %d', (int)$this->disabled); } if ($this->identifiers !== null) { $parts = array(); if ($this->identifierIDs) { $parts[] = qsprintf( $conn, 'blueprint.id IN (%Ld)', $this->identifierIDs); } if ($this->identifierPHIDs) { $parts[] = qsprintf( $conn, 'blueprint.phid IN (%Ls)', $this->identifierPHIDs); } $where[] = qsprintf( $conn, '%LO', $parts); } return $where; } protected function shouldGroupQueryResultRows() { if ($this->authorizedPHIDs !== null) { return true; } return parent::shouldGroupQueryResultRows(); } protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) { $joins = parent::buildJoinClauseParts($conn); if ($this->authorizedPHIDs !== null) { $joins[] = qsprintf( $conn, 'JOIN %T authorization ON authorization.blueprintPHID = blueprint.phid AND authorization.objectPHID IN (%Ls) AND authorization.objectAuthorizationState = %s AND authorization.blueprintAuthorizationState = %s', id(new DrydockAuthorization())->getTableName(), $this->authorizedPHIDs, DrydockAuthorization::OBJECTAUTH_ACTIVE, DrydockAuthorization::BLUEPRINTAUTH_AUTHORIZED); } return $joins; } }
true
0c5314e3f388d38b3d90bd873aee18a27ad1b25d
PHP
armandolazarte/hello
/src/LLPP/backup/articoli_backup.php
UTF-8
1,177
2.796875
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php /** * @ORM\OneToMany(targetEntity="CommentiArticoli",mappedBy="articolo") * */ class Articoli { private $commenti; public function __construct() { $this->categorie = new \Doctrine\Common\Collections\ArrayCollection(); $this->commenti = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Add commenti * * @param \LLPP\IndexBundle\Entity\CommentiArticoli $commenti * @return Articoli */ public function addCommenti(\LLPP\IndexBundle\Entity\CommentiArticoli $commenti) { $this->commenti[] = $commenti; return $this; } /** * Remove commenti * * @param \LLPP\IndexBundle\Entity\CommentiArticoli $commenti */ public function removeCommenti(\LLPP\IndexBundle\Entity\CommentiArticoli $commenti) { $this->commenti->removeElement($commenti); } /** * Get commenti * * @return \Doctrine\Common\Collections\Collection */ public function getCommenti() { return $this->commenti; } /** * @ORM\ManyToMany(targetEntity="Articoli",mappedBy="categorie") * */ private $articoli; } ?>
true
fb6da1411716770eeab7082e54bfe9f81348f07e
PHP
wolftracks/pushyads
/www/admin/data/save-this.php
UTF-8
7,968
2.640625
3
[]
no_license
<?php include_once("pushy_common.inc"); include_once("pushy_commonsql.inc"); $db = getPushyDatabaseConnection(); function describeTable($db,$tablename) { printf("\n\n------ TABLE=%s -------------------------------\n",$tablename); printf("%-22s | ","Field Name"); printf("%-12s | ","Type"); printf("%-6s | ","Null"); printf("%-6s | ","Key"); printf("%-8s | ","Default"); printf("%-10s\n","Extra"); $sql = "DESCRIBE $tablename"; $result = mysql_query($sql,$db); if ($result) { while ($myrow=mysql_fetch_array($result)) { $field = $myrow[0]; $type = $myrow[1]; $null = $myrow[2]; $key = $myrow[3]; $default = $myrow[4]; $extra = $myrow[5]; printf("%-22s | ",$field); printf("%-12s | ",$type); printf("%-6s | ",$null); printf("%-6s | ",$key); printf("%-8s | ",$default); printf("%-10s\n",$extra); } } } function listFields($db, $tablename) { $fields=array(); $fcount=0; $sql = "DESCRIBE $tablename"; $result = mysql_query($sql,$db); if ($result) { while ($myrow=mysql_fetch_array($result)) { $fields[$fcount] = array( "fieldname" => $myrow[0], "fieldtype" => $myrow[1], "fieldnull" => $myrow[2], "fieldkey" => $myrow[3], "fielddefault" => $myrow[4], "fieldextra" => $myrow[5]); $fcount++; } } return $fields; } function listTables($db) { $tables=array(); $tcount=0; $sql = "SHOW TABLES"; $result = mysql_query($sql,$db); if ($result) { while ($myrow=mysql_fetch_array($result)) { $tables[$tcount]=$myrow[0]; $tcount++; } } return $tables; } function _select($db,$tablename,$where="",$order="",$group="",$limit="") { $fields=array(); $fcount=0; $sql = "DESCRIBE $tablename"; $result = mysql_query($sql,$db); if ($result) { while ($myrow=mysql_fetch_array($result)) { $fields[$fcount] = array( "fieldname" => $myrow[0], "fieldtype" => $myrow[1], "fieldnull" => $myrow[2], "fieldkey" => $myrow[3], "fielddefault" => $myrow[4], "fieldextra" => $myrow[5]); $fcount++; } $sql = "SELECT * from $tablename"; if (strlen($where) > 0) $sql .= " WHERE $where"; if (strlen($order) > 0) $sql .= " ORDER BY $order"; if (strlen($group) > 0) $sql .= " GROUP BY $order"; if (strlen($limit) > 0) $sql .= " LIMIT $limit"; $result = mysql_query($sql,$db); printf("SQL: %s<br>\n",$sql); printf("ERR: %s<br>\n",mysql_error()); $rows=array(); $rcount=0; if ($result) { while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $rows[$rcount]=$row; $rcount++; } } } return array($fields,$rows); } //describeTable($db,"account"); //describeTable($db,"member"); //describeTable($db,"profile"); //describeTable($db,"campaign"); //describeTable($db,"participant"); //describeTable($db,"leadtable"); // list($fields, $rows) = _select($db,"participant"); // // for ($i=0; $i<count($rows); $i++) // for ($i=0; $i<1; $i++) // { // $row=$rows[$i]; // for ($j=0; $j<count($fields); $j++) // { // $field=$fields[$j]; // printf("%s => %s\n", $field["fieldname"],$row[$field["fieldname"]]); // } // } ?> <html> <head> <link rel="stylesheet" type="text/css" href="../autoprospector/styles.css"> <title>DB Edit</title> </head> <body> <?php if ($op == "SQL-SELECT") { $where="$sql_field $sql_compare '$sql_value'"; $sql="SELECT * FROM $sql_table WHERE $where"; printf("SQL: %s<br><br>\n",$sql); list($fields, $rows) = _select($db,$sql_table,$where); for ($i=0; $i<count($rows); $i++) { $row=$rows[$i]; for ($j=0; $j<count($fields); $j++) { $field=$fields[$j]; printf("%s => %s\n", $field["fieldname"],$row[$field["fieldname"]]); } } } ?> <form method="POST" action="index.php"> <input type="hidden" name="op" value="SQL-SELECT"> <table width=600 cellpadding=4 cellspacing=2> <tr> <td width="200" class="bigdarkbluebold">SELECT</td> <td width="400" class="normaltext">&nbsp;</td> </tr> <tr> <td width="200" class="normaldarkbluebold">Table:</td> <td width="400" class="normaltext"> <select name="sql_table" class="smalltext"> <?php $tables = listTables($db); for ($i=0; $i<count($tables); $i++) { echo " <option value=\"".$tables[$i]."\">".$tables[$i]."</option>\n"; } ?> </select> </td> </tr> <!--- <tr> <td width="200" class="normaldarkbluebold">Operation:</td> <td width="400" class="normaltext"> <select name="sql_verb" class="smalltext"><option value="SELECT" selected>SELECT</option> <option value="UPDATE" selected>UPDATE</option> <option value="DELETE" selected>DELETE</option> </select> </td> </tr> ---> <tr> <td width="200" class="normaldarkbluebold">Where:</td> <td width="400" class="normaltext"> <select name="sql_field" class="smallmono"> <?php $fields = listFields($db,"participant"); $longest=0; for ($i=0; $i<count($fields); $i++) { $field = $fields[$i]; $fieldname = $field["fieldname"]; if (strlen($fieldname) > $longest) $longest=strlen($fieldname); } $longest+=3; for ($i=0; $i<count($fields); $i++) { $field = $fields[$i]; $fieldname = $field["fieldname"]; $fieldtype = $field["fieldtype"]; $pad = $longest - strlen($fieldname); $vpad=""; for ($j=0; $j<$pad; $j++) $vpad.="&nbsp;"; echo " <option value=\"$fieldname\">$fieldname $vpad $fieldtype</option>\n"; } ?> </select> </td> </tr> <tr> <td width="200" class="normaldarkbluebold">&nbsp;</td> <td width="400" class="normaltext"> <select name="sql_compare" class="smallmono"><option value="=" selected> = </option> <option value="!=" selected> != </option> <option value="<" selected> < </option> <option value=">" selected> > </option> <option value="<=" selected> <= </option> <option value=">=" selected> >= </option> <option value="like" selected> like </option> </select> </td> </tr> <tr> <td width="200" class="normaldarkbluebold">&nbsp;</td> <td width="400" class="normaltext"><b>Value:</b>&nbsp;&nbsp; <input type="text" name="sql_value" value=""> </td> </tr> <tr height="30"> <td width="200" class="normaldarkbluebold">&nbsp;</td> <td width="400" class="normaltext"> <input type="submit" class="button" value=" Submit "> </td> </tr> </table> </form> </body> </html>
true
21bc6813ab5c5a39a629e3ca6afefbcbd9bc2ce6
PHP
aion1/User-management-SW_project
/swe/connection.php
UTF-8
559
3.046875
3
[]
no_license
<?php class connection { var $host="localhost"; var $db="user acounts"; var $username="root"; var $password=""; var $connect; function connect() { $this->connect=mysqli_connect($this->host,$this->username,$this->password); mysqli_select_db($this->connect, $this->db); } function disconnect() { if (isset($this->connect)) { mysqli_close($this->connect); } } function getConnect(){ return $this->connect; } } ?>
true
cc6619832ef06600eb61969e3251d0aae4cf67f8
PHP
JasperLichte/jaspress
/server/classes/settings/settings/AppNameSetting.php
UTF-8
749
2.6875
3
[]
no_license
<?php namespace settings\settings; use settings\BaseSetting; use settings\categories\GeneralSettingCategory; use settings\categories\SettingsCategory; use settings\validator\StringValidator; use settings\validator\Validator; class AppNameSetting extends BaseSetting { public function getDefaultValue(): string { return 'My website'; } public static function dbKey(): string { return 'APP_NAME'; } public function description(): string { return 'Name of the application'; } public function getCategory(): SettingsCategory { return new GeneralSettingCategory(); } public function getValidator(): Validator { return new StringValidator(); } }
true
5c2f516a91536378dbf6a4851257080936ca7b90
PHP
HaciKandemir/simple-e-commerce
/basket.php
UTF-8
2,050
2.59375
3
[]
no_license
<?php session_start(); //session_destroy(); require ('vendor/autoload.php'); new \App\Database\Database("src/Database/database.json"); //basket sayfasındaki adet değiştirme işlemli if (isset($_POST['id']) && isset($_POST['action'])){ $id = $_POST['id']; $action = $_POST['action']; $total = null; $returnData = null; if (isset($_SESSION['basket'][$id])){ if ($action==="up"){ $_SESSION['basket'][$id]['count']+=1; $_SESSION['total_basket_count'] +=1; $total = ($_SESSION['basket'][$id]['count']*$_SESSION['basket'][$id]['price']); }else if ($action==="down" && $_SESSION['basket'][$id]['count']>1){ $_SESSION['basket'][$id]['count']-=1; $_SESSION['total_basket_count'] -=1; $total = ($_SESSION['basket'][$id]['count']*$_SESSION['basket'][$id]['price']); }else if($action==="delete"){ $_SESSION['total_basket_count'] -= $_SESSION['basket'][$id]['count']; unset($_SESSION['basket'][$id]); } echo json_encode($returnData = ['success'=>true, 'basket_count'=>$_SESSION['total_basket_count'], 'this_total_price'=>$total] ); } }else if (isset($_POST['id'])){ //index sayfasındaki sepete ekeleme işlemi $id = $_POST['id']; if (isset($_SESSION['basket'][$id])){ $_SESSION['basket'][$id]['count']+=1; $_SESSION['total_basket_count'] +=1; }else{ $prdct=\App\Database\Database::find($id,"products"); if (isset($prdct)){ $_SESSION['basket'][$id] = [ "id"=>$prdct['id'], "name"=>$prdct['name'], "price"=>$prdct['price'], "currency"=>$prdct['currency'], "img_url"=>$prdct['image_url'], "count"=>1 ]; $_SESSION['total_basket_count'] +=1; } } echo json_encode(['basket_count'=>$_SESSION['total_basket_count']]); }else{ echo json_encode(["err"=>"id parametresi gönderilmedi"]); }
true
10d6429f7cc8b4e80a9d88b27af38b9cbc9525fe
PHP
gwalesh/fswd-static
/index.php
UTF-8
877
3.5
4
[]
no_license
<?php // $name = 'Gwalesh Singh Panchal'; // $salary = 20000; // $incentive = 5000; // $good = 18000; // $total = $salary + $incentive; // $students = array( // 1 => "Sunny", // 2 => "Sahil", // ); // foreach ($students as $key => $st) { // echo "We have many students whose names are $st <br>"; // } // echo "Hello world from <strong>$name</strong><br>"; // echo "He gets $total every month !!"; // $sales = 500; // $purchase = 15000; // $profit = $sales-$purchase; // if ( // $sales > $purchase // ) // echo "Well done you have made a total profit of $profit"; // elseif ($sales >= $purchase) { // echo "You have made no profit and you are niether in loss"; // } // else // return myfunction(); // function myfunction() // { // echo "You have to improve your sales"; // } ?>
true
5658caeb74a6b9a12b1ea45840709324606ca8ad
PHP
crazywhalecc/WTask
/src/BlueWhale/WTask/Mods/WRobot/WRobot.php
UTF-8
2,998
2.609375
3
[ "MIT" ]
permissive
<?php namespace BlueWhale\WTask\Mods\WRobot; use BlueWhale\WTask\Mods\ModBase; use pocketmine\event\Listener; use BlueWhale\WTask\Config; use pocketmine\Utils\Utils; use pocketmine\event\player\PlayerCommandPreprocessEvent; class WRobot extends ModBase implements Listener { private $plugin; public $status; const ROBOT_API = 'c6297a8608f54e6ebb9129a26679d6c6'; const VERSION = "1.0.0"; const NAME = "WRobot"; private $sign; /** @var Config */ public $config; public function onEnable() { $this->plugin = $this->getWTask(); $desc = $this->plugin->getModule("WRobot"); $this->getCommandMap()->register("WTask", new WRobotCommand($this, $desc)); try { $this->plugin->getServer()->getPluginManager()->registerEvents($this, $this->plugin); } catch (\Throwable $e) { } @mkdir($this->plugin->getDataFolder() . "Mods/WRobot/"); $this->config = new Config($this->plugin->getDataFolder() . "Mods/WRobot/" . "config.yml", Config::YAML, array( "status" => true, "sign" => '#', "消息处理方式" => "direct", "文本前缀" => "§b", "key" => "default" )); $this->status = $this->config->get("status"); $this->sign = $this->config->get("sign"); } public function getTopMessageDirect(string $string) { try { $URL = "www.tuling123.com/openapi/api?key=" . $this->getTuringAPI() . "&info=" . $string; $info = json_decode(Utils::getURL($URL), true); return $info["text"]; } catch (\Throwable $e) { $this->getServer()->getLogger()->logException($e); } return null; } public function callAsyncTask($p, $string, $color) { $class = new TuringTask($p, $string, $color); $this->getServer()->getScheduler()->scheduleAsyncTask($class); return true; } public function onChat(PlayerCommandPreprocessEvent $event) { if ($this->status === false) return; else { $msg = $event->getMessage(); $key = substr($msg, 0, 1); if ($key == $this->sign) { $msg = substr($msg, 1); if ($this->config->get("消息处理方式") == "direct") { $event->getPlayer()->sendMessage($this->config->get("文本前缀") . $this->getTopMessageDirect($msg)); $event->setCancelled(true); } elseif ($this->config->get("消息处理方式") == "async") { $this->callAsyncTask($event->getPlayer(), $msg, $this->config->get("文本前缀")); $event->setCancelled(true); } } } } protected function getTuringAPI() { if ($this->config->get("key") == "default") { return self::ROBOT_API; } else { return $this->config->get("key"); } } }
true
4282a706f1401c8f9e059371f3f8d0ba2b860196
PHP
TungPV998/manager
/app/Transformers/PositionTransformer.php
UTF-8
657
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Transformers; use League\Fractal\TransformerAbstract; use App\Model\Position; /** * Class PositionTransformer. * * @package namespace App\Transformers; */ class PositionTransformer extends TransformerAbstract { /** * Transform the Position entity. * * @param \App\Model\Position $model * * @return array */ public function transform(Position $model) { return [ 'id' => (int) $model->id, /* place your other model properties here */ 'created_at' => $model->created_at, 'updated_at' => $model->updated_at ]; } }
true
6abf5d69acab579c532f446c91cbc6808eb5ffad
PHP
vegas-cmf/session
/src/Session/ScopeInterface.php
UTF-8
1,346
2.765625
3
[]
no_license
<?php /** * This file is part of Vegas package * * @author Slawomir Zytko <slawek@amsterdam-standard.pl> * @copyright Amsterdam Standard Sp. Z o.o. * @homepage http://vegas-cmf.github.io * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Vegas\Session; /** * * @package Vegas\Session */ interface ScopeInterface { /** * Returns the name of session namespace * * @return string */ public function getName(); /** * Returns an instance of storage where scope stores data * * @return mixed */ public function getStorage(); /** * Sets value by name * * @param $property * @param $value * @return mixed */ public function set($property, $value); /** * Returns stored value by name * * @param $property * @return mixed */ public function get($property); /** * Determines if indicated value is stored in session * * @param $property * @return mixed */ public function has($property); /** * Removes stored value by name * * @param $property */ public function remove($property); /** * Destroys session scope * * @return mixed */ public function destroy(); }
true
d5667b6bec795242a8afd8817460b5ae385836ff
PHP
AMgrade/google-geocoding-api
/src/Components/UrlBuilder.php
UTF-8
3,348
3.078125
3
[]
no_license
<?php declare(strict_types = 1); namespace McMatters\GoogleGeocoding\Components; use InvalidArgumentException; use McMatters\GoogleGeocoding\Exceptions\GeoCodingException; use McMatters\GoogleGeocoding\Exceptions\UrlLengthExceededException; use const false, true; use function array_filter, gettype, http_build_query, implode, mb_strlen, strpos; /** * Class UrlBuilder * * @package McMatters\GoogleGeocoding\Components */ class UrlBuilder { const URL_MAX_LENGTH = 8192; /** * @var string */ protected $baseUrl; /** * @var array */ protected $params; /** * @var array|string */ protected $components; /** * UrlBuilder constructor. * * @param array $params * @param array|string $components * @param bool $secure */ public function __construct( array $params, $components = [], bool $secure = true ) { $this->setBaseUrl($secure); $this->params = $params; $this->components = $components; } /** * @return string * @throws InvalidArgumentException * @throws GeoCodingException */ public function buildUrl(): string { $query[] = $this->buildComponents(); $query[] = http_build_query($this->params); $queries = implode('&', array_filter($query)); $url = "{$this->baseUrl}?{$queries}"; $this->checkUrlLength($url); return $url; } /** * @return string * @throws InvalidArgumentException */ protected function buildComponents(): string { if (empty($this->components)) { return ''; } switch (gettype($this->components)) { case 'string': return $this->buildStringComponents(); case 'array': return $this->buildArrayComponents(); } throw new InvalidArgumentException('$components must be string or array'); } /** * @return string * @throws InvalidArgumentException */ protected function buildStringComponents(): string { if (strpos($this->components, ':') === false) { throw new InvalidArgumentException( '$components must be valid string or array' ); } return strpos($this->components, 'components=') === 0 ? $this->components : "components={$this->components}"; } /** * @return string */ protected function buildArrayComponents(): string { $build = []; foreach ((array) $this->components as $key => $component) { $build[] = "{$key}:{$component}"; } return !empty($build) ? 'components='.implode('|', $build) : ''; } /** * @param bool $secure * * @return void */ protected function setBaseUrl(bool $secure = true) { $scheme = $secure ? 'https' : 'http'; $this->baseUrl = "{$scheme}://maps.googleapis.com/maps/api/geocode/json"; } /** * @param string $url * * @return void * @throws GeoCodingException */ protected function checkUrlLength(string $url) { if (mb_strlen($url) > self::URL_MAX_LENGTH) { throw new UrlLengthExceededException(); } } }
true
b4ec7eb09d2e875cb99a50bab3af152b924f7dc8
PHP
voidstone/DesignPatterns
/app/DesignPatterns/Creational/Multiton/MultitonTrait.php
UTF-8
1,317
3.1875
3
[]
no_license
<?php namespace App\DesignPatterns\Creational\Multiton; use App\DesignPatterns\Creational\Multiton\MultitonInterface; trait MultitonTrait { /** * @var array */ protected static $instances = []; /** * @var */ private $name; /** * */ private function __construct() { } /** * */ private function __clone() { } /** * */ private function __wakeup() { } // /** // * @param string $instanceName // * @return static // */ // public static function getInstance(string $instanceName): MultitonInterface // { // // TODO: Implement getInstance() method. // } /** * @param string $instanceName * @return static */ public static function getInstance(string $instanceName): MultitonInterface { if(isset(static::$instances[$instanceName])) { return static::$instances[$instanceName]; } static::$instances[$instanceName] = new static(); static::$instances[$instanceName]->setName($instanceName); return static::$instances[$instanceName]; } /** * @param $value * @return $this */ public function setName($value) { $this->name = $value; return $this; } }
true
a4a3cd81cac411885ba19d238b112722af4e15da
PHP
tkuiitfcchangbackup/POSS107G05
/action_page.php
UTF-8
2,900
2.671875
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>Mushroom Dictionary!</title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="icon" href="favicon.ico" type="image/x-icon" /> <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" /> </head> <body style="background-color:black;"> <center> <div style="width:350px;background-color:#D4E6F8;text-align:center;"> <table border="1"> <tr> <td style="width:350px;"> <table style="border:3px #FFFFFF solid;padding:5px;" rules="all" cellpadding='5';> <?php $search=$_POST["searchQuest"]; $u_name=$_POST["searchName"]; $servername = "localhost"; $username = "nicholas"; $password = "12313"; $dbname = "the_db"; $Brah="https://www.urbandictionary.com/define.php?term=".$search; $brah=str_replace(" ","+",$Brah); $url = $brah; $contents = file_get_contents($url); //如果出現中文亂碼使用下面程式碼 //$getcontent = iconv("gb2312", "utf-8",$contents); //echo $contents; $from="<div class=\"meaning\">"; $end="</div>"; function cut($file,$from,$end){ $message=explode($from,$file); $message=explode($end,$message[1]); return $message[0]; } $q=cut($contents, $from, $end); $p=strip_tags($q); if (empty($p)){ $p="Word not found..."; } ?> <?php // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO rec (user_id, word_req, word_trans) VALUES ('$u_name', '$search', '$p')"; if (mysqli_query($conn, $sql)) { echo "<br><br>"; echo "The word you are looking for 👀 is : "; echo "<h2>".$search."</h2><br>"; } else { echo "Error: ".$sql."<br>".mysqli_error($conn); } mysqli_close($conn); ?> </table> </td> </tr> </table> </div> <br> <div style="width:350px;background-color:#D4E6F8;text-align:center;"> <table border="1"> <tr> <td style="width:350px;"> <table style="border:3px #FFFFFF solid;padding:5px;" rules="all" cellpadding='5';> <?php echo "<h2>Meaning:</h2><br> ".$p; $from="<div class=\"example\">"; $end="</div>"; $q=cut($contents, $from, $end); $p=strip_tags($q); if (empty($p)){ $p="Word not found..."; } echo "<br><br><h2>Example:</h2><br> ".$p; $from="<div class=\"contributor\">"; $end="</div>"; $q=cut($contents, $from, $end); $p=strip_tags($q); if (empty($p)){ $p="Word not found..."; } echo "<br><br><h2>Contributor:</h2><br> ".$p."<br>"; ?> </table> </td> </tr> </table> </div> <br> <div style="width:350px;background-color:#D4E6F8;text-align:center;"> <table border="1"> <tr> <td style="width:350px;"> <table style="border:3px #FFFFFF solid;padding:5px;" rules="all" cellpadding='5';> <br> <a href="index.php"><h3>>>BACK TO FRONT PAGE<<</h3></a> <br> </table> </td> </tr> </table> </div> </center> </body> </html>
true
bafb2ec0f088656dfb0e0196b51023b3ad248e72
PHP
mustardandrew/muan-laravel-acl
/src/Commands/Role/DetachPermissionCommand.php
UTF-8
1,148
2.75
3
[ "MIT" ]
permissive
<?php namespace Muan\Acl\Commands\Role; use Illuminate\Console\Command; use Muan\Acl\Models\Role; /** * Class DetachPermissionCommand * * @package Muan\Acl\Commands\Role */ class DetachPermissionCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'role:detach {role : Role name} {--id=* : Permission ID} {--name=* : Permission name}'; /** * The console command description. * * @var string */ protected $description = 'Detach permission'; /** * Execute the console command. * * @return mixed */ public function handle() { $roleName = $this->argument('role'); if (! $role = Role::whereName($roleName)->first()) { $this->warn("Role {$roleName} not exists."); return 1; } $attachList = array_merge($this->option('id'), $this->option('name')); $role->detachPermission($attachList); echo "Detached permissions. Done!", PHP_EOL; return 0; } }
true
8bce7eefa128f19ecaf71d7e5fbc2c504edb4b96
PHP
ereckart/cis450FinalProj
/PHP/addToWatchList.php
UTF-8
1,230
2.53125
3
[]
no_license
<? session_start(); if (isset($_SESSION['userid'])) { $movieid = $_GET['movieid']; $userid = $_SESSION['userid']; $dbhost = 'tester.ca4um1hva9qk.us-east-1.rds.amazonaws.com'; $dbport = '3306'; $dbname = 'tester'; $charset = 'utf8' ; $username = 'cis450test'; $password = 'password'; $link = mysqli_connect($dbhost, $username, $password, $dbname, $dbport); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $query = "SELECT * FROM watchlist WHERE userid = '$userid' AND movieid = '$movieid'"; $result = mysqli_query($link, $query) or die('Error querying database.'); if (mysqli_num_rows($result) > 0) { $query = "DELETE FROM watchlist WHERE userid = '$userid' AND movieid = '$movieid';"; $result = mysqli_query($link, $query) or die('Error querying database.'); echo "Removed"; } else { $query = "INSERT INTO `watchlist` (`userid`, `movieid`) VALUES ( '$userid', '$movieid');"; $result = mysqli_query($link, $query) or die('Error querying database.2'); echo "Added"; } } else { echo "error"; } ?>
true
6b6fa2b3e1c6166ad3dbc6431a815922507b7bb4
PHP
kadnan/simpleb2b
/database/factories/ModelFactory.php
UTF-8
2,975
2.546875
3
[ "MIT" ]
permissive
<?php /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | Here you may define all of your model factories. Model factories give | you a convenient way to create models for testing and seeding your | database. Just tell the factory how a default model should look. | */ $factory->define(App\User::class, function (Faker\Generator $faker) { static $password; return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => $password ?: $password = bcrypt('secret'), 'remember_token' => str_random(10), ]; }); $factory->define(App\SellOffer::class, function (Faker\Generator $faker) { //Find User $result = DB::table('users')->where('first_name', 'Adnan')->first(); $user_id = $result->id; //constructing images Array $images = [ $faker->imageUrl(), $faker->imageUrl() ]; $color = $faker->colorName; $min_qty = ['value' => $faker->randomNumber(), 'unit' => 'ton']; $supply_ability = ['value' => $faker->numberBetween(5000, 10000), 'unit' => 'ton']; return [ 'user_id' => $user_id, 'title' => 'I want to sell ' . $color . ' BOX related to Agriculture', 'description' => $faker->text, 'images' => json_encode($images), 'keywords' => $color . ', Box', 'fob_min' => $faker->numberBetween(1, 10), 'fob_max' => $faker->numberBetween(100, 200), 'supply_ability' => json_encode($supply_ability), 'delivery' => $faker->text(20), 'package_details' => $faker->text(30), 'min_order_qty' => json_encode($min_qty), 'validity_date' => $faker->dateTimeThisMonth ]; }); $factory->define(App\Product::class, function (Faker\Generator $faker) { //$result = DB::table('pr')->truncate(); //Find User $result = DB::table('users')->where('first_name', 'Adnan')->first(); $user_id = $result->id; //constructing images Array $images = [ $faker->imageUrl(), $faker->imageUrl() ]; $color = $faker->colorName; $min_qty = ['value' => $faker->randomNumber(), 'unit' => 'ton']; $supply_ability = ['value' => $faker->numberBetween(5000, 10000), 'unit' => 'ton']; return [ 'user_id' => $user_id, 'title' => 'Product ' . $color . ' BOX related to Agriculture', 'description' => $faker->text, 'images' => json_encode($images), 'specs' => $color . ', Box', 'fob_min' => $faker->numberBetween(1, 10), 'fob_max' => $faker->numberBetween(100, 200), 'supply_ability' => json_encode($supply_ability), 'delivery' => $faker->text(20), 'package_details' => $faker->text(30), 'min_qty' => json_encode($min_qty), 'payment_type' => 'paypal', 'supply_ability' => json_encode($min_qty), ]; });
true
41bb8cc475de7ba9068355679de1ab29bc0906de
PHP
rhorber/id3rw
/src/Encoding/Iso88591.php
UTF-8
1,297
2.90625
3
[ "MIT" ]
permissive
<?php /** * Class Iso88591. * * @author Raphael Horber * @version 01.08.2019 */ namespace Rhorber\ID3rw\Encoding; /** * Implementation of EncodingInterface for 'ISO-8859-1'. * * @author Raphael Horber * @version 01.08.2019 */ class Iso88591 implements EncodingInterface { /** * Returns the encoding's code (0x00). * * @return string Code byte. * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getCode(): string { return "\x00"; } /** * Returns the encoding's name ('ISO-8859-1'). * * @return string Code byte. * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getName(): string { return "ISO-8859-1"; } /** * Returns the encoding's delimiter (0x00). * * @return string Delimiter byte(s). * @access public * @author Raphael Horber * @version 01.08.2019 */ public function getDelimiter(): string { return "\x00"; } /** * Returns whether a BOM is used with this encoding or not. * * @return false * @access public * @author Raphael Horber * @version 01.08.2019 */ public function hasBom(): bool { return false; } }
true
5142a7e204e2d26afb3fe77714acd33d7573917a
PHP
vadikdev/json_to_csv_converter
/src/Parser/Parsers/JsonParser.php
UTF-8
403
2.640625
3
[]
no_license
<?php namespace App\Parser\Parsers; use App\Parser\FileParserInterface; use Symfony\Component\HttpFoundation\File\File; class JsonParser implements FileParserInterface { public function supports(File $file): bool { return 'application/json' == $file->getMimeType(); } public function parse(File $file): iterable { return json_decode($file->getContent()); } }
true
7a3f0a2afbb851f21d1372598d64e52a97678b9e
PHP
spatie/emoji
/src/Exceptions/CouldNotDetermineFlag.php
UTF-8
339
2.6875
3
[ "MIT" ]
permissive
<?php namespace Spatie\Emoji\Exceptions; use Exception; class CouldNotDetermineFlag extends Exception { public static function countryCodeLenghtIsWrong(string $invalidCountryCode): self { return new static("`{$invalidCountryCode}` is not a valid country code. A valid country code should have two characters."); } }
true
768edfa5fd2ca111d5e08ba485da09594770f66e
PHP
emeka-osuagwu/daily_devotional_api
/app/Http/Services/NotificationService.php
UTF-8
1,299
2.671875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Services; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Guzzle\Http\Exception\ClientErrorResponseException; class NotificationService { protected $http; protected $baseUrl; public function __construct() { $this->http = new Client(); $this->baseUrl = "https://exp.host/--/api/v2/push/send"; } public function makeRequest($method, $endpoint, $data = '') { $data = json_encode($data); $requestTimeout = false; $counter = 0; do { try { $request = $this->http->request('POST', $this->baseUrl . $endpoint, [ 'headers' => [ 'Accept' => 'application/json', 'Content-Type' => 'application/json', 'accept-encoding' => 'gzip, deflate' ], 'body' => $data ]); return json_decode($request->getBody(), true); } catch (Exception $exception) { $counter++; \Log::debug('ARM API Error. Attempt No. ' . $counter); $requestTimeout = true; } } while ($requestTimeout === true && $counter < 5); throw $exception; } public function emeka($data) { return $this->makeRequest('POST', '', $data); } public function varifyPayment($data) { return $this->makeRequest('GET', 'transaction/verify/'. $data, $data); } } ?>
true
634e823f915cbb374e2ad00197e34cacdf88c56b
PHP
carlosruesta/php_doctrine_xml
/teste_atores_duplicados.php
UTF-8
526
2.71875
3
[]
no_license
<?php use Alura\Doctrine\Entity\Ator; use Alura\Doctrine\Entity\Filme; use Alura\Doctrine\Entity\Idioma; require_once 'vendor/autoload.php'; $em = (new \Alura\Doctrine\Helper\EntityManagerCreator())->criaEntityManager(); $ator1 = new Ator(null, 'Vinicius', 'Dias'); $ator2 = new Ator(null, 'Vinicius', 'Dias'); try { $em->persist($ator1); $em->persist($ator2); $em->flush(); echo "Atores gravados com sucesso"; } catch (\Exception $e) { echo "Aconteceu um erro ao gravar atores: {$e->getMessage()}"; }
true
77bd0ccb3999bb64f17804365e218e166ef41112
PHP
keruald/keruald
/omnitools/src/Debug/_register_to_global_space.php
UTF-8
369
2.625
3
[ "BSD-2-Clause" ]
permissive
<?php /* This code is intentionally left in the global namespace. */ use Keruald\OmniTools\Debug\Debugger; if (!function_exists("dprint_r")) { function dprint_r ($variable) { Debugger::printVariable($variable); } } if (!function_exists("dieprint_r")) { function dieprint_r ($variable) { Debugger::printVariableAndDie($variable); } }
true
a3804ce1a7219b6b723f18293fb41cdc99938343
PHP
peedrop/SIGC
/gerenciar/relatorios/RelatorioVendaPDF.php
UTF-8
3,338
2.625
3
[]
no_license
<?php include("../../class/Banco.php"); include("../../arquivos/mpdf/mpdf.php"); require_once '../../class/PedidoDAO.php'; require_once '../../class/PedidoProdutoDAO.php'; $mpdf = new mPDF(); $mpdf->SetDisplayMode("fullpage"); $html = "<div id='area02'> <img width = '100%' src='../../arquivos/img/cabecalho.png'> </div> "; $inicio = $_POST["inicio"]; $fim = $_POST["fim"]; $datas = '<i> • Relatório gerado entre os dias <strong>' . date("d/m/Y", strtotime($inicio)) . '</strong> e <strong>' . date("d/m/Y", strtotime($fim)) . '</strong></i>'; $html = $html . "<div id = 'area04'> <h1 class='titulo' > Vendas por Período </h1> </div> <div id='area03'> {$datas} <table class='tabela' border=1 cellspacing=0 cellpadding=2 > <thead> <tr> <th width='30%' class='corAzul'><center>Cliente</center></th> <th width='20%' class='corVermelha'><center>Produtos</center></th> <th width='15%' class='corVerde'><center>Forma de pagamento</center></th> <th width='20%' class='corVermelha'><center>Data</center></th> <th width='15%' class='corAzul'><center>Valor</center></th> </tr> </thead> <tbody>"; $pedidoDAO = new PedidoDAO(); $pedidoProdutoDAO = new PedidoProdutoDAO(); $lista = $pedidoDAO->listarEntreDatas($inicio, $fim); $formaPagamento = null; $total = 0; foreach($lista as $pedido){ $html = $html . "<tr>"; $nomeCliente = $pedido->getCliente()->getNome(); $html = $html . "<td><center>{$nomeCliente}</center></td>"; $lista = $pedidoProdutoDAO->listarPorPedidoAgrupado($pedido->getIdPedido()); $html = $html ."<td>"; foreach($lista as $pedidoProduto){ $html = $html ."{$pedidoProduto[0]} / "; } $html = $html ."</td>"; if ($pedido->getFormaPagamento() == 1){ $formaPagamento = 'Dinheiro'; } if ($pedido->getFormaPagamento() == 2){ $formaPagamento = 'Cartão'; } if ($pedido->getFormaPagamento() == 3){ $formaPagamento = 'Crediário'; } $html = $html . "<td><center>{$formaPagamento}</center></td>"; $data = date("d/m/Y", strtotime($pedido->getDataPedido())); $html = $html . "<td><center>{$data}</center></td>"; $valor = $pedido->getValor(); $html = $html . "<td><center>R$ ".number_format($valor, 2, ',', '.')."</center></td>"; $html = $html . "</tr>"; $total += $valor; } $html = $html . "<tr> <td></td> <td></td> <td></td> <td class='corVermelha'><strong><center>Total:</center></strong></td> <td><strong><center>R$ ".number_format($total, 2, ',', '.')."</center></strong></td> </tr>"; $html = $html . "</tbody> </table> </div>"; $dataEmissao = date("d/m/Y H:i:s"); $css = file_get_contents('../../arquivos/css/relatorios.css'); $mpdf->WriteHTML($css, 1); $mpdf->SetHeader(''); $mpdf->setFooter("Emissão: {$dataEmissao} | | {PAGENO} de {nb}"); $mpdf->WriteHTML($html, 2); $mpdf->Output('RelatorioVenda.pdf',I); exit(); ?>
true
4c0a95f6b02c9bfecb100fd55396e4b6247cca23
PHP
paulalcabasa/vehicle_monitoring
/ajax/get_driver_details.php
UTF-8
316
2.59375
3
[]
no_license
<?php require_once("../initialize.php"); // convert $_POST global variable to object $post = (object)$_POST; $vehicle = new Vehicle(); $carplan_details = $vehicle->getCarPlanDetails($post->employee_no); if(empty($carplan_details[0])){ echo "false"; } else { echo json_encode($carplan_details[0]); }
true
622d6eba6d2be444110d60b55679f5889a00e0ab
PHP
archaugust/terraviva
/src/AppBundle/MiscFunctions.php
UTF-8
457
2.8125
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace AppBundle; class MiscFunctions { public function slug($str) { $str = strtolower(trim($str)); $str = preg_replace('/[^a-z0-9-]/', '-', $str); $str = preg_replace('/-+/', "-", $str); if ($str == '-') $str = time(); return $str; } public function unslug($str) { $str = str_replace('-', ' ', $str); $str = ucwords(trim($str)); return $str; } }
true
2a6b3047416f70bcfc22f09483c57973467ff6a6
PHP
langrid/langrid-php-library
/commons/Choice.php
UTF-8
749
2.96875
3
[ "BSD-2-Clause" ]
permissive
<?php /** * Created by JetBrains PhpStorm. * User: tetsu * Date: 12/01/16 * Time: 23:34 * To change this template use File | Settings | File Templates. */ class Choice { // String private $choiceId; // String private $value; function __construct($choiceId, $value) { $this->setChoiceId($choiceId); $this->setValue($value); } public function setChoiceId($choiceId) { $this->choiceId = $choiceId; } public function getChoiceId() { return $this->choiceId; } public function setValue($value) { $this->value = $value; } public function getValue() { return $this->value; } }
true
122d01de68067eab97dde48cb51dfa9c4cb3250b
PHP
mochtioui/projets
/produits.php
UTF-8
853
2.734375
3
[]
no_license
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "projet_web"; $id=$_POST['id']; $nom=$_POST['nom']; $desc=$_POST['description']; $prix=$_POST['prix']; $quant=$_POST['quantite']; $categorie=$_POST['categorie']; $image=$_POST['image']; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $req="select * from produits where id='$id'"; if ($conn->query($req) === FALSE) { } else { $sql = "INSERT INTO produits (id,nom,description,prix,quantite,categorie,image) VALUES ('$id','$nom','$desc','$prix','$quant','$categorie','$image')"; if ($conn->query($sql) === TRUE) { echo "Sucess"; } else { echo "id deja existe" ; } } $conn->close(); ?>
true
7a696560546eb4c1cc91df4bb99c91fdbb9ddc11
PHP
tuancode/design-pattern
/Behavioral/Strategy/AdventureGame/src/Knight.php
UTF-8
386
2.9375
3
[]
no_license
<?php namespace AdventureGame; use AdventureGame\Weapon\AxeBehavior; /** * The Knight. */ class Knight extends AbstractCharacter { /** * Init Knight weapon. */ public function __construct() { $this->weapon = new AxeBehavior(); } /** * {@inheritdoc} */ public function fight(): string { return 'Take a kick'; } }
true
63156c52dec4bfd7229f27cfa13bd98bb781c012
PHP
Jorzel21/chat
/app/Repositories/ClienteRepository.php
UTF-8
803
2.78125
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use App\Models\Cliente; class ClienteRepository{ public function save($data){ $cliente = new Cliente(); $cliente->fill($data); $cliente->save(); return $cliente->fresh(); } public function getAll(){ $clientes = Cliente::all(); return $clientes; } public function find($id){ $cliente = Cliente::find($id); return $cliente; } public function getNome($id){ $cliente = Cliente::find($id); return $cliente->nome; } public function update($request, $id){ $cliente = Cliente::find($id); $cliente->nome = $request->nome; $cliente->doc = $request->doc; $cliente->save(); return $cliente; } }
true
6823b4b5e5496484059837f09664505797e9b3ff
PHP
khonghung/demo_6_10
/app/Http/Controllers/LoginController.php
UTF-8
1,884
2.578125
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Models\User; use App\Http\Services\LoginService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; class LoginController extends Controller { protected $loginService; public function __construct(LoginService $loginService) { $this->loginService = $loginService; } function showFormLogin() { return view('login'); } function login(Request $request) { $this->validate($request, [ 'email' => 'required|email:filter', 'password' => 'required' ]); if ($this->loginService->checkLogin($request)) { return redirect()->route('home.index'); } Session::flash('error', 'Tài khoản mật khẩu không chính xác!'); return back(); } public function logout(Request $request) { Auth::logout(); $request->session()->invalidate(); $request->session()->regenerateToken(); return redirect()->route('login'); } public function showFormChangePassword(){ return view('change-password'); } public function changePassword(Request $request){ $user = Auth::user(); $currentPassword = $user->password; $request->validate([ 'currentPassword' => 'required', 'newPassword' => 'required|min:3', 'confirmPassword' => 'required|same:newPassword', ]); if(!Hash::check($request->currentPassword, $currentPassword)){ return redirect()->back()->withErrors(['currentPassword' => 'Sai Password hiện tại ']); } $user->password = Hash::make($request->newPassword); $user->save(); return redirect()->route('login'); } }
true
0eb23d53dc81e8685f5ec0818aefa556a23a76f8
PHP
rajeevp727/PHP_Office
/addProd.php
UTF-8
3,176
2.859375
3
[]
no_license
<!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> <?php require "config/config.inc.php"; if(isset($_POST['Submit'])){ $prodName = $_POST['prodName']; $prodDesc = $_POST['prodDesc']; $prodLongDesc = $_POST['prodLongDesc']; $prodPrice = $_POST['prodPrice']; // $image = $_FILES['image']; try{ $statusMsg=""; echo 1; $tar_dir = "images/Uploads/"; echo 2; $fileName = basename($_FILES['image']['name']); echo 3; $targetFilePath = $tar_dir. $fileName; echo 4; $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION); echo 5; if(!empty($_FILES['image']['name'])){ echo 6; $allowedTypes = array('jpg', 'png', 'jpeg'); echo 7; if(in_array($fileType, $allowedTypes)){ echo 8; if(move_uploaded_file($_FILES['image']['tmp_name'], $targetFilePath)){ echo 9; $sqlImage = $conn->query("INSERT INTO products(image) VALUES ('$fileName')"); echo 10; if($sqlImage){ echo 11; $statusMsg = "File ".$fileName." is successfully uuploaded"; }else{ echo 12; $statusMsg = "File".$fileName." Could not be inserted"; echo 13; } }else{ echo 14; $statusMsg = "There was an error, try again.";} }else{ echo 15; $statusMsg = "Only the file types png jpg and jpeg ae allowed."; } $sqlInsert = "INSERT INTO products(prodName, prodDesc, prodLongDesc, prodPrice, image) VALUES('$prodName', '$prodDesc', '$prodLongDesc', '$prodPrice', '$fileName')"; $sqlBlank = "DELETE FROM products where prodName = ''"; $resInsert = mysqli_query($conn, $sqlInsert); if($resInsert){ exit; header("location: categories.php"); } else{ echo "<a href=addProd.php>try agin</a>"; } $resDel = mysqli_query($conn, $sqlBlank); if($resDel){ exit; header("location: categories.php"); } else{ echo "<a href=addProd.php>try agin</a>"; } } else{ echo "<script>alert('Please select a file to Upload');</script>"; } }catch(Exception $e){ echo $e; } } ?> <form action="#" method="post" enctype="multipart/form-data"> <input type="text" name="prodName" placeholder="Enter Product Name" required> <br> <input type="text" name="prodDesc" placeholder="Enter Product Description" required> <br> <input type="text" name="prodLongDesc" placeholder="Enter Product LOng Description" required> <br> <input type="number" name="prodPrice" placeholder="Enter product Price" required> <br> <input type="file" name="image"> <br> <button name="Submit">Submit</button> </form> </body> </html>
true
158d4597ae1628566ceba5385156bbc7a38408d5
PHP
YuhiAida/ProgramacionWebII
/panel/procesarUpload.php
UTF-8
2,076
2.65625
3
[]
no_license
<?php require_once("../database/registroCategorias.php"); require_once("../funciones.php"); if(empty($_POST["nombreCategoria"]) || empty($_POST["descripcionCategoria"]) || empty($_FILES["imagenCategoria"])){ header("Location:index.php?seccion=edit&estado=vacio"); die(); }else { $nombre = $_POST["nombreCategoria"]; $descripcion = $_POST["descripcionCategoria"]; $imagen = $_FILES["imagenCategoria"]; //Se comprueba el tipo de imagen y se asigna a la variable formato para analisar despues. if($imagen["type"] == "image/jpeg"){ $formato = "jpg"; }elseif($imagen["type"] == "image/png"){ $formato = "png"; }elseif($imagen["type"] == "image/gif"){ $formato = "gif"; }else{ //si el formato no es el indicado se redirecciona al error. header("Location:index.php?seccion=edit&estado=formato"); die(); } //si la carpeta existe se redirecciona al error. if (is_dir("../img/categoria/$nombre")) { header("Location:index.php?seccion=edit&estado=existe;"); die(); }else { //si es uno delos formatos admitidos se crea el directorio con el nombre y se guarda la descripcion y la imagen. mkdir("../img/categoria/$nombre"); file_put_contents("../img/categoria/$nombre/descripcion.txt", $descripcion); move_uploaded_file($imagen["tmp_name"], "../img/categoria/$nombre/$nombre.$formato"); } foreach ($categorias as $categoria) { if ($categoria["nombre"] == $nombre) { continue; }else { echo "<h2>Errorh2</h2>"; } } $id = ultimoId($categorias) + 1; $nuevaCategoria = [ "id" => $id, "nombre" => $nombre, "imagen" => "img/categoria/$nombre/$nombre.$formato", "descripcions" => "img/categoria/$nombre/descripcion.txt" ]; $categorias[] = $nuevaCategoria; $categoriasJSON = json_encode($categorias); file_put_contents("../database/categorias.json", $categoriasJSON); header("Location:index.php?seccion=catList&estado=realizado"); } ?>
true
0b14372047434ed51d3ea7935cdba0b107fc2bbe
PHP
gyaan/php_laravel_challenge_template
/app/Http/Controllers/CustomerController.php
UTF-8
2,406
2.6875
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Http\Requests\CreateCustomerRequest; use App\Models\Customer; use Illuminate\Http\Request; /** * Customer controller handles all requests that has to do with customer * Some methods needs to be implemented from scratch while others may contain one or two bugs. * * NB: Check the BACKEND CHALLENGE TEMPLATE DOCUMENTATION in the readme of this repository to see our recommended * endpoints, request body/param, and response object for each of these method * * Class CustomerController * @package App\Http\Controllers */ class CustomerController extends Controller { /** * Allow customers to create a new account. * * @param CreateCustomerRequest $request * @return \Illuminate\Http\JsonResponse */ public function create(CreateCustomerRequest $request) { return response()->json(['message' => 'this works']); } /** * Allow customers to login to their account. * * @return \Illuminate\Http\JsonResponse */ public function login() { return response()->json(['message' => 'this works']); } /** * Allow customers to view their profile info. * * @return \Illuminate\Http\JsonResponse */ public function getCustomerProfile(Customer $customer) { return response()->json(['status' => 'truw', 'customer' => $customer]); } /** * Allow customers to update their profile info like name, email, password, day_phone, eve_phone and mob_phone. * * @return \Illuminate\Http\JsonResponse */ public function updateCustomerProfile() { return response()->json(['message' => 'this works']); } /** * Allow customers to update their address info/ * * @return \Illuminate\Http\JsonResponse */ public function updateCustomerAddress() { return response()->json(['message' => 'this works']); } /** * Allow customers to update their credit card number. * * @return \Illuminate\Http\JsonResponse */ public function updateCreditCard() { return response()->json(['message' => 'this works']); } /** * Apply something to customer. * * @return \Illuminate\Http\JsonResponse */ public function apply() { return response()->json(['message' => 'this works']); } }
true
618cec0083380ed719e34299034bdd29b8db27e7
PHP
keshavsharma89/Loan
/models/UserSearch.php
UTF-8
2,067
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\Users; /** * OrderSearch represents the model behind the search form about `app\models\Orders`. */ class UserSearch extends Users { /** * @inheritdoc */ public function rules() { return [ [['firstName', 'lastName', 'email'], 'string', 'max' => 225], [['personalCode', 'phone', 'active', 'isDead'], 'integer'], [['createdDate', 'totalLoans', 'age'], 'safe'], [['lang'], 'string', 'max' => 100], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } public function attributes() { return array_merge(parent::attributes(), ['totalLoans']); } /** * Creates data provider instance with search query applied * @param array $params * @return ActiveDataProvider */ public function search($params) { $query = Users::find(); // add conditions that should always apply here $dataProvider = new ActiveDataProvider([ 'query' => $query, 'pagination' => [ 'pageSize' => 5, ] ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to return any records when validation fails return $dataProvider; } // grid filtering conditions $query->andFilterWhere(['LIKE', 'firstName', $this->getAttribute('firstName')]) ->andFilterWhere(['LIKE', 'lastName', $this->getAttribute('lastName')]) ->andFilterWhere(['LIKE', 'email', $this->getAttribute('email')]) ->andFilterWhere(['LIKE', 'personalCode', $this->getAttribute('personalCode')]) ->andFilterWhere(['LIKE', 'phone', $this->getAttribute('phone')]); return $dataProvider; } }
true
c2565f48bf3c7181845b941a5451d043d160c247
PHP
gvisis/bank
/public/newaccount.php
UTF-8
1,661
2.5625
3
[]
no_license
<!-- Forma resubmitinasi refreshinant --> <?php require_once __DIR__.'/../bootstrap.php'; checkIfLoggedIn(); require_once DIR.'/header.php'; require_once DIR.'/accFile.php'; $accountFile = DIR.'/../src/data/accounts.json'; $firstname = ""; $lastname = ""; $accNumb = $_SESSION['accNumb'] ?? ''; $personalID = ''; $accbalance = 0; $errors = []; if ($_SERVER['REQUEST_METHOD'] === 'POST') { require_once DIR.'/validForm.php'; } else { $accNumb = randIban(); $_SESSION['accNumb'] = $accNumb; } ?> <?php if(!empty($errors)) : ?> <div class="alert alert-danger" role="alert"> <?php foreach ($errors as $error) : ?> <div><?= $error ?></div> <?php endforeach ;?> </div> <?php endif ;?> <form action="" method="post"> <div class="mb-3"> <label class="form-label">First name</label> <input type="text" class="form-control" name='firstname' value="<?= ucfirst($firstname) ?>"> </div> <div class="mb-3"> <label class="form-label">Last name</label> <input type="text" class="form-control" name='lastname' value="<?= ucfirst($lastname) ?>"> </div> <div class="mb-3"> <label class="form-label">Account Number</label> <input type="text" readonly class="form-control" maxlength="35" name='accNumb' value="<?= $accNumb ?>"> </div> <div class="mb-3"> <label class="form-label">Personal ID number</label> <input type='text' maxlength="11" class="form-control" name='persid' value="<?= $personalID ?>"> <div class="form-text">No more than 11 symbols</div> </div> <button type="submit" class="btn btn-primary">Submit</button> <a href='<?= URL ?>' class="btn btn-secondary">Back</a> </form>
true
a868f357bb16706f49deb64db5ce3227e5d0d26b
PHP
xprt64/todosample-cqrs-es
/vendor/xprt64/code-analysis/src/Gica/CodeAnalysis/PhpClassInFileInspector.php
UTF-8
1,565
2.921875
3
[ "MIT" ]
permissive
<?php namespace Gica\CodeAnalysis; use Gica\FileSystem\FileSystemInterface; use Gica\FileSystem\OperatingSystemFileSystem; class PhpClassInFileInspector { /** * @var FileSystemInterface */ private $fileSystem; public function __construct( FileSystemInterface $fileSystem = null ) { $this->fileSystem = $fileSystem ?? new OperatingSystemFileSystem(); } /** * @param $fullFilePath * @return null|string */ public function getFullyQualifiedClassName(string $fullFilePath) { $content = $this->readFile($fullFilePath); $content = preg_replace('!/\*.*?\*/!s', '', $content); $content = preg_replace('/\n\s*\n/', "\n", $content); if (!preg_match('#class\s+(?P<className>[a-z0-9_]+)\s#ims', $content, $m)) { return null; } $unqualifiedClassName = $m['className']; if (!preg_match('#namespace\s+(?P<namespace>\S+);#ims', $content, $m)) { return null; } $namespace = $m['namespace']; if ($namespace) $namespace = '\\' . $namespace; $fqn = $namespace . '\\' . $unqualifiedClassName; if (!class_exists($fqn)) { $this->evaluateCode($content); } return $fqn; } private function readFile($fullFilePath) { return $this->fileSystem->fileGetContents($fullFilePath); } private function evaluateCode($content) { $content = str_replace('<?php', '', $content); eval($content); } }
true
ae025e1af74830150f2ecaa267ba237d32882d1c
PHP
shinichimc/IIC-Cainta-Library
/tsv_test.php
UTF-8
954
3.25
3
[]
no_license
<?php SortByMedal('medal_results.tsv'); function SortByMedal($file) { $tsv = array(); $fp = fopen($file, "r"); while (($data = fgetcsv($fp, 0, "\t")) !== FALSE) { $tsv[] = $data; } fclose($fp); //国名、金メダル、銀メダル、銅メダル、それぞれの配列を作成 foreach($tsv as $key=>$row) { $country[$key] = $row[0]; $gold[$key] = $row[1]; $silver[$key] = $row[2]; $bronze[$key] = $row[3]; } //array_multisortで配列並び替え array_multisort($gold, SORT_DESC, $silver, SORT_DESC, $bronze, SORT_DESC, $country, SORT_ASC, $tsv); $fileName = 'medal_results_sorted.tsv'; header('Content-Type: application/x-csv'); header("Content-Disposition: attachment; filename=$fileName"); $fp = fopen('php://output', 'w'); //並び替えた配列をmedal_results_sorted.tsvに出力 foreach ($tsv as $row) { fputcsv($fp, $row, "\t"); } fclose($fp); }
true
b3c4e1d91b2978f65e9b9aefe5652bd601c67d9b
PHP
programgames/DesignPattern
/src/Patterns/Structural/Flyweight/ProductFlyweight.php
UTF-8
868
3.296875
3
[]
no_license
<?php namespace Flyweight; /** * Le poids-mouche stocke une portion commune de l'état ( appelé intrinsèque ) * qui appartient a plusieurs objets métier. le poids-mouche accepte le reste de l'état ( extrinsèque ) * unique à chaque entité dans les méthodes autre que le constructeur. */ class ProductFlyweight { /** * Etat intrinsèque * @var Website */ private $website; /** * Flyweight constructor. * @param Website $website */ public function __construct(Website $website) { $this->website = $website; } public function affichageInfo($name): void { echo strtr( "Unique state : %name% - intrinsic state : %intrinsic% ", [ '%name%' => $name, '%intrinsic%' => $this->website->getName() ] ); } }
true
ebf011d456402bc9a722a3fd6bc29c29755eecf0
PHP
Kasparsu/KMS19laravel
/app/Http/Controllers/ImageController.php
UTF-8
2,070
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\Image; use Illuminate\Http\Request; use Illuminate\Http\UploadedFile; class ImageController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $validated = $request->validate([ 'file' => 'required|image|mimes:jpeg,bmp,png,jpg|max:2048' ]); $image = $validated['file']; /** @var $image UploadedFile */ $path = $image->storePublicly('/public/uploads'); $image = new Image(); $image->filename = '/storage/' . str_replace('public/', '', $path); $image->save(); return $image; } /** * Display the specified resource. * * @param \App\Models\Image $image * @return \Illuminate\Http\Response */ public function show(Image $image) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Image $image * @return \Illuminate\Http\Response */ public function edit(Image $image) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Image $image * @return \Illuminate\Http\Response */ public function update(Request $request, Image $image) { // } /** * Remove the specified resource from storage. * * @param \App\Models\Image $image * @return \Illuminate\Http\Response */ public function destroy(Image $image) { // } }
true
8a03ebc267b978a2f2f55fd2374ea6af46abc964
PHP
tibaredha/mvc
/PDF/impcomp.php
UTF-8
3,346
2.625
3
[ "MIT" ]
permissive
<?php require('DNR.php'); $pdf = new DNR( 'L', 'mm', 'A4' );$pdf->AliasNbPages();//importatant pour metre en fonction le totale nombre de page avec "/{nb}" $date=date("d-m-y"); $pdf->SetFillColor(230);//fond gris il faut ajouter au cell un autre parametre pour qui accepte la coloration $pdf->SetTextColor(0,0,0);//text noire $pdf->SetFont('Times', 'B', 11); $pdf->entetepage1('LISTE COMPAGNES DES DONS'); $h=40; $pdf->SetXY(5,$h);$pdf->cell(15,5,"IDC",1,0,'C',1,0); $pdf->SetXY(20,$h);$pdf->cell(25,5,"DATEDON",1,0,'C',1,0); $pdf->SetXY(45,$h);$pdf->cell(15,5,"WILAYA",1,0,'C',1,0); $pdf->SetXY(60,$h);$pdf->cell(60,5,"COMMUNE",1,0,'C',1,0); $pdf->SetXY(120,$h);$pdf->cell(40,5,"ADRESSE",1,0,'C',1,0); $pdf->SetXY(160,$h);$pdf->cell(20,5,"STR",1,0,'C',1,0); $pdf->SetXY(180,$h);$pdf->cell(25,5,"IND",1,0,'C',1,0); $pdf->SetXY(205,$h);$pdf->cell(25,5,"CIND",1,0,'C',1,0); $pdf->SetXY(230,$h);$pdf->cell(25,5,"MASCULIN",1,0,'C',1,0); $pdf->SetXY(255,$h);$pdf->cell(35,5,"FEMININ",1,0,'C',1,0); $pdf->SetXY(5,45); function nbrtostring($db_name,$tb_name,$colonename,$colonevalue,$resultatstring) { $db_host="localhost"; $db_user="root"; $db_pass=""; $cnx = mysql_connect($db_host,$db_user,$db_pass)or die ('I cannot connect to the database because: ' . mysql_error()); $db = mysql_select_db($db_name,$cnx) ; mysql_query("SET NAMES 'UTF8' "); $result = mysql_query("SELECT * FROM $tb_name where $colonename=$colonevalue" ); $row=mysql_fetch_object($result); $resultat=$row->$resultatstring; return $resultat; } $db_host="localhost"; $db_name="mvc"; $db_user="root"; $db_pass=""; $cnx = mysql_connect($db_host,$db_user,$db_pass)or die ('I cannot connect to the database because: ' . mysql_error()); $db = mysql_select_db($db_name,$cnx) ; mysql_query("SET NAMES 'UTF8' "); $query="select * from compagne where DATEDON >='2015-01-01' order by DATEDON "; // % %will search form 0-9,a-z $resultat=mysql_query($query); $totalmbr1=mysql_num_rows($resultat); while($row=mysql_fetch_object($resultat)) { $pdf->SetFont('Times', '', 10); $pdf->cell(15,8,trim($row->id),1,0,'C',0); $pdf->cell(25,8,trim($row->DATEDON),1,0,'C',0); $pdf->cell(15,8,trim(nbrtostring('mvc','WIL','IDWIL',$row->WILAYA,'WILAYAS')),1,0,'C',0); $pdf->SetFont('Times', '', 10); $pdf->cell(60,8,trim(nbrtostring('mvc','com','IDCOM',$row->COMMUNE,'COMMUNE')),1,0,'L',0); $pdf->SetFont('Times', '', 12); $pdf->cell(40,8,trim($row->ADRESSE),1,0,'L',0); $pdf->cell(20,8,trim($row->STR),1,0,'L',0); $pdf->cell(25,8,'',1,0,'C',0); $pdf->cell(25,8,'',1,0,'C',0); $pdf->cell(25,8,'',1,0,'C',0); $pdf->cell(35,8,'',1,0,'C',0); $pdf->SetXY(5,$pdf->GetY()+8); } $pdf->SetXY(5,$pdf->GetY());$pdf->cell(15,5,"Total",1,0,'C',1,0); $pdf->SetXY(20,$pdf->GetY());$pdf->cell(270,5,$totalmbr1." "."Compagnes",1,0,'C',1,0); $pdf->SetXY(130,$pdf->GetY()+20);$pdf->cell(60,5,"DR TIBA PTS AIN OUSSERA ",0,0,'C',0); $pdf->AddPage(); $pdf->SetFont('Arial','',10); $data = array( 'Group 1' => array( '08-02' => 2, '08-23' => 4, '09-13' => 2, '10-04' => 4, '10-25' => 2 ), 'Group 2' => array( '08-02' =>0, '08-23' => 0, '09-13' => 0, '10-04' => 0, '10-25' => 0 ) ); $colors = array( 'Group 1' => array(114,171,237), 'Group 2' => array(163,36,153) ); $pdf->LineGraph(190,100,$data,'VHkBvBgBdB',$colors,100,6); $pdf->Output();
true
2683e9416bd4f3cbb2f3bf804291f874a524d117
PHP
slickframework/cache
/tests/Driver/MemoryTest.php
UTF-8
1,603
2.609375
3
[ "MIT" ]
permissive
<?php /** * This file is part of slick/cache package * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Slick\Tests\Cache\Driver; use PHPUnit_Framework_TestCase as TestCase; use Slick\Cache\CacheItem; use Slick\Cache\Driver\Memory; /** * Memory cache driver test case * * @package Slick\Tests\Cache\Driver * @author Filipe Silva <silvam.filipe@gmail.com> */ class MemoryTest extends TestCase { /** * @var Memory */ protected $driver; /** * Sets the SUT memory driver object */ protected function setUp() { parent::setUp(); $this->driver = new Memory(); } public function testSet() { $item = new CacheItem( [ 'key' => 'test', 'data' => 'I am a value' ] ); $this->assertSame($this->driver, $this->driver->set($item)); } public function testGet() { $this->assertEquals('I am a value', $this->driver->get('test')->getData()); } public function testErase() { $this->driver->erase('test'); $item = $this->driver->get('test'); $this->assertFalse($item->isValid()); } public function testFlush() { $item = new CacheItem( [ 'key' => 'test', 'data' => 'I am a value' ] ); $this->driver->set($item); $this->driver->flush(); $item = $this->driver->get('test'); $this->assertFalse($item->isValid()); } }
true
225db8152a37577c1df9de7fa1787f7ccb2ade1e
PHP
RamilYumaev/aa_dev
/olympic/repositories/UserOlimpiadsRepository.php
UTF-8
1,934
2.6875
3
[]
permissive
<?php namespace olympic\repositories; use common\helpers\FlashMessages; use olympic\models\OlimpicList; use olympic\models\UserOlimpiads; class UserOlimpiadsRepository { public function get($id): UserOlimpiads { if (!$model = UserOlimpiads::findOne($id)) { throw new \DomainException(FlashMessages::get()["noFoundRegistrationOnOlympic"]); } return $model; } public function getOlympic($olympic_id, $user_id): UserOlimpiads { if (!$model = UserOlimpiads::findOne(['olympiads_id' => $olympic_id, 'user_id' => $user_id])) { throw new \DomainException(FlashMessages::get()["noFoundRegistrationOnOlympic"]); } return $model; } public function getUserExits($user_id): bool { return UserOlimpiads::find()->where(['user_id' => $user_id])->exists(); } public function isUserOlympic($olympic_id, $user_id): bool { return UserOlimpiads::find()->andWhere(['olympiads_id' => $olympic_id, 'user_id' => $user_id])->exists(); } public function isOlympic($olympic_id): bool { return UserOlimpiads::find()->andWhere(['olympiads_id' => $olympic_id])->exists(); } public function isOlympicUserYear($year, $user_id): bool { return UserOlimpiads::find() ->alias('uo') ->innerJoin(OlimpicList::tableName(). ' olympic', 'olympic.id = uo.olympiads_id') ->andWhere(['user_id' => $user_id]) ->andWhere(['olympic.year'=>$year]) ->exists(); } public function save(UserOlimpiads $model): void { if (!$model->save()) { throw new \RuntimeException(FlashMessages::get()["saveError"]); } } public function remove(UserOlimpiads $model): void { if (!$model->delete()) { throw new \RuntimeException(FlashMessages::get()["deleteError"]); } } }
true
c455631a809257d7469c3047139964674772e40e
PHP
smsloverss/sms99
/your-project/app/Services/MessagebirdService.php
UTF-8
978
2.890625
3
[ "MIT" ]
permissive
<?php namespace App\Services; use Illuminate\Support\Facades\Log; use MessageBird\Client; use MessageBird\Exceptions\AuthenticateException; use MessageBird\Exceptions\BalanceException; use MessageBird\Objects\Message; class MessagebirdService { protected $api; public function __construct() { $this->api = new Client(env('MESSAGEBIRD_API')); } public function sendMessage(string $originator, array $recipients, string $body): bool { $message = new Message(); $message->originator = $originator; $message->recipients = $recipients; $message->body = $body; try { $result = $this->api->messages->create($message); return true; } catch (AuthenticateException $e) { Log::debug('Your messagebird credentials are incorrect'); } catch (BalanceException $e) { Log::debug('Your balance is insufficient'); } return false; } }
true
7dfc2c8b455a7ef52a02321076c5c870ecc72f67
PHP
famfij/TP-BilletsDuLouvre
/src/AppBundle/Tests/DataFixtures/LoadTicketTypeData.php
UTF-8
4,594
2.515625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: jean FRIRY * Date: 22/11/2015 * Time: 00:29 */ namespace AppBundle\Tests\DataFixtures; use AppBundle\Entity\TicketType; use AppBundle\Entity\TicketTypeDetail; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; class LoadTicketTypeData extends AbstractFixture implements OrderedFixtureInterface { /** * Load data fixtures with the passed EntityManager * * @param ObjectManager $manager */ public function load(ObjectManager $manager) { $ticketTypes = array( array( 'name' => 'Normal', 'longDescription' => 'De 12 ans à 59 ans', 'shortDescription' => '12 à 59 ans', 'price' => 16.00, 'shown' => true, 'details' => array( array( 'number' => 1, 'ageMin' => 12, 'ageMax' => 59, ), ), ), array( 'name' => 'Enfant', 'longDescription' => 'De 4 ans à 11 ans', 'shortDescription' => '4 à 11 ans', 'price' => 8.00, 'shown' => true, 'details' => array( array( 'number' => 1, 'ageMin' => 4, 'ageMax' => 11, ), ), ), array( 'name' => 'Senior', 'longDescription' => 'A partir de 60 ans', 'shortDescription' => 'Plus de 60 ans', 'price' => 12.00, 'shown' => true, 'details' => array( array( 'number' => 1, 'ageMin' => 60, 'ageMax' => 999, ), ), ), array( 'name' => 'Réduit', 'longDescription' => 'A partir de 12 ans', 'shortDescription' => 'Plus de 12 ans', 'price' => 10.00, 'shown' => false, 'details' => array( array( 'number' => 1, 'ageMin' => 12, 'ageMax' => 999, ), ), ), array( 'name' => 'Famille', 'longDescription' => 'Famille (2 adultes et 2 enfants de même nom de famille', 'shortDescription' => 'Famille: 2adu./2enf.', 'price' => 35.00, 'shown' => true, 'details' => array( array( 'number' => 1, 'ageMin' => 12, 'ageMax' => 999, ), array( 'number' => 2, 'ageMin' => 12, 'ageMax' => 999, ), array( 'number' => 3, 'ageMin' => 4, 'ageMax' => 11, ), array( 'number' => 4, 'ageMin' => 4, 'ageMax' => 11, ), ), ), ); foreach ($ticketTypes as $type) { $ticketType = new TicketType(); $ticketType->setName($type['name']); $ticketType->setLongDescription($type['longDescription']); $ticketType->setShortDescription($type['shortDescription']); $ticketType->setPrice($type['price']); $ticketType->setShown($type['shown']); $manager->persist($ticketType); foreach ($type['details'] as $detail) { $ticketTypeDetail = new TicketTypeDetail(); $ticketTypeDetail->setNumber($detail['number']); $ticketTypeDetail->setAgeMin($detail['ageMin']); $ticketTypeDetail->setAgeMax($detail['ageMax']); $ticketType->addTicketTypeDetail($ticketTypeDetail); } } $manager->flush(); } /** * Get the order of this fixture * * @return integer */ public function getOrder() { return 1; } }
true
6c16e728584819e9c390cd5cfcaccf8fe896f2dd
PHP
TheDoctorOne/PHP-JSChart
/index.php
UTF-8
1,181
2.546875
3
[ "MIT" ]
permissive
<html> <table style='width:100%;height:100%;'> <tr> <td style='width:20%'> <?php $fileList = scandir("/xampp/htdocs/ChartJS/data"); foreach($fileList as $file) { if(!($file == "." || $file == "..")){ echo "<span style=\"cursor:pointer;\" onclick=\"changePage('" . $file . "',this)\">"; echo $file; echo "</span><br>"; } } ?> </td> <td style='width:80%;height:100%;'> <iframe id="chartPage" src="" style="width:80%;height:100%"></iframe> </td> </tr> </table> <script> var oldMe = null; function changePage(msg,me) { if(oldMe==null) { oldMe=me; } oldMe.style.color = "black"; me.style.color = "red"; oldMe = me; document.getElementById("chartPage").outerHTML = "<iframe id='chartPage' src='chart.php?name=" + msg + "' style='width:80%;height:100%'></iframe>"; } </script> </html>
true
871f57a23dcb15b8193187c9641d377e33d94bc8
PHP
firebus/design-patterns
/Ndleton/SchroedingersNdleton.php
UTF-8
3,254
3.015625
3
[]
no_license
<?php namespace Firebus\DesignPatterns\Ndleton; /** * In a Schroedinger's Ndleton getInstance() will either return an instance or a null. * * There is no way of knowing if the $instanceContainer contains instances or nulls until you call getInstance() and "open the * box". A naive physicist might argue that the container has *both* instances AND nulls until getInstance() is called. This is * clearly absurd, thus this Ndleton is excellent for use cases that require a refutation of the Copenhagen Interpretation. * * The details of Schroedinger's experiment are ambiguous for lengths of time shorter or longer than an hour. We'll assume that * the machine of death contains a single atom, of a substance that undergoes exponential decay, with a half-life set by a class * constant. * * http://en.wikipedia.org/wiki/Schr%C3%B6dinger%27s_cat * One can even set up quite ridiculous cases. A cat is penned up in a steel chamber, along with the following device (which must * be secured against direct interference by the cat): in a Geiger counter, there is a tiny bit of radioactive substance, so small * that perhaps in the course of the hour, one of the atoms decays, but also, with equal probability, perhaps none; if it happens, * the counter tube discharges, and through a relay releases a hammer that shatters a small flask of hydrocyanic acid. If one has * left this entire system to itself for an hour, one would say that the cat still lives if meanwhile no atom has decayed. The * psi-function of the entire system would express this by having in it the living and dead cat mixed or smeared out in equal * parts. It is typical of these cases that an indeterminacy originally restricted to the atomic domain becomes transformed into * macroscopic indeterminacy, which can then be resolved by direct observation. That prevents us from so naively accepting as * valid a "blurred model" for representing reality. In itself, it would not embody anything unclear or contradictory. There is a * difference between a shaky or out-of-focus photograph and a snapshot of clouds and fog banks. */ abstract class SchroedingersNdleton extends AbstractNdleton { protected static $halfLife = 3600; // One hour by default const ATOM_COUNT = 1; /** @var float $startTime A microtimestamp */ protected static $startTime = null; protected static $isDead = false; public static function getInstance($className) { if (is_null(self::$startTime)) { self::$startTime = microtime(true); } if (self::$isDead || self::openTheBox()) { return null; } else { return parent::getInstance($className); } } /** * Calculate the probabilty of decay since $startTime * http://en.wikipedia.org/wiki/Half-life#Formulas_for_half-life_in_exponential_decay */ protected static function openTheBox() { $now = microtime(true); $diff = $now - self::$startTime; $probability = self::ATOM_COUNT * pow(0.5, $diff / self::$halfLife); // TODO: This needs to vary between 0 and ATOM_COUNT $random = mt_rand() / mt_getrandmax(); if ($probability < $random) { self::$isDead = true; return true; } else { return false; } } public static function setHalfLife($seconds) { self::$halfLife = $seconds; } }
true
ae3a290ae3a183b51b35cbea5c8ba0937ba62896
PHP
sunil209/mvc_Iinsta
/wp-content/themes/instapagev3/v5/components/v70/feature-repeater/templates/tile.php
UTF-8
1,902
2.703125
3
[]
no_license
<?php /** * Template file. Template params are stored in $params array * * @param string $sectionTitle Title of the section. * @param string $sectionSubtitle Subtitle of the section. * @param array $repeater Array of features to loop over, each containing: * string $icon Link to an svg icon * string $title Title of a feature. * string $url URL to a related page to follow. * string $url_text Text to represent the URL to follow. * * @example Default * Component::render('feature-repeater', 'tile'); * * @endexample */ use Instapage\Classes\Component; if (empty($repeater)) { return; } ?> <section class="v7 v7-mt-80 v7-content"> <?php if (!empty($sectionTitle)) { Component::dumbRender('division-header', [ 'title' => $sectionTitle, 'subtitle' => $sectionSubtitle, 'class' => 'v7-mb-40 v7-mb-md-50' ]); } ?> <div class="v7-box <?= esc_attr($repeaterLayout) ?>"> <?php foreach ($repeater as $feature) : ?> <div class="v7-feature-in-tile"> <img class="v7-mt-5" src="<?= esc_url($feature['icon']) ?>" alt="<?= esc_attr($feature['title']) ?>" /> <div class="v7-ml-20"> <h4 class="v7-mb-10 v7-feature-in-tile-title"><?= esc_html($feature['title']) ?></h4> <?php if (!empty($feature['url'])) : Component::render( 'button', [ 'url' => $feature['url'], 'class' => 'v7-btn v7-btn-flat', 'text' => $feature['url_text'] ] ); endif ?> </div> </div> <?php endforeach; ?> </div> </section>
true
274b524f525266a787ae449d57090743d8f5596e
PHP
Repflez/osu-card
/public/osu.php
UTF-8
1,955
2.71875
3
[ "BSD-2-Clause" ]
permissive
<?php // Your app's name $appName = 'osu!card'; // Your app's URL $appURL = 'http://example.com'; // Your app's version number $appVersion = '1.0'; // Your e-mail (This is sent to the server) $appEmail = 'example@example.com'; // Your osu! API Key $apiKey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // osu!APIlib path in the server $apiPath = '/path/to/osucard'; // osu!'s API URL (Don't modify this unless osu! changes URL) $osuPath = 'https://osu.ppy.sh/api/'; // Include osu!api.php include_once( $apiPath . '/osu!api.php' ); // Include Card Framework include_once( $apiPath . '/card.php' ); // Load modes depending og the get string. if (!isset($_GET['get'])||$_GET['get']==''||empty($_GET['get'])) make_error(); // Show Error if ($_GET['debug']=='very') $rawStats = true; // Raw Stats if ($_GET['get']=='user') include_once( $apiPath . '/mode/user.php' ); // User Card elseif ($_GET['get']=='userbar') include_once( $apiPath . '/mode/userbar.php' ); // Userbar else make_error(); // Show Error // Show raw data. if ($rawStats) { // Escape HTML in the data array. // http://php.net/htmlspecialchars#45340 function recurse_array_HTML_safe(&$arr) { foreach ($arr as $key => $val) if (is_array($val)) recurse_array_HTML_safe($arr[$key]); else $arr[$key] = htmlspecialchars($val, ENT_QUOTES); } echo 'osu! Data Obtained:<br /><pre>````<br />'; recurse_array_HTML_safe($data); print_r($data); echo '````</pre><br />Raw Data:<br /><pre>'; echo htmlspecialchars($result, ENT_QUOTES); echo '</pre>'; die(); } send_image($img); destroy_image($img); ?>
true
be16773eb74315de816ae640973babe2e549b275
PHP
faresouerghi98/snack-fit
/front/view/event/SMS.php
UTF-8
1,104
2.75
3
[]
no_license
<?php /** * */ class SMS { public static function send($from_number,$sms_text) { $key="1e36922a"; $secret="yWs8iZL4bJCwxq7k"; $to_number="21654855094"; return self::cspd_send_nexmo_sms($key,$secret,$to_number,$from_number,$sms_text); } public static function cspd_send_nexmo_sms($key,$secret,$to_number,$from_number,$sms_text) { $data=[ 'api_key' => $key, 'api_secret' => $secret, 'to' => $to_number, 'from' => $from_number, 'text' => $sms_text ]; $options = array( 'http' => array( 'method' => 'POST', 'content' => json_encode( $data ), 'header'=> "Content-Type: application/json\r\n" . "Accept: application/json\r\n" ) ); $url="https://rest.nexmo.com/sms/json"; $context = stream_context_create( $options ); $result = file_get_contents( $url, false, $context ); $response = json_decode( $result ); return $response; } } //var_dump(SMS::send("test","bla")) ; ?>
true
00acb4c541c45cb1740c0cb9e0be6ca605c5c393
PHP
SofaKingCool/Webradio-API
/service/MP3Library.php
UTF-8
1,747
3.09375
3
[ "MIT" ]
permissive
<?php class MP3Library { public function search($query) { $number = rand(1, 8); $url = "http://cn{$number}.mp3li.org/audio.search/?"; $url .= http_build_query([ "query" => $query, "format" => "json", ]); $body = json_decode(file_get_contents($url)); $results = []; foreach ($body->result->items as $song) { $results[] = [ "id" => $song->hash, "title" => $song->track . " - " . $song->artist, "duration" => $song->length, ]; } return $results; } public function url($hash) { $number = rand(1, 8); $url = "http://cn{$number}.mp3li.org/audio.getlinks/?"; $url .= http_build_query([ "hash" => $hash, "format" => "json", ]); $body = json_decode(file_get_contents($url)); $direct = []; $ported = []; // There are two kind types: "d" (direct?) and "p" (ported)? foreach ($body->result as $source) { if ($source->kind != "d") { $ported[] = $source->url; } else { $direct[] = $source->url; } } // Try to find a healthy direct link foreach ($direct as $url) { if (alive($url)) { return $url; } } // Otherwise try to find a working ported link foreach ($ported as $url) { $body = json_decode(file_get_contents($url)); if ($body && isset($body->result) && alive($body->result->url)) { return $body->result->url; } } return false; } }
true
feb4bb6c9c74283227eb16a60e8d8aa2b95be699
PHP
Nitneuk-zz/training-api-platform
/src/DataPersister/CarPersister.php
UTF-8
1,237
2.53125
3
[]
no_license
<?php declare(strict_types=1); namespace App\DataPersister; use ApiPlatform\Core\DataPersister\DataPersisterInterface; use App\Entity\Car; use Symfony\Bridge\Doctrine\RegistryInterface; use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Serializer\Encoder\XmlEncoder; use Symfony\Component\Serializer\SerializerInterface; class CarPersister implements DataPersisterInterface { private $registry; private $serializer; private $fileSystem; public function __construct(RegistryInterface $registry, SerializerInterface $serializer) { $this->registry = $registry; $this->serializer = $serializer; $this->fileSystem = new Filesystem(); } public function supports($data): bool { return $data instanceof Car; } public function persist($data): Car { $em = $this->registry->getEntityManager(); $em->persist($data); $em->flush(); $this->fileSystem->dumpFile(\sprintf('../data/car_%d.xml', $data->getId()), $this->serializer->serialize($data, XmlEncoder::FORMAT)); return $data; } public function remove($data): void { throw \BadMethodCallException('You cannot delete a car.'); } }
true
7cf310c484f997e4e5258cf23bcef2732068b2db
PHP
qwibit/testjob
/php/src/Database.php
UTF-8
1,268
3.15625
3
[]
no_license
<?php namespace src; class Database { /** * @var DI */ private $di; /** * @var \PDO */ private $link; /** * @param \src\DI $di */ public function __construct(DI $di) { $this->di = $di; $this->connect(); } /** * @return $this */ private function connect() { $dbConfig = $this->di->get('config')['db']; $dsn = 'mysql:'; $dsn .= 'host=' . $dbConfig['host'] . ';'; $dsn .= 'dbname=' . $dbConfig['dbname'] . ';'; $dsn .= 'charset=' . $dbConfig['charset']; $this->link = new \PDO( $dsn, $dbConfig['username'], $dbConfig['password'] ); return $this; } /** * @param string $sql * @return array */ public function query($sql) { $sth = $this->link->prepare($sql); $sth->execute(); $result = $sth->fetchAll(\PDO::FETCH_ASSOC); if ($result === false) { return []; } return $result; } /** * @param string $sql * @return bool */ public function execute($sql) { $sth = $this->link->prepare($sql); return $sth->execute(); } }
true
7af9a710fcbb9414610ce9111d03ad10e3db5022
PHP
zhanzhaopeng1/yaf-support
/tests/SignTest.php
UTF-8
721
2.765625
3
[]
no_license
<?php namespace Yaf\Support\Test; class SignTest { public function testAes() { $content = json_encode(['name' => 'test', 'age' => 20]); $key = '123456789'; $encryptMethod = 'AES-128-CBC'; $ivLength = openssl_cipher_iv_length($encryptMethod); $iv = openssl_random_pseudo_bytes($ivLength, $isStrong); if (false === $iv && false === $isStrong) { die('IV generate failed'); } $res = base64_encode(openssl_encrypt($content, $encryptMethod, $key, 1,$iv)); var_dump(rtrim(openssl_decrypt(base64_decode($res), $encryptMethod, $key, 1, $iv), "\x00..\x1F")); } } $s = new SignTest(); $s->testAes();
true
f975db722de24354ddd13dfb2da8ab47e5ab2597
PHP
rjbijl/mapscript-doc-parser
/src/Model/ArgumentModel.php
UTF-8
731
3.09375
3
[ "MIT" ]
permissive
<?php namespace Rjbijl\Model; /** * Rjbijl\Model\ArgumentModel * * @author Robert-Jan Bijl <robert-jan@prezent.nl> */ class ArgumentModel { /** * @var string */ private $name; /** * @var string */ private $type; /** * ArgumentModel constructor. * @param string$name * @param string $type */ public function __construct($name, $type) { $this->name = $name; $this->type = $type; } /** * Getter for name * * @return string */ public function getName() { return $this->name; } /** * Getter for type * * @return string */ public function getType() { return $this->type; } }
true
3c5b9abfc6f2f4eb37413c6a88b7cc4f1da208c5
PHP
oleg-nyc/task-app
/task/models/UserAction.php
UTF-8
2,823
2.984375
3
[]
no_license
<?php require_once "UserDB.php"; require_once __DIR__ . "/../settings.php"; class UserAction { protected $db; protected $min_lvl = MIN_ACC_LVL; public function __construct(PDO $db) { $this->db = $db; $this->sess = $sess; } private function unserializesession($data) { $vars = preg_split('/([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff^|]*)\|/',$data,-1,PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); for( $i=0; $vars[$i]; $i++ ) $result[$vars[$i++]] = unserialize($vars[$i]); return $result; } private function read($row) { $result = new User(); $result->id = $row["id"]; $result->name = $row["name"]; $result->email = $row["email"]; $result->task = $row["task"]; $result->done = $row["done"] == 1 ? true : false; return $result; } private function lvl($sid=0) { $lvl = 1; $file = session_save_path() . 'sess_' . $sid; if(file_exists($file)) { $sess = $this->unserializesession(file_get_contents($file)); $lvl = $sess['lvl']; } return $lvl; } public function getById($id) { $q = $this->db->prepare("SELECT * FROM tasks WHERE id = :id"); $q->bindParam(":id", $id, PDO::PARAM_INT); $q->execute(); $rows = $q->fetchAll(); return $this->read($rows[0]); } public function getAll() { $q = $this->db->prepare("SELECT * FROM tasks"); $q->execute(); $rows = $q->fetchAll(); $result = array(); foreach($rows as $row) { array_push($result, $this->read($row)); } return $result; } public function insert($data) { $q = $this->db->prepare("INSERT INTO tasks (name, email, task) VALUES (:name, :email, :task)"); $q->bindParam(":name", $data["name"]); $q->bindParam(":email", $data["email"]); $q->bindParam(":task", $data["task"]); $q->execute(); return $this->getById($this->db->lastInsertId()); } public function update($data,$sid) { if( $this->lvl($sid) >= MIN_ACC_LVL ) { if($data) { $q = $this->db->prepare("UPDATE tasks SET name = :name, email = :email, task = :task, done = :done WHERE id = :id"); $q->bindParam(":name", $data["name"]); $q->bindParam(":email", $data["email"]); $q->bindParam(":task", $data["task"]); $q->bindParam(":done", $data["done"]); $q->bindParam(":id", $data["id"], PDO::PARAM_INT); $q->execute(); } return true; } else return false; } public function remove($id,$sid) { if( $this->lvl($sid) >= MIN_ACC_LVL ) { if($id) { $q = $this->db->prepare("DELETE FROM tasks WHERE id = :id"); $q->bindParam(":id", $id, PDO::PARAM_INT); $q->execute(); } return true; } else return false; } } ?>
true
a68980db9e0c18d555b9ee8266c860693f5c253a
PHP
IvanGonzalezMartin/Inventario
/src/Application/User/LogIn/UserLogInCommand.php
UTF-8
677
2.890625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: programador * Date: 28/05/18 * Time: 14:28 */ namespace App\Application\User\LogIn; class UserLogInCommand { private $anyThing; private $password; /** * UserLogInCommand constructor. * @param $anyThing * @param $password */ public function __construct($anyThing, $password) { $this->anyThing = $anyThing; $this->password = $password; } /** * @return mixed */ public function anyThing() { return $this->anyThing; } /** * @return mixed */ public function password() { return $this->password; } }
true
5eaf634df4f921e78588aaaf711f9867584e7ee6
PHP
cyonder/StudentValley-PHP-New
/signup.php
UTF-8
7,435
2.578125
3
[]
no_license
<?php ob_start(); session_start(); require_once("./include/header-global-2.php"); $error_message = "none"; $user_first_name = NULL; $user_last_name = NULL; $user_email = NULL; $user_re_email = NULL; $user_password = NULL; $pass = 0; if($_POST){ $result = user_exist($dbConnection, $_POST['email']); if($result){ $error = "<p class='message-title'>Email Already Exist</p> <p>Sorry, the email you tried belongs to an existing account. If it is you, <a href='/login'><b>try to log in</b></a> or if you forgot your password <a href='/forgot'><b>try to reset</b></a>.</p>"; $error_message = "block"; }else{ /* FIRST NAME */ if(!empty($_POST['first_name'])){ if(preg_match("/^[a-zA-Z]+$/", $_POST['first_name'])){ $user_first_name = trim(mysqli_real_escape_string($dbConnection, $_POST['first_name'])); $pass++; }else{ $first_name_error = "First name can contain only letters"; } }else{ $first_name_error = "Please enter your first name"; } /* LAST NAME */ if(!empty($_POST['last_name'])){ if(preg_match("/^[a-zA-Z]+$/", $_POST['last_name'])){ $user_last_name = trim(mysqli_real_escape_string($dbConnection, $_POST['last_name'])); $pass++; }else{ $last_name_error = "Last name can contain only letters"; } }else{ $last_name_error = "Please enter your last name"; } /* EMAIL */ if(!empty($_POST['email'])){ if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){ /* RE-EMAIL */ if(!empty($_POST['re_email']) && ($_POST['email'] == $_POST['re_email'])){ $user_email = trim(mysqli_real_escape_string($dbConnection, $_POST['email'])); $pass++; }else{ $email_error = "Email address does not match"; } }else{ $email_error = "Invalid email address"; } }else{ $email_error = "Please enter both email "; } /* PASSWORD */ if(!empty($_POST['password'])){ if(strlen($_POST['password']) >= 6){ $user_password = crypt(trim(mysqli_real_escape_string($dbConnection, $_POST['password']))); $pass++; }else{ $password_error = "Password should be at least 6 characters long"; } }else{ $password_error = "Please enter your password"; } /* REGISTRATION DATE */ $user_registration_date = date("Y-m-d H:i:s"); if($pass == 4){ //If pass is 5, it means form is validated. echo "<script>alert('Registration system is close!\\nStudent Valley is under maintenance.');</script>"; //UN-COMMENT BELOW SECTION TO MAKE USER REGISTRATION ACTIVE. // $query = "INSERT INTO USERS("; // $query .= "USER_FIRST_NAME, USER_LAST_NAME, USER_EMAIL, USER_PASSWORD, USER_REGISTRATION_DATE"; // $query .= ")VALUES("; // $query .= "'{$user_first_name}', '{$user_last_name}', '{$user_email}', '{$user_password}', '{$user_registration_date}'"; // $query .= ")"; // // $result = mysqli_query($dbConnection, $query) or die(mysqli_error($dbConnection)); // if(!$result){ // $error = "<p class='message-title'>Oops! Something Went Wrong</p> // <p>We were not able to sign you up for Student Valley. Please try to sign up again. // If you are seeing this message for the second time, <a href='/contact'><b>contact us</b></a> with the email you tried to sign up // and the following error code inside the email content.</p> // <p><b>Error Code: 1003</b></p>"; // $error_message = "block"; // }else{ //Registration is successful. Create a row for the user in settings table. // $user_id = return_user_id($dbConnection, $user_email); // // $query = "INSERT INTO SETTINGS("; // $query .= "SETTING_USER, SETTING_FREEZE, SETTING_EMAIL_DISPLAY"; // $query .= ")VALUES("; // $query .= "'{$user_id}', 'No', 'Login Email'"; // $query .= ")"; // // mysqli_query($dbConnection, $query) or die(mysqli_error($dbConnection)); // // $_SESSION['email'] = $user_email; // header("Location: /dashboard"); // } }else{ $error_message = "block"; } } } ?> <div id="body-lsfr"> <div id="body-wrapper"> <div id="form"> <div id="form-title">Student Valley Sign Up</div> <div id="error" style="display:<?php echo $error_message; ?>"> <div id="error-wrapper"> <span <?php if(!isset($error)) echo "style='display:none'";else echo "style='background: none; padding-left: 0;'"; ?>><?php echo $error; ?></span> <span <?php if(!isset($first_name_error)) echo "style='display:none'"; ?>><?php echo $first_name_error; ?></span> <span <?php if(!isset($last_name_error)) echo "style='display:none'"; ?>><?php echo $last_name_error; ?></span> <span <?php if(!isset($email_error)) echo "style='display:none'"; ?>><?php echo $email_error; ?></span> <span <?php if(!isset($password_error)) echo "style='display:none'"; ?>><?php echo $password_error; ?></span> </div> </div> <div id="form-wrapper"> <div class="logo"></div> <form action="/signup" method="post" name="signup-form"> <label for="first_name">First Name</label> <input type="text" class="input-box" id="first_name" name="first_name" value="<?php echo $user_first_name ?>"> <label for="last_name">Last Name</label> <input type="text" class="input-box" id="last_name" name="last_name" value="<?php echo $user_last_name ?>"> <label for="email">Email</label> <input type="email" class="input-box" id="email" name="email" value="<?php echo $user_email ?>"> <label for="re_email">Re-enter Email</label> <input type="email" class="input-box" id="re_email" name="re_email" value="<?php echo $user_re_email ?>"> <label for="password">Password</label> <input type="password" class="input-box" id="password" name="password"> <div id="buttons"> <input type="submit" class="button" name="submit" value="Sign Up"> <a class="link" href="/login"><span>Log into an existing account</span></a> </div> </form> </div> </div> </div> </div> <?php require_once("./include/footer.php"); ?>
true
ea15abed787013c3f8ab92fbaf92a9ad286401a5
PHP
turkprogrammer/php-objects-patterns-practice-5-rus
/src/ch11/batch05/Observable.php
UTF-8
262
2.59375
3
[]
no_license
<?php declare(strict_types=1); namespace vitaliyviznyuk\popp5rus\ch11\batch05; /* Листинг 11.24 */ interface Observable { public function attach(Observer $observer); public function detach(Observer $observer); public function notify(); }
true
1ecdf0d60d0e67930d54e6975147895808ef429d
PHP
Mefyros/e-commerce
/back/app/Http/Controllers/TransporterController.php
UTF-8
3,711
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Transporter; class TransporterController extends Controller { // public function create(Request $request){ $toPush = $this->parseFromFront($request->all()); return Transporter::create([ 'name' => $toPush['name'], 'base_cost' => json_encode($toPush['base_cost']), 'extra' => json_encode($toPush['extra']), 'disponibility' => json_encode($toPush['disponibility']), 'delivery_delay' => $toPush['delivery_delay'], 'per_product' => $toPush['per_product'], 'blacklist' => json_encode($toPush['blacklist']) ]); } public function delete($id){ $transporter = Transporter::find($id); if(null !== $transporter){ $transporter->delete(); } else { return ['err' => 'transporter not found']; } } public function update($id, Request $request){ $transporter = Transporter::find($id); if(null !== $transporter){ $toPush = $this->parseFromFront($request->all()); $transporter->name = $toPush['name']; $transporter->base_cost = json_encode($toPush['base_cost']); $transporter->extra = json_encode($toPush['extra']); $transporter->blacklist = json_encode($toPush['blacklist']); $transporter->per_product = $toPush['per_product']; $transporter->delivery_delay = $toPush['delivery_delay']; $transporter->disponibility = json_encode($toPush['disponibility']); $transporter->save(); return $transporter; } return ['err' => 'transporter not found']; } public function getAll(){ $temp = []; foreach(Transporter::all() as $transporter){ $temp[] = $this->parseToFront($transporter); } return $temp; } public function readOne($id){ $transporter = Transporter::find($id); if(null !== $transporter){ return $this->parseToFront($transporter); } return ['err' => 'transporter not found']; } public function parseToFront($transporter){ $temp = []; foreach(json_decode($transporter->base_cost) as $weight => $value){ $temp['base_cost'][] = ['weight' => $weight, 'base_cost' => $value]; } foreach(json_decode($transporter->extra) as $pays => $multiplier){ if($multiplier !== null){ $temp['extra'][] = ['pays' => $pays, 'multiplier' => $multiplier]; } else { $temp['extra'] = null; } } $temp['blacklist'] = json_decode($transporter->blacklist); $temp['disponibility'] = json_decode($transporter->disponibility); $temp['id'] = $transporter->id; $temp['delivery_delay'] = $transporter->delivery_delay; $temp['per_product'] = $transporter->per_product; $temp['name'] = $transporter->name; return $temp; } public function parseFromFront($request){ $temp = []; foreach($request as $key => $value){ switch($key){ case 'base_cost': foreach($request['base_cost'] as $b){ $temp['base_cost'][$b['weight']] = $b['base_cost']; } break; case 'extra': foreach($request[$key] as $p){ $temp[$key][$p['pays']] = $p['multiplier']; } break; default: $temp[$key] = $value; } } return $temp; } }
true
5c5f42682f550dfc71dd5389aeb088e216d0b3db
PHP
luclanet/Twitter
/libraries/twitter_tags.php
UTF-8
4,760
2.828125
3
[]
no_license
<?php class Twitter_Tags extends TagManager { /** * Tags declaration * To be available, each tag must be declared in this static array. * * @var array * */ public static $tag_definitions = array ( // <ion:twitter:tweets /> calls the method tag_tweets "twitter:tweets" => "tag_tweets", "twitter:tweets:tweet" => "tag_tweet" ); /** * Base module tag * The index function of this class refers to the <ion:#module_name /> tag * In other words, this function makes the <ion:#module_name /> tag * available as main module parent tag for all other tags defined * in this class. * * @usage <ion:twitter > * ... * </ion:twitter> * */ public static function index(FTL_Binding $tag) { $str = $tag->expand(); return $str; } /** * Loops through tweets * * @param FTL_Binding $tag * @return string * * @usage <ion:twitter:tweets max="#num" > * ... * </ion:twitter:tweets> * */ public static function tag_tweets(FTL_Binding $tag) { // Model load self::load_model('twitter_tweets_model', 'tweets_model'); self::load_model('twitter_user_model', 'twitter_user_model'); $users = self::$ci->twitter_user_model->get_list(); foreach ($users as $user){ /* De la bdd obtenemos el "ultima_actualizacion*/ $lastupdate = $user['lastupdate']; /*No last update*/ $needs_update = false; if ($lastupdate != null){ /*Calculamos el delta de actualizacion*/ $timedifference = time() - $lastupdate; $max_time_difference = $user['max_time_difference']; /* Si ambas difieren por mas de el valor de "actualización" */ if ($timedifference > $max_time_difference){ $needs_update = true; } }else{ $needs_update = true; } if ($needs_update){ /*Curl is -REQUIRED- by twitteroauth*/ require_once('twitteroauth-master/twitteroauth/twitteroauth.php'); /* Get user access tokens out of the session. */ $access_token = $user['accesstoken']; $access_token_secret = $user['accesstokensecret']; $consumer_key = $user['consumerkey']; $consumer_secret = $user['consumersecret']; /* Create a TwitterOauth object with consumer/user tokens. */ $connection = new TwitterOAuth($consumer_key, $consumer_secret, $access_token, $access_token_secret); /* If method is set change API call made. */ $content = $connection->get('statuses/user_timeline'); /*save tweets in model*/ self::$ci->twitter_user_model->update_user($user['id_user'], $content); } } // Returned string $str = ''; $max = $tag->getAttribute('max'); $limit = 20; if (! is_null($max)){ $limit = $max + 0; } // Tweets array $conds = array( 'order_by' => 'id_tweet DESC', 'limit' => $limit ); $tweets = self::$ci->tweets_model->get_list($conds); foreach($tweets as $tweet) { // Set the local tag var "tweet" $tag->set('tweet', $tweet); // Tag expand : Process of the children tags $str .= $tag->expand(); } return $str; } /** * Tweet tag * * @param FTL_Binding Tag object * @return String Tag attribute or '' * * @usage <ion:twitter:tweets> * <ion:tweet field="id_user|id_tweet|screen_name|userurl|text" /> * </ion:twitter:tweets> * */ public static function tag_tweet(FTL_Binding $tag) { // Returns the field value or NULL if the attribute is not set $field = $tag->getAttribute('field'); if ( ! is_null($field)) { $tweet = $tag->get('tweet'); if ( ! empty($tweet[$field])) { return self::output_value($tag, $tweet[$field]); } // Here we have the choice : // - Ether return nothing if the field attribute isn't set or doesn't exist // - Ether silently return '' return self::show_tag_error( $tag, 'The attribute <b>"field"</b> is not set' ); // return ''; } } }
true