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
7934343d96f97967578f1c0664ac0756880c03fb
PHP
PratikumWebDasar4101/tamimodul6-irfanfazri16
/db2/register.php
UTF-8
1,877
2.859375
3
[]
no_license
<?php require_once("config.php"); if(isset($_POST['register'])){ $name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING); $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING); $password = password_hash($_POST["password"], PASSWORD_DEFAULT); $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); $sql = "INSERT INTO users (name, username, email, password) VALUES (:name, :username, :email, :password)"; $stmt = $db->prepare($sql); $params = array( ":name" => $name, ":username" => $username, ":password" => $password, ":email" => $email ); $saved = $stmt->execute($params); if($saved) header("Location: login.php"); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title></title> </head> <body > <form action="" method="POST"> <table> <tr><td><h1>Silahkan daftarkan diri anda</td></tr> <tr><td>Nama Lengkap <td><input type="text" name="name" placeholder="Nama kamu" /> <tr><td>Username <td><input type="text" name="username" placeholder="Username" /> <tr><td>Email <td><input type="email" name="email" placeholder="Alamat Email" /> <tr><td>Password <td><input type="password" name="password" placeholder="Password" /> <tr><td><input type="submit" name="register" value="Daftar" /> </form> </body> </html>
true
d1133eb02f7bafdce4f8d1a87d06ac2f270507fa
PHP
ytteroy/airtel.airshop
/application/modules/cwservers/models/cwservers_model.php
UTF-8
4,386
2.609375
3
[]
no_license
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Cwservers_model extends CI_Model { /** * Main variables */ public $table_structure = array(); public $sql_services_table = NULL; /** * Class constructor */ public function __construct() { parent::__construct(); // Loading database from config $this->load->database($this->config->item($this->module->active_module), FALSE, TRUE); // Load table structure $this->table_structure = $this->config->item($this->module->active_module.'_table_structure'); // Private actions initialization $this->individual_init(); } public function individual_init() { // Get name of services table $this->sql_services_table = $this->config->item('cwservers_sql_table'); } private function get_expired_servers($table_name) { $current_time = time(); $q = $this->db->where('expires <', $current_time) ->where('expires !=', 0) ->get($table_name); if($q->num_rows() > 0) { return $q->result(); } } public function clear_expired($table_name) { // Get all expired serverss $expired_servers = $this->get_expired_servers($table_name); // If there is at least one expired server if(count($expired_servers) > 0) { // Lets work with each expired server foreach($expired_servers as $server) { // Load SSH lib $settings = $this->module->services[$server->module]['ssh']; // Load ssh lib $this->load->library('core/ssh', $settings); // Do SSH command $this->ssh->execute('screen -X -S '.$server->module.'-'.$server->port.' kill'); // Set array with empty values $data = array( 'name' => '', 'server_rcon' => '', 'server_password' => '', 'expires' => 0, ); // Update server data $this->occupy_server($server->id, $server->module, $data); } } } public function get_available_servers($module) { $q = $this->db->where('expires', 0) ->where('module', $module) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Function gets occupied servers by internal active module * @return type */ public function get_occupied_servers() { $q = $this->db->where('expires >', 0) ->where('module', $this->module->active_service) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Function gets occupied servers by specified external service * @param type $service * @return type */ public function get_occupied_servers_external($service = 'hlds') { $q = $this->db->where('expires >', 0) ->where('module', $service) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->result(); } } /** * Updates server row with new information. Function can be used also for clearing row. * @param type $server_id * @param type $module * @param type $data */ public function occupy_server($server_id, $module, $data = array()) { $this->db->where('id', $server_id) ->where('module', $module) ->update($this->sql_services_table, $data); } public function get_server($server_id) { $q = $this->db->where('id', $server_id) ->get($this->sql_services_table); if($q->num_rows() > 0) { return $q->row(); } } }
true
5167ae1bf1169e578e379c92bdb9ccd368504ca8
PHP
nwebcode/framework
/src/Nweb/Framework/Application/Service/Locator.php
UTF-8
1,321
2.546875
3
[]
no_license
<?php /** * Nweb Framework * * @category NwebFramework * @package Application * @subpackage Service * @author Krzysztof Kardasz <krzysztof@kardasz.eu> * @copyright Copyright (c) 2013 Krzysztof Kardasz * @license http://www.gnu.org/licenses/lgpl-3.0.txt GNU Lesser General Public * @version 0.1-dev * @link https://github.com/nwebcode/framework * @link http://framework.nweb.pl */ namespace Nweb\Framework\Application\Service; /** * Service Locator * * @category NwebFramework * @package Application * @subpackage Service * @author Krzysztof Kardasz <krzysztof@kardasz.eu> * @copyright Copyright (c) 2013 Krzysztof Kardasz * @version 0.1-dev */ class Locator { /** * @var array */ protected $services = array(); /** * @param string $name * @return bool */ public function has ($name) { return isset($this->services[$name]); } /** * @param string $name * @return object */ public function get ($name) { if (!isset($this->params[$name])) { $params = $this->params[$name]; } return $this->services[$name]; } /** * @param string $name * @param object $serviceObj */ public function set ($name, $serviceObj) { $this->services[$name] = $serviceObj; } }
true
c64bc66afa4af038a33afb8dd43ced6cff735d39
PHP
Raza448/thoughtbase
/application/view_latest/vendor_only/allres_comment.php
UTF-8
912
2.53125
3
[]
no_license
<?php $sql ='select client_answes.id as kid,client_answes.comment,client_answes.client_id,client_answes.survey_id,client_answes.question_id, users.age,users.gender,users.zipcode from client_answes left join users on client_answes.client_id = users.id where client_answes.survey_id='.$survey.' and client_answes.question_id='.$question; $data_img = $this->db->query($sql)->result_array(); ?> <?php if(count($data_img ) > 0 ){ foreach($data_img as $row => $val ){ ?> <div> <?php echo $val['comment']; ?> <h6><i class="fa fa-star"></i>Age:<?php echo $val['age']; ?> <i class="fa fa-star"></i>Gender:<?php echo $val['gender']; ?> <i class="fa fa-star"></i>Zip:<?php echo $val['zipcode']; ?> </h6> </div> <br /> <?php }}else{ ?> <div> No Comments yet <h6 style="display:none;"><i class="fa fa-star"></i>Age:~ <i class="fa fa-star"></i>Gender:~ <i class="fa fa-star"></i>Zip:~ </h6> </div> <br /> <?php } ?>
true
94aa2264fb2d4fbcf81c4eaed146b2016763f17b
PHP
id0612/openapi-sdk-php
/src/Cms/V20180308/GetMonitoringTemplate.php
UTF-8
1,435
2.65625
3
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace AlibabaCloud\Cms\V20180308; use AlibabaCloud\Client\Request\RpcRequest; /** * Request of GetMonitoringTemplate * * @method string getName() * @method string getId() */ class GetMonitoringTemplate extends RpcRequest { /** * @var string */ public $product = 'Cms'; /** * @var string */ public $version = '2018-03-08'; /** * @var string */ public $action = 'GetMonitoringTemplate'; /** * @var string */ public $method = 'POST'; /** * @deprecated deprecated since version 2.0, Use withName() instead. * * @param string $name * * @return $this */ public function setName($name) { return $this->withName($name); } /** * @param string $name * * @return $this */ public function withName($name) { $this->data['Name'] = $name; $this->options['query']['Name'] = $name; return $this; } /** * @deprecated deprecated since version 2.0, Use withId() instead. * * @param string $id * * @return $this */ public function setId($id) { return $this->withId($id); } /** * @param string $id * * @return $this */ public function withId($id) { $this->data['Id'] = $id; $this->options['query']['Id'] = $id; return $this; } }
true
4fc011f0184c787bbdac7410df64c1e396470eb7
PHP
kernvalley/needs-api
/roles/index.php
UTF-8
679
2.59375
3
[ "MIT" ]
permissive
<?php namespace Roles; use \shgysk8zer0\PHPAPI\{PDO, API, Headers, HTTPException}; use \shgysk8zer0\PHPAPI\Abstracts\{HTTPStatusCodes as HTTP}; use \shgysk8zer0\{Role}; require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'autoloader.php'; try { $api = new API('*'); $api->on('GET', function(API $req): void { if ($roles = Role::fetchAll(PDO::load())) { Headers::contentType('application/json'); echo json_encode($roles); } else { throw new HTTPException('Error fetching roles', HTTP::INTERNAL_SERVER_ERROR); } }); $api(); } catch (HTTPException $e) { Headers::status($e->getCode()); Headers::contentType('application/json'); echo json_encode($e); }
true
1ea0afcddce9ffde9274b324d172296f4a719f62
PHP
DeDoOozZz/brighterycms
/source/brightery/core/Style.php
UTF-8
2,113
2.703125
3
[]
no_license
<?php /** * Management application styles and interfaces * @package Brightery CMS * @version 1.0 * @property object $instance Codeigniter instance * @property string $interface User Interface name * @property string $styleName Style name * @property string $styleAssets Style assets path * @property string $stylePath Style path * @property string $styleUri Style URI * @property string $styleDirection Style Direction * @author Muhammad El-Saeed <muhammad@el-saeed.info> * */ class Style { private $instance; private $interface; private $styleName; private $styleAssets; private $styleUri; private $styleDirection; public $stylePath; public function __construct() { Log::set('Initialize Style class'); $this->instance = & Brightery::SuperInstance(); $this->initialize(); } private function initialize() { $this->interface = $this->instance->Twig->interface; $this->styleName = $this->instance->Twig->styleName; $this->styleDirection = $this->instance->language->getLanguageDirection(); $this->stylePath = ROOT . '/styles/' . $this->interface . '/' . $this->styleName; $this->styleUri = BASE_URL . 'styles/' . $this->interface . '/' . $this->styleName; if (!is_dir($this->stylePath)) Brightery::error_message($this->stylePath . " is missed."); $this->parsing(); $this->createStyleConstants(); } private function parsing() { $style_ini = $this->stylePath . '/style.ini'; if (!file_exists($style_ini)) Brightery::error_message($style_ini . " is missed."); $this->styleAssets = parse_ini_file($style_ini, true); } private function createStyleConstants() { $settings = $this->styleAssets[$this->styleDirection]; define('STYLE_IMAGES', $this->styleUri . '/assets/' . $settings['images']); define('STYLE_JS', $this->styleUri . '/assets/' . $settings['js']); define('STYLE_CSS', $this->styleUri . '/assets/' . $settings['css']); define('MODULE_URL', BASE_URL . 'source/app/modules/'); } }
true
506a18bd0dd3aa08eac41a157877680f69cfaa83
PHP
didembilgihan/Bookmark-Management-System
/register.php
UTF-8
679
2.734375
3
[ "MIT" ]
permissive
<?php if ( $_SERVER["REQUEST_METHOD"] == "POST") { // var_dump($_POST) ; require "db.php" ; extract($_POST) ; try { // Validate email, name and password $sql = "insert into user ( name, email, password) values (?,?,?)" ; $stmt = $db->prepare($sql); $hash_password = password_hash($password, PASSWORD_DEFAULT) ; $stmt->execute([$name, $email, $hash_password]); addMessage("Registered"); header("Location: ?page=loginForm") ; exit ; } catch(PDOException $ex) { addMessage("Insert Failed!") ; header("Location: ?page=registerForm"); exit; } }
true
24fac03e9a4d620c1c8575f84ec56252fc424fc1
PHP
jwmcpeak/TutsPlus-PHP-Design-Patterns
/chain-of-responsibility.php
UTF-8
1,907
3.5625
4
[]
no_license
<?php // chain of handlers // request abstract class LogType { const Information = 0; const Debug = 1; const Error = 2; } abstract class AbstractLog { protected $level; private $nextLogger = null; public function setNext(AbstractLog $logger) { $this->nextLogger = $logger; } public function log(int $level, string $message) { if ($this->level <= $level) { $this->write("$message\n"); } if ($this->nextLogger != null) { $this->nextLogger->log($level, $message); } } protected abstract function write(string $message); } class ConsoleLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "CONSOLE: $message"; } } class FileLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "FILE: $message"; } } class EventLog extends AbstractLog { public function __construct(int $logLevel) { $this->level = $logLevel; } protected function write(string $message) { echo "EVENT: $message"; } } class AppLog { private $logChain; public function __construct() { $console = new ConsoleLog(LogType::Information); $debug = new FileLog(LogType::Debug); $error = new EventLog(LogType::Error); $console->setNext($debug); $debug->setNext($error); $this->logChain = $console; } public function log(int $level, string $message) { $this->logChain->log($level, $message); } } $app = new AppLog(); $app->log(LogType::Information, "This is information."); $app->log(LogType::Debug, "This is debug."); $app->log(LogType::Error, "This is error.");
true
cc0de231c8619e429820f088d5833fd27b91758c
PHP
gungungggun/workspace
/collatz-problem/php.php
UTF-8
391
3.65625
4
[]
no_license
<?php $t = microtime(true); $count = 0; for ($i = 2; $i <= 10000; $i++) { $x = $i; while ($x != 1) { if ($x % 2 == 0) { $x = a($x); } else { $x = b($x); } $count++; } } echo '処理時間' . (microtime(true) - $t); echo "\n"; echo 'count:' . $count; function a ($n) { return $n / 2; } function b ($n) { return $n * 3 + 1; }
true
92803af814f4d592e219db466a90c528d1ae06af
PHP
aliliin/thinkPhp51
/extend/ObjArray.php
UTF-8
905
3.453125
3
[ "Apache-2.0" ]
permissive
<?php // ArrayAccess(数组式访问)接口 // 提供像访问数组一样访问对象的能力的接口。 class ObjArray implements \ArrayAccess { private $container = ['title' => 'Aliliin']; // 设置一个偏移位置的值 public function offsetSet($offset, $value) { if (is_null($offset)) { $this->container[] = $value; } else { $this->container[$offset] = $value; } } // 检查一个偏移位置是否存在 public function offsetExists($offset) { return isset($this->container[$offset]); } // 复位一个偏移位置的值 public function offsetUnset($offset) { unset($this->container[$offset]); } // 获取一个偏移位置的值 public function offsetGet($offset) { return isset($this->container[$offset]) ? $this->container[$offset] : null; } }
true
542288972f173c2f99f6a4ea0a15c1cf85f82e56
PHP
crow1796/rev-cms
/RevCMS/src/Http/Controllers/PagesController.php
UTF-8
2,220
2.703125
3
[ "MIT" ]
permissive
<?php namespace RevCMS\Http\Controllers; use Illuminate\Http\Request; use RevCMS\Http\Controllers\RevBaseController; use RevCMS\Modules\Cms\Wrapper\Page; class PagesController extends RevBaseController { public function index(){ $this->menuOrder = 2; return $this->makeView('revcms.pages.index', 'Pages'); } /** * Create new page. * @param Request $request * @return mixed */ public function store(Request $request){ $this->checkAjaxRequest($request); $page = $this->rev ->cms() ->createPage($request->all()); if(!$page instanceof Page) { // If page is not equal to false/null, then return all errors with a failed status, else return failed return $page ? $page->errors()->all() + ['status' => false] : [0 => 'Something went wrong. Please make sure that the permalink is unique.','status' => false]; } $response = ['status' => true]; return $response; } public function create(){ $this->menuOrder = 2; return $this->makeView('revcms.pages.create', 'New Page'); } public function edit($id){ dd($id); } /** * Retreive all pages. * @param Request $request * @return array */ public function allPages(Request $request){ $this->checkAjaxRequest($request); return $this->rev ->cms() ->getPageArray(); } /** * Populate controllers and layouts fields. * @param Request $request * @return array */ public function populateFields(Request $request){ $fieldValues = [ 'controllers' => $this->rev->mvc()->allControllers(), 'layouts' => $this->rev->cms()->getActiveThemesLayouts(), ]; return $fieldValues; } /** * Generate slug and action name based on page's title. * @param Request $request * @return array */ public function generateFields(Request $request){ $this->checkAjaxRequest($request); return $this->rev ->cms() ->generateFieldsFor($request->page_title); } }
true
a8967ab776debe04d03cc200d88f94469ecb16c6
PHP
mobilejazz-contrib/yii2-api
/app/frontend/models/PasswordResetRequestForm.php
UTF-8
1,520
2.609375
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php namespace frontend\models; use common\models\User; use yii\base\Model; /** * Password reset request form */ class PasswordResetRequestForm extends Model { public $email; /** * @inheritdoc */ public function rules () { return [ ['email', 'filter', 'filter' => 'trim'], ['email', 'required'], ['email', 'email'], ['email', 'exist', 'targetClass' => '\common\models\User', 'filter' => ['status' => User::STATUS_ACTIVE], 'message' => 'There is no user with such email.' ], ]; } /** * Sends an email with a link, for resetting the password. * * @return boolean whether the email was send */ public function sendEmail () { /* @var $user User */ $user = User::findOne ([ 'status' => User::STATUS_ACTIVE, 'email' => $this->email, ]); if ($user) { if (!User::isPasswordResetTokenValid ($user->password_reset_token)) { $user->generatePasswordResetToken (); } if ($user->save ()) { $data = [ 'name' => $user->name, 'url' => \Yii::$app->urlManager->createAbsoluteUrl(['site/reset-password','token'=>$user->password_reset_token]) ]; return \Yii::$app->mailer ->compose ('recover-password-'.\Yii::$app->language, $data) ->setGlobalMergeVars ($data) ->setTo ($this->email) ->setSubject (\Yii::t('app','Password reset request')) ->enableAsync () ->send (); } } return false; } }
true
6e3ebe6c5d9ea851939dcca52c43e0ade43ce04d
PHP
cddsky2014/121
/php20160504/array_keys.php
UTF-8
228
2.828125
3
[]
no_license
<?php $arr1 = array(1,2,3,"name"=>"lucy","age"=>23,"addr"=>"USA"); print_r($arr1); print_r(array_keys($arr1)); function uarray_keys($a){ $arr = array(); foreach($a as $k=>$v){ $arr[]=$k; } return $arr; } ?>
true
5a3e69b98671dc9a55dc4728743fdf5efb07e72f
PHP
medV3dkO/bootcamp
/admin/login.php
UTF-8
4,199
2.53125
3
[]
no_license
<?php if ($_POST['login']!='' && $_POST['pass']!=''){//проверяем что поля не пустые if (strlen($_POST['login'])<=30 && strlen ($_POST['pass'])<= 30){//проверяем чтоб логин и пароль был меньше 30 символов $login = htmlspecialchars($_POST['login']);//убираем спецсимволы $pass = htmlspecialchars($_POST['pass']);//убираем спецсимволы $login = mysql_real_escape_string($login);//еще одна экранизация $pass = mysql_real_escape_string($pass);//еще одна экранизация } } if ($_POST['login']=='' || $_POST['password']=='') echo '<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Авторизация | BOOTCAMP</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mini.css/3.0.1/mini-default.css"> </head> <body> <div class="container"> <div class="row"> <div class="col-sm-3"></div> <div class="col-sm-6"> <br> <form id="form" method="post" action="login"> <fieldset> <legend>Авторизуйтесь</legend> <div class="row"> <div class="col-sm-12 col-md-6"> <label for="user">Логин</label> <input type="text" id="login" name="login" placeholder="Имя пользователя"> </div> <div class="col-sm-12 col-md-6"> <label for="password">Пароль</label> <input type="password" id="password" name="password" placeholder="Пароль"> </div> </div> <div class="row"> <mark id="error" class="inline-block secondary hidden" style="margin: 10px 0 10px 8px;">Текст ошибки</mark> </div> <div class="row"> <input type="submit" id="button" value="Войти"> </div> </fieldset> </form> </div> <div class="col-sm-3"></div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </body> </html>'; else{ //вот так данные можно отправлять без проверки вовсе, ни чего очень плохого случиться не должно. //PDO все заэкранирует и превратит в текст. //Можно разве что проверять длинну текста и какие то специфическиие данные $sql = "SELECT * FROM admin_users WHERE login=:login AND password=:pass";//Формируем запрос без данных $result = $pdo->prepare($sql); $result->bindvalue(':login', $_POST['login']); //Заполняем данные $result->bindvalue(':pass', md5($_POST['password'])); //Заполняем данные. Пароли хранить в открытом виде, дело такое. Поэтому двойной md5) $result->execute( ); //Выполняем запросы $result = $result->fetchAll(); //переводим обьект ПДО в массив данных, для удобной работы if (count($result)>0) {//Если база вернула 1 значение, значит и логин и пароль совпали. отлично echo 'Ура! Мы авторизировались! Перенаправляем в панель...'; $_SESSION['user'] = $result[0];//сохраняем обьект пользователя в сессии header("refresh: 3; url=https://medv3dko.xyz/admin/"); }else echo '<meta charset="UTF-8"><mark id="error" class="inline-block secondary hidden" style="margin: 10px 0 10px 8px;">Логин или пароль не верный или пользователь не существует.</mark> <a href="https://medv3dko.xyz/admin/">Попробовать ещё раз</a>'; } ?>
true
02acd4cbae8054282c69b34610987f6f6d578348
PHP
amsify42/php-domfinder
/tests/TestXML.php
UTF-8
531
2.78125
3
[ "MIT" ]
permissive
<?php namespace Amsify42\Tests; use Amsify42\DOMFinder\DOMFinder; class TestXML { private $domFinder; function __construct() { $this->domFinder = new DOMFinder(getSample('books.xml')); } public function process() { $books = $this->domFinder->getElements('book'); if($books->length) { foreach($books as $book) { echo $this->domFinder->getHtml($book); } } echo "\n\n"; $book = $this->domFinder->find('book')->byId('bk101')->first(); if($book) { echo $this->domFinder->getHtml($book); } } }
true
c826aef2b0721c6bd99c9f626c20cefb41d94848
PHP
chris-peng-1244/otc-cms
/app/Services/Repositories/Customer/CustomerRepository.php
UTF-8
1,017
2.8125
3
[]
no_license
<?php namespace OtcCms\Services\Repositories\Customer; use Illuminate\Contracts\Pagination\Paginator; use Illuminate\Database\Eloquent\Collection; use OtcCms\Models\Customer; class CustomerRepository implements CustomerRepositoryInterface { /** * @param string $customerName * @param array $columns * @return Collection */ public function searchByName($customerName, $columns = ['*']) { return Customer::where('nickname', 'like', "%$customerName%") ->get(); } /** * @param int $limit * @return Paginator */ public function paginate($limit) { return Customer::paginate($limit); } /** * @param string $query * @return Collection */ public function searchByNameOrId($query) { if (is_numeric($query)) { $customer = Customer::find((int) $query); return $customer ? collect($customer) : collect([]); } return $this->searchByName($query); } }
true
f3304a721fa0d0a3a94a8fbe60a86450aa257624
PHP
kuljitsingh94/HTMLParse
/studyGuideGen.php
UTF-8
3,527
3.328125
3
[]
no_license
<?php #give the script the URL to scrape $URLbegin= "https://cs.csubak.edu/~clei/teaching/files/S19_3500/hw"; $URLend = "s.html"; #function that returns an array populated with everything #in between the parameters tag_open and tag_close function tag_contents($string, $tag_open, $tag_close){ foreach (explode($tag_open, $string) as $key => $value) { if(strpos($value, $tag_close) !== FALSE){ $result[] = trim(substr($value, 0, strpos($value, $tag_close))); } } return $result; } $output = fopen('./output.txt','w'); for($hwNum = 1; $hwNum <= 5; $hwNum++) { if($hwNum < 10) $URL = $URLbegin."0".$hwNum.$URLend; else $URL = $URLbegin.$hwNum.$URLend; #download HTML from URL and save as a string $file = file_get_contents($URL); #get the number of questions from the num_quests variable #in the HTML/JavaScript $NUM_QUESTIONS = tag_contents($file, "num_quests =",";"); #save as an integer since tag_contents returns strings #also look at subscript 1 since subscript 0 is garbage $NUM_QUESTIONS = trim($NUM_QUESTIONS[1])+0; #remove all head tag info, leaving just the body #which is all we want $body = substr($file,strpos($file, "<pre class=verbatim>")); #get all comparison expressions since this is where #the answers are located $parsed= tag_contents($body, 'if (', ')'); $questions= tag_contents($body, '<pre class=verbatim>', '</pre>'); array_unshift($questions, "placeholder"); //var_dump($questions); $answers = array(); $i = 0; #all string parsing below requires knowledge of the #structure of the #downloaded HTML and requires pattern recognition #traverse array full of comparison expressions foreach($parsed as $key){ #break the comparison expressions into separate #variables, delimited by && $ifStatment = explode("&&",$key); #this checks if the if statement we grabbed #pertains to answers or something else if(!strpos($key,"hwkform")) { continue; } #if previous if statement fails, we have an #answer if statement $i++; #traverse each comparison expression foreach($ifStatment as $value){ #remove whitespace $value = trim($value); #! tells us its a wrong answer, so #if the ! is not there, meaning its a #right answer if($value[0]!='!'){ #grab the value of right answers,0123 $answer = tag_contents($value, '[',']'); #output formatting, convert 0123 -> ABCD #by ascii value usage if(isset($answers[$i])) $answers[$i].=','.chr($answer[0]+65); else $answers[$i]=chr($answer[0]+65); } } } #error checking, if NUM_QUESTIONS != i then we #got an extra if statement comparison expression if($i!=$NUM_QUESTIONS) { echo "\n\n\tERROR PARSING HTML! DOUBLE CHECK ANSWERS!!\n\n\n"; } echo "\tGenerating Study Guide Output File for $hwNum\n"; #output questions and answers //var_dump($answers); #write to output file for($i = 1; $i<=$NUM_QUESTIONS ; $i++) { fwrite($output, $questions[$i]."<split>".$answers[$i].'<endofquestion>'); } foreach($answers as $question => $ans) { //usleep(0250000); echo "Question $question\t: $ans\n"; } } ?>
true
0ea15d126f06d7a3274cdd342b8f1c98a70630c8
PHP
jeyroik/extas-q-crawlers-jira
/src/components/quality/crawlers/jira/JiraIssueChangelogItem.php
UTF-8
762
2.734375
3
[ "MIT" ]
permissive
<?php namespace extas\components\quality\crawlers\jira; use extas\components\Item; use extas\interfaces\quality\crawlers\jira\IJiraIssueChangelogItem; /** * Class JiraIssueChangelogItem * * @package extas\components\quality\crawlers\jira * @author jeyroik@gmail.com */ class JiraIssueChangelogItem extends Item implements IJiraIssueChangelogItem { /** * @param bool $asTimestamp * * @return false|int|string */ public function getCreated(bool $asTimestamp) { $created = $this->config[static::FIELD__CREATED] ?? ''; return $asTimestamp ? strtotime($created) : $created; } /** * @return string */ protected function getSubjectForExtension(): string { return static::SUBJECT; } }
true
1a150ec40f4d58b1d254c01c7345271e475296e9
PHP
LaunaKay/codingdojoserver
/WishList/application/models/M_Wish.php
UTF-8
666
2.625
3
[ "MIT" ]
permissive
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class M_Wish extends CI_Model { public function __construct() { parent::__construct(); } public function addwish($wish) { $id = $this->session->userdata('id'); $wish = array ( 'item' => $wish['item'], 'user_id' => $id['id'] ); $this->db->insert('wishes', $wish); } public function removewish($wishID) { $this->db->where('id', $wishID); $this->db->delete('wishes'); $this->db->where('item_id', $wishID); $this->db->delete('wishlists'); } }
true
5ad38c6f4a2be085bef4680975cea39668b6d4b3
PHP
lazyman00/ajsas
/pages/Front_end/allarticle/send_email_1.php
UTF-8
4,324
2.578125
3
[]
no_license
<?php include('../../../connect/connect.php'); ?> <?php require("../../../phpmailer/PHPMailerAutoload.php");?> <?php header('Content-Type: text/html; charset=utf-8'); $sql_article = sprintf("SELECT * FROM `article` left join type_article on article.type_article_id = type_article.type_article_id WHERE `article_id` = %s",GetSQLValueString($_POST['article_id'], 'int')); $query_article = $conn->query($sql_article); $row_article = $query_article->fetch_assoc(); for($i=0; $i<count($_POST['user_id']); $i++){ if($_POST['user_id'][$i]!=""){ $sql = sprintf("SELECT user.name_en, user.surname_en, pre.pre_en_short FROM `user` left join pre on user.pre_id = pre.pre_id WHERE `user`.`user_id` = %s ",GetSQLValueString($_POST['user_id'][$i], 'text')); $query = $conn->query($sql); $row = $query->fetch_assoc(); // echo "<pre>"; // print_r($_POST); // echo "</pre>"; // exit(); $mail = new PHPMailer; $mail->CharSet = "utf-8"; $mail->isSMTP(); // $mail->Debugoutput = 'html'; $mail->Host = 'smtp.gmail.com'; $mail->Port = 587; $mail->SMTPSecure = 'tls'; $mail->SMTPAuth = true; $gmail_username = "darktolightll@gmail.com"; // gmail ที่ใช้ส่ง $gmail_password = "SunandMoon00"; // รหัสผ่าน gmail // ตั้งค่าอนุญาตการใช้งานได้ที่นี่ https://myaccount.google.com/lesssecureapps?pli=1 $sender = "Article Review Request [AJSAS]"; // ชื่อผู้ส่ง $email_sender = "noreply@ibsone.com"; // เมล์ผู้ส่ง $email_receiver = $_POST["email"][$i]; // เมล์ผู้รับ *** // $email_receiver = "darktolightll@gmail.com"; $subject = "จดหมายเทียบเชิญผู้ทรงคุณวุฒิ"; // หัวข้อเมล์ $mail->Username = $gmail_username; $mail->Password = $gmail_password; $mail->setFrom($email_sender, $sender); $mail->addAddress($email_receiver); $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true ) ); $mail->Subject = $subject; // $mail->SMTPDebug = 1; $email_content = "<!DOCTYPE html> <html lang='en'> <head> <meta charset='UTF-8'> <title>Document</title> </head> <body> <p><b>Dear ".$row['pre_en_short']." ".$row['name_en']." ".$row['surname_en']."</b></p> <p style='text-indent: 50px;' >I believe that you would serve as an excellent reviewer of the manuscript, ".$row_article['article_name_en']." </p> <p>which has been submitted to Academic Journal of Science and Applied Science. The submission's abstract is</p> <p>inserted below, and I hope that you will consider undertaking this important task for us.</p> <p style='text-indent: 50px;'>Please log into the journal web site by ".$row_article['date_article']." to indicate whether you will undertake the</p> <p>review or not, as well as to access the submission and to record your review and recommendation. After this job</p> <p>is done, you will receive a THB 1,000 cash prize.</p> <p style='text-indent: 50px;'>The review itself is due ".$row_article['date_article'].".</p> <p style='text-indent: 50px;'>Submission URL: <a href='http://localhost/ajsas/rechack_email.php?u=".$_POST['user_id'][$i]."&e=".$row_article['article_name_en']."&t=".$row_article['article_name_th']."&i=".$row_article['article_id']."&sm=".$_POST['id_sendMail']."'>>> ระบบวารสารวิชาการวิทยาศาสตร์และวิทยาศาสตร์ประยุกต์ <<</a></p> <br/> <p>Assoc. Prof. Dr. Issara Inchan </p> <p>Faculty of Science and Technology, Uttaradit Rajabhat University.</p> <p>ajsas@uru.ac.th </p> <br/> <p>".$row_article['article_name_en']." </p> <p>".$row_article['abstract_en']."</p> <p>................. </p> </body> </html>"; // ถ้ามี email ผู้รับ if($email_receiver){ $mail->msgHTML($email_content); if ($mail->send()) { $sql = sprintf("INSERT INTO `tb_sendmail`(`id_sendMail`, `user_id`, `article_id`) VALUES (%s,%s,%s)", GetSQLValueString($_POST['id_sendMail'],'text'), GetSQLValueString($_POST['user_id'][$i],'text'), GetSQLValueString($row_article['article_id'],'text')); $query = $conn->query($sql); } } $mail->smtpClose(); } } // echo "ระบบได้ส่งข้อความไปเรียบร้อย"; ?>
true
dd89c7c961bdf80d129c570cdcd9b8654e59cc31
PHP
crebiz76/phptest
/ch19/quiz_result.php
UTF-8
2,004
3.140625
3
[]
no_license
<?php $ans = array($_REQUEST['ex1'], $_REQUEST['ex2'], $_REQUEST['ex3']); require_once('MyDB.php'); $pdo = db_connect(); ?> <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>퀴즈 응시 결과</title> </head> <body> <h2>퀴즈 응시 결과</h2> <?php try{ $sql = "select * from quiz"; $stmh = $pdo->query($sql); $count = $stmh->rowCount(); } catch (PDOException $Exception){ print "오류 :".$Exception->getMessage(); } $i = 0; $score = 0; while($row=$stmh->fetch(PDO::FETCH_ASSOC)){ if($ans[$i] == $row['dap']) { $score++; $correct[$i] = 'O'; } else { $correct[$i] = 'X'; } $i++; } $result = ''; switch($score) { case 0: case 1: $result = '미흡'; break; case 2: $result = '보통'; break; case 3: $result = '우수'; break; } ?> <p>판정: <?=$result?></p> <table border="1"> <tr> <td width="100" align="center">순번</td> <td width="100" align="center">선택</td> <td width="100" align="center">정답</td> <td width="100" align="center">결과</td> </tr> <?php try{ $sql = "select * from quiz"; $stmh = $pdo->query($sql); $count = $stmh->rowCount(); } catch (PDOException $Exception){ print "오류 :".$Exception->getMessage(); } $j = 0; while($row=$stmh->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td width="100" align="center"><?=$row['id']?></td> <td width="100" align="center"><?=$ans[$j]?></td> <td width="100" align="center"><?=$row['dap']?></td> <td width="100" align="center"><?=$correct[$j]?></td> </tr> <?php $j++; } ?> </table> </body> </html>
true
175bc2a392f215181f29fe73a3201dc91e41b1e4
PHP
boukeversteegh/DecoratorModule
/test/src/Fixtures/Library/lendableTrait.php
UTF-8
246
2.640625
3
[]
no_license
<?php namespace Fixtures\Library; trait lendableTrait { protected $lending_user; public function lendTo(\Fixtures\Entity\User $user) { $this->lending_user = $user; } public function getLendingTo() { return $this->lending_user; } }
true
92600040e18121fbbe05ee90c35734a72af4e6c2
PHP
walterra/J4p5Bundle
/j4p5/parse/easy_parser.php
UTF-8
841
2.53125
3
[]
no_license
<?php namespace Walterra\J4p5Bundle\j4p5\parse; use \Walterra\J4p5Bundle\j4p5\parse\parser; use \Walterra\J4p5Bundle\j4p5\jsly; class easy_parser extends parser { function __construct($pda, $strategy = null) { parent::__construct($pda); $this->call = $this->action; //array(); $this->strategy = ($strategy ? $strategy : new default_parser_strategy()); /* foreach($this->action as $k => $body) { $this->call[$k] = create_function( '$tokens', preg_replace('/{(\d+)}/', '$tokens[\\1]', $body)); } */ } function reduce($action, $tokens) { $call = $this->call[$action]; return jsly::$call($tokens); } function parse($symbol, $lex, $strategy = null) { return parent::parse($symbol, $lex, $this->strategy); } } ?>
true
053035df4f0eb6ebbf8b2f9204d0cf2bdfd3653b
PHP
HouraiSyuto/php_practice
/part2/chapter5/reference_array.php
UTF-8
342
3.65625
4
[]
no_license
<?php function array_pass($array){ $array[0] *= 2; $array[1] *= 2; } function array_pass_ref(&$array){ $array[0] *= 2; $array[1] *= 2; } $a = 10; $b = 20; $array = array($a, $b); array_pass_ref($array); echo $a, PHP_EOL; echo $b, PHP_EOL; $array = array($a, &$b); array_pass($array); echo $a, PHP_EOL; echo $b, PHP_EOL;
true
1bb4215e1ae1605c17f0d163193ac2f293ae40c5
PHP
DeschampsManon/Facebook_app
/task.php
UTF-8
4,908
2.59375
3
[]
no_license
<?php require __DIR__.'/loaders/dependencies.php'; require __DIR__.'/loaders/classLoader.php'; require __DIR__.'/loaders/bdd.php'; require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php'; // On stock la variable fb (api facebook) dans une variable statique MyController::$fb = new Facebook\Facebook([ 'app_id' => '325674481145757', 'app_secret' => '', 'default_graph_version' => 'v2.8', ]); MyController::$fb->setDefaultAccessToken('325674481145757|'); // On demande une instance sur la class ApiController qui permet de lancer une requette à l'API Facebook $api = ApiController::getInstance(); function array_sort($array, $on, $order=SORT_DESC) { $new_array = array(); $sortable_array = array(); if (count($array) > 0) { foreach ($array as $k => $v) { if (is_array($v)) { foreach ($v as $k2 => $v2) { if ($k2 == $on) { $sortable_array[$k] = $v2; } } } else { $sortable_array[$k] = $v; } } switch ($order) { case SORT_ASC: asort($sortable_array); break; case SORT_DESC: arsort($sortable_array); break; } foreach ($sortable_array as $k => $v) { $new_array[$k] = $array[$k]; } } return $new_array; } // On regarde si un concours est terminé $request = MyController::$bdd->query('SELECT id_concours, end_date FROM concours WHERE status = 1'); $result = $request->fetch(PDO::FETCH_ASSOC); if(!empty($result['id_concours'])) { $concours = $result['id_concours']; $today = date('U'); $end = date('U', strtotime($result['end_date'])); if($result['end_date'] <= $today) { // On stoppe le concours s'il est terminé $request = MyController::$bdd->exec('UPDATE concours SET status = 0 WHERE status = 1'); $request = MyController::$bdd->exec('UPDATE users SET participation = 0'); /* GET LIKES */ $resultats = array(); $count = 0; $request = MyController::$bdd->query('SELECT * FROM photos WHERE id_concours = '. $concours); $result = $request->fetchAll(PDO::FETCH_ASSOC); foreach ($result as $photo) { $likes = $api->getRequest($photo['link_like']); $countLikes = (isset($likes['share'])) ? $likes['share']['share_count'] : 0; $request = MyController::$bdd->query('SELECT first_name, name FROM users WHERE id_user = '. $photo['id_user']); $result = $request->fetch(PDO::FETCH_ASSOC); $resultats[$count]['user'] = $result['first_name'] . ' ' . $result['name']; $resultats[$count]['link_photo'] = $photo['link_photo']; $resultats[$count]['likes'] = $countLikes; $count++; } $resultats = array_sort($resultats, 'likes'); $data = array( 'message' => 'Découvrez ci-dessous la photo du gagnant du concours pardon maman !', 'link' => $resultats[0]['link_photo'] ); // On récupère les id de tous les utilisateurs $request = MyController::$bdd->query('SELECT id_user FROM users'); $result = $request->fetchAll(PDO::FETCH_ASSOC); foreach($result as $id) { $api->postRequest('/'.$id['id_user'].'/feed', $data); } // Send mail to admin $accounts = $api->getRequest('/app/roles', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY'); foreach ($accounts['data'] as $key => $account) { if($account['role'] == 'administrators') { $administrators[] = $account['user']; } } foreach ($administrators as $id) { $email = $api->getRequest('/'.$id.'?fields=email', '325674481145757|2_coNBtFEJH6uQenqtAHJCLBcaY'); $emails[] = $email['email']; } $body = ""; $body .= "<table border='1'>"; $body .= "<tr>"; $body .= "<th>User</th>"; $body .= "<th>link photo</th>"; $body .= "<th>likes</th>"; $body .= "</tr>"; foreach ($resultats as $resultat) { $body .= "<tr>"; $body .= "<td>".$resultat['user']."</td>"; $body .= "<td>".$resultat['link_photo']."</td>"; $body .= "<td>".$resultat['likes']."</td>"; $body .= "</tr>"; } $body .= "</table>"; foreach($emails as $email) { $mail = new PHPMailer; $mail->isHTML(true); $mail->setFrom('concourspardonmaman@no-reply.fr', 'Concours Photo Pardon Maman'); $mail->addAddress($email); $mail->addReplyTo('info@example.com', 'Information'); $mail->Subject = 'Résultats du concours'; $mail->Body = $body; $mail->send(); } } }
true
7676e84c098398d2e87756aabc10b5c82ee4077f
PHP
nmusco/assuresign-sdk-php-v2
/src/StructType/PingResult.php
UTF-8
1,265
2.703125
3
[]
no_license
<?php namespace Nmusco\AssureSign\v2\StructType; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for PingResult StructType * @subpackage Structs */ class PingResult extends AbstractStructBase { /** * The Success * Meta information extracted from the WSDL * - use: required * @var bool */ public $Success; /** * Constructor method for PingResult * @uses PingResult::setSuccess() * @param bool $success */ public function __construct($success = null) { $this ->setSuccess($success); } /** * Get Success value * @return bool */ public function getSuccess() { return $this->Success; } /** * Set Success value * @param bool $success * @return \Nmusco\AssureSign\v2\StructType\PingResult */ public function setSuccess($success = null) { // validation for constraint: boolean if (!is_null($success) && !is_bool($success)) { throw new \InvalidArgumentException(sprintf('Invalid value %s, please provide a bool, %s given', var_export($success, true), gettype($success)), __LINE__); } $this->Success = $success; return $this; } }
true
c0372bf6d73553f6f6227fe1bd7dcd8672049bd8
PHP
taufik-ashari/slightly-big-Flip
/disburse/getById.php
UTF-8
1,259
2.78125
3
[]
no_license
<?php // required headers header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Headers: access"); header("Access-Control-Allow-Methods: GET"); header("Access-Control-Allow-Credentials: true"); header('Content-Type: application/json'); // include database and object files include_once '../config/database.php'; include_once '../object/disburse.php'; // get database connection $database = new Database(); $db = $database->getConnection(); // prepare product object $disburse = new Disburse($db); // set ID property of record to read $disburse->id = isset($_GET['id']) ? $_GET['id'] : die(); // read the details of product to be edited $disburse->readOne(); if($disburse->id!=null){ // create array $disburses_arr = array( "id" => $disburse->id, "time_served" => $disburse->time_served, "receipt" => $disburse->receipt, "status" => $disburse->status ); // set response code - 200 OK http_response_code(200); // make it json format echo json_encode($disburses_arr); } else{ // set response code - 404 Not found http_response_code(404); // tell the user product does not exist echo json_encode(array("message" => "Disburse does not exist.")); } ?>
true
a3c53217dc2801449e58a72aab1e6d9ff4272f68
PHP
jamesjoel/tss_12_30
/ravi/ci/application/views/admin/view_users.php
UTF-8
1,067
2.53125
3
[]
no_license
<div class="container mt-4 pt-3"> <div class="row"> <div class="col-md-10 offset-md-1"> <h2 class="text-center">View All User</h2> <table class="table table-dark table-hover table-bordered"> <tr> <th>S.No.</th> <th>Full Name</th> <th>Username</th> <th>Contact</th> <th>Status</th> <th>Change</th> </tr> <?php $n=1; foreach($result->result_array() as $data) { if($data['status']==1) $a = "Enable"; else $a = "Disable"; ?> <tr> <td><?php echo $n; ?></td> <td><?php echo $data['full_name']; ?></td> <td><?php echo $data['username']; ?></td> <td><?php echo $data['contact']; ?></td> <td><?php echo $a; ?></td> <td><a href="<?php echo site_url('admin/change_status/'.$data['id'].'/'.$data['status']) ?>" class="btn btn-sm btn-info">Change</a></td> </tr> <?php $n++; } ?> </table> </div> </div> </div>
true
511c2f3a8e3ce616bc2fa8763ba767747f310b92
PHP
ghuysmans/php-u2flib-server
/examples/pdo/login.php
UTF-8
1,546
2.71875
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
<?php require_once('U2F_Login.php'); class L extends U2F_Login { protected function getUserId() { if (isset($_SESSION['user_id'])) return $_SESSION['user_id']; else return 0; } protected function plaintextLogin($username, $password) { $sel = $this->pdo->prepare('SELECT user_id FROM user WHERE user=?'); $sel->execute(array($username)); //FIXME $password return $sel->fetchColumn(0); } protected function login($user_id) { $_SESSION['user_id'] = $user_id; } } $pdo = new PDO('mysql:dbname=u2f', 'test', 'bonjour'); $login = new L($pdo); if (isset($_GET['force'])) { $_SESSION['user_id'] = $_GET['force']; header('Location: login.php'); } $login->route(); ?> <!DOCTYPE html> <html> <head> <title>PHP U2F example</title> <script src="../assets/u2f-api.js"></script> <script src="ajax.js"></script> <script src="login.js"></script> </head> <body> <pre> <?=print_r($_SESSION)?> </pre> <form onsubmit="return login(this)"> <p><label>User name: <input name="username" required></label></p> <!-- FIXME required --> <p><label>Password: <input name="password" type="password"></label></p> <p> <label>Register <input value="register" name="action" type="radio" required> <input name="comment" placeholder="device name"> <label>Authenticate: <input value="authenticate" name="action" type="radio"></p> <p><button type="submit">Submit!</button></p> </form> </body> </html>
true
66f48156e0cbdf7529838ce463fc6295fde2af12
PHP
HeleneBoivin/PHP_5_Les_tableaux
/exercice1/index.php
UTF-8
537
3.40625
3
[]
no_license
<!DOCTYPE HTML> <html> <head> <title>Exercice1</title> <h3>PHP - Partie 5 - Exercice 1</h3> </head> <body> <p>Créer un tableau months et l'initialiser avec les mois de l'année<p> <?php // $months = array ('janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'décembre'); $months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'décembre']; // les crochets remplace "array" print_r($months); ?> </body> </html>
true
eba7dc0a8bd0a64a96bfc25112b8c15b634e7f43
PHP
salvoab/laravel-comics
/database/seeds/AuthorSeeder.php
UTF-8
459
2.859375
3
[ "MIT" ]
permissive
<?php use App\Author; use Illuminate\Database\Seeder; use Faker\Generator as Faker; class AuthorSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run(Faker $faker) { for ($i=0; $i < 10; $i++) { $author = new Author(); $author->name = $faker->firstName(); $author->lastname = $faker->lastName; $author->save(); } } }
true
c3941a123fc242017610c46abdec247cf902d342
PHP
loveorigami/shop_prototype
/tests/widgets/AdminCreateSubcategoryWidgetTests.php
UTF-8
7,983
2.671875
3
[]
no_license
<?php namespace app\tests\widgets; use PHPUnit\Framework\TestCase; use app\widgets\AdminCreateSubcategoryWidget; use app\forms\AbstractBaseForm; /** * Тестирует класс AdminCreateSubcategoryWidget */ class AdminCreateSubcategoryWidgetTests extends TestCase { private $widget; public function setUp() { $this->widget = new AdminCreateSubcategoryWidget(); } /** * Тестирует свойства AdminCreateSubcategoryWidget */ public function testProperties() { $reflection = new \ReflectionClass(AdminCreateSubcategoryWidget::class); $this->assertTrue($reflection->hasProperty('form')); $this->assertTrue($reflection->hasProperty('categories')); $this->assertTrue($reflection->hasProperty('header')); $this->assertTrue($reflection->hasProperty('template')); } /** * Тестирует метод AdminCreateSubcategoryWidget::setForm */ public function testSetForm() { $form = new class() extends AbstractBaseForm {}; $this->widget->setForm($form); $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInstanceOf(AbstractBaseForm::class, $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setCategories */ public function testSetCategories() { $categories = [new class() {}]; $this->widget->setCategories($categories); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('array', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setHeader */ public function testSetHeader() { $header = 'Header'; $this->widget->setHeader($header); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('string', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::setTemplate */ public function testSetTemplate() { $template = 'Template'; $this->widget->setTemplate($template); $reflection = new \ReflectionProperty($this->widget, 'template'); $reflection->setAccessible(true); $result = $reflection->getValue($this->widget); $this->assertInternalType('string', $result); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::form * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: form */ public function testRunEmptyForm() { $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::categories * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: categories */ public function testRunEmptyCategories() { $form = new class() extends AbstractBaseForm {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $form); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::header * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: header */ public function testRunEmptyHeader() { $mock = new class() {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $mock); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, [$mock]); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run * если пуст AdminCreateSubcategoryWidget::template * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: template */ public function testRunEmptyTemplate() { $mock = new class() {}; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $mock); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, [$mock]); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'Header'); $result = $this->widget->run(); } /** * Тестирует метод AdminCreateSubcategoryWidget::run */ public function testRun() { $form = new class() extends AbstractBaseForm { public $name; public $seocode; public $id_category; public $active; }; $categories = [ new class() { public $id = 1; public $name = 'One'; }, new class() { public $id = 2; public $name = 'Two'; }, ]; $reflection = new \ReflectionProperty($this->widget, 'form'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $form); $reflection = new \ReflectionProperty($this->widget, 'categories'); $reflection->setAccessible(true); $reflection->setValue($this->widget, $categories); $reflection = new \ReflectionProperty($this->widget, 'header'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'Header'); $reflection = new \ReflectionProperty($this->widget, 'template'); $reflection->setAccessible(true); $reflection->setValue($this->widget, 'admin-create-subcategory.twig'); $result = $this->widget->run(); $this->assertRegExp('#<p><strong>Header</strong></p>#', $result); $this->assertRegExp('#<form id="subcategory-create-form" action="..+" method="POST">#', $result); $this->assertRegExp('#<input type="text" id=".+" class="form-control" name=".+\[name\]">#', $result); $this->assertRegExp('#<select id=".+" class="form-control" name=".+\[id_category\]" data-disabled>#', $result); $this->assertRegExp('#<option value="0">------------------------</option>#', $result); $this->assertRegExp('#<option value="1">One</option>#', $result); $this->assertRegExp('#<option value="2">Two</option>#', $result); $this->assertRegExp('#<input type="text" id=".+" class="form-control" name=".+\[seocode\]">#', $result); $this->assertRegExp('#<label><input type="checkbox" id=".+" name=".+\[active\]" value="1"> Active</label>#', $result); $this->assertRegExp('#<input type="submit" value="Создать">#', $result); } }
true
e2e53775768928bcf9bde6fa7b7e4efcc8b8450e
PHP
puterakahfi/MessageBus
/src/Handler/Map/MessageHandlerMap.php
UTF-8
372
2.546875
3
[ "MIT" ]
permissive
<?php namespace SimpleBus\Message\Handler\Map; use SimpleBus\Message\Handler\Map\Exception\NoHandlerForMessageName; use SimpleBus\Message\Handler\MessageHandler; interface MessageHandlerMap { /** * @param string $messageName * @throws NoHandlerForMessageName * @return MessageHandler */ public function handlerByMessageName($messageName); }
true
20623fd0931c9d27b0922946fc65488cf2eeee5d
PHP
itsrsy/SocietasPro
/tests/phpunit/Objects/SubscriberTest.php
UTF-8
600
2.71875
3
[]
no_license
<?php /** * Test the subscriber object * * @author Chris Worfolk <chris@societaspro.org> * @package UnitTests * @subpackage Objects */ class SubscriberTest extends PHPUnit_Framework_TestCase { protected $object; protected function setUp () { require_once("../../application/admin/objects/Subscriber.php"); $this->object = new Subscriber(); } public function testSetEmailAddress () { $this->assertTrue($this->object->setEmailAddress("test@example.com")); $this->assertFalse($this->object->setEmailAddress("not-a-valid-email-address!")); $this->assertSame($this->object->subscriberEmail, "test@example.com"); } }
true
8458be938b47bd94a6f91ac19e678f990f2f7493
PHP
5baddi/lifemoz-coding-challenge
/app/Http/Resources/RoomResource.php
UTF-8
752
2.53125
3
[]
no_license
<?php namespace App\Http\Resources; use Carbon\Carbon; use Illuminate\Http\Resources\Json\JsonResource; class RoomResource extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'id' => $this->id, 'uuid' => $this->uuid, 'name' => $this->name, 'user' => $this->user ?? null, 'updated_at' => Carbon::parse($this->updated_at)->format('H:i d/m/Y'), 'created_at' => Carbon::parse($this->created_at)->format('H:i d/m/Y'), ]; } }
true
01679d3ad5b3b0c9469e0d0ad55d64fd34eebcf7
PHP
ryanhellyer/auto-xml-backup
/inc/class-auto-xml-backup-admin-notice.php
UTF-8
730
2.6875
3
[]
no_license
<?php /** * Adds an admin notice, alerting the admin that the email address field is blank. */ class Auto_XML_Backup_Admin_Notice extends Auto_XML_Backup_Abstract { /** * Fire the constructor up :) */ public function __construct() { add_action( 'admin_notices', array( $this, 'message' ) ); } /** * Output the message. */ public function message() { // Bail out if email addresses already stored if ( '' != get_option( self::SLUG ) ) { return; } echo ' <div class="notice notice-warning"> <p>' . sprintf( __( 'Email addresses need to be added to the <a href="%s">Auto XML Backup settings page</a>.', 'auto-xml-backup' ), esc_url( $this->get_settings_url() ) ) . '</p> </div>'; } }
true
238be97af2f39ad6ad6242aa292efa5a1b7c6d56
PHP
JohnHasmie/restaurant
/classes/Stripe.class.php
UTF-8
1,572
2.640625
3
[]
no_license
<?php class Stripe { protected $stripToken; public function __construct($data) { $this->stripToken = $data['stripeToken']; \Stripe\Stripe::setApiKey('sk_test_51Ie6PpL8uWnAKjvMZ6aZwNXtiuxGyhOlUV8CXKT2JDdflqKXKyfDc96SqAzrwh92xdULc8lCX5lOMh8DSaM2vRzl00W5fOmfHN'); } public function processPayment($orders) { $order = $orders[0]; $stripToken = $this->stripToken; \Stripe\Charge::create ([ "amount" => round($order->grand_total)*100, "currency" => 'USD', "source" => $stripToken, "description" => "Test payment from click and collect." ]); $orderClass = new Order; $orderClass->payOrder($order->order_number, 'Stripe-'.$order->order_number); // $checkout_session = \Stripe\Checkout\Session::create([ // 'payment_method_types' => ['card'], // 'line_items' => [[ // 'price_data' => [ // 'currency' => 'USD', // 'unit_amount' => round($order->grand_total)*100, // 'product_data' => [ // 'name' => $order->name, // // 'images' => [Config::PRODUCT_IMAGE], // ], // ], // 'quantity' => 1, // ]], // 'mode' => 'payment', // 'client_reference_id' => $order->id, // 'success_url' => BASE_URL.'/callback/stripe.cb.php?success=true', // 'cancel_url' => BASE_URL.'/callback/stripe.cb.php?success=false', // ]); // return $checkout_session; } }
true
a4674ae8bbb11c939aa79caf146362b96f5c693d
PHP
shuvro-zz/Symfony-3-ERPMedical
/src/BackendBundle/Entity/TypeGender.php
UTF-8
2,417
2.859375
3
[ "MIT" ]
permissive
<?php /* Namespace **************************************************************************************************/ namespace BackendBundle\Entity; /* Añadimos el VALIDADOR **************************************************************************************/ /* * Definimos el sistema de validación de los datos en las entidades dentro de "app\config\config.yml" * y la gestionamos en "src\AppBundle\Resources\config\validation.yml", * cada entidad deberá llamar a "use Symfony\Component\Validator\Constraints as Assert;" * VER src\BackendBundle\Entity\User.php */ use Symfony\Component\Validator\Constraints as Assert; /**************************************************************************************************************/ /* * Un ArrayCollection es una implementación de colección que se ajusta a la matriz PHP normal. */ use Doctrine\Common\Collections\ArrayCollection; /* * También deberá incluir "use Doctrine\ORM\Mapping as ORM;"" como ORM; instrucción, que importa el * prefijo de anotaciones ORM. */ use Doctrine\ORM\Mapping as ORM; /**************************************************************************************************************/ class TypeGender { /* Un ArrayCollection es una implementación de colección que se ajusta a la matriz PHP normal. */ private $genderArray; public function __construct() { $this->genderArray = new ArrayCollection(); } /* Id de la Tabla *********************************************************************************************/ private $id; public function getId() { return $this->id; } /**************************************************************************************************************/ /* gender *****************************************************************************************************/ private $type; public function setType($type = null) { $this->type = $type; return $this; } public function getType() { return $this->type; } /**************************************************************************************************************/ /* * la función __toString(){ return $this->gender; } permite * listar los campos cuando referenciemos la tabla */ public function __toString(){ return (string)$this->type; } /**************************************************************************************************************/ }
true
0b33d04a0409e60306cbc57dc3ff29e1cbecc133
PHP
shiroro666/Vaccination_System
/index.php
UTF-8
2,460
2.765625
3
[]
no_license
<!DOCTYPE html> <html> <title>Patient Index Page</title> <?php include ("connectdb.php"); if(!isset($_SESSION["user_id"])) { echo "You are currently not logged in. <br /><br >\n"; echo 'Click <a href="login.php">login</a> to login or <a href="register.php">register</a> if you don\'t have an account yet.<br /><br />'; echo 'Click <a href="signup.php">Signup</a> to login if you are a provider.'; echo "\n"; } else { $username = htmlspecialchars($_SESSION["username"]); $user_id = htmlspecialchars($_SESSION["user_id"]); //echo "4"; if ($stmt = $mysqli->prepare("select patientId, name, ssn, birthday, address, phone, email from patient where patientId=?")){ //echo("1"); $stmt->bind_param("s", $user_id); $stmt->execute(); $stmt->bind_result($pid, $name, $ssn, $birthday, $address, $phone, $email); if ($stmt->fetch()){ echo "Welcome $username. You are logged in to the system.<br /><br />\n"; echo "Your Information:<br />"; echo "UserID:".$pid."<br />"; echo "Name:".$name."<br />"; echo "SSN:".$ssn."<br />"; echo "Birthday:".$birthday."<br />"; echo "Address:".$address."<br />"; echo "Phone:".$phone."<br />"; echo "E-Mail:".$email."<br /><br />"; echo 'To view the your appointment offers, <a href="view.php">click here</a>, '; echo "<br /><br />"; echo 'Update information: <a href="update_info.php">click here</a>, '; echo "<br /><br />"; echo 'View or add preferences: <a href="preference.php">click here</a>, '; echo "<br /><br />"; echo 'Log out: <a href="logout.php">click here</a>.'; echo "\n"; } $stmt->close(); } if ($stmt = $mysqli->prepare("select providertype, name, phone, address from provider where providerId=?")){ //echo("2"); $stmt->bind_param("s", $user_id); $stmt->execute(); $stmt->bind_result($pt, $name, $phone, $address); if ($stmt->fetch()){ echo "Welcome $username. You are logged in to the system.<br /><br />\n"; echo "Your Information:<br />"; echo "Provider Type:".$pt."<br />"; echo "Name:".$name."<br />"; echo "Address:".$address."<br />"; echo "Phone:".$phone."<br /><br />"; echo "To view or add appointment <a href=\"appointment.php\">here</a>."; echo "<br /><br />"; echo 'Log out: <a href="logout.php">click here</a>.'; echo "\n"; } $stmt->close(); } } ?> </html>
true
6f9fc1a1c7e0ec206a848408924c01cc32ad5374
PHP
KrisoprasEpikuros/unbk
/application/libraries/JalurState/JalurState.php
UTF-8
962
2.90625
3
[]
no_license
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Description of JalurState * @property CI_Controller $ci * @property StateManager $stateManager * @property JenisSiswaState $jenisSiswaState * * @author m.rap */ abstract class JalurState { protected $ci; protected $stateManager; private $jenisSiswaState; protected $name; public function __construct(&$ci, &$stateManager) { $this->ci =& $ci; $this->stateManager =& $stateManager; } public function &getName() { return $this->name; } public function __get($name) { if ($this->$name == null) { switch ($name) { case 'jenisSiswaState': $this->jenisSiswaState =& $this->stateManager->getJenisSiswaState(); break; } } return $this->$name; } public abstract function validasi(); }
true
58bf076ad98b71b8e346dfd194630f9a7fb3ec66
PHP
juanda/curso_php7_ejercicios
/ejercicio3/find.php
UTF-8
625
2.578125
3
[]
no_license
<?php require __DIR__ . '/libs/autoloader.php'; require __DIR__ . '/readline.php'; use Acme\TopSecret\AES256Crypter; use Acme\KeyStorage\KeyFileStorage; use Acme\KeyStorage\KeyRegister; if($argc != 2){ echo "Uso: $argv[0] nombre_registro". PHP_EOL; exit; } $nombreRegistro = $argv[1]; $keyfile = "keyfile"; $key = _readline('key: '); $crypter = new AES256Crypter($key); $keyStorage = new KeyFileStorage($crypter, $keyfile); $item = $keyStorage->find($nombreRegistro); if(is_null($item)){ echo "No hay ningún registro con ese nombre"; echo PHP_EOL; } print_r($item);
true
060996196d76d763aa438cb253cb743ae79faa4c
PHP
brunocaramelo/estudos
/php/zendframework-modulo-1/estoque/skeleton-application/module/Estoque/src/View/Helper/PaginationHelper.php
UTF-8
711
2.65625
3
[]
no_license
<?php namespace Estoque\View\Helper; use Zend\View\Helper\AbstractHelper; class PaginationHelper extends AbstractHelper{ public function __invoke( $itens , $qtdPagina , $url ){ $this->url = $url; $this->totalItens = $itens->count(); $this->qtdPagina = $qtdPagina; return $this; } public function render(){ $count = 0; $totalPaginas = ceil( $this->totalItens / $this->qtdPagina ); $html = "<ul class='nav nav-pills'>"; while( $count < $totalPaginas ){ $count++; $html.= "<li><a href='{$this->url}/{$count}' >{$count}</a></li>"; } $html.="</ul>"; return $html; } }
true
9beaf237f0e7a9706aaf9dec1d58e2b61d188319
PHP
danielkiesshau/WebPractice
/PHP/update.php
UTF-8
1,462
2.6875
3
[]
no_license
<?php require_once("Sql.php"); $sql = new Sql(); //This will result in a query of active drivers to pass to the JS to update the UI $rs = $sql->select("SELECT nome FROM MOTORISTAS WHERE sstatus = :STATUS",array(":STATUS"=>1)); $data = json_encode($rs); $tipo = $_GET['tipo']; setcookie("tabela","1", time() + (400), "/"); ?> <script src="../lib/jquery-1.11.1.js"></script> <script type=text/javascript> //Get the data stored in dadosPHP $(document).ready(function(){ var dadosJson = $("#dadosPHP").html(); //Converting data to JSON var objJson = JSON.parse(dadosJson); //Store localStorage.setItem('obj', JSON.stringify(objJson)); var tipo = $("#tipo").html(); //Redirecting to passageiro.html if(tipo == 'passageiro'){ window.location.href="https://whispering-eyrie-32116.herokuapp.com/Paginas/HTML/passageiro.html?update=1"; }else if(tipo == 'corrida'){ window.location.href="https://whispering-eyrie-32116.herokuapp.com/Paginas/HTML/corrida.html?update=1"; }else{ window.location.href="https://whispering-eyrie-32116.herokuapp.com/index.html"; } }); </script> <!DOCTYPE html> <html> <meta charset='UTF-8'> <head></head> <body> <div id="dadosPHP" style="display:none;"><?php echo $data;?></div> <div id="tipo" style="display:none;"><?php echo $tipo;?></div> </body> </html>
true
ba68d0b1e36147bc60f7aef3497a3be4b8c88e73
PHP
stephenjohndev/renewmember-them-little
/public/_system/php/api/customer/getAgeCounts.php
UTF-8
1,866
2.9375
3
[]
no_license
<?php # Set database parameters require_once $_SERVER['DOCUMENT_ROOT'].'/_system/php/connection/db_connection.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/_system/php/functions/checkAdminToken.php'; try { # Connect to Database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); # Perform SQL Query // $stmt = $conn->prepare("SELECT DATE(account_created) as date, COUNT(account_id) as count FROM accounts WHERE account_created BETWEEN $start_date AND $end_date GROUP BY date"); $stmt = $conn->prepare( "SELECT CASE WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) < 18 THEN 'Below 18' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 18 AND 30 THEN '18-30' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 31 AND 45 THEN '31-45' WHEN TIMESTAMPDIFF(YEAR, account_birthdate, CURDATE()) BETWEEN 46 AND 60 THEN '46-60' ELSE 'Over 60' END AS age_range, COUNT(account_id) as count FROM accounts GROUP BY age_range" ); $stmt->execute(); # Fetch Result $age_ranges = array(); $counts = array(); while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { array_push($age_ranges, $row['age_range']); array_push($counts, $row['count']); } $result = array( 'age_ranges' => $age_ranges, 'counts' => $counts ); # Print Result in JSON Format echo json_encode((object)[ 'success' => true, 'data' => $result ],JSON_NUMERIC_CHECK); } catch(PDOException $e) { echo json_encode((object)[ 'success' => false, 'message' => "Connection failed: " . $e->getMessage() ]); } ?>
true
1acb58be632664fa589152ec5cc990dd5a3f91cb
PHP
stoyantodorovbg/PHP-Web-Development-Basics
/PHP Associate Arrays and Functions - Lab/1 asociativeArrays/1-characterCount.php
UTF-8
561
3.328125
3
[ "MIT" ]
permissive
<?php $word = fgets(STDIN); $word = strtolower($word); $countLetters = []; for ($i = 0; $i < strlen($word); $i++) { if (isset($countLetters[$word[$i]])) { $countLetters[$word[$i]]++; } else { $countLetters[$word[$i]] = 1; } } $result = '['; $counter = 0; foreach ($countLetters as $key => $value) { $counter++; $result .= '"'; $result .= $key; $result .= '" => "'; $result .= $value; if ($counter === count($countLetters)) { } else { $result .= '", '; } } $result .= ']'; echo($result);
true
e6e4fc27278c55d2ac057e9d68109430ce5fde80
PHP
PhilippeSimier/Gestion_Inscriptions
/administration/authentification/auth.php
UTF-8
2,852
2.6875
3
[]
no_license
<?php if(!isset($_POST['md5'])) { header("Location: ../index.php"); exit(); } if(!isset($_POST['login'])) { header("Location: ../index.php"); exit(); } if($_POST['login']==NULL) { header("Location: ../index.php?&erreur=Requiert un identifiant et un mot de passe."); exit(); } require_once('../../definitions.inc.php'); // connexion à la base $bdd = new PDO('mysql:host=' . SERVEUR . ';dbname=' . BASE, UTILISATEUR,PASSE); // utilisation de la méthode quote() // Retourne une chaîne protégée, qui est théoriquement sûre à utiliser dans une requête SQL. $sql = sprintf("SELECT * FROM utilisateur WHERE utilisateur.login=%s", $bdd->quote($_POST['login'])); $stmt = $bdd->query($sql); $utilisateur = $stmt->fetchObject(); // vérification des identifiants login et md5 par rapport à ceux enregistrés dans la base if (!($_POST['login'] == $utilisateur->login && $_POST['md5'] == $utilisateur->passe)){ header("Location: ../index.php?&erreur=Incorrectes! Vérifiez vos identifiant et mot de passe."); exit(); } // A partir de cette ligne l'utilisateur est authentifié // donc nouvelle session session_start(); // écriture des variables de session pour cet utilisateur $_SESSION['last_access'] = time(); $_SESSION['ipaddr'] = $_SERVER['REMOTE_ADDR']; $_SESSION['ID_user'] = $utilisateur->ID_user; $_SESSION['login'] = $utilisateur->login; $_SESSION['identite'] = $utilisateur->identite; $_SESSION['email'] = $utilisateur->email; $_SESSION['droits'] = $utilisateur->droits; $_SESSION['path_fichier_perso'] = $utilisateur->path_fichier_perso; // enregistrement de la date et heure de son passage dans le champ date_connexion de la table utilisateur $ID_user = $utilisateur->ID_user; $sql = "UPDATE `utilisateur` SET `date_connexion` = CURRENT_TIMESTAMP WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1" ; $stmt = $bdd->query($sql); // Incrémentation du compteur de session $sql = "UPDATE utilisateur SET `nb_session` = `nb_session`+1 WHERE `utilisateur`.`ID_user` =$ID_user LIMIT 1" ; $stmt = $bdd->query($sql); // sélection de la page de menu en fonction des droits accordés switch ($utilisateur->droits) { case 0: // Utilisateur révoqué sans droit header("Location: ../index.php?&erreur=révoqué! "); break; case 1: // Organisateurs de niveau 1 header("Location: ../orga_menu.php"); break; case 2: // Organisateurs de niveau 2 header("Location: ../orga_menu.php"); break; case 3: // Administrateurs de niveau 3 header("Location: ../orga_menu.php"); break; default: header("Location: ../index.php"); } ?>
true
abf3c72df1963548b31c942011da660ba2779b93
PHP
Mirdrack/prueba
/classes/Vehicles.php
UTF-8
1,123
3.3125
3
[]
no_license
<?php require_once('Vehicle.php'); /** * This class will manage an array of Vehicles object instances */ class Vehicles { private $sql; private $error; private $vehicles; function __construct() { $this->sql = new SqlEngine(); $this->sql->connect(); $this->vehicles = array(); } public function getAll() { $query = 'SELECT *'; $query .= 'FROM vehicles '; $result = $this->sql->query($query); if($result != 1) { return false; $this->error = $this->sql->geterror(); // This will send an error to up level } else { if($this->sql->getRowsAffected() > 0 ) { while($row = mysql_fetch_array($this->sql->getQueryResult(), MYSQL_BOTH)) { $current = new Vehicle(); $current->setVehicle($row); array_push($this->vehicles, $current); } return true; } else { $this->error = "No vehicles"; return false; } } } public function getVehicles() { $data = array(); foreach ($this->vehicles as $vehicle) { array_push($data, $vehicle->asArray()); } return $data; } public function getError() { return $this->error; } } ?>
true
c3dafcdc1cf8cf95f3f50cc73e9b549556d6380c
PHP
andreafiori/php-coding-dojo
/src/algorithms/math/Calculator.php
UTF-8
580
3.859375
4
[]
no_license
<?php namespace algorithms\math; class Calculator { /** * @var int|float */ public $op1; /** * @var int|float */ public $op2; /** * Addition * * @return float|int */ public function add() { return $this->op1 + $this->op2; } /** * Subtraction * * @return float|int */ public function subtract() { return $this->op1 - $this->op2; } /** * Check if number is divisible * * @return bool */ public function isDivisible() { return $this->op1 % $this->op2 == 0; } }
true
1b2ef6891fc923b4957d5d139c606bad6ac070c7
PHP
845alex845/consultorafisi
/app/model/Escuela.php
UTF-8
414
2.53125
3
[]
no_license
<?php class Escuela{ $cod_facultad; $nom_facultad; $nom_decano; public function obtenerEscuela($cod_facultad){ $sql="SELECT * from facultad where cod_fac=$id"; $conn=oci_connect("consultora","consultora"); $prepare=oci_parse($conn,$sql); oci_execute($prepare); $scar = oci_fetch_assoc($prepare); return $scar; } } ?>
true
7e4927d6a3bf4319af1c1f81c32fe84dfdd37481
PHP
puiutucutu/geophp
/src/functions/createUtmFromLatLng.php
UTF-8
339
2.75
3
[]
no_license
<?php use PHPCoord\LatLng; use PHPCoord\RefEll; use PHPCoord\UTMRef; /** * Uses WGS84 ellipsoid. * * @param float $latitude * @param float $longitude * * @return UTMRef */ function createUtmFromLatLng($latitude, $longitude) { $LatLng = new LatLng($latitude, $longitude, 0, RefEll::wgs84()); return $LatLng->toUTMRef(); }
true
65919c02274116037b4969c1fc2b4be4854335a1
PHP
mstremante/advent-of-code-2019
/13/part2.php
UTF-8
6,654
3.203125
3
[]
no_license
<?php // Run with php part2.php [input] // If no input file is specified defaults to input.txt in local directory $file = "input.txt"; if(isset($argv[1])) { $file = $argv[1]; } if(file_exists($file)) { $handle = fopen($file, "r"); $opcodes = explode(",", fread($handle, filesize($file))); fclose($handle); $opcodes[0] = 2; $computer = new Computer($opcodes); $screen = array(); $ballX = $paddleX = $score = 0; while(!$computer->isFinished()) { $input = 0; if($ballX > $paddleX) { $input = 1; } if($ballX < $paddleX) { $input = -1; } $outputs = $computer->runProgram($input); $i = 0; while($i < count($outputs)) { if($outputs[$i] == "-1") { $score = $outputs[$i + 2]; } else { if($outputs[$i + 2] == 4) { $ballX = $outputs[$i]; } if($outputs[$i + 2] == 3) { $paddleX = $outputs[$i]; } $screen[$outputs[$i]][$outputs[$i + 1]] = $outputs[$i + 2]; } $i = $i + 3; } // Optional //printScreen($screen); } echo $score; } function printScreen($screen) { $i = 0; $smallX = $bigX = $smallY = $bigY = null; foreach($screen as $x => $y) { if(is_null($smallX)) { $smallX = $x; } if(is_null($bigX)) { $bigX = $x; } if($smallX > $x) { $smallX = $x; } if($bigX < $x) { $bigX = $x; } foreach($y as $id => $tile) { if(is_null($smallY)) { $smallY = $id; } if(is_null($bigY)) { $bigY = $id; } if($smallY > $id) { $smallY = $id; } if($bigY < $id) { $bigY = $id; } } } // Print drawing for($y = $smallY; $y <= $bigY; $y++) { for($x = $smallX; $x <= $bigX; $x++) { $char = " "; if(isset($screen[$x][$y])) { $tile = $screen[$x][$y]; switch($tile) { case 1: $char = "#"; break; case 2: $char = "@"; break; case 3: $char = "_"; break; case 4: $char = "*"; break; } } echo $char; } echo "\n"; } echo "\n\n"; } class Computer { private $data = array(); private $pointer = 0; private $relativeBase = 0; private $finished = false; function __construct($program) { $this->data = $program; } // Executes program function runProgram($inputs = array()) { $outputs = false; if(!is_array($inputs)) { $inputs = array($inputs); } while(($command = $this->data[$this->pointer]) != 99) { // Parse command: $op = substr($command, -2); $command = str_pad($command, 5, 0, STR_PAD_LEFT); switch($op) { // Addition and multiplication case "01": case "02": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if($op == 01) { $res = $op1 + $op2; } else { $res = $op1 * $op2; } $this->setValue($command, 3, $res); $this->pointer += 4; break; // Input value case "03": if(!count($inputs)) { return $outputs; } $input = array_shift($inputs); $this->setValue($command, 1, $input); $this->pointer += 2; break; // Output value case "04": $mode1 = substr($command, -3)[0]; $outputs[] = $this->getValue($command, 1); $this->pointer += 2; break; // Jump if true and jump if false case "05": case "06": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if(($op == "05" && $op1 != 0) || ($op == "06" && $op1 == 0)) { $this->pointer = $op2; } else { $this->pointer +=3; } break; // Less than and equals case "07": case "08": $op1 = $this->getValue($command, 1); $op2 = $this->getValue($command, 2); if(($op == "07" && $op1 < $op2) || ($op == "08" && $op1 == $op2)) { $res = 1; } else { $res = 0; } $this->setValue($command, 3, $res); $this->pointer += 4; break; // Adjust relative base case "09": $op1 = $this->getValue($command, 1); $this->relativeBase += $op1; $this->pointer += 2; break; } } $this->finished = true; return $outputs; } function getValue($command, $param) { $mode = substr($command, -($param + 2))[0]; $addr = $this->data[$this->pointer + $param]; if($mode == 1) { return $addr; } elseif($mode == 2) { $addr = $addr + $this->relativeBase; } // Initialize memory if(!isset($this->data[$addr])) { $this->data[$addr] = 0; } return $this->data[$addr]; } function setValue($command, $param, $value) { $mode = substr($command, -($param + 2))[0]; $addr = $this->data[$this->pointer + $param]; if($mode == 1 || $mode == 0) { $this->data[$addr] = $value; } elseif($mode == 2) { $this->data[$addr + $this->relativeBase] = $value; } } function isFinished() { return $this->finished; } } ?>
true
f2f9c72ae514b27a23380a13ff1573154b323ea5
PHP
holiday/Validator
/Validator.php
UTF-8
3,175
3.34375
3
[]
no_license
<?php namespace Validator; require_once 'Bootstrapper.php'; require_once 'Rule.php'; class Validator { //stores the rules and options private $rules; //stores the data as key:value pairs private $data; //logs errors for each field private $errors = array(); /** * Initializes a new Validator with rules and the data to perform the validation on * @param type $rules Array of fieldnames to rules * @param type $data Array of key value pairs of data */ public function __construct($rules, $data) { $this->rules = $rules; $this->data = $data; // Initialize the bootstrapper $bootstrap = new \Validator\Bootstrapper(dirname(__FILE__)); $bootstrap->register(); } /** * Getter for the errors * @return type Array */ public function getErrors() { return $this->errors; } /** * Return true if there are no errors * @return type Boolean */ public function isValid() { return empty($this->errors); } /** * Parses through each rule * @return type void */ public function validate($rules = null) { //Rules dictating which fields to validate and strategy to use if ($rules == null) { $rules = $this->rules; } //Loop over each field:rule pairs foreach ($rules as $fieldName => $rule) { //single rule detected if (!is_array($rule)) { //validate the field with specifications in array $rule $this->_validate($fieldName, $rule); } else { //multiple rules detected, recurse foreach ($rule as $singleRule) { $multiRule[$fieldName] = $singleRule; $this->validate($multiRule); } } } } /** * Helper method for validate(). Validates an individual field by loading the correct AbstractValidator * and passing in the necessart options. * @param type $fieldName String * @param type $rule Array * @return type void */ private function _validate($fieldName, $rule) { //single rule $validator = '\\ValidationTypes\\' . ucfirst($rule->getValidator()) . 'Validator'; $val = new $validator($this->getData($fieldName), $rule->getOptions()); //Validate and log any errors if (!$val->validate() && !isset($this->errors[$fieldName])) { $this->errors[$fieldName] = $rule->getMessage(); } } /** * Return the data if found, null otherwise * @param type $fieldName * @return null */ private function getData($fieldName) { if (!isset($this->data[$fieldName])) { return null; } else { $data = $this->data[$fieldName]; if(is_string($data)) { $data = trim($this->data[$fieldName]); } return $data; } } } ?>
true
79e5337b912b712e6ab7125bff1865b8e14b86a3
PHP
onenook/helper
/src/string/Sign.php
UTF-8
1,129
3.34375
3
[ "Apache-2.0" ]
permissive
<?php namespace nook\string; class Sign { // ------------------------------ 微信签名 ------------------------------ /** * 生成签名 * @param array $data * @return string */ public static function makeSign(array $data): string { // 签名步骤一:按字典序排序参数 ksort($data); $string = self::toUrlParams($data); // 签名步骤二:在string后加入time $string = $string . '&time=' . time(); // 签名步骤三:sha1加密 $string = sha1($string); // md5() // 签名步骤四:所有字符转为大写 $string = strtoupper($string); return $string; } /** * 格式化参数格式化成url参数 * @param array $data * @return string */ public static function toUrlParams(array $data): string { $buff = ''; foreach ($data as $k => $v) { if ($k != 'sign' && $v != '' && !is_array($v)) { $buff .= $k . '=' . $v . '&'; } } $buff = trim($buff, '&'); return $buff; } }
true
ee5dddaf65cb860277505b6ba4042b574bcb2e89
PHP
robsli/Web-Apps-TESI-Calendar
/dboperation.php
UTF-8
206
2.6875
3
[ "MIT" ]
permissive
<?php function connectToDB($user, $pw, $dbname){ $dbc = @mysqli_connect("localhost", $user, $pw, $dbname) OR die("Could not connect to MySQL on cscilab: ". mysqli_connect_error()); return $dbc; } ?>
true
2b2e01627f94f73cadbb793c2c9a949f1fdb150b
PHP
pmatiash/shape-drawer
/app/Trapezoid.php
UTF-8
1,647
3.4375
3
[]
no_license
<?php namespace app; /** * Class Trapezoid Shape * @package app */ class Trapezoid extends Shape { private $sideTop; private $sideBottom; private $height; /** * @param int $sideTop * @param int $sideBottom * @param int $height * @param string $color */ public function __construct($sideTop, $sideBottom, $height, $color) { if (!$this->isCorrectTrapezoid($sideTop, $sideBottom, $height)) { throw new \Exception("Trapezoid with these parameters can't be exists"); } $this->sideTop = (int) $sideTop; $this->sideBottom = (int) $sideBottom; $this->height = (int) $height; $this->color = $color; } /** * @param $sideTop * @param $sideBottom * @param $height * @return bool */ private function isCorrectTrapezoid($sideTop, $sideBottom, $height) { if ($sideTop <= 0 ) { return false; } if ($sideBottom <= 0) { return false; } if ($height <= 0) { return false; } return true; } /** * @inheritdoc */ public function getName() { return 'Трапеция'; } /** * @inheritdoc */ public function draw() { return parent::draw() . sprintf(', верхняя сторона: %s, нижняя сторона: %s, высота: %s', $this->sideTop, $this->sideBottom, $this->height); } /** * @inheritdoc */ public function getSquare() { return ($this->sideTop + $this->sideBottom) / 2 * $this->height; } }
true
fdd9f6f70ce5ac4c94ed991ca9bb69ddc205093c
PHP
alexdiasgonsales/organizador
/sistema/model/mysql/SessaoMySqlDAO.class.php
UTF-8
6,396
2.625
3
[]
no_license
<?php /** * Classe de operação da tabela 'sessao'. Banco de Dados Mysql. * Estas classes não contemplam meu projeto final, por estarem obsoletas, estou contruindo * novos templates em Persistent Data Object com definição de prepared statements contra * sql injection, utilize para meio de testes, nunca coloque em produção, servindo * apenas de trampolin para classe de produção * * @autor: Alessander Wasem * @data: 2014-05-21 21:57 */ class SessaoMySqlDAO implements SessaoDAO{ protected $table = 'sessao'; /** * Implementa o dominio chave primária na seleção de único registro * * @parametro String $id primary key * @retorna SessaoMySql */ public function load($id){ $sql = "SELECT * FROM $this->table WHERE id_sessao = :id_sessao"; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetch(); } public function querySessaoByAvaliador($id_avaliador) { $sql =<<<SQL select sessao.id_sessao, sessao.numero, sessao.nome, sessao.sala, sessao.nome_sala, sessao.andar, sessao.nome_andar, sessao.data, sessao.hora_ini, sessao.hora_fim, avaliador_sessao.status from sessao inner join avaliador_sessao on sessao.id_sessao = avaliador_sessao.fk_sessao where fk_avaliador = :id_avaliador; SQL; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(); } public function updateConfirmacaoSessao($id_avaliador, $id_sessao, $status_int) { $sql =<<<SQL update avaliador_sessao set status = :status_int where fk_sessao = :id_sessao and fk_avaliador = :id_avaliador SQL; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_avaliador', $id_avaliador, PDO::PARAM_INT); $stmt->bindParam(':id_sessao', $id_sessao, PDO::PARAM_INT); $stmt->bindParam(':status_int', $status_int, PDO::PARAM_INT); return $stmt->execute(); } /** * Obtem todos o registros das Tabelas */ public function queryAll(){ $sql = "SELECT * FROM $this->table"; $stmt = ConnectionFactory::prepare($sql); $stmt->execute(); return $stmt->fetchAll(); } /** * Exclui um registro da tabela * @parametro sessao chave primária */ public function delete($id){ $sql = "DELETE FROM $this->table WHERE id_sessao = :id_sessao"; $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id_sessao', $id, PDO::PARAM_INT); return $stmt->execute(); } /** * Inseri um registro na tabela * * @parametro SessaoMySql sessao */ public function insert(Sessao $Sessao){ $sql = "INSERT INTO $this->table (numero, nome, sala, nome_sala, andar, nome_andar, data, hora_ini, hora_fim, fk_modalidade, status) VALUES ( :numero, :nome, :sala, :nomeSala, :andar, :nomeAndar, :data, :horaIni, :horaFim, :fkModalidade, :status)"; $numero = $Sessao->getNumero(); $nome = $Sessao->getNome(); $sala = $Sessao->getSala(); $nomeSala = $Sessao->getNomeSala(); $andar = $Sessao->getAndar(); $nomeAndar = $Sessao->getNomeAndar(); $data = $Sessao->getData(); $horaIni = $Sessao->getHoraIni(); $horaFim = $Sessao->getHoraFim(); $fkModalidade = $Sessao->getFkModalidade(); $status = $Sessao->getStatus(); $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':numero', $numero); $stmt->bindParam(':nome', $nome); $stmt->bindParam(':sala', $sala); $stmt->bindParam(':nomeSala', $nomeSala); $stmt->bindParam(':andar', $andar); $stmt->bindParam(':nomeAndar', $nomeAndar); $stmt->bindParam(':data', $data); $stmt->bindParam(':horaIni', $horaIni); $stmt->bindParam(':horaFim', $horaFim); $stmt->bindParam(':fkModalidade', $fkModalidade); $stmt->bindParam(':status', $status); return $stmt->execute(); } /** * atualiza um registro da tabela * * @parametro SessaoMySql sessao */ public function update(Sessao $Sessao){ $sql = "UPDATE $this->table SET numero = :numero, nome = :nome, sala = :sala, nome_sala = :nome_sala, andar = :andar, nome_andar = :nome_andar, data = :data, hora_ini = :hora_ini, hora_fim = :hora_fim, fk_modalidade = :fk_modalidade, status = :status WHERE id_sessao = :id"; $id = $Sessao->getIdSessao(); $numero = $Sessao->getNumero(); $nome = $Sessao->getNome(); $sala = $Sessao->getSala(); $nomeSala = $Sessao->getNomeSala(); $andar = $Sessao->getAndar(); $nomeAndar = $Sessao->getNomeAndar(); $data = $Sessao->getData(); $horaIni = $Sessao->getHoraIni(); $horaFim = $Sessao->getHoraFim(); $fkModalidade = $Sessao->getFkModalidade(); $status = $Sessao->getStatus(); $stmt = ConnectionFactory::prepare($sql); $stmt->bindParam(':id', $id); $stmt->bindParam(':numero', $numero); $stmt->bindParam(':nome', $nome); $stmt->bindParam(':sala', $sala); $stmt->bindParam(':nomeSala', $nomeSala); $stmt->bindParam(':andar', $andar); $stmt->bindParam(':nomeAndar', $nomeAndar); $stmt->bindParam(':data', $data); $stmt->bindParam(':horaIni', $horaIni); $stmt->bindParam(':horaFim', $horaFim); $stmt->bindParam(':fkModalidade', $fkModalidade); $stmt->bindParam(':status', $status); return $stmt->execute(); } }
true
d3a69d76ef83838df21d374dfc259ed02dae7dc8
PHP
activecollab/authentication
/src/AuthenticationResult/Transport/Transport.php
UTF-8
2,630
2.625
3
[ "MIT" ]
permissive
<?php /* * This file is part of the Active Collab Authentication project. * * (c) A51 doo <info@activecollab.com>. All rights reserved. */ declare(strict_types=1); namespace ActiveCollab\Authentication\AuthenticationResult\Transport; use ActiveCollab\Authentication\Adapter\AdapterInterface; use LogicException; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; abstract class Transport implements TransportInterface { private $adapter; private $payload; public function __construct(AdapterInterface $adapter, $payload = null) { $this->adapter = $adapter; $this->payload = $payload; } public function getAdapter(): AdapterInterface { return $this->adapter; } public function getPayload() { return $this->payload; } public function setPayload($value): TransportInterface { $this->payload = $value; return $this; } public function isEmpty(): bool { return false; } private $isAppliedToRequest = false; private $isAppliedToResponse = false; public function applyToRequest(ServerRequestInterface $request): ServerRequestInterface { if ($this->isEmpty()) { throw new LogicException('Empty authentication transport cannot be applied'); } if ($this->isAppliedToRequest) { throw new LogicException('Authentication transport already applied'); } $this->isAppliedToRequest = true; return $this->getAdapter()->applyToRequest($request, $this); } public function applyToResponse(ResponseInterface $response): ResponseInterface { if ($this->isEmpty()) { throw new LogicException('Empty authentication transport cannot be applied'); } if ($this->isAppliedToResponse) { throw new LogicException('Authentication transport already applied'); } $this->isAppliedToResponse = true; return $this->getAdapter()->applyToResponse($response, $this); } public function applyTo(ServerRequestInterface $request, ResponseInterface $response): array { return [ $this->applyToRequest($request), $this->applyToResponse($response), ]; } public function isApplied(): bool { return $this->isAppliedToRequest && $this->isAppliedToResponse; } public function isAppliedToRequest(): bool { return $this->isAppliedToRequest; } public function isAppliedToResponse(): bool { return $this->isAppliedToResponse; } }
true
efc1624d2a3359d12ade6f749b993da717fdf766
PHP
FindMyFriends/api
/App/Domain/Access/PgEntrance.php
UTF-8
1,075
2.75
3
[]
no_license
<?php declare(strict_types = 1); namespace FindMyFriends\Domain\Access; use Klapuch\Storage; /** * Entrance to PG database */ final class PgEntrance implements Entrance { /** @var \Klapuch\Storage\Connection */ private $connection; /** @var \FindMyFriends\Domain\Access\Entrance */ private $origin; public function __construct(Entrance $origin, Storage\Connection $connection) { $this->origin = $origin; $this->connection = $connection; } /** * @param array $credentials * @throws \UnexpectedValueException * @return \FindMyFriends\Domain\Access\Seeker */ public function enter(array $credentials): Seeker { $seeker = $this->origin->enter($credentials); (new Storage\NativeQuery($this->connection, 'SELECT globals_set_seeker(?)', [$seeker->id()]))->execute(); return $seeker; } /** * @throws \UnexpectedValueException * @return \FindMyFriends\Domain\Access\Seeker */ public function exit(): Seeker { (new Storage\NativeQuery($this->connection, 'SELECT globals_set_seeker(NULL)'))->execute(); return $this->origin->exit(); } }
true
2dfdc1de9ef3792c6a2b1224c967b7a4142e5330
PHP
araiy555/6ch
/getleak/image.movie.php
UTF-8
5,664
2.671875
3
[ "MIT" ]
permissive
<?php $count = count($_FILES['files']['tmp_name']); $errmsg = ""; // エラーメッセージ $gazou = []; $imageset = 0; $dougaset = 0; try { for ($i = 0; $i < $count; $i++) { //ファイル名の取得 $file_name = $_FILES["files"]["type"][$i]; //preg_match関数で判別するファイルの拡張子に「jpg」「jpeg」「png」「gif」が含まれているか確認する if ($_FILES["files"]["error"][$i] !== 4) { switch ($file_name) { case 'image/png': $imagecount = $imageset + 1; break; case 'image/jpeg': $imagecount = $imageset + 1; break; case 'image/jpg': $imagecount = $imageset + 1; break; case 'video/mp4': $dougaset = $dougaset + 1; $dougacount = $dougaset; break; default: $error = "$i'.枚目 拡張子は「jpg」「jpeg」「png」「mp4」です。</br>"; break; } } } if ($dougacount >= 1 AND $imagecount >= 1) { $error = "画像か動画のアップロードどちらかを設定してください。"; } if ($dougacount >= 2) { $error = "動画は1つのみです。"; } //エラー処理 if (empty($error)) { //動画アップロード if ($dougacount == 1) { $file_nm = $_FILES['files']['name'][0]; $tmp_ary = explode('.', $file_nm); $extension = $tmp_ary[count($tmp_ary) - 1]; if ($extension == 'mp4') { $size = $_FILES['files']['size'][0]; //30MB $san = '125829120'; if ($size < $san) { //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); $name = $_FILES['files']['name'][0]; $type = explode('.', $name); $type = end($type); $size = $_FILES['files']['size'][0]; $tmp = $_FILES['files']['tmp_name'][0]; $random_name = rand(); move_uploaded_file($tmp, 'files/' . $random_name . '.' . $type); $stmt = $pdo->prepare("INSERT INTO douga VALUES('','$name','files/$random_name.$type','')"); $stmt->execute(); $douga = $pdo->lastInsertId(); $stmt = $pdo->query("select * from douga where id = " . "$douga"); $result = $stmt->fetch(); ?> <input type="hidden" id="result1" name="" value="<?php echo $douga; ?>"> <video src="<?php echo $result['raw_data']; ?>" width="50%" height="50%" poster="thumb.jpg" controls></video> <?php } else { $error = "ファイルサイズが大きすぎます。"; echo $error; exit; } } } //画像アップロード if ($imagecount > 0) { for ($i = 0; $i < $count; $i++) { $size = $_FILES['files']['size'][$i]; if ($size < 20000) { $tmp = $_FILES["files"]["tmp_name"][$i]; $fp = fopen($tmp, 'rb'); $data = bin2hex(fread($fp, $size)); //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); //$dsn='mysql:host=localhost;dbname=mini_bbs'; $dsn = 'mysql:host=mysql5027.xserver.jp;dbname=earthwork_sample'; $pdo->exec("INSERT INTO `upload`(`type`,`data`) values ('$type',0x$data)"); $gazou[] = $pdo->lastInsertId(); $pdo = null; } else { $error = "画像は20KB以内です。"; echo $error; exit; } } $color = implode(",", $gazou); //$pdo = new PDO('mysql:dbname=mini_bbs;host=localhost','root','1234'); $pdo = new PDO('mysql:dbname=earthwork_sample;host=mysql5027.xserver.jp', 'earthwork_arai', 'q1w2e3r4'); $images = $pdo->query("select * from upload where id IN (" . $color . ")"); if (!empty($images)): foreach ($images as $i => $img): if ($i): endif; ?> <li id="<?php echo $img['id']; ?>"> <input type="hidden" id="result" name="" value="<?php echo $color ?>"> <img src="data:image/jpeg;base64,<?= base64_encode($img['data']) ?>" width="10%" height="10%" class="img"> </li> <?php endforeach; endif; } } else { echo $error; exit; } } catch (PDOException $e) { // 500 Internal Server Errorでテキストとしてエラーメッセージを表示 http_response_code(500); header('Content-Type: text/plain; charset=UTF-8', true, 500); exit($e->getMessage()); } ?>
true
2a1ccb95936a4bc640dbb97473ded42ea0c5ec88
PHP
fransaez85/clinica_js
/php/consultaTodosMedicos.php
UTF-8
1,069
2.953125
3
[]
no_license
<?php include_once 'conexion.php'; //consulta todos los registros $query = "SELECT * FROM medico"; $resul = $conexion->query($query); $dimension=$resul->num_rows; if ($dimension>0) { # code... for ($i=0; $i < $dimension; $i++) { $array_fila[] = $resul->fetch_assoc(); $objmedico =$array_fila[$i]; $array_medicos[$i] = $objmedico; } $obj_JSON = json_encode($array_medicos); //alert($obj_JSON); echo $obj_JSON; } else { echo "error"; } /*include_once("conexion.php"); class medico { public $id; public $nombre; public $id_especialidad; public $foto; public function __construct ($id, $nombre,$id_especialidad, $foto){ $this->id = $id; $this->nombre = $nombre; $this->id_especialidad = $id_especialidad; $this->foto = $foto; } } $sql = "SELECT * FROM medico"; $res = $conexion->query($sql); $aux = $res->num_rows; if ($res->num_rows > 0) { while ($aux > 0) { $datos= $res->fetch_object(); $dat[]=$datos; $aux--; } $json=JSON_encode($dat); echo $json; }else { echo "error"; }*/ ?>
true
05237daf21ec12a0afa44941ca316c219e93a909
PHP
matthewdimatteo/ctrex
/php/content/content-disclosures.php
UTF-8
1,887
2.515625
3
[]
no_license
<?php /* php/content/content-disclosures.php By Matthew DiMatteo, Children's Technology Review This is the content file for the disclosures page It is included dynamically in the file 'php/document.php' */ // PAGE HEADER if($disclosuresHeader != NULL) { echo '<div class = "page-header">'.$disclosuresHeader.'</div>'; } // PAGE BODY echo '<div class = "paragraph left bottom-10">'; // INTRO if($disclosuresIntro != NULL) { echo '<p>'.parseLinksOld($disclosuresIntro).'</p>'; } // SOURCES OF INCOME if(count($disclosuresIncomeItems > 0)) { echo '<p>'; for($i = 0; $i <= count($disclosuresIncomeItems); $i++) { $incomeItem = $disclosuresIncomeItems[$i]; $incomeDescription = $disclosuresIncomeDescriptions[$i]; if($incomeItem != NULL) { echo '<strong>'.$incomeItem.'</strong>'; if($incomeDescription != NULL) { echo parseLinksOld($incomeDescription); } echo '<br/>'; } // end if $incomeItem } // end for echo '</p>'; } // end if $disclosuresIncomeItems // ADVERTISING AND SPONSORSHIP RELATIONSHIPS if($disclosuresRelHeader == NULL) { $disclosuresRelHeader = 'ADVERTISING AND SPONSORSHIP RELATIONSHIPS<br/></br>In order to be a sponsor or underwriter (e.g., for research), the business partner must meet the following conditions:'; } // end if !$disclosuresRelHeader if(count($disclosuresRelItems) > 0) { echo '<ul>'; for($i = 0; $i <= count($disclosuresRelItems); $i++) { $thisRelItem = $disclosuredRelItems[$i]; if($thisRelItem != NULL) { echo '<li>'.parseLinksOld($thisRelItem).'</li>'; } } // end for echo '</ul>'; } // end if $disclosuresRelItems // CONCLUSION, DATE MODIFIED if($disclosuresConclusion != NULL) { echo '<p>'.parseLinksOld($disclosuresConclusion).'</p>'; } if($disclosuresDateModified != NULL) { echo 'Last update: '.$disclosuresDateModified; } echo '</div>'; // /.paragraph left bottom-10 ?>
true
51f033530f7c168b50dce06012c036d83587a4c7
PHP
ck6390/CMS
/application/controllers/Attandance_bioMonth.php
UTF-8
8,002
2.515625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* * *****************Welcome.php********************************** * @product name : Global School Management System Pro * @type : Class * @class name : Welcome * @description : This is default class of the application. * @author : Codetroopers Team * @url : https://themeforest.net/user/codetroopers * @support : yousuf361@gmail.com * @copyright : Codetroopers Team * ********************************************************** */ class Attandance_bioMonth extends CI_Controller { /* * **************Function index********************************** * @type : Function * @function name : index * @description : this function load login view page * @param : null; * @return : null * ********************************************************** */ function __construct() { parent::__construct(); $this->load->model('Attandances_bio','m_bio_att'); } public function index() { $employee = $this->m_bio_att->get_bio_att_emp();//bio data // var_dump($employee); // die(); $curr_year = date('Y'); $curr_month = '08'; //$curr_month = date('m'); $curr_day = date('d'); foreach ($employee as $emp) { //$id_bio = ''; $sub_str = substr($emp->EmployeeCode, 0, 1); $id = substr($emp->EmployeeCode, 1); $em_id = $emp->EmployeeCode; //var_dump($sub_str); //die(); if($sub_str == '3'){ $type = 'employee'; $result_att = $this->m_bio_att->get_employee_lists($id); $condition = array( 'month' => $curr_month, 'year' => $curr_year, //'employee_id' =>'31011' 'employee_id' =>@$result_att->employee_id ); $data = $condition; if (!empty($result_att)) { $attendance = $this->m_bio_att->get_single_data($condition,$type); } $bio_att_year = date('Y'); $bio_att_month = date('m'); //$bio_att_month = '08'; $bio_att_day = date('d'); $today = date('Y-m-d'); $time = date("h:i:s a"); $no_of_days = cal_days_in_month(CAL_GREGORIAN, $bio_att_month,$bio_att_year); $attend = array(); for ($i=1; $no_of_days >= $i; $i++) { $attend[] = array('day'=>$i,'attendance'=>'','attendance_date'=>'','attendance_time'=>'','out_time'=>''); } if (empty($attendance)) { $data['employee_id'] = $result_att->employee_id; $data['status'] = '1'; $data['created_at'] = date('Y-m-d H:i:s'); $data['attendance_data'] = json_encode($attend); $this->m_bio_att->insert($data,$type); }else{ var_dump($attendance); $this->update_atten($em_id,$attendance,$condition,$type); } } } die(); echo "<h1 style='text-align:center;'>Employee Attendance Updated.</h1>"; } public function update_atten($em_id,$attendance,$condition,$type) { //var_dump($em_id); $result = $this->m_bio_att->get_bio_att($em_id);//bio data //$result = $this->m_bio_att->get_bio_att('31011'); //echo "<pre>"; //var_dump($result); // die(); $attendance_data = $attendance->attendance_data; $attendance_data_decode = json_decode($attendance_data); //var_dump($attendance_data_decode); $attend = array(); $today = date('Y-m-d'); /* if($em_id == @$result->UserId) //if($em_id == "31011") { //var_dump($result->LogDate); $bio_att_day = date('d',strtotime($result->LogDate)); $today = date('Y-m-d',strtotime($result->LogDate)); $time = date("h:i:sa",strtotime($result->LogDate)); $out_time = date("h:i:sa",strtotime($result->LogDate)); $status = "P"; //P for present var_dump($out_time); // die(); }else{ $bio_att_day = date('d'); $today = date('Y-m-d'); $time = ""; $status = "A"; //P for present } */ //echo "<PRe>"; //print_r($result); $attend_blank = array(); $no_of_days = 31; for ($i=1; $no_of_days >= $i; $i++) { if($i < 10){ $j = '0'.$i; }else{ $j = $i; } $today = date('Y-08-'.$j); $attend_blank[$today] = array('day'=>$i,'attendance'=>'A','attendance_date'=>$today,'attendance_time'=>'','out_time'=>''); } $dateArray = array(); if(!empty($result)){ foreach ($result as $key_res => $res) { $bio_att_day = date('d',strtotime($res->LogDate)); //if(empty($res->attendance_time)){ $today = date('Y-m-d',strtotime($res->LogDate)); $time = date("h:i:sa",strtotime($res->LogDate)); $out_time = date("h:i:sa",strtotime($res->LogDate)); $status = "P"; if(in_array($today, $dateArray)){ $tempArray = $attend[$today]; $attend[$today] = array('day'=>$tempArray['day'],'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$tempArray['attendance_time'],'out_time'=>$out_time); }else{ $attend[$today] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>''); } $dateArray[$key_res]= $today; } } //echo "<PRe>"; //print_r($attend); //print_r($attend_blank); //$final_array = array_merge($attend,$attend_blank); foreach ($attend_blank as $key_blank => $blank) { if(array_key_exists($key_blank, $attend)){ $final_array[$key_blank] = $attend[$key_blank]; }else{ $final_array[$key_blank] = $blank; } } //print_r($final_array); echo $attendance_record = json_encode(array_values($final_array)); die; //*/var_dump($today); /*foreach ($attendance_data_decode as $att_data) { // var_dump($out_time); // die(); if($att_data->day == $bio_att_day){ /// for out time check 'attendance_time' if(empty($att_data->attendance_time)){ $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$time,'out_time'=>''); }else{ $attend[] = array('day'=>$bio_att_day,'attendance'=>$status,'attendance_date'=>$today,'attendance_time'=>$att_data->attendance_time,'out_time'=>$out_time); } }else{ $attend[] = $att_data; } } $attendance_record = json_encode($attend); */ //var_dump($condition); //$this->m_bio_att->update_attandance($attendance_record,$time,$condition,$type); $em_id = substr($em_id, 1); // $data['attendance_data'] = json_encode($attend); $data['attendance_data'] = $attendance_record; $this->db->where('employee_id',$em_id); $this->db->where('month','08'); $this->db->where('year','2019'); $this->db->update('employee_attendances',$data); //$this->m_bio_att->update_attandance($data); //die; } }
true
0b216ed27db043f8f090cbd8e10d276b2660b494
PHP
StepanKovalenko/trustly-client-php
/Trustly/Data/jsonrpcrequest.php
UTF-8
7,005
2.8125
3
[ "Apache-2.0", "MIT" ]
permissive
<?php /** * Trustly_Data_JSONRPCRequest class. * * @license https://opensource.org/licenses/MIT * @copyright Copyright (c) 2014 Trustly Group AB */ /* The MIT License (MIT) * * Copyright (c) 2014 Trustly Group AB * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /** * Class implementing the structure for data used in the signed API calls */ class Trustly_Data_JSONRPCRequest extends Trustly_Data_Request { /** * Constructor. * * @throws Trustly_DataException If the combination of $data and * $attributes is invalid * * @param string $method Outgoing call API method * * @param mixed $data Outputgoing call Data (if any). This can be either an * array or a simple non-complex value. * * @param mixed $attributes Outgoing call attributes if any. If attributes * is set then $data needs to be an array. */ public function __construct($method=NULL, $data=NULL, $attributes=NULL) { $payload = NULL; if(isset($data) || isset($attributes)) { $payload = array('params' => array()); if(isset($data)) { if(!is_array($data) && isset($attributes)) { throw new Trustly_DataException('Data must be array if attributes is provided'); } $payload['params']['Data'] = $data; } if(isset($attributes)) { if(!isset($payload['params']['Data'])) { $payload['params']['Data'] = array(); } $payload['params']['Data']['Attributes'] = $attributes; } } parent::__construct($method, $payload); if(isset($method)) { $this->payload['method'] = $method; } if(!isset($this->payload['params'])) { $this->payload['params'] = array(); } $this->set('version', '1.1'); } /** * Set a value in the params section of the request * * @param string $name Name of parameter * * @param mixed $value Value of parameter * * @return mixed $value */ public function setParam($name, $value) { $this->payload['params'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of a params parameter in the request * * @param string $name Name of parameter of which to obtain the value * * @return mixed The value */ public function getParam($name) { if(isset($this->payload['params'][$name])) { return $this->payload['params'][$name]; } return NULL; } /** * Pop the value of a params parameter in the request. I.e. get the value * and then remove the value from the params. * * @param string $name Name of parameter of which to obtain the value * * @return mixed The value */ public function popParam($name) { $v = NULL; if(isset($this->payload['params'][$name])) { $v = $this->payload['params'][$name]; } unset($this->payload['params'][$name]); return $v; } /** * Set the UUID value in the outgoing call. * * @param string $uuid The UUID * * @return string $uuid */ public function setUUID($uuid) { $this->payload['params']['UUID'] = Trustly_Data::ensureUTF8($uuid); return $uuid; } /** * Get the UUID value from the outgoing call. * * @return string The UUID value */ public function getUUID() { if(isset($this->payload['params']['UUID'])) { return $this->payload['params']['UUID']; } return NULL; } /** * Set the Method value in the outgoing call. * * @param string $method The name of the API method this call is for * * @return string $method */ public function setMethod($method) { return $this->set('method', $method); } /** * Get the Method value from the outgoing call. * * @return string The Method value. */ public function getMethod() { return $this->get('method'); } /** * Set a value in the params->Data part of the payload. * * @param string $name The name of the Data parameter to set * * @param mixed $value The value of the Data parameter to set * * @return mixed $value */ public function setData($name, $value) { if(!isset($this->payload['params']['Data'])) { $this->payload['params']['Data'] = array(); } $this->payload['params']['Data'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of one parameter in the params->Data section of the * request. Or the entire Data section if no name is given. * * @param string $name Name of the Data param to obtain. Leave as NULL to * get the entire structure. * * @return mixed The value or the entire Data depending on $name */ public function getData($name=NULL) { if(isset($name)) { if(isset($this->payload['params']['Data'][$name])) { return $this->payload['params']['Data'][$name]; } } else { if(isset($this->payload['params']['Data'])) { return $this->payload['params']['Data']; } } return NULL; } /** * Set a value in the params->Data->Attributes part of the payload. * * @param string $name The name of the Attributes parameter to set * * @param mixed $value The value of the Attributes parameter to set * * @return mixed $value */ public function setAttribute($name, $value) { if(!isset($this->payload['params']['Data'])) { $this->payload['params']['Data'] = array(); } if(!isset($this->payload['params']['Data']['Attributes'])) { $this->payload['params']['Data']['Attributes'] = array(); } $this->payload['params']['Data']['Attributes'][$name] = Trustly_Data::ensureUTF8($value); return $value; } /** * Get the value of one parameter in the params->Data->Attributes section * of the request. Or the entire Attributes section if no name is given. * * @param string $name Name of the Attributes param to obtain. Leave as NULL to * get the entire structure. * * @return mixed The value or the entire Attributes depending on $name */ public function getAttribute($name) { if(isset($this->payload['params']['Data']['Attributes'][$name])) { return $this->payload['params']['Data']['Attributes'][$name]; } return NULL; } } /* vim: set noet cindent sts=4 ts=4 sw=4: */
true
2838764f80fb96c99eac7279a5716585b7f97fcb
PHP
igorbunov/checkbox-in-ua-php-sdk
/src/Models/CashRegisters/CashRegistersQueryParams.php
UTF-8
691
2.75
3
[ "MIT" ]
permissive
<?php namespace igorbunov\Checkbox\Models\CashRegisters; class CashRegistersQueryParams { /** @var bool|null $inUse */ public $inUse; // null, true, false /** @var int $limit */ public $limit; /** @var int $offset */ public $offset; public function __construct( ?bool $inUse = null, int $limit = 25, int $offset = 0 ) { if ($offset < 0) { throw new \Exception('Offset cant be lower then 0'); } if ($limit > 1000) { throw new \Exception('Limit cant be more then 1000'); } $this->inUse = $inUse; $this->offset = $offset; $this->limit = $limit; } }
true
fdda5b5b4e22b9510ee83070887ccc9676e2bb32
PHP
thulioprado/api-next
/src/Database/Collection.php
UTF-8
1,488
2.890625
3
[]
no_license
<?php declare(strict_types=1); namespace Directus\Database; use Directus\Contracts\Database\Collection as CollectionContract; use Directus\Contracts\Database\Database as DatabaseContract; use Illuminate\Database\Connection; use Illuminate\Database\Query\Builder; /** * Directus collection. */ class Collection implements CollectionContract { /** * @var string */ private $name; /** * @var string */ private $prefix; /** * @var Connection */ private $connection; /** * Constructor. */ public function __construct(DatabaseContract $database, string $name) { $this->name = $name; $this->prefix = $database->prefix(); /** @var Connection $connection */ $connection = $database->connection(); $this->connection = $connection; } public function name(): string { return $this->prefix.$this->name; } public function prefix(): string { return $this->prefix; } public function fullName(): string { return $this->connection->getTablePrefix().$this->prefix.$this->name; } public function builder(): Builder { return $this->connection->table($this->name()); } public function drop(): void { $this->connection->getSchemaBuilder()->drop($this->name()); } public function truncate(): void { $this->connection->table($this->name())->truncate(); } }
true
796efcedbc4ed92b5fc7cce81952ff86e2c0c1c7
PHP
ZED-Magdy/PHP-DDD-Blog-exapmle
/src/Domain/Blog/Service/DeleteTagServiceInterface.php
UTF-8
359
2.578125
3
[]
no_license
<?php namespace App\Domain\Blog\Service; use App\Domain\Blog\Exception\TagNotFoundException; use App\Domain\Blog\ValueObject\TagId; interface DeleteTagServiceInterface { /** * Undocumented function * * @param TagId $tagId * @return void * @throws TagNotFoundException */ public function execute(TagId $tagId): void; }
true
595f53679ef82e20abefd4a77651a81910d4b5ff
PHP
NatashaAC/HTTP5203_Final_Project-Natasha_Chambers
/views/breed_details.php
UTF-8
2,291
2.578125
3
[]
no_license
<?php // Grabbing the cat breed's name and accounting for spaces $url = 'https://api.thecatapi.com/v1/breeds/search?q=' . str_replace(' ', '%20', $_GET["name"]); $results = json_decode(file_get_contents($url)); $breed_name = $results[0]->name; $breed_alt_name = $results[0]->alt_names; $breed_image = $results[0]->image->url; $breed_des = $results[0]->description; $breed_temp = $results[0]->temperament; $breed_life_span = $results[0]->life_span; $breed_origin = $results[0]->origin; $breed_weight = $results[0]->weight->imperial; $wiki_page = $results[0]->wikipedia_url; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device=width, initial-scale=1" /> <meta name="description" content="A website for all cat lovers!"> <!-- Scripts --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-U1DAWAznBHeqEIlVSCgzq+c9gqGAJn5c/t99JyeKa9xxaYpSvHU5awsuZVVFIhvj" crossorigin="anonymous"></script> <!-- Style Sheets --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <link rel="stylesheet" href="../css/main.css"> <title>Breeds</title> </head> <body> <?php require_once "shared/header.php"; ?> <main id="page"> <?php echo '<div class="container-fluid card detailCard"> <h1>' . $breed_name . '</h1> <h2>Alternate Names: ' . $breed_alt_name . '</h2> <div class="card-body"> <p>' . $breed_des . '</p> <p>This cat breed is from ' . $breed_origin . '</p> <p>Life Span: ' . $breed_life_span . ' years</p> <p>Weight: ' . $breed_weight . 'lb</p> <p>Temperament: ' . $breed_temp . '</p> <a class="btn btn-outline-info" href="' . $wiki_page . '">Checkout Wikipedia Page!</a> </div> </div>'; ?> </main> <?php include "shared/footer.php"; ?> </body> </html>
true
d762a3aa4e638b71e3fe5b5fbfc4ef4e39b18eea
PHP
30002731/6210-SCP
/SCP Files/connection.php
UTF-8
479
2.578125
3
[]
no_license
<?php //Create Database credential variables $user = "a3000273_user"; $password = "Toiohomai1234"; $db = "a3000273_SCP_Files"; //Create php db connection object $connection = new mysqli("localhost", $user, $password, $db) or die(mysqli_error($connection)); //Get all data from table and save in a variable for use on our page application $result = $connection->query("select * from SCP_Subjects") or die($connection->error()); ?>
true
28e6a389df275333f7d793ac4f4c64bb54260622
PHP
vkabachenko/yii2-eer
/common/models/Student.php
UTF-8
2,323
2.6875
3
[]
no_license
<?php namespace common\models; use Yii; /** * This is the model class for table "student". * * @property integer $id * @property string $name * @property string $email * * @property StudentEducation[] $studentEducations * @property StudentPortfolio[] $studentPortfolios */ class Student extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'student'; } /** * @inheritdoc */ public function rules() { return [ [['name','email'], 'required'], [['name'], 'string', 'max' => 100], [['email'], 'string', 'max' => 250], [['email'], 'email'], [['email'], 'unique'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Фамилия Имя Отчество', 'email' => 'Email', ]; } /** * @return \yii\db\ActiveQuery */ public function getStudentEducations() { return $this->hasMany(StudentEducation::className(), ['id_student' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getStudentPortfolios() { return $this->hasMany(StudentPortfolio::className(), ['id_student' => 'id']); } /** * @inheritdoc */ public function beforeDelete() { /* * Удаляются все записи портфолио. * Поскольку модель Tree не поддерживает удаление корневых элементов, * для удаления не используется стандартный метод delete модели, а * используется DAO. */ if (parent::beforeDelete()) { /* * Сначала удаляются все файлы, связанные с портфолио, а затем все записи */ $models = $this->studentPortfolios; foreach ($models as $model) { $model->deleteFile(); } Yii::$app->db-> createCommand()-> delete('student_portfolio',['id_student' => $this->id])-> execute(); return true; } else { return false; } } }
true
cc5badccabbf19be1208393873734aed98301de5
PHP
michael158/vidafascinante
/modules/Admin/Entities/User.php
UTF-8
2,324
2.6875
3
[ "MIT" ]
permissive
<?php namespace Modules\Admin\Entities; use Illuminate\Auth\Authenticatable; use Illuminate\Database\Eloquent\Model; use Illuminate\Auth\Passwords\CanResetPassword; use Illuminate\Foundation\Auth\Access\Authorizable; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract; use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract; use Illuminate\Support\Facades\DB; class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract { use Authenticatable, Authorizable, CanResetPassword; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'image', 'description', 'admin','facebook','twitter', 'google_plus', 'instagram', 'youtube' ]; /** * The attributes excluded from the model's JSON form. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function newUser($data) { DB::beginTransaction(); try { if (isset($data['image'])) { $mUpload = new Upload(); $data['image'] = !empty($data['image']) ? $mUpload->upload($data['image'], null, 'users'): null; } $data['password'] = bcrypt($data['password']); $post = $this->create($data); } catch (\Exception $e) { throw $e; DB::rollback(); } DB::commit(); return $post; } public function editUser($data , $user) { DB::beginTransaction(); try { if (isset($data['image'])) { $mUpload = new Upload(); $data['image'] = !empty($data['image']) ? $mUpload->upload($data['image'], null, 'users') : null; } if (!empty($data['password'])) { $data['password'] = bcrypt($data['password']); } else { unset($data['password']); } $post = $user->update($data); } catch (\Exception $e) { throw $e; DB::rollback(); } DB::commit(); return $post; } }
true
72e9b344591c4af0f9ecbb3d596a91a086bb3f08
PHP
i80586/RCache
/tests/FileCacheTest.php
UTF-8
2,060
2.703125
3
[]
no_license
<?php use RCache\Cache; use RCache\FileCache; /** * FileCacheTest tests class * Test cache for file * * @author Rasim Ashurov <rasim.ashurov@gmail.com> * @date 11 August, 2016 */ class FileCacheTest extends PHPUnit_Framework_TestCase { /** * @var RCache\Cache */ private $cache; /** * Init test */ public function setUp() { # create temporary directory for cache if ( ! is_dir($directory = __DIR__ . '/cache')) { mkdir($directory); } $this->cache = new Cache(new FileCache($directory)); } /** * Test set and get value */ public function testManually() { $this->cache->set('test-identifier', 'test-value', 120); # assert existing cache and equal value $this->assertEquals('test-value', $this->cache->get('test-identifier')); } /** * Test fragment cache */ public function testFragment() { # write content to cache if ($this->cache->start('test-fragment', 120)) { echo 'test-fragment-content'; $this->cache->end(); } # test fragment cache if ($this->cache->start('test-fragment', 120)) { $this->assertTrue(false); $this->cache->end(); } } /** * Test cache expire / duration */ public function testCacheExpire() { $this->cache->set('test-expire', 'test-value', 2); # assert existing cache $this->assertTrue($this->cache->has('test-expire')); sleep(3); # assert for expire cache $this->assertFalse($this->cache->has('test-expire')); } /** * Test deleting cache */ public function testDelete() { foreach (['test-identifier', 'test-fragment'] as $identifier) { $this->cache->drop($identifier); $this->assertFalse($this->cache->has($identifier)); } } }
true
68e3ff779db20c9b82f6faa6676467330781eafd
PHP
theolaye/symfony2
/src/Entity/User.php
UTF-8
2,312
2.53125
3
[]
no_license
<?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\UserRepository") */ class User { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $nomcomplet; /** * @ORM\Column(type="integer") */ private $telephone; /** * @ORM\Column(type="string", length=255) */ private $email; /** * @ORM\Column(type="string", length=255) */ private $adresse; /** * @ORM\ManyToOne(targetEntity="App\Entity\profil", inversedBy="users") * @ORM\JoinColumn(nullable=false) */ private $idprofil; /** * @ORM\ManyToOne(targetEntity="App\Entity\partenaire", inversedBy="users") * @ORM\JoinColumn(nullable=false) */ private $idpartenaire; public function getId(): ?int { return $this->id; } public function getNomcomplet(): ?string { return $this->nomcomplet; } public function setNomcomplet(string $nomcomplet): self { $this->nomcomplet = $nomcomplet; return $this; } public function getTelephone(): ?int { return $this->telephone; } public function setTelephone(int $telephone): self { $this->telephone = $telephone; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getAdresse(): ?string { return $this->adresse; } public function setAdresse(string $adresse): self { $this->adresse = $adresse; return $this; } public function getIdprofil(): ?profil { return $this->idprofil; } public function setIdprofil(?profil $idprofil): self { $this->idprofil = $idprofil; return $this; } public function getIdpartenaire(): ?partenaire { return $this->idpartenaire; } public function setIdpartenaire(?partenaire $idpartenaire): self { $this->idpartenaire = $idpartenaire; return $this; } }
true
099d3679399b42c2ad53f082c008e8f4ada21ea7
PHP
pear/pear-core
/PEAR/Command.php
UTF-8
12,395
2.828125
3
[ "BSD-2-Clause" ]
permissive
<?php /** * PEAR_Command, command pattern class * * PHP versions 4 and 5 * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1 */ /** * Needed for error handling */ require_once 'PEAR.php'; require_once 'PEAR/Frontend.php'; require_once 'PEAR/XMLParser.php'; /** * List of commands and what classes they are implemented in. * @var array command => implementing class */ $GLOBALS['_PEAR_Command_commandlist'] = array(); /** * List of commands and their descriptions * @var array command => description */ $GLOBALS['_PEAR_Command_commanddesc'] = array(); /** * List of shortcuts to common commands. * @var array shortcut => command */ $GLOBALS['_PEAR_Command_shortcuts'] = array(); /** * Array of command objects * @var array class => object */ $GLOBALS['_PEAR_Command_objects'] = array(); /** * PEAR command class, a simple factory class for administrative * commands. * * How to implement command classes: * * - The class must be called PEAR_Command_Nnn, installed in the * "PEAR/Common" subdir, with a method called getCommands() that * returns an array of the commands implemented by the class (see * PEAR/Command/Install.php for an example). * * - The class must implement a run() function that is called with three * params: * * (string) command name * (array) assoc array with options, freely defined by each * command, for example: * array('force' => true) * (array) list of the other parameters * * The run() function returns a PEAR_CommandResponse object. Use * these methods to get information: * * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) * *_PARTIAL means that you need to issue at least * one more command to complete the operation * (used for example for validation steps). * * string getMessage() Returns a message for the user. Remember, * no HTML or other interface-specific markup. * * If something unexpected happens, run() returns a PEAR error. * * - DON'T OUTPUT ANYTHING! Return text for output instead. * * - DON'T USE HTML! The text you return will be used from both Gtk, * web and command-line interfaces, so for now, keep everything to * plain text. * * - DON'T USE EXIT OR DIE! Always use pear errors. From static * classes do PEAR::raiseError(), from other classes do * $this->raiseError(). * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2009 The Authors * @license http://opensource.org/licenses/bsd-license.php New BSD License * @version Release: @package_version@ * @link http://pear.php.net/package/PEAR * @since Class available since Release 0.1 */ class PEAR_Command { // {{{ factory() /** * Get the right object for executing a command. * * @param string $command The name of the command * @param object $config Instance of PEAR_Config object * * @return object the command object or a PEAR error */ public static function &factory($command, &$config) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { $a = PEAR::raiseError("unknown command `$command'"); return $a; } $ui =& PEAR_Command::getFrontendObject(); $obj = new $class($ui, $config); return $obj; } // }}} // {{{ & getObject() public static function &getObject($command) { $class = $GLOBALS['_PEAR_Command_commandlist'][$command]; if (!class_exists($class)) { require_once $GLOBALS['_PEAR_Command_objects'][$class]; } if (!class_exists($class)) { return PEAR::raiseError("unknown command `$command'"); } $ui =& PEAR_Command::getFrontendObject(); $config = &PEAR_Config::singleton(); $obj = new $class($ui, $config); return $obj; } // }}} // {{{ & getFrontendObject() /** * Get instance of frontend object. * * @return object|PEAR_Error */ public static function &getFrontendObject() { $a = &PEAR_Frontend::singleton(); return $a; } // }}} // {{{ & setFrontendClass() /** * Load current frontend class. * * @param string $uiclass Name of class implementing the frontend * * @return object the frontend object, or a PEAR error */ public static function &setFrontendClass($uiclass) { $a = &PEAR_Frontend::setFrontendClass($uiclass); return $a; } // }}} // {{{ setFrontendType() /** * Set current frontend. * * @param string $uitype Name of the frontend type (for example "CLI") * * @return object the frontend object, or a PEAR error */ public static function setFrontendType($uitype) { $uiclass = 'PEAR_Frontend_' . $uitype; return PEAR_Command::setFrontendClass($uiclass); } // }}} // {{{ registerCommands() /** * Scan through the Command directory looking for classes * and see what commands they implement. * * @param bool (optional) if FALSE (default), the new list of * commands should replace the current one. If TRUE, * new entries will be merged with old. * * @param string (optional) where (what directory) to look for * classes, defaults to the Command subdirectory of * the directory from where this file (__FILE__) is * included. * * @return bool TRUE on success, a PEAR error on failure */ public static function registerCommands($merge = false, $dir = null) { $parser = new PEAR_XMLParser; if ($dir === null) { $dir = dirname(__FILE__) . '/Command'; } if (!is_dir($dir)) { return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory"); } $dp = @opendir($dir); if (empty($dp)) { return PEAR::raiseError("registerCommands: opendir($dir) failed"); } if (!$merge) { $GLOBALS['_PEAR_Command_commandlist'] = array(); } while ($file = readdir($dp)) { if ($file[0] == '.' || substr($file, -4) != '.xml') { continue; } $f = substr($file, 0, -4); $class = "PEAR_Command_" . $f; // List of commands if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php'; } $parser->parse(file_get_contents("$dir/$file")); $implements = $parser->getData(); foreach ($implements as $command => $desc) { if ($command == 'attribs') { continue; } if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return PEAR::raiseError('Command "' . $command . '" already registered in ' . 'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary']; if (isset($desc['shortcut'])) { $shortcut = $desc['shortcut']; if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) { return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' . 'registered to command "' . $command . '" in class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"'); } $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; } if (isset($desc['options']) && $desc['options']) { foreach ($desc['options'] as $oname => $option) { if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) { return PEAR::raiseError('Option "' . $oname . '" short option "' . $option['shortopt'] . '" must be ' . 'only 1 character in Command "' . $command . '" in class "' . $class . '"'); } } } } } ksort($GLOBALS['_PEAR_Command_shortcuts']); ksort($GLOBALS['_PEAR_Command_commandlist']); @closedir($dp); return true; } // }}} // {{{ getCommands() /** * Get the list of currently supported commands, and what * classes implement them. * * @return array command => implementing class */ public static function getCommands() { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_commandlist']; } // }}} // {{{ getShortcuts() /** * Get the list of command shortcuts. * * @return array shortcut => command */ public static function getShortcuts() { if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { PEAR_Command::registerCommands(); } return $GLOBALS['_PEAR_Command_shortcuts']; } // }}} // {{{ getGetoptArgs() /** * Compiles arguments for getopt. * * @param string $command command to get optstring for * @param string $short_args (reference) short getopt format * @param array $long_args (reference) long getopt format * * @return void */ public static function getGetoptArgs($command, &$short_args, &$long_args) { if (empty($GLOBALS['_PEAR_Command_commandlist'])) { PEAR_Command::registerCommands(); } if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) { return null; } $obj = &PEAR_Command::getObject($command); return $obj->getGetoptArgs($command, $short_args, $long_args); } // }}} // {{{ getDescription() /** * Get description for a command. * * @param string $command Name of the command * * @return string command description */ public static function getDescription($command) { if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) { return null; } return $GLOBALS['_PEAR_Command_commanddesc'][$command]; } // }}} // {{{ getHelp() /** * Get help for command. * * @param string $command Name of the command to return help for */ public static function getHelp($command) { $cmds = PEAR_Command::getCommands(); if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; } if (isset($cmds[$command])) { $obj = &PEAR_Command::getObject($command); return $obj->getHelp($command); } return false; } // }}} }
true
7cd4bfa1eb3937b09d14801840dc3fb9b94611f2
PHP
toanht15/moni
/apps/classes/brandco/cp/CpInstantWinActionManager.php
UTF-8
9,745
2.5625
3
[]
no_license
<?php AAFW::import('jp.aainc.lib.base.aafwObject'); AAFW::import('jp.aainc.classes.entities.CpAction'); AAFW::import('jp.aainc.classes.services.CpTransactionService'); AAFW::import('jp.aainc.classes.services.instant_win.InstantWinPrizeService'); AAFW::import('jp.aainc.classes.brandco.cp.interface.CpActionManager'); AAFW::import('jp.aainc.classes.brandco.cp.trait.CpActionTrait'); use Michelf\Markdown; /** * Class CpInstantWinActionManager * TODO トランザクション */ class CpInstantWinActionManager extends aafwObject implements CpActionManager { use CpActionTrait; /** @var CpInstantWinActions $cp_concrete_actions */ protected $cp_concrete_actions; /** @var CpTransactionService $cp_transaction_service */ protected $cp_transaction_service; /** @var InstantWinPrizeService $instant_win_prize_service */ protected $instant_win_prize_service; protected $logger; const LOGIC_TYPE_RATE = 1; const LOGIC_TYPE_TIME = 2; function __construct() { parent::__construct(); $this->cp_actions = $this->getModel("CpActions"); $this->cp_concrete_actions = $this->getModel("CpInstantWinActions"); $this->cp_transaction_service = $this->getService('CpTransactionService'); $this->instant_win_prize_service = $this->getService('InstantWinPrizeService'); $this->logger = aafwLog4phpLogger::getDefaultLogger(); } /** * @param $cp_action_id * @return mixed */ public function getCpActions($cp_action_id) { $cp_action = $this->getCpActionById($cp_action_id); if ($cp_action === null) { $cp_concrete_action = null; } else { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); } if($cp_concrete_action == null) { $instant_win_prizes = null; } else { $instant_win_prizes = $this->instant_win_prize_service->getInstantWinPrizesByCpInstantWinActionId($cp_concrete_action->id); } return array($cp_action, $cp_concrete_action, $instant_win_prizes); } /** * @param $cp_action_group_id * @param $type * @param $status * @param $order_no * @return array|mixed */ public function createCpActions($cp_action_group_id, $type, $status, $order_no) { $cp_action = $this->createCpAction($cp_action_group_id, $type, $status, $order_no); $cp_concrete_action = $this->createConcreteAction($cp_action); $this->cp_transaction_service->createCpTransaction($cp_action->id); $this->instant_win_prize_service->createInitInstantWinPrizes($cp_concrete_action->id); return array($cp_action, $cp_concrete_action); } /** * @param CpAction $cp_action * @return mixed|void */ public function deleteCpActions(CpAction $cp_action) { $this->cp_transaction_service->deleteCpTransaction($cp_action->id); $this->deleteConcreteAction($cp_action); $this->deleteCpAction($cp_action); } /** * @param CpAction $cp_action * @param $data * @return mixed|void */ public function updateCpActions(CpAction $cp_action, $data) { $this->updateCpAction($cp_action); $cp_concrete_action = $this->updateConcreteAction($cp_action, $data); $this->instant_win_prize_service->updateInstantWinPrizes($cp_concrete_action->id, $data); } /** * @param CpAction $cp_action * @return mixed */ public function getConcreteAction(CpAction $cp_action) { return $this->getCpConcreteActionByCpAction($cp_action); } /** * @param CpAction $cp_action * @return mixed */ public function createConcreteAction(CpAction $cp_action) { $cp_concrete_action = $this->cp_concrete_actions->createEmptyObject(); $cp_concrete_action->cp_action_id = $cp_action->id; $cp_concrete_action->title = "スピードくじ"; $cp_concrete_action->text = ""; $cp_concrete_action->time_value = 1; $cp_concrete_action->time_measurement = CpInstantWinActions::TIME_MEASUREMENT_DAY; $cp_concrete_action->logic_type = CpInstantWinActions::LOGIC_TYPE_RATE; $cp_concrete_action->once_flg = InstantWinPrizes::ONCE_FLG_ON; $this->cp_concrete_actions->save($cp_concrete_action); return $cp_concrete_action; } /** * @param CpAction $cp_action * @param $data * @return mixed|void */ public function updateConcreteAction(CpAction $cp_action, $data) { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); $cp_concrete_action->title = $data['title']; $cp_concrete_action->text = $data['text']; $cp_concrete_action->html_content = Markdown::defaultTransform($data['text']); $cp_concrete_action->time_value = $data['time_value']; $cp_concrete_action->time_measurement = $data['time_measurement']; $cp_concrete_action->once_flg = $data['once_flg']; $cp_concrete_action->logic_type = $data['logic_type']; $this->cp_concrete_actions->save($cp_concrete_action); return $cp_concrete_action; } /** * @param CpAction $cp_action * @return mixed|void */ public function deleteConcreteAction(CpAction $cp_action) { $cp_concrete_action = $this->getCpConcreteActionByCpAction($cp_action); $cp_concrete_action->del_flg = 1; $this->cp_concrete_actions->save($cp_concrete_action); } /** * @param CpAction $old_cp_action * @param $new_cp_action_id * @return mixed|void */ public function copyConcreteAction(CpAction $old_cp_action, $new_cp_action_id) { $old_concrete_action = $this->getConcreteAction($old_cp_action); $new_concrete_action = $this->cp_concrete_actions->createEmptyObject(); $new_concrete_action->cp_action_id = $new_cp_action_id; $new_concrete_action->title = $old_concrete_action->title; $new_concrete_action->text = $old_concrete_action->text; $new_concrete_action->html_content = $old_concrete_action->html_content; $new_concrete_action->time_value = $old_concrete_action->time_value; $new_concrete_action->time_measurement = $old_concrete_action->time_measurement; $new_concrete_action->once_flg = $old_concrete_action->once_flg; $new_concrete_action->logic_type = $old_concrete_action->logic_type; $new_cp_instant_win_action = $this->cp_concrete_actions->save($new_concrete_action); $this->cp_transaction_service->createCpTransaction($new_cp_action_id); $this->instant_win_prize_service->copyInstantWinPrizes($new_cp_instant_win_action->id, $old_concrete_action->id); } /** * @param CpAction $cp_action * @return entity */ private function getCpConcreteActionByCpAction(CpAction $cp_action) { return $this->cp_concrete_actions->findOne(array("cp_action_id" => $cp_action->id)); } /** * @param $cp_action_id * @return entity */ public function getCpConcreteActionByCpActionId($cp_action_id) { return $this->cp_concrete_actions->findOne(array("cp_action_id" => $cp_action_id)); } /** * 次回参加までの待機時間を変換する * @param $cp_concrete_action * @return string */ public function changeValueIntoTime($cp_concrete_action) { if ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_MINUTE) { $waiting_time = '+' . $cp_concrete_action->time_value . ' minutes'; } elseif ($cp_concrete_action->time_measurement == CpInstantWinActions::TIME_MEASUREMENT_HOUR) { $waiting_time = '+' . $cp_concrete_action->time_value . ' hours'; } else { $waiting_time = '+' . $cp_concrete_action->time_value . ' days'; } return $waiting_time; } /** * @param CpAction $cp_action * @return mixed|void */ public function deletePhysicalRelatedCpActionData(CpAction $cp_action, $with_concrete_actions = false) { if (!$cp_action || !$cp_action->id) { throw new Exception("CpInstantWinActionManager#deletePhysicalRelatedCpActionData cp_action_id=" . $cp_action->id); } if ($with_concrete_actions) { //TODO delete concrete action } //delete instant win action user log /** @var InstantWinUserService $instant_win_user_service */ $instant_win_user_service = $this->getService("InstantWinUserService"); $instant_win_user_service->deletePhysicalUserLogsByCpActionId($cp_action->id); // 当選予定時刻か初期化 $cp_concrete_action = $this->getConcreteAction($cp_action); $instant_win_prize = $this->instant_win_prize_service->getInstantWinPrizeByPrizeStatus($cp_concrete_action->id, InstantWinPrizes::PRIZE_STATUS_PASS); $this->instant_win_prize_service->resetInstantWinTime($instant_win_prize); } public function deletePhysicalRelatedCpActionDataByCpUser(CpAction $cp_action, CpUser $cp_user) { if (!$cp_action || !$cp_user) { throw new Exception("CpInstantWinActionManager#deletePhysicalRelatedCpActionDataByCpUser cp_action_id=" . $cp_action->id); } /** @var InstantWinUserService $instant_win_user_service */ $instant_win_user_service = $this->getService("InstantWinUserService"); $instant_win_user_service->deletePhysicalUserLogsByCpActionIdAndCpUserId($cp_action->id, $cp_user->id); } }
true
175d34f6241c51d1532d4c12e74fc164b1bee943
PHP
nam-duc-tong/ban_hang_hoa_qua_PHP
/admin/product/add.php
UTF-8
7,054
2.5625
3
[]
no_license
<?php require_once('../../db/dbhelper.php'); $id = $title = $thumbnail = $content = $id_category = $price =''; if(!empty($_POST)){ if(isset($_POST['title'])){ $title = $_POST['title']; $title = str_replace('"', '\\"', $title); } if(isset($_POST['id'])){ $id = $_POST['id']; // $id = str_replace('"', '\\"', $id); } if(isset($_POST['price'])){ $price = $_POST['price']; $price = str_replace('"', '\\"', $price); } if(isset($_POST['thumbnail'])){ $thumbnail = $_POST['thumbnail']; $thumbnail = str_replace('"', '\\"', $thumbnail); } if(isset($_POST['content'])){ $content = $_POST['content']; $content = str_replace('"', '\\"', $content); } if(isset($_POST['id_category'])){ $id_category = $_POST['id_category']; $id_category = str_replace('"', '\\"', $id_category); } if(!empty($title)){ $created_at = $updated_at =date('Y-m-d H:s:i'); //luu vao database if($id == ''){ $sql = 'insert into product(title,thumbnail,price,content,id_category,created_at,updated_at) values ("'.$title.'","'.$thumbnail.'","'.$price.'","'.$content.'","'.$id_category.'","'.$created_at.'","'.$updated_at.'")'; } else{ $sql = 'update product set title = "'.$title.'",updated_at="'.$updated_at.'",thumbnail="'.$thumbnail.'",price = "'.$price.'",content = "'.$content.'",id_category="'.$id_category.'" where id = '.$id; } execute($sql); header('Location: index.php'); die(); } } if(isset($_GET['id'])){ $id = $_GET['id']; $sql = 'select * from product where id = '.$id; $product = executeSingleResult($sql); if($product != null){ $title = $product['title']; $price = $product['price']; $thumbnail = $product['thumbnail']; $id_category = $product['id_category']; $content = $product['content']; } } ?> <!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>Thêm sửa sản phẩm</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <!-- Popper JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script> <!-- summernote --> <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.css" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote.min.js"></script> <style> thead tr td{ font-weight: bold; } </style> </head> <body> <ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" href="../category/"> Quản Lý Danh Mục </a> </li> <li class="nav-item"> <a class="nav-link" href="index.php"> Quản Lý Sản Phẩm </a> </li> </ul> <div class="container"> <div class="panel panel-primary"> <div class="panel-heading" style= "font-weight: bold; margin-bottom:10px;"> <h2 class="text-center">Thêm/Sửa Sản Phẩm</h2> </div> <div class="panel-body"> <form method="post"> <div class="form-group"> <label for="name">Tên Sản Phẩm:</label> <input type="text" name="id" value="<?=$id?>" hidden="true"> <input required = "true" type="text" class="form-control" id="title" name="title" value="<?=$title?>"> </div> <div class="form-group"> <label for="price">Chọn Danh Mục:</label> <select class="form-control" name="id_category" id="id_category"> <option>--Lua chon danh muc--</option> <?php $sql = 'select * from category'; $categoryList = executeResult($sql); foreach($categoryList as $item){ if($item['id'] == $id_category){ echo '<option selected value="'.$item['id'].'">'.$item['name'].'</option>'; } else{ echo '<option value="'.$item['id'].'">'.$item['name'].'</option>'; } } ?> </select> </div> <div class="form-group"> <label for="price">Giá Bán:</label> <input required = "true" type="number" class="form-control" id="price" name="price" value="<?=$price?>"> </div> <div class="form-group"> <label for="thumbnail">Thumbnail:</label> <input required = "true" type="text" class="form-control" id="thumbnail" name="thumbnail" value="<?=$thumbnail?>" onchange="updateThumbnail()"> <img src="<?=$thumbnail?>"style="max-width:200px" id="img_thumbnail"> </div> <div class="form-group"> <label for="content">Nội Dung:</label> <textarea class = "form-control" name="content" id="content"rows="5"><?=$price?></textarea> </div> <button class="btn btn-success">Lưu</button> </form> </div> </div> </div> <script type="text/javascript"> function updateThumbnail(){ $('#img_thumbnail').attr('src', $('#thumbnail').val()) } $(function(){ $('#content').summernote({ height: 300, // set editor height minHeight: null, // set minimum height of editor maxHeight: null, // set maximum height of editor // focus: true // set focus to editable area after initializing summernote }); }) </script> </body> </html>
true
47cd3e734204dda7140c70f05d31f04dd11f3a81
PHP
renanfvcunha/devsbook
/src/controllers/LoginController.php
UTF-8
4,139
3.015625
3
[]
no_license
<?php namespace src\controllers; use core\Controller; use src\handlers\LoginHandler; use src\handlers\ValidatorsHandler; use src\models\User; /** * Classe que lida com autenticação e * cadastro de usuários */ class LoginController extends Controller { private $loggedUser; /** * Renderização de tela para efetuar login */ public function SignInRequest() { $this->loggedUser = LoginHandler::checkLoggedUser(); if ($this->loggedUser) { $this->redirect(''); } $this->render('signin'); } /** * Efetuar Login */ public function SignInAction() { $data = json_decode(file_get_contents('php://input')); $email = filter_var($data->email, FILTER_VALIDATE_EMAIL); $password = filter_var($data->password, FILTER_SANITIZE_STRING); // Validando inputs if (!$email || !$password) { http_response_code(400); echo json_encode([ "error" => "Verifique se preencheu corretamente todos os campos.", ]); exit(); } // Verificando dados para autenticação try { $token = LoginHandler::verifyLogin($email, $password); if (!$token) { http_response_code(401); echo json_encode([ "error" => "E-mail e/ou Senha Incorreto(s).", ]); exit(); } // Autenticando usuário e atribuindo token $_SESSION['token'] = $token; } catch (\Throwable $th) { http_response_code(500); echo json_encode([ "error" => "Erro interno do servidor. Tente novamente ou contate o suporte.", ]); $this->setErrorLog($th); exit(); } } /** * Renderização de tela para * cadastro de novo usuário */ public function SignUpRequest() { $this->loggedUser = LoginHandler::checkLoggedUser(); if ($this->loggedUser) { $this->redirect(''); } $this->render('signup'); } /** * Cadastro de novo usuário */ public function SignUpAction() { $data = json_decode(file_get_contents('php://input')); $name = filter_var($data->name, FILTER_SANITIZE_FULL_SPECIAL_CHARS); $email = filter_var($data->email, FILTER_VALIDATE_EMAIL); $password = filter_var($data->password, FILTER_SANITIZE_STRING); $birthdate = filter_var($data->birthdate, FILTER_SANITIZE_STRING); // Verificando campos obrigatórios if (!$name || !$email || !$password || !$birthdate) { http_response_code(400); echo json_encode([ "error" => "Verifique se preencheu corretamente todos os campos.", ]); exit(); } // Validando campo birthdate $birthdate = ValidatorsHandler::birthdateValidator($birthdate); if (!$birthdate) { http_response_code(400); echo json_encode(["error" => "Data informada é inválida."]); exit(); } try { // Verificando duplicidade if (User::emailExists($email)) { http_response_code(400); echo json_encode([ "error" => "E-mail informado já está cadastrado.", ]); exit(); } // Cadastrando e autenticando usuário $token = User::addUser($name, $email, $password, $birthdate); $_SESSION['token'] = $token; } catch (\Throwable $th) { http_response_code(500); echo json_encode([ "error" => "Erro interno do servidor. Tente novamente ou contate o suporte.", ]); $this->setErrorLog($th); exit(); } } public function SignOut() { $_SESSION['token'] = ''; $this->redirect(''); } }
true
d078eed7cea7803640fed404b61e88c41759de3d
PHP
cenpaul07/test_app_laracast
/app/Http/Controllers/PaymentsController.php
UTF-8
1,049
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Events\ProductPurchased; use App\Notifications\PaymentReceived; use Illuminate\Support\Facades\Notification; class PaymentsController extends Controller { public function create() { return view('payment.create'); } public function store() { /*TODO: Core Logic : 1. Payment Processing 2. Unlocking Purchase Side Effects: 3. Notifying User 4. Generating rewards 5.Sending Shareable Coupons Example: Event = ProductPurchased , Listeners = Notifying User,Generating rewards, Sending Shareable Coupons */ //Notification::send(request()->user(),new PaymentReceived()); //use this syntax for multiple users // request()->user()->notify(new PaymentReceived('5$')); //better and readable syntax for single users ProductPurchased::dispatch('toy');//or event(new ProductPurchased('toy')); // return redirect(route('payment.create')) // ->with('message','User Notified Successfully.'); } }
true
39747dfb2595bb13b4eac616a82a09e9ee9fc32d
PHP
ThomasWeinert/carica-firmata
/src/Response/SysEx/PinStateResponse.php
UTF-8
1,453
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace Carica\Firmata\Response\SysEx { use Carica\Firmata; /** * @property-read int $pin * @property-read int $mode * @property-read int $value */ class PinStateResponse extends Firmata\Response { /** * @var int */ private $_pin; /** * @var int */ private $_mode; /** * @var int */ private $_value; private $_modes = [ 0x01 => Firmata\Pin::MODE_OUTPUT, 0x00 => Firmata\Pin::MODE_INPUT, 0x02 => Firmata\Pin::MODE_ANALOG, 0x03 => Firmata\Pin::MODE_PWM, 0x04 => Firmata\Pin::MODE_SERVO, 0x05 => Firmata\Pin::MODE_SHIFT, 0x06 => Firmata\Pin::MODE_I2C ]; /** * @param array $bytes */ public function __construct(array $bytes) { parent::__construct(Firmata\Board::PIN_STATE_RESPONSE, $bytes); $length = count($bytes); $this->_pin = $bytes[0]; $this->_mode = $this->_modes[$bytes[1]] ?? FALSE; $this->_value = $bytes[2]; for ($i = 3, $shift = 7; $i < $length; ++$i, $shift *= 2) { $this->_value |= ($bytes[$i] << $shift); } } /** * @param string $name * @return int */ public function __get($name) { switch ($name) { case 'pin' : return $this->_pin; case 'mode' : return $this->_mode; case 'value' : return $this->_value; } return parent::__get($name); } } }
true
303a3ad434f7cf18fdab30209304776becb53670
PHP
alphachoi/duobaohui
/package/search/SearchObject.class.php
UTF-8
8,428
2.875
3
[]
no_license
<?php namespace Snake\Package\Search; /** * 对search操作封装的一个文件 * @author xuanzheng@meilishuo.com * @version alpha */ class SearchObject extends Search{ private $sphinxClient = NULL; private $limit = array(); private $filters = array(); private $filterRanges = array(); private $filterFloatRanges = array(); private $sortMode = SPH_SORT_RELEVANCE; private $sortBy = ''; private $index = ''; private $matchMode = SPH_MATCH_ANY; private $searchResult = array(); private $maxQueryTime = 4000; private $searchType = "normal"; private $useCache = FALSE; private $keywords = ''; const max = 12000; const daysFilter = 201; function __construct($searchType = "normal") { parent::__construct(); $this->searchType = $searchType; if ($searchType == "cpc") { $this->sphinxClient = parent::_getSecondSphinxClient(); } else { $this->sphinxClient = parent::_getSphinxClient(); } } public function __tostring() { //排序 uasort($this->filters, array($this, "cmp")); uasort($this->filterRanges, array($this, "cmp")); uasort($this->filterFloatRanges, array($this, "cmp")); $filtersString = print_r($this->filters, TRUE); $filterRangesString = print_r($this->filterRanges, TRUE); $filterFloatRangesString = print_r($this->filterFloatRanges, TRUE); $keywordsString = print_r($this->keywords, TRUE); $limitString = print_r($this->limit, TRUE); $key = "filters:{$filtersString}_filterRanges:{$filterRangesString}_filterFloatRanges:{$filterFloatRangesString}_keyWords:{$keywordsString}_limit:{$limitString}"; return $key; } public function cmp($a, $b) { $bigger = 0; if ($a['attribute'] > $b['attribute']) { $bigger = 1; } else if ($a['attribute'] === $b['attribute']) { $bigger = 0; } else { $bigger = -1; } return $bigger; } /** * 调用获取SearchObject * @author xuanzheng@meilishuo.com */ // static public function getSearchClient() { // return new SearchObject(); // } /** * 设置limit * @author xuanzheng@meilishuo.com */ public function setLimit($offset, $limit, $maxMatches = 12000, $cutoff = 0) { if ($limit <= 0) { $limit = 1; } $newLimit = array( 'offset' => $offset, 'limit' => $limit, 'maxMatches' => $maxMatches, 'cutoff' => $cutoff ); $this->limit = $newLimit; return TRUE; } /** * 设置过滤条件,搜索出values中指定的内容 * @author xuanzheng@meilishuo.com * @param string attribute * @param array values * @param bool exclude */ public function setFilter($attribute, $values, $exclude = false) { if (empty($attribute)) { return FALSE; } $filter = array('attribute' => $attribute, 'values' => $values, 'exclude' => $exclude); array_push($this->filters, $filter); return TRUE; } /** * 设置过滤条件,搜索出min,max中指定的范围 * @author xuanzheng@meilishuo.com * @param string attribute * @param int min * @param int max * @param bool exclude */ public function setFilterRange($attribute, $min, $max, $exclude = false) { if (empty($attribute)) { return FALSE; } $filterRange = array('attribute' => $attribute, 'min' => intval($min), 'max' => intval($max), 'exclude' => $exclude); array_push($this->filterRanges, $filterRange); return TRUE; } /** * 设置过滤条件,搜索出min,max中指定的范围 * @author xuanzheng@meilishuo.com * @param string attribute * @param float min * @param float max * @param bool exclude */ public function setFilterFloatRange($attribute, $min, $max, $exclude = false) { if (empty($attribute)) { return FALSE; } $filterFloatRange = array('attribute' => $attribute, 'min' => (float)$min, 'max' => (float)$max, 'exclude' => $exclude); array_push($this->filterFloatRanges, $filterFloatRange); return TRUE; } /** * 设置排序模式,详见文档 * @author xuanzheng@meilishuo.com * @param NULL define in API * @param string sortBy */ public function setSortMode($mode, $sortBy) { if (empty($mode)) { return FALSE; } $this->sortMode = $mode; $this->sortBy = $sortBy; return TRUE; } /** * SetMatchMode * */ public function setMatchMode($matchMode) { if (empty($matchMode)) { return FALSE; } $this->matchMode = $matchMode; return TRUE; } /** * 设置所用的搜索索引 * @param string */ public function setIndex($index) { if (empty($index)) { return FALSE; } $this->index = $index; return TRUE; } public function setMaxQueryTime($maxQueryTime) { $this->maxQueryTime = $maxQueryTime; return TRUE; } public function setUseCache($useCache = TRUE) { $this->useCache = $useCache; return TRUE; } /** * 开始搜索 * @author xuanzheng@meilishuo.com * @param keywords */ public function search($keywords) { $this->keywords = $keywords; $this->conditionLoad(); if ($this->useCache) { $result = $this->searchFromCache($this); if (empty($result['matches'])) { $result = $this->searchFromSphinx($keywords, $this->index); $this->putSearchResultIntoCache($result); } } else { $result = $this->searchFromSphinx($keywords, $this->index); } $this->searchResult = $result; return TRUE; } private function searchFromCache($searchObject) { $searchResult = SearchCache::getSearch($this); return $searchResult; } private function putSearchResultIntoCache($searchResult) { $bool = SearchCache::setSearch($this, $searchResult); return $bool; } private function searchFromSphinx($keywords, $index) { if ($this->searchType == 'cpc') { $result = parent::secondQueryViaValidConnection($keywords, $index); } else { $result = parent::queryViaValidConnection($keywords, $index); } return $result; } public function getSearchResult() { return $this->searchResult; } public function conditionLoad() { $this->conditionReset(); $this->maxQueryTimeLoad(); $this->limitLoad(); $this->filtersLoad(); $this->filterRangeLoad(); $this->filterFloatRangesLoad(); $this->sortModeLoad(); $this->matchModeLoad(); return TRUE; } public function resetFilters() { $this->sphinxClient->ResetFilters(); $this->filters = array(); $this->filterRanges = array(); $this->filterFloatRanges = array(); return TRUE; } /** * TODO 加入limit reset */ private function conditionReset() { $this->sphinxClient->ResetFilters(); return TRUE; } private function maxQueryTimeLoad() { $this->sphinxClient->SetMaxQueryTime($this->maxQueryTime); return TRUE; } private function matchModeLoad() { $this->sphinxClient->SetMatchMode($this->matchMode); return TRUE; } private function sortModeLoad() { $this->sphinxClient->SetSortMode($this->sortMode, $this->sortBy); return TRUE; } private function limitLoad() { if (empty($this->limit)) { return FALSE; } if(!empty($this->limit) && !isset($this->limit['maxMatches'])) { $this->limit['maxMatches'] = self::max; } $this->sphinxClient->SetLimits($this->limit['offset'], $this->limit['limit'], $this->limit['maxMatches'], $this->limit['cutoff']); return TRUE; } private function filtersLoad() { foreach ($this->filters as $filter) { $this->sphinxClient->SetFilter($filter['attribute'], $filter['values'], $filter['exclude']); } return TRUE; } private function filterRangeLoad() { foreach ($this->filterRanges as $filterRange) { $this->sphinxClient->SetFilterRange($filterRange['attribute'], $filterRange['min'], $filterRange['max'], $filterRange['exclude']); } return TRUE; } private function filterFloatRangesLoad() { foreach ($this->filterFloatRanges as $filterFloatRange) { $this->sphinxClient->SetFilterFloatRange($filterFloatRange['attribute'], $filterFloatRange['min'], $filterFloatRange['max'], $filterFloatRange['exclude']); } return TRUE; } public function getSearchString($wordParams) { if (empty($wordParams['word_id']) && empty($wordParams['word_name'])) { return FALSE; } $params = array(); $params['word_name'] = $wordName; $params['isuse'] = 1; $wordInfo = AttrWords::getWordInfo($params, "/*searchGoods-zx*/word_id,word_name"); if (!empty($wordInfo)) { $searchKeyArr = AttrWords::getSearchString($wordInfo[0]['word_id'], $wordName); } else{ $searchKeyArr = array("{$wordName}"); } $searchString = "(" . implode(")|(", $searchKeyArr) . ")"; $this->searchString = $searchString; return $searchString; } public function getIndex() { return $this->index; } }
true
2ca7813263dcaa8a2153b1fab5cb8140b34671f8
PHP
apuc/guild
/frontend/modules/api/controllers/TaskUserController.php
UTF-8
1,514
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace frontend\modules\api\controllers; use common\models\ProjectTaskUser; use Yii; use yii\filters\auth\HttpBearerAuth; use yii\rest\Controller; use yii\web\BadRequestHttpException; use yii\web\NotFoundHttpException; class TaskUserController extends ApiController { public function verbs(): array { return [ 'get-task-users' => ['get'], 'set-task-user' => ['post', 'patch'], ]; } public function actionSetTaskUser() { $taskUserModel = new ProjectTaskUser(); $params = Yii::$app->request->post(); $taskUserModel->attributes = $params; if(!$taskUserModel->validate()){ throw new BadRequestHttpException(json_encode($taskUserModel->errors)); } $taskUserModel->save(); return $taskUserModel->toArray(); } /** * @throws NotFoundHttpException */ public function actionGetTaskUsers() { $task_id = Yii::$app->request->get('task_id'); if(empty($task_id) or !is_numeric($task_id)) { throw new NotFoundHttpException('Incorrect task ID'); } $tasks = $this->findUsers($task_id); if(empty($tasks)) { throw new NotFoundHttpException('The task does not exist or there are no employees for it'); } return $tasks; } private function findUsers($project_id): array { return ProjectTaskUser::find()->where(['task_id' => $project_id])->all(); } }
true
f444ca26f7fba9c771148a778c341f5295a4c87b
PHP
nxsaloj/miudl
/app/miudl/Carrera/CarreraValidator.php
UTF-8
2,742
2.65625
3
[ "MIT" ]
permissive
<?php namespace miudl\Carrera; use Validator; class CarreraValidator implements CarreraValidatorInterface { protected $mensajes = array( 'Nombre.required' => 'El campo Nombre no debe estar vacío', 'Apellidos.required' => 'El campo Apellidos no debe estar vacío', 'Ciclos.required' => 'El campo Ciclo no debe estar vacío', 'Facultad_id.required' => 'El campo Facultad no debe estar vacío', 'Codigo.required' => 'El campo Codigo no debe estar vacío', 'Codigo.unique' => 'El codigo especificado ya ha sido utilizado anteriormente', ); public function isValid(array $params= array()) { $reglas = array( 'Codigo' => 'required|unique:TB_Carrera', 'Nombre' => 'required', 'Ciclos'=>'required', 'Facultad_id' => 'required' ); //\Log::debug('Puesto P ' . print_r($params['facultad'], true)); //$facultad = \App\Models\Utils::getVueParam($params,"facultad","Facultad_id"); //\Log::debug('Puesto ' . $facultad); $datos = array( 'Codigo' => $params['codigo'], 'Nombre' => $params['nombre'], 'Ciclos' => $params['ciclos'], 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null, ); $validator = Validator::make($datos, $reglas, $this->mensajes); if ($validator->fails()){ $respuesta['mensaje'] = 'Por favor verifique los datos ingresados'; $respuesta['errors'] = $validator; $respuesta['error'] = true; return $respuesta; } return $datos; } public function isValidUpdate(array $params, $id) { $reglas = array( 'Codigo' => 'required|unique:TB_Carrera,Codigo,'.$id.',id', 'Nombre' => 'required', 'Ciclos'=>'required', 'Facultad_id' => 'required' ); //\Log::debug('Puesto P ' . print_r($params['facultad'], true)); //$facultad = \App\Models\Utils::getVueParam($params,"facultad","Facultad_id"); //\Log::debug('Puesto ' . $facultad); $datos = array( 'Codigo' => $params['codigo'], 'Nombre' => $params['nombre'], 'Ciclos' => $params['ciclos'], 'Facultad_id' => isset($params['facultad'])? $params['facultad']:null, ); $validator = Validator::make($datos, $reglas, $this->mensajes); if ($validator->fails()){ $respuesta['mensaje'] = 'Por favor verifique los datos ingresados'; $respuesta['errors'] = $validator; $respuesta['error'] = true; return $respuesta; } return $datos; } }
true
5420b92db3ec20e8f5eda3e3f3a1b5ddbeeb28dc
PHP
kanjengsaifu/erp_bnp
/models/StockModel.php
UTF-8
14,750
2.6875
3
[]
no_license
<?php require_once("BaseModel.php"); class StockModel extends BaseModel{ private $table_name = ""; function __construct(){ if(!static::$db){ static::$db = mysqli_connect($this->host, $this->username, $this->password, $this->db_name); } mysqli_set_charset(static::$db,"utf8"); } function setTableName($table_name = "tb_stock"){ $this->table_name = $table_name; } function createStockTable(){ $sql = " CREATE TABLE `".$this->table_name."` ( `stock_code` int(11) NOT NULL COMMENT 'รหัสอ้างอิงคลังสินค้า', `stock_type` varchar(10) NOT NULL COMMENT 'ประเภท รับ หรือ ออก', `product_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงสินค้า', `stock_date` date DEFAULT NULL COMMENT 'วันที่ดำเนินการ', `in_qty` int(11) NOT NULL COMMENT 'จำนวน (เข้า)', `in_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (เข้า)', `in_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (เข้า)', `out_qty` int(11) NOT NULL COMMENT 'จำนวน (ออก)', `out_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (ออก)', `out_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (ออก)', `stock_qty` int(11) NOT NULL COMMENT 'จำนวน (คงเหลือ)', `stock_cost_avg` double NOT NULL COMMENT 'ราคาต่อชิ้น (คงเหลือ)', `stock_cost_avg_total` double NOT NULL COMMENT 'ราคารวม (คงเหลือ)', `delivery_note_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการยืมเข้า', `delivery_note_customer_list_code` varchar(50) DEFAULT NULL COMMENT 'รหัสอ้างอิงรายการยืมออก', `invoice_supplier_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการซื้อเข้า', `invoice_customer_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการขายออก', `stock_move_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการย้ายคลังสินค้า', `stock_issue_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการตัดคลังสินค้า', `credit_note_list_code` varchar(50) NOT NULL COMMENT 'รหัสอ้างอิงรายการใบลดหนี้', `summit_product_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้ายกยอด', `stock_change_product_list_code` varchar(50) NOT NULL COMMENT 'รหัสรายการสินค้าเปลี่ยนชื่อ', `addby` varchar(50) NOT NULL COMMENT 'ผู้เพิ่ม', `adddate` datetime DEFAULT NULL COMMENT 'เวลาเพิ่ม', `updateby` varchar(50) DEFAULT NULL COMMENT 'ผู้แก้ไข', `lastupdate` datetime DEFAULT NULL COMMENT 'เวลาแก้ไข' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "; if (mysqli_query(static::$db,$sql)) { $sql = "ALTER TABLE `".$this->table_name."` ADD PRIMARY KEY (`stock_code`), ADD KEY `invoice_code` (`invoice_customer_list_code`,`invoice_supplier_list_code`); "; if (mysqli_query(static::$db,$sql)) { $sql = "ALTER TABLE `".$this->table_name."` MODIFY `stock_code` int(11) NOT NULL AUTO_INCREMENT COMMENT 'รหัสอ้างอิงคลังสินค้า'; "; if (mysqli_query(static::$db,$sql)) {return true;} else {return false;} }else {return false;} }else {return false;} } function deleteStockTable(){ $sql = "DROP TABLE IF EXISTS ".$this->table_name." ;"; if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { return true; }else { return false; } } function getStockBy(){ $sql = " SELECT * FROM $table_name WHERE 1 "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockLogListByDate($date_start = '', $date_end = '', $stock_group_code = '', $keyword = ''){ $str = " AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') "; $sql_old_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'in' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')"; $sql_old_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'out' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') < STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s')"; $sql_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'in' ".$str; $sql_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'out' ".$str; $sql_borrow_in = "SELECT SUM(in_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'borrow_in' ".$str; $sql_borrow_out = "SELECT SUM(out_qty) FROM ".$this->table_name." WHERE ".$this->table_name.".product_code = tb.product_code AND stock_type = 'borrow_out' ".$str; $sql_minimum = "SELECT SUM(minimum_stock) FROM tb_product_customer WHERE tb_product_customer.product_code = tb.product_code AND product_status = 'Active' "; $sql_safety = "SELECT SUM(safety_stock) FROM tb_product_customer WHERE tb_product_customer.product_code = tb.product_code AND product_status = 'Active' "; $sql = "SELECT tb.product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , (IFNULL(($sql_old_in),0) - IFNULL(($sql_old_out),0)) as stock_old, IFNULL(($sql_in),0) as stock_in, IFNULL(($sql_out),0) as stock_out, IFNULL(($sql_borrow_in),0) as stock_borrow_in, IFNULL(($sql_borrow_out),0) as stock_borrow_out, IFNULL(($sql_safety),0) as stock_safety, IFNULL(($sql_minimum),0) as stock_minimum FROM tb_stock_report LEFT JOIN tb_product as tb ON tb_stock_report.product_code = tb.product_code WHERE stock_group_code = '$stock_group_code' AND ( CONCAT(product_code_first,product_code) LIKE ('%$keyword%') OR product_name LIKE ('%$keyword%') ) ORDER BY CONCAT(product_code_first,product_code) "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockInByDate($date_start = '', $date_end = ''){ $sql = "SELECT stock_code, stock_date, ".$this->table_name.".product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , in_qty , supplier_name_th, supplier_name_en FROM ".$this->table_name." LEFT JOIN tb_product ON ".$this->table_name.".product_code = tb_product.product_code LEFT JOIN tb_invoice_supplier_list ON ".$this->table_name.".invoice_supplier_list_code = tb_invoice_supplier_list.invoice_supplier_list_code LEFT JOIN tb_invoice_supplier ON tb_invoice_supplier_list.invoice_supplier_code = tb_invoice_supplier.invoice_supplier_code LEFT JOIN tb_supplier ON tb_invoice_supplier.supplier_code = tb_supplier.supplier_code WHERE stock_type = 'in' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function getStockOutByDate($date_start = '', $date_end = ''){ $sql = "SELECT stock_code, stock_date, ".$this->table_name.".product_code, CONCAT(product_code_first,product_code) as product_code, product_name, product_type, product_status , out_qty , customer_name_th, customer_name_en FROM ".$this->table_name." LEFT JOIN tb_product ON ".$this->table_name.".product_code = tb_product.product_code LEFT JOIN tb_invoice_customer_list ON ".$this->table_name.".invoice_customer_list_code = tb_invoice_customer_list.invoice_customer_list_code LEFT JOIN tb_invoice_customer ON tb_invoice_customer_list.invoice_customer_code = tb_invoice_customer.invoice_customer_code LEFT JOIN tb_customer ON tb_invoice_customer.customer_code = tb_customer.customer_code WHERE stock_type = 'out' AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') >= STR_TO_DATE('$date_start','%Y-%m-%d %H:%i:%s') AND STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') <= STR_TO_DATE('$date_end','%Y-%m-%d %H:%i:%s') ORDER BY STR_TO_DATE(stock_date,'%d-%m-%Y %H:%i:%s') "; if ($result = mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { $data = []; while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){ $data[] = $row; } $result->close(); return $data; } } function updateStockByCode($code,$data = []){ $sql = " UPDATE $table_name SET stock_type = '".$data['stock_type']."' , product_code = '".$data['product_code']."' , stock_date = '".$data['stock_date']."' , in_qty = '".$data['in_qty']."' , in_cost_avg = '".$data['in_cost_avg']."' , in_cost_avg_total = '".$data['in_cost_avg_total']."' , out_qty = '".$data['out_qty']."' , out_cost_avg = '".$data['out_cost_avg']."' , out_cost_avg_total = '".$data['out_cost_avg_total']."' , balance_qty = '".$data['balance_qty']."' , balance_price = '".$data['balance_price']."' , balance_total = '".$data['balance_total']."' , delivery_note_supplier_list_code = '".$data['delivery_note_supplier_list_code']."' , delivery_note_customer_list_code = '".$data['delivery_note_customer_list_code']."' , invoice_supplier_list_code = '".$data['invoice_supplier_list_code']."' , invoice_customer_list_code = '".$data['invoice_customer_list_code']."' , stock_move_list_code = '".$data['stock_move_list_code']."' , regrind_supplier_list_code = '".$data['regrind_supplier_list_code']."' , updateby = '".$data['updateby']."', lastupdate = NOW() WHERE stock_code = '$code' "; if (mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)) { return true; }else { return false; } } function insertStock($data = []){ $sql = " INSERT INTO tb_stock_group ( stock_type, product_code, stock_date, in_qty, in_cost_avg, in_cost_avg_total, out_qty, out_cost_avg, out_cost_avg_total, balance_qty, balance_price, balance_total, delivery_note_supplier_list_code, delivery_note_customer_list_code, invoice_supplier_list_code, invoice_customer_list_code, regrind_supplier_list_code, stock_move_list_code, addby, adddate ) VALUES ( '".$data['stock_type']."', '".$data['product_code']."', '".$data['stock_date']."', '".$data['customer_code']."', '".$data['supplier_code']."', '".$data['in_qty']."', '".$data['in_cost_avg']."', '".$data['in_cost_avg_total']."', '".$data['out_qty']."', '".$data['out_cost_avg']."', '".$data['out_cost_avg_total']."', '".$data['balance_qty']."', '".$data['balance_price']."', '".$data['balance_total']."', '".$data['delivery_note_supplier_list_code']."', '".$data['delivery_note_customer_list_code']."', '".$data['invoice_supplier_list_code']."', '".$data['invoice_customer_list_code']."', '".$data['regrind_supplier_list_code']."', '".$data['stock_move_list_code']."', '".$data['addby']."', NOW() )"; if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){ return true; }else{ return false; } } function deleteStockByCode($code){ $sql = " DELETE FROM $table_name WHERE stock_code = '$code' ;"; if(mysqli_query(static::$db,$sql, MYSQLI_USE_RESULT)){ return true; }else{ return false; } } } ?>
true
71b97e151d285faf37567f6df8084405fce87756
PHP
zhangjiquan1/phpsourcecode
/web3d/yuncart/include/common/session.class.php
UTF-8
4,321
2.546875
3
[ "Apache-2.0" ]
permissive
<?php defined('IN_CART') or die; class Session { private $lifetime = 1800; private $session_name = ''; private $session_id = ''; private $session_time = ''; private $session_md5 = ''; private $time = ""; private $initdata = array(); /** * * 构造函数 * */ function __construct($session_name = 'sess', $session_id = '', $lifetime = 1800) { $GLOBALS['_session'] = array(); $this->session_name = $session_name; $this->lifetime = $lifetime; $this->_time = time(); //验证session_id $tmpsess_id = ''; if ($session_id) { $tmpsess_id = $session_id; } else { $tmpsess_id = cgetcookie($session_name); } if ($tmpsess_id && $this->verify($tmpsess_id)) { $this->session_id = substr($tmpsess_id, 0, 32); } if ($this->session_id) { //session_id 存在,加载session $this->read_session(); } else { //session_id 不存在,生成,写入到cookie $this->session_id = $this->gene_session_id(); $this->init_session(); csetcookie($this->session_name, $this->session_id . $this->gene_salt($this->session_id)); } //关闭时执行gc register_shutdown_function(array(&$this, 'gc')); } /** * * DB中insert新的session * */ private function init_session() { DB::getDB()->insert("session", array("session_id" => $this->session_id, "session_data" => serialize(array()), 'time' => $this->_time)); } /** * * 生成session_id * */ private function gene_session_id() { $id = strval(time()); while (strlen($id) < 32) { $id .= mt_rand(); } return md5(uniqid($id, true)); } /** * * 生成salt,验证 * */ private function gene_salt($session_id) { $ip = getClientIp(); return sprintf("%8u", crc32(SITEPATH . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "") . $ip . $session_id)); } /** * * 生成salt,验证 * */ private function verify($tmpsess_id) { return substr($tmpsess_id, 32) == $this->gene_salt(substr($tmpsess_id, 0, 32)); } /** * * 读出已知session * */ private function read_session() { $session = DB::getDB()->selectrow("session", "*", "session_id = '" . $this->session_id . "'"); if (empty($session)) { //session为空, $this->init_session(); $this->session_md5 = md5('a:0:{}'); $this->session_time = 0; $GLOBALS['_SESSION'] = array(); } else { if (!empty($session['session_data']) && $session['time'] > $this->_time - $this->lifetime) { $this->session_md5 = md5($session['session_data']); $this->session_time = $session['time']; $GLOBALS['_SESSION'] = unserialize($session['session_data']); } else { //session过期 $this->session_md5 = md5(serialize(array())); $this->session_time = 0; $GLOBALS['_SESSION'] = array(); } } } /** * * 更新session * */ private function write_session() { $data = serialize(!empty($GLOBALS['_SESSION']) ? $GLOBALS['_SESSION'] : array()); $this->_time = time(); //session未变化 if (md5($data) == $this->session_md5 && $this->_time - $this->session_time < 10) { return true; } $ret = DB::getDB()->update("session", array("time" => $this->_time, "session_data" => addslashes($data)), "session_id='" . $this->session_id . "'", true); return $ret; } /** * * 执行gc * */ public function gc() { $this->write_session(); if ($this->_time % 2 == 0) { DB::getDB()->delete("session", "time<" . ($this->_time - $this->lifetime)); } return true; } }
true
d1c92ef71291db71bb8916a01a27add5639e1a82
PHP
cyingfan/m3o-php
/src/Model/Routing/RouteOutput.php
UTF-8
1,739
2.984375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace M3O\Model\Routing; use M3O\Model\AbstractModel; class RouteOutput extends AbstractModel { private float $distance; private float $duration; /** @var Waypoint[] */ private array $waypoints; public function getDistance(): float { return $this->distance; } /** * @param float $distance * @return static */ public function setDistance(float $distance) { $this->distance = $distance; return $this; } public function getDuration(): float { return $this->duration; } /** * @param float $duration * @return static */ public function setDuration(float $duration) { $this->duration = $duration; return $this; } /** * @return Waypoint[] */ public function getWaypoints(): array { return $this->waypoints; } /** * @param Waypoint[]|array[] $waypoints * @return static */ public function setWaypoints(array $waypoints) { $this->waypoints = $this->castModelArray($waypoints, Waypoint::class); return $this; } public static function fromArray(array $array): RouteOutput { return (new RouteOutput()) ->setDistance((float) ($array['distance'] ?? 0.0)) ->setDuration((float) ($array['duration'] ?? 0.0)) ->setWaypoints($array['waypoints'] ?? []); } public function toArray(): array { return [ 'distance' => $this->getDistance(), 'duration' => $this->getDuration(), 'waypoints' => array_map(fn(Waypoint $w) => $w->toArray(), $this->getWaypoints()) ]; } }
true
b2b78ec55aff1406eee46b2c68d12ebaaba373a2
PHP
renilsoni/mvc
/Cybercom/Model/Customer/Address.php
UTF-8
432
2.59375
3
[]
no_license
<?php namespace Model\Customer; \Mage::loadFileByClassName('Model\Core\Table'); class Address extends \Model\Core\Table { const STATUS_ENABLED = 1; const STATUS_DISABLED = 0; function __construct() { $this->setTableName('customer_address'); $this->setPrimaryKey('addressId'); } public function getStatusoptions() { return [ self::STATUS_ENABLED => 'Enable', self::STATUS_DISABLED => 'Disable' ]; } } ?>
true
48912c8a02aa2a3a77c4ad6c30bbc95f20bf5af9
PHP
leanf19/TP_Final_IPOO
/TPFinal/testTeatroFinal.php
UTF-8
10,844
2.953125
3
[]
no_license
<?php require_once ("ORM/Teatro.php"); require_once "ABM_Teatro.php"; require_once "ABM_FuncionMusical.php"; require_once "ABM_FuncionCine.php"; require_once "ABM_FuncionTeatro.php"; //Leandro Gabriel Fuentes FAI-465 Universidad Nacional del Comahue / Carrera TUDW , Materia: IPOO function menu() { do { echo "************INGRESE UNA OPCION DEL MENU***********\n"; echo "1.- Visualizar la informacion de los teatros de la base de datos \n"; echo "2.- Agregar un nuevo teatro a la base de datos\n"; echo "3.- Eliminar un teatro de la base de datos\n"; echo "4.- Salir.\n"; $opcionTeatro = trim(fgets(STDIN)); switch ($opcionTeatro) { case 1: menuTeatros(); break; case 2: altaTeatro(); break; case 3: bajaTeatro(); break; case 4: echo "*************Terminando Sesion*************\n"; break; default: echo "Ingrese una opcion correcta (1-4)\n"; break; } } while ($opcionTeatro <> 4); } function menuTeatros() { $unTeatro = new Teatro(); $auxTeatros = $unTeatro->listar(); if (count($auxTeatros) != 0) { foreach ($auxTeatros as $teatro) { print $teatro->__toString(); } do { echo "\n***Seleccione el id de uno de estos teatros***\n"; $idteatro = trim(fgets(STDIN)); $exito = $unTeatro->buscar($idteatro); } while (!$exito); echo "***Teatro obtenido, seleccione una de las siguientes opciones***\n"; do { // $exito = $unTeatro->buscar($idteatro); echo "1.- Mostrar Informacion del teatro\n"; echo "2.- Modificar datos del teatro(nombre,direccion,funciones)\n"; echo "3.- Calcular costo total por uso del teatro\n"; echo "4.- Volver al menu de inicio\n"; $opcion = trim(fgets(STDIN)); switch ($opcion) { case 1: print $unTeatro->__toString(); break; case 2: modificarDatos($unTeatro); break; case 3: echo "Costo por el uso de las instalaciones: {$unTeatro->darCosto()}\n"; break; case 4: break; default: echo "Opcion no valida, ingrese una opcion->(1-4)\n"; } } while ($opcion <> 4); } else { echo "***No hay teatros para mostrar***\n"; } } function modificarDatos($unTeatro) { $id = $unTeatro->getIdTeatro(); $op = -1; do { echo "***Seleccione una de las siguientes opciones***\n"; echo "1.- Cambiar datos del teatro(nombre y direccion)\n"; echo "2.- Agregar una nueva funcion\n"; echo "3.- Modificar una funcion\n"; echo "4.- Eliminar una funcion\n"; echo "5.- Volver al menú anterior\n"; $op = trim(fgets(STDIN)); switch ($op) { case 1: modificarTeatro($id); break; case 2: altaFuncion($unTeatro); break; case 3: modificarFuncion($unTeatro); break; case 4: bajaFuncion($unTeatro); break; default: echo "Ingrese una opción correcta(1-5)\n"; } } while ($op <> 5); } //Modifica el nombre y la direccion del teatro con la id pasada por parametro function modificarTeatro($idTeatro) { $unTeatro = new Teatro(); $unTeatro->buscar($idTeatro); $nombre=$unTeatro->getNombre(); $direccion=$unTeatro->getDireccion(); $exito = false; $aux = 0; echo "Desea modificar el nombre del teatro? (s/n):\n"; $resp = trim(fgets(STDIN)); if($resp == 's') { echo "Ingrese el nuevo nombre del teatro seleccionado: \n"; $nombre = trim(fgets(STDIN)); $aux++; } $resp = "n"; echo "Desea modificar la direccion del teatro? (s/n):\n"; $resp = trim(fgets(STDIN)); if($resp == 's'){ echo "Ingrese la nueva direccion del teatro seleccionado: \n"; $direccion = trim(fgets(STDIN)); $aux++; } if($aux != 0){ $exito =ABM_Teatro::modificarTeatro($idTeatro, $nombre, $direccion); if($exito){ echo "Datos del teatro modificados con exito!!!!\n"; } } } function altaFuncion($unTeatro) { echo "Ingrese el nombre de la función a agregar:\n"; $nombreFuncion = strtolower(trim(fgets(STDIN))); do { echo "Ingrese el tipo de funcion (Cine,Teatro,Musical):\n"; $tipo = strtolower(trim(fgets(STDIN))); } while($tipo != "cine" && $tipo != "musical" && $tipo != "teatro"); do { echo "Ingrese el precio de la funcion:\n"; $precio = trim(fgets(STDIN)); } while (!is_numeric($precio)); echo "Ingrese el horario de la funcion en formato 24hrs (HH:MM):\n"; $horaInicio = trim(fgets(STDIN)); do { echo "Ingrese la duracion de la funcion en minutos:\n"; $duracion = trim(fgets(STDIN)); } while (!is_numeric($duracion)); switch ($tipo) { case "teatro": $exito = ABM_FuncionTeatro::altaFuncionTeatro(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro); break; case "cine": echo "Ingrese el pais de origen:\n"; $pais = trim(fgets(STDIN)); echo "Ingrese el genero:\n"; $genero = trim(fgets(STDIN)); $exito = ABM_FuncionCine::altaFuncionCine(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $genero, $pais); break; case "musical": echo "Ingrese el director:\n"; $director = trim(fgets(STDIN)); echo "Ingrese la cantidad de personas en escena:\n"; $elenco = trim(fgets(STDIN)); $exito = ABM_FuncionMusical::altaFuncionMusical(0, $nombreFuncion, $horaInicio, $duracion, $precio, $unTeatro, $director, $elenco); break; } if (!$exito) { echo "No es posible agregar la funcion, el horario de la funcion ingresada se solapa con otra funcion\n"; } } function modificarFuncion($unTeatro) { $unaFuncion = new Funcion(); echo "Funciones disponibles en este teatro :\n"; $cadenaFunciones = $unTeatro->recorrerFunciones(); do { echo $cadenaFunciones; echo "Ingrese el id de la función a modificar: \n"; $idfuncion = strtolower(trim(fgets(STDIN))); $exito= $unaFuncion->buscar($idfuncion); } while (!is_numeric($idfuncion) || !$exito); echo "Ingrese el nuevo nombre de la función: \n"; $nombreFuncion = trim(fgets(STDIN)); do { echo "Ingrese el nuevo precio de la función: \n"; $precioFuncion = trim(fgets(STDIN)); } while (!is_numeric($precioFuncion)); echo "Ingrese la hora de la funcion en formato 24hrs (HH:MM):\n"; $horaInicio = trim(fgets(STDIN)); do { echo "Ingrese la duracion de la funcion en minutos:\n"; $duracion = trim(fgets(STDIN)); } while (!is_numeric($duracion)); $unaFuncion = $unTeatro->obtenerFunciones($idfuncion); $exito = false; switch (get_class($unaFuncion)) { case "FuncionCine": echo "Ingrese el pais de origen de la funcion de cine:\n"; $pais = trim(fgets(STDIN)); echo "Ingrese el genero de la funcion de cine:\n"; $genero = trim(fgets(STDIN)); $exito = ABM_FuncionCine::modificarFuncionCine($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $pais, $genero); break; case "FuncionMusical": echo "Ingrese el director:\n"; $director = trim(fgets(STDIN)); echo "Ingrese la cantidad de personas en escena:\n"; $elenco = trim(fgets(STDIN)); $exito = ABM_FuncionMusical::modificarFuncionMusical($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro, $director, $elenco); break; case "FuncionTeatro": $exito = ABM_FuncionTeatro::modificarFuncionTeatro($idfuncion, $nombreFuncion, $horaInicio, $duracion, $precioFuncion, $unTeatro); } if (!$exito) { echo "No se modificó la función porque el horario se solapa con el de otra funcion existente\n"; } else { echo "La funcion se modifico con exito!!!!"; } } function bajaFuncion($unTeatro) { $unaFuncion = new Funcion(); echo "Funciones disponibles en este teatro :\n"; $funcionesTeatro = $unTeatro->recorrerFunciones(); $exito = false; echo $funcionesTeatro; echo "Seleccione el id de la función a eliminar:\n"; $idfuncion = trim(fgets(STDIN)); $unaFuncion=$unTeatro->obtenerFunciones($idfuncion); switch (get_class($unaFuncion)) { case "FuncionCine": $exito = ABM_FuncionCine::bajaFuncionCine($idfuncion); break; case "FuncionMusical": $exito = ABM_FuncionMusical::bajaFuncionMusical($idfuncion); break; case "FuncionTeatro": $exito = ABM_FuncionTeatro::bajaFuncionTeatro($idfuncion); } if($exito){ echo "Funcion eliminada con exito!!!"; } else { echo "No se ha podido eliminar la funcion elegida"; } } function altaTeatro() { echo "Ingrese el nombre del teatro:\n"; $nombre = trim(fgets(STDIN)); echo "Ingrese la dirección del teatro:\n"; $direccion = trim(fgets(STDIN)); $exito = ABM_Teatro::altaTeatro($nombre, $direccion); if($exito) { echo "***Teatro agregado con exito a la base de datos***\n"; } else { echo "***Fallo la carga del teatro a la base de datos***\n"; } } function bajaTeatro() { mostrarTeatros(); do { $exito = false; echo "Seleccione el id del teatro que desea eliminar \n"; $idteatro = trim(fgets(STDIN)); $exito = ABM_Teatro::eliminarTeatro($idteatro); if($exito) { echo "Se ha eliminado con exito el teatro de la BD\n"; } else { echo "No se pudo eliminar el teatro seleccionado"; } } while (!is_numeric($idteatro)); } function mostrarTeatros() { $teatroTemp = new Teatro(); $teatros = $teatroTemp->listar(); foreach ($teatros as $teatro) print $teatro->__toString(); echo "---------------------------\n"; } function main() { menu(); } main();
true
58c651ebc6c3440354274073de3cab20a3bf4cfe
PHP
lidonghui-ht/poptrip
/Libs/ThirdParty/Ctrip/Hotel/Common/getDate.php
UTF-8
2,363
3.296875
3
[]
no_license
<?php /** * 获取年月日形式的日期(参数为空,输出2012年12月23日;输入分隔符,则输出2012-12-23形式) * cltang 2012年5月11日 携程 * @param $linkChar */ function getDateYMD($linkChar) { date_default_timezone_set('PRC');//设置时区 $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d"):date("Y年m月d日"); return $coutValue; } /** * 获取年月日形式的日期(参数为空,输出2012年12月23日;输入分隔符,则输出2012-12-23形式) * cltang 2012年5月11日 携程 * @param $linkChar-分隔符号; */ function getDateYMD_addDay($linkChar,$addDay) { $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d",strtotime("$d +$addDay day")):date("Y年m月d日",strtotime("$d +$addDay day")); return $coutValue; } date("Y-m-d",strtotime("$d +1 day")); /** * 获取年月日时分秒形式的日期(参数为空,输出2012年12月23日 12:23:50;输入分隔符,则输出2012-12-23 12:23:50形式) * cltang 2012年5月11日 携程 * @param $linkChar */ function getDateYMDSHM($linkChar) { $coutValue=strlen($linkChar)>0?date("Y".$linkChar."m".$linkChar."d H:i:s"):date("Y年m月d日 H:i:s"); return $coutValue; } /** * 获取到当前Unix时间戳:分msec sec两个部分,msec是微妙部分,sec是自Unix纪元(1970-1-1 0:00:00)到现在的秒数 */ function getMicrotime() { return microtime(); } /** * * 将日期转换为秒 * @param $datatime */ function timeToSecond($datatime) { return strtotime($datatime); } /** * * 计算时间的差值:返回{天、小时、分钟、秒} * @param $begin_time * @param $end_time */ function timediff($begin_time,$end_time) { if($begin_time < $end_time){ $starttime = $begin_time; $endtime = $end_time; } else{ $starttime = $end_time; $endtime = $begin_time; } $timediff = $endtime-$starttime; //echo $begin_time.$end_time.$timediff; $days = intval($timediff/86400); $remain = $timediff%86400; $hours = intval($remain/3600); $remain = $remain%3600; $mins = intval($remain/60); $secs = $remain%60; $res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs); return $res; } ?>
true
72957372cfa2e0c22cf0ff14e39ac22178863d07
PHP
Arkos13/auth-service-symfony
/application/src/Infrastructure/User/Repository/NetworkRepository.php
UTF-8
2,163
2.765625
3
[]
no_license
<?php namespace App\Infrastructure\User\Repository; use App\Model\User\Entity\Network; use App\Model\User\Repository\NetworkRepositoryInterface; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\NonUniqueResultException; class NetworkRepository implements NetworkRepositoryInterface { private EntityManagerInterface $em; public function __construct(EntityManagerInterface $em) { $this->em = $em; } /** * @param string $email * @param string $network * @return Network|null * @throws NonUniqueResultException */ public function findOneByEmailAndNetwork(string $email, string $network): ?Network { return $this->em->createQueryBuilder() ->select("networks") ->from(Network::class, "networks") ->innerJoin("networks.user", "user") ->andWhere("user.email = :email")->setParameter("email", $email) ->andWhere("networks.network = :network")->setParameter("network", $network) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); } /** * @param string $email * @param string $accessToken * @param string $network * @return Network|null * @throws NonUniqueResultException */ public function findOneByEmailAndAccessToken(string $email, string $accessToken, string $network): ?Network { return $this->em->createQueryBuilder() ->select("networks") ->from(Network::class, "networks") ->innerJoin("networks.user", "user") ->andWhere("user.email = :email")->setParameter("email", $email) ->andWhere("networks.accessToken = :accessToken")->setParameter("accessToken", $accessToken) ->andWhere("networks.network = :network")->setParameter("network", $network) ->setMaxResults(1) ->getQuery() ->getOneOrNullResult(); } public function updateAccessToken(Network $network, ?string $accessToken): void { $network->setAccessToken($accessToken); $this->em->persist($network); $this->em->flush(); } }
true
520f4f5118d97a03206dc6a8fe29bab51f6b10e3
PHP
knh/werewolf
/create_game.php
UTF-8
1,917
2.984375
3
[]
no_license
<?php require_once('init.php'); $raw_role_string = $_POST['role_list']; $role_array = preg_split("/(\r\n|\n|\r)/", $raw_role_string); // parse the raw string $role_num_array = array(); //Holds the final result of parsed role_array. $counter = 0; $player_num = 0; //Parse the role_array. Final result is an array[$role] = num foreach($role_array as &$role){ $sub_role = explode("*", $role); if(isset($sub_role[1])){ $role=$sub_role[0]; $role_num_array[$counter] = (int)$sub_role[1]; } else{ $role_num_array[$counter] = 1; } $player_num += $role_num_array[$counter]; $counter++; } // Output the role table. for($counter=0; $counter < count($role_array); $counter++){ echo $role_array[$counter] . " * " . $role_num_array[$counter] ."</br>"; } $game_id = mt_rand(100000, 999999); //create a better random game id. $query="SELECT * FROM werewolf_gameid WHERE game_id=" . $game_id; // to make sure the game id is unique while(true){ $result=$mysqli->query($query); if($result->num_rows == 0) break; $game_id=rand(100000, 999999); $query="SELECT * FROM werewolf_gameid WHERE game_id = " . $game_id; } if($mysqli->query("INSERT INTO werewolf_gameid (game_id, player_num_limit)" . "VALUES ('" . $game_id . "', '" . $player_num ."')") == true){ echo "</br>Create game succeed. Your game id is " . $game_id .". Your friend can use this number to join in the game.</br>"; }else{ echo "</br>Create game failed. Please try again later.</br>"; } $query="INSERT INTO werewolf_detail (game_id, all_roles) VALUES ('" . $game_id . "', '" . $raw_role_string . "')"; if($mysqli->query($query)){ echo "Redirecting to game console in 3 seconds. Do not refresh the page. </br>"; echo "<script>window.setInterval(function(){document.location='./control_game.php?game_id=". $game_id . "'}, 3000)</script>"; // redirecting to control_game.php after creating game. }else{ echo "Detail writing failed. </br>"; } ?>
true
7a53190f49179883fdb49b034066f15c1548e8a1
PHP
makasim/yadm-benchmark
/src/Entity/OrmOrder.php
UTF-8
1,175
2.71875
3
[ "MIT" ]
permissive
<?php namespace YadmBenchmark\Entity; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="orders") */ class OrmOrder { /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") * * @var integer $id */ private $id; /** * @ORM\Column(name="number", type="string") */ private $number; /** @ORM\Embedded(class = "OrmPrice") */ private $price; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id */ public function setId($id) { $this->id = $id; } /** * @return mixed */ public function getNumber() { return $this->number; } /** * @param mixed $number */ public function setNumber($number) { $this->number = $number; } /** * @return OrmPrice */ public function getPrice() { return $this->price; } /** * @param OrmPrice $price */ public function setPrice(OrmPrice $price = null) { $this->price = $price; } }
true
9e85ba580f4363fe1b7830365abc96dd83bcf6d8
PHP
michaelvickersuk/laravel-tv-library
/database/migrations/2020_05_06_203601_create_genres_table.php
UTF-8
1,048
2.59375
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Schema; class CreateGenresTable extends Migration { public function up() { Schema::create('genres', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps(); }); DB::table('genres') ->insert([ ['name' => 'Action'], ['name' => 'Animation'], ['name' => 'Comedy'], ['name' => 'Crime'], ['name' => 'Documentary'], ['name' => 'Drama'], ['name' => 'Horror'], ['name' => 'Mystery'], ['name' => 'Reality'], ['name' => 'Science Fiction'], ['name' => 'Thriller'], ['name' => 'Western'], ]); } public function down() { Schema::dropIfExists('genres'); } }
true
37258cae0c9f72b4856d0d1adaa2843306fc78f9
PHP
rosko/AlmazService
/php/backup/JsonResponseBuilder.php
UTF-8
481
3.109375
3
[]
no_license
<?php include_once 'ResponseBuilder.php'; class JsonResponseBuilder implements ResponseBuilder { private $response = ""; public function makeResponseError($errorType, $errorMsg = '') { $this->response .= "Error " . $errorType . ": " . $errorMsg; } public function addResource($resource) { } public function makeResponse() { } public function printResponse() { echo $this->response; } } ?>
true
de54900417e4174abca15868f7b56a9c2cedc232
PHP
798256478/Design-Pattern
/Strategy.php
UTF-8
965
3.6875
4
[]
no_license
<?php /** * 策略模式 * 使用场景:有一个Strategy类, 类中有一个可以直接调用的getData方法 * 返回xml数据,随着业务扩展要求输出json数据,这时就可以使用策略模式 * 根据需求获取返回数据类型 */ class Strategy { protected $arr; function __construct($title, $info) { $this->arr['title'] = $title; $this->arr['info'] = $info; } public function getData($objType) { return $objType->get($this->arr); } } /** * 返回json类型的数据格式 */ class Json { public function get($data) { return json_encode($data); } } /** * 返回xml类型的数据格式 */ class Xml { public function get($data) { $xml = '<?xml version = "1.0" encoding = "utf-8"?>'; $xml .= '<return>'; $xml .= '<data>'.serialize($data).'</data>'; $xml .= '</return>'; return $xml; } } $strategy = new Strategy('cd_1', 'cd_1'); echo $strategy->getData(new Json); echo $strategy->getData(new Xml); ?>
true
dcb62df97882fb75c7c6daaecb3568b48b0be456
PHP
lesstif/php-jira-rest-client
/src/ClassSerialize.php
UTF-8
1,318
3.015625
3
[ "Apache-2.0" ]
permissive
<?php namespace JiraRestApi; trait ClassSerialize { /** * class property to Array. * * @param array $ignoreProperties this properties to be (ex|in)cluded from array whether second param is true or false. * @param bool $excludeMode * * @return array */ public function toArray(array $ignoreProperties = [], bool $excludeMode = true): array { $tmp = get_object_vars($this); $retAr = null; foreach ($tmp as $key => $value) { if ($excludeMode === true) { if (!in_array($key, $ignoreProperties)) { $retAr[$key] = $value; } } else { // include mode if (in_array($key, $ignoreProperties)) { $retAr[$key] = $value; } } } return $retAr; } /** * class property to String. * * @param array $ignoreProperties this properties to be excluded from String. * @param bool $excludeMode * * @return string */ public function toString(array $ignoreProperties = [], bool $excludeMode = true): string { $ar = $this->toArray($ignoreProperties, $excludeMode); return json_encode($ar, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE); } }
true
6d0fa897f2975eb6630c0ba6883559ff1d1d387a
PHP
sdboyer/frozone
/src/Lockable.php
UTF-8
1,128
3.203125
3
[ "MIT" ]
permissive
<?php namespace Frozone; /** * Interface for 'locking', which locks an object's state using a key. * * State can only be unlocked (that is, state can be mutated) by calling the * unlock method with the same key. */ interface Lockable { /** * Locks this object using the provided key. * * The object can only be unlocked by providing the same key. * * @param mixed $key * The key used to lock the object. * * @throws LockedObjectException * Thrown if the collector is already locked. */ public function lock($key); /** * Attempts to unlock the collector with the provided key. * * Key comparison is done using the identity operator (===). * * @param mixed $key * The key with which to unlock the object. * * @throws LockedObjectException * Thrown if the incorrect key is provided, or if the collector is not * locked. */ public function unlock($key); /** * Indicates whether this collector is currently locked. * * @return bool */ public function isLocked(); }
true
ff83a56fc15e796a6c0e3df81ed1e160ae30036a
PHP
momentphp/framework
/src/CallableResolver.php
UTF-8
1,286
2.875
3
[]
no_license
<?php namespace momentphp; /** * CallableResolver */ class CallableResolver implements \Slim\Interfaces\CallableResolverInterface { use traits\ContainerTrait; /** * Base resolver * * @var \Slim\Interfaces\CallableResolverInterface */ protected $baseResolver; /** * Constructor * * @param \Interop\Container\ContainerInterface $container * @param array $options */ public function __construct(\Interop\Container\ContainerInterface $container, \Slim\Interfaces\CallableResolverInterface $baseResolver) { $this->container($container); $this->baseResolver = $baseResolver; } /** * Resolve `$toResolve` into a callable * * @param mixed $toResolve * @return callable */ public function resolve($toResolve) { try { $resolved = $this->baseResolver->resolve($toResolve); return $resolved; } catch (\Exception $e) { } $toResolveArr = explode(':', $toResolve); $class = $toResolveArr[0]; $method = isset($toResolveArr[1]) ? $toResolveArr[1] : null; $instance = $this->container()->get('registry')->load($class); return ($method) ? [$instance, $method] : $instance; } }
true
0187e9344bfe37285930b758eb4d9b0e052d39f1
PHP
DamienKusters/wbsMonitor
/functions/removeProject.php
UTF-8
287
2.515625
3
[]
no_license
<?php include("../connect.php"); $projectId = $_POST["projectId"]; $sql = "DELETE FROM project WHERE id='$projectId'"; if(mysqli_query($conn ,$sql)) { echo "Project removed!"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
true
d805a65f6877fc03a2848a40cc4908fb140a3074
PHP
DMPR-dev/woocommerce-2plus1
/wc_2plus1action/wc_2plus1action.php
UTF-8
2,643
2.953125
3
[ "MIT" ]
permissive
<?php /* Plugin Name: WooCommerce 2+1 Action Description: Purchase 2, get 1 free! This plugin provides an ability to make an action "2+1", each 3rd item on WooCommerce cart produces one free item(the cheapest one on the cart). Author: Dmytro Proskurin Version: 0.0.1 Author URI: http://github.com/DMPR-dev */ namespace WC_2plus1; /* Included additional classes */ require_once plugin_dir_path(__FILE__) . '/classes/checkers.php'; require_once plugin_dir_path(__FILE__) . '/classes/getters.php'; require_once plugin_dir_path(__FILE__) . '/classes/setters.php'; require_once plugin_dir_path(__FILE__) . '/functions.php'; /* This class provides an ability to make an action "2+1", each 3rd item on Woocommerce cart produces one free item(the cheapest one on the cart) */ class Action { /* Constructor */ public function __construct() { $this->initHooks(); } /* Inits needed hook(s) */ protected function initHooks() { add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } /* This method is attached to 'woocommerce_before_calculate_totals' hook @param $cart - an object of current cart that is being processed @returns VOID */ public function setThirdItemAsFree($cart) { /* Keep free items refreshed everytime cart gets updated */ $this->cleanCart($cart); if ($cart->cart_contents_count > 2) { /* Detect the cheapest product on cart */ $cheapest_product_id = Getters::getCheapestProduct($cart,array("return" => "ID")); if($cheapest_product_id === FALSE || intval($cheapest_product_id) < 0) return; /* Make one of the cheapest items free @returns the original item quantity decreased on 1 */ $this->addFreeItem($cart); } } /* Prevents recursion because adding a new item to cart will cause hook call @param $cart - an object of cart @returns VOID */ protected function addFreeItem($cart) { remove_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree")); Functions::addAsUniqueFreeProductToCart($cart,Getters::getCheapestProduct($cart,array("return" => "object")),"0.00"); add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } /* Prevents recursion because removing an item from cart will cause hook call @param $cart - an object of cart @returns VOID */ protected function cleanCart($cart) { remove_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree")); Functions::removeFreeItemsFromCart($cart); add_action('woocommerce_before_calculate_totals',array($this,"setThirdItemAsFree"),10,1); } } new Action();
true
b92975b84e42d13c5c6157470b829629195587ee
PHP
kerolesgeorge/php-products
/product.php
UTF-8
1,621
2.5625
3
[]
no_license
<?php include_once __DIR__ . '/includes/autoload.php'; $product_id = $_GET['id']; function getProduct($product, $product_id) { return $product->readByID($product_id); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>PHP Products Home Page</title> <link rel="stylesheet" href="style/css/bootstrap.min.css"> <!-- bootstrap --> <link rel="stylesheet" href="style/css/all.min.css"> <!-- fontaweson --> <link rel="stylesheet" href="style/css/product.css"> <!-- my-style --> </head> <body> <div class="wrapper"> <header class="nav_bar"></header> <section class="main-section"> <div class="card"> <?php $product = getProduct(new Product(), $product_id); foreach($product as $details): ?> <img src="<?= $details['image_url'] ?>" class="card-img-top" alt="Product Image"> <div class="card-body"> <h5 class="card-title"><?= $details['name'] ?></h5> <div class="space">Price: <b><?= $details['price'] ?></b></div> <div class="card-text space"><?= $details['description'] ?></div> <div class="space"> <button class="btn btn-primary">Add to cart</button> <button class="btn btn-secondary">Save to list</button> </div> </div> <?php endforeach; ?> </div> </section> </div> <script src="js/jquery-3.4.1.min.js"></script> <!-- jQuery script --> <script src="js/bootstrap.min.js"></script> <!-- bootstrap --> <script src="js/front.js"></script> </body> </html>
true