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
2e9473b528bec3e882f51d2ff7e35a008a812006
PHP
dvg18/backend-php-chat
/app/routes.php
UTF-8
9,979
2.796875
3
[ "BSD-3-Clause" ]
permissive
<?php // Routes use App\Middleware\AuthMiddleware; use App\Middleware\GuestMiddleware; use App\Middleware\RoleMiddleware; //сохранить диалог $app->post('/chat', function ($request, $response){ $json_data = $request->getParsedBody(); $visitor = $json_data['visitor']; $user = $json_data['user']; $messages = $json_data['messages']; try{ //сохраняем сообщения $query = $this->db->prepare(" INSERT INTO VisitorMessage (date, text, user_id, site_id) VALUES (:date, :text, :user_id, :site_id); "); //VisitorMessage (date) - дата первого сообщения $dt = new DateTime($messages[0]['datetime']); //получаем дату первого сообщения и конвертим дату в DateTime $result_dt = $dt->format('Y-m-d H:i:s'); //затем конвертим в формат даты MySql $text = json_encode($json_data); //типа заглушка, пока нет site_id $site = "1"; $query->bindParam("date", $result_dt); $query->bindParam("user_id", $user['id']); $query->bindParam("text", $text); $query->bindParam("site_id", $site); $query->execute(); $json_data = ""; $json_data['data']['id'] = $this->db->lastInsertId(); return $response->withJson($json_data); } catch (Exception $e){ $json_data =""; $json_data['error']['code'] = 404; $json_data['error']['message'] = "ID not found"; // $json_data['error']['message'] = $e->getMessage(); //для себя return $response->withJson($json_data); } }); $app->group('', function () { $this->get('/chat', function($request, $response, $args){ // Ловим ajax запрос if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') { //получаем параметры запроса из заголовка $date_from = $_GET['date_from']; $date_to = $_GET['date_to']; $user_id = $_GET['user_id']; // $site_id = $_GET['site_id']; //пока без него // echo $date_from. " ". $date_to. " ". $user_id ."\n"; //$operator_WHERE будет меняться в зависимости от наличия полей фильтра $operator_WHERE = "WHERE user_id = :user_id AND (date BETWEEN :dt_from AND :dt_to)"; if ($date_from == "") { //если не заполнили дату ОТ, присваиваем предыдущий день $date_from = date("Y-m-d H:i:s"); $date_from = date("Y-m-d H:i:s", strtotime($date_from .' -1 day')); // echo "\n date from: ". $date_from ."\n"; } if ($date_to == "") { //если не заполнили дату ОТ, присваиваем текущую дату $date_to = date("Y-m-d H:i:s"); } if ($user_id == "") { //если нет user_id ищем по всем user'ам $operator_WHERE = "WHERE date BETWEEN :dt_from AND :dt_to"; } try{ //соединяем таблицы VisitorMessage, User, Visitor. Выбираем некоторые поля. $query = $this->db->prepare(" SELECT VisitorMessage.id AS dialog_id, VisitorMessage.date AS dialog_date, User.id AS user_id, User.login AS user_login, User.first_name AS user_firstname, User.last_name AS user_lastname, User.info AS user_info, VisitorMessage.text AS text FROM VisitorMessage INNER JOIN User ON VisitorMessage.user_id = User.id ". $operator_WHERE. ";"); // echo "select prepared \n"; $dt_from = new DateTime($date_from); $dt_from = $dt_from->format('Y-m-d H:i:s'); $query->bindParam("dt_from", $dt_from); $dt_to = new DateTime($date_to); $dt_to = $dt_to->format('Y-m-d H:i:s'); $query->bindParam("dt_to", $dt_to); if($user_id != "") { $query->bindParam("user_id", $user_id); } $query->execute(); // echo "select executed \n"; $dialogs = $query->fetchAll(); // echo "dialogs: \n"; // print_r($dialogs); $data = []; foreach ($dialogs as $dialog){ $t = json_decode($dialog['text'], true); $temp_user['id'] = $dialog['user_id']; $temp_user['login'] = $dialog['user_login']; $temp_user['first_name'] = $dialog['user_firstname']; $temp_user['last_name'] = $dialog['user_lastname']; $temp_user['info'] = $dialog['user_info']; $temp_row['id'] = $dialog['dialog_id']; $temp_row['date'] = $dialog['dialog_date']; $temp_row['user'] = $temp_user; $temp_row['visitor'] = $t['visitor']; $temp_row['text'] = $dialog['text']; $data[] = $temp_row; } // echo "output data:\n"; // print_r(json_encode($data)); $json_data['data'] = $data; return json_encode($json_data); } catch (Exception $e){ // echo "ERROR filter dialogs: ". $e->getMessage(); $json_data['error']['message'] = $e->getMessage(); $json_data['error']['line'] = $e->getLine(); return json_encode($json_data); } } //Если это не ajax запрос return $this->view->render($response, 'chat.twig'); })->setName('chat'); $this->get('/chat/{filter}', function($request, $response, $args){ //в запросе приходит фильтр, он определяет какой шаблон отправляется обратно return $this->view->render($response, $args['filter'] . '.twig'); }); })->add(new RoleMiddleware($container, 'owner')); /*$app->group('', function () { $this->get('/admin', function ($request, $response, $args) { return $this->view->render($response, 'chat.twig'); //временная заглушка для проверки работоспособности })->setName('auth.admin'); })->add(new RoleMiddleware($container, 'admin')); */ /* $app->group('', function () { $this->get('/owner', function($request, $response, $args){ return $this->view->render($response, 'chat.twig'); //тоже самое })->setName('auth.owner'); })->add(new RoleMiddleware($container, 'owner')); */ $app->group('', function () { $this->get('/operator', 'OperatorController:redirectOperator')->setName('auth.operator'); /***Для работы на localhost***/ $this->get('/operator-test-page', function($request, $response, $args){ return $this->view->render($response, 'operator.twig'); }); /*** ***/ })->add(new RoleMiddleware($container, 'operator')); $app->get('/', 'HomeController:index')->setName('home'); $app->group('', function (){ $this->get('/login', 'AuthController:getSignIn')->setName('auth.signin'); $this->post('/login', 'AuthController:postSignIn'); })->add(new GuestMiddleware($container)); $app->group('', function (){ $this->get('/auth/signout', 'AuthController:getSignOut')->setName('auth.signout'); })->add(new AuthMiddleware($container)); $app->group('', function (){ /***** User CRUD *****/ $this->get('/user', 'UserController:user')->setName('user.all'); $this->get('/user/login/{id}', 'UserController:directLogin')->setName('user.direct'); $this->get('/user/create', 'UserController:getCreate')->setName('user.create'); $this->post('/user/create', 'UserController:postCreate'); $this->get('/user/list', 'UserController:list')->setName('user.list'); $this->get('/user/{id}', 'UserController:read'); $this->post('/user', 'UserController:postCreate'); $this->put('/user/{id}', 'UserController:update'); $this->delete('/user/{id}', 'UserController:delete'); //api $this->get('/user/role/{id}', 'UserController:role'); /***** ******/ /***** Department CRUD *****/ $this->get('/department/all', 'DepartmentController:readAll'); $this->get('/department/all/{site_id}', 'DepartmentController:readSite'); $this->get('/department', 'DepartmentController:department')->setName('department'); $this->get('/department/create', 'DepartmentController:getCreate')->setName('department.create'); $this->post('/department/create', 'DepartmentController:postCreate'); $this->get('/department/list', 'DepartmentController:list')->setName('department.list'); $this->get('/department/{id}', 'DepartmentController:read'); $this->post('/department', 'DepartmentController:postCreate'); $this->put('/department/{id}', 'DepartmentController:update'); $this->delete('/department/{id}', 'DepartmentController:delete'); /***** ******/ /**operator api**/ $this->get('/operators', 'OperatorController:dropdownOperator')->setName('dropdownOperator'); /** site **/ $this->get('/site/create', 'SiteController:getCreate')->setName('site.create'); $this->post('/site/create', 'SiteController:postCreate'); //<<--------------------------ЗАГЛУШКА $this->get('/site', 'SiteController:site')->setName('site'); $this->get('/site/edit/{id}', 'SiteController:edit')->setName('site.edit'); // api $this->get('/site/list', 'SiteController:list')->setName('site.list'); $this->put('/site/{id}', 'SiteController:update'); $this->get('/sites', 'SiteController:dropdownSite'); })->add(new RoleMiddleware($container, 'owner'));
true
2814976a6f2538c2dd52a5840e11b444011132f5
PHP
brianykim/OS-work
/code/php/column.php
UTF-8
921
2.9375
3
[]
no_license
<?php $host ="localhost"; $user="user12"; $pass = "34klq*"; $db = "mydb"; $r = mysql_connect($host,$user,$pass); if(!$r) { echo "Could not connect to server\n"; trigger_error(mysql_error(), E_USER_ERROR); } else { echo "Connection established\n"; } $r2 = mysql_select_db($db); if(!$r2) { echo "Cannot select database\n"; trigger_error(mysql_error(), E_USER_ERROR); } else { echo "Database selected\n"; } $query = "SELECT * From Cars LIMIT 8"; $rs = mysql_query($query); if(!$rs) { echo "Could not execute query: $query"; trigger_error(mysql_error, E_USER_ERROR); } else { echo "Query: $query executed\n"; } $cname1 = mysql_fetch_field($rs,0); $cname2 = mysql_fetch_field($rs,1); $cname3 = mysql_fetch_field($rs,2); printf("%3s %-11s %8s\n",$cname1->name, $cname2->name,$cname3->name); while ($row = mysql_fetch_row($rs)) { printf("%3s %-11s %8s\n",$row[0],$row[1],$row[2]); } mysql_close(); ?>
true
625dc832beef0c65d25f00114891d27ace79f92a
PHP
4iwi33/JuniorKit
/foreach/index.php
UTF-8
1,156
3.8125
4
[]
no_license
<?php $birth = [ "Tom" => "1980-11-22", "Nick" => "1981-05-05", "Jim" => "1981-05-05", "Mike" => "1981-05-05", "Mick" => "1981-05-05", "Nike" => "1981-05-05" ]; foreach ($birth as $key => $value) echo "$key Was Born $value <br>"; // $key - это ключи(имена) // $value -это значения(даты) echo "<hr>"; // У цикла foreach имеется и другая форма записи, которую следует применять, // когда нас не интересует значение ключа очередного элемента. // Выглядит она так: $birth = [ "Tom" => "1980-11-22", "Nick" => "1981-05-05", "Jim" => "1981-05-05", "Mike" => "1981-05-05", "Mick" => "1981-05-05", "Nike" => "1981-05-05" ]; foreach ($birth as $value) { echo $value . "<br>"; } // В этом случае доступно лишь значение очередного элемента массива, но не его ключ. // Это может быть полезно, например, для работы с массивами-списками:
true
b9a08190753f381ea5914b91facb716488d6ec37
PHP
Jihell/LibraryRBTree
/src/Model/AbstractNode.php
UTF-8
4,551
3.265625
3
[ "MIT" ]
permissive
<?php /** * @package library * @author Joseph LEMOINE <j.lemoine@ludi.cat> * @link https://ludi.cat */ namespace Jihel\Library\RBTree\Model; /** * Class Node */ abstract class AbstractNode implements NodeInterface { /** * id the value tha we will compare. * Basically it's an integer. You can override the Tree::compare * to set other comparison functions * * @var int */ protected $id; /** * The content of this node. Can be anything * * @var mixed */ protected $value; /** * Current color of the node * * @var bool */ protected $color = self::COLOR_BLACK; /** * @var array|NodeInterface[] */ protected $children = [ self::POSITION_LEFT => null, self::POSITION_RIGHT => null, ]; /** * Node's position relative to parent * * @var bool */ protected $position; /** * Parent of the node * * @var NodeInterface */ protected $parent = null; /** * @param int $id * @param mixed $value */ public function __construct($id, $value) { $this ->setId($id) ->setValue($value) ; } public abstract function __toString(); /** * @return mixed */ public abstract function getId(); /** * @param mixed $id * @return $this */ public abstract function setId($id); /** * @return mixed */ public abstract function getValue(); /** * @param mixed $value * @return $this */ public abstract function setValue($value); /** * @return boolean */ public function getColor() { return $this->color; } /** * @param boolean $color * @return $this */ public function setColor($color) { $this->color = $color; return $this; } /** * @param int $position * @return NodeInterface */ public function getChild($position) { return $this->children[$position]; } /** * @param int $position * @return bool */ public function haveChild($position) { return null !== $this->children[$position]; } /** * Set child * * @param int $position * @param NodeInterface|null $child * @return $this */ public function setChild($position, NodeInterface $child = null) { $this->children[$position] = $child; if (null !== $child) { $child->setParent($this)->setPosition($position); } return $this; } /** * @return integer */ public function getPosition() { return $this->position; } /** * @param integer|null $position * @return $this */ public function setPosition($position) { $this->position = $position; return $this; } /** * @return NodeInterface|null */ public function getParent() { return $this->parent; } /** * @param NodeInterface|null $parent * @return $this */ public function setParent(NodeInterface $parent = null) { $this->parent = $parent; return $this; } /** * ========================================================================= * SHORTCUTS * ========================================================================= */ /** * get grand parent if a parent exist * * @return NodeInterface|null */ public function getGrandParent() { if (null !== $this->getParent()) { return $this->getParent()->getParent(); } return null; } /** * Get uncle if grand parent exist * * @return NodeInterface|null */ public function getUncle() { if (null !== $this->getGrandParent()) { return $this->getGrandParent()->getChild(-$this->getParent()->getPosition()); } return null; } /** * Is a NIL / Leaf * * @return bool */ public function isLeaf() { return null === $this->children[static::POSITION_LEFT] && null === $this->children[static::POSITION_RIGHT]; } }
true
88eabebe1dad6497abe8558d6cd46de63d4a1f89
PHP
edisonramaa/supermetrics_api
/Services/ResponseService.php
UTF-8
3,015
3
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Edison * Date: 11/28/2019 * Time: 1:20 AM */ namespace Services; use Services\Interfaces\IResponseService; /** * Class ResponseService */ class ResponseService implements IResponseService { /** * @var array $_successStatuses */ protected $_successStatuses = [200, 201]; /** * @var array $_availableFormats */ protected $_availableFormats = ['json']; /** * @var string $_format */ protected $_format = 'json'; /** * @var int $_status */ protected $_status = 200; /** * @param int $status * @return $this */ public function withStatus($status) : ResponseService { $this->_status = $status; return $this; } /** * @param string $format * @return $this * @throws \Exception */ public function format($format) : ResponseService { $this->__checkFormat($format); $this->_format = $format; return $this; } /** * Returns the results for multiple objects * * @param int $total * @param array $data * @param string $key * @param string $message * @param null $error * @return string */ public function multiple($total, $data, $key = '', $message = null, $error = null) : string { if (empty($key)) { $key = "items"; } $data = [ 'total' => $total, 'success' => in_array($this->_status, $this->_successStatuses), $key => $data, ]; if (!is_null($message)) { $data['message'] = $message; } if (!is_null($error)) { $data['error'] = $error; } return $this->_response($data); } /** * Returns the result for single objects * * @param array $object * @param string $key * @param string $message * @param null $error * @return string */ public function single($object, $key = '', $message = null, $error = null) : string { if (empty($key)) { $key = "data"; } $data = [ 'success' => in_array($this->_status, $this->_successStatuses), ]; $data[$key] = $object; if (!is_null($message)) { $data['message'] = $message; } if (!is_null($error)) { $data['error'] = $error; } return $this->_response($data); } /** * Returns the json encoded string * * @param array $data * @return string */ protected function _response($data) : string { return json_encode($data); } /** * * Will check is format available for this * * @param string $format * @throws \Exception */ private function __checkFormat($format) { if (!in_array($format, $this->_availableFormats)) { throw new \Exception(); } } }
true
01d63bc427fc0ddefcd3f495b74456af4b575276
PHP
zyl6868/bh
/common/clients/OrganizationService.php
UTF-8
6,344
2.734375
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Created by PhpStorm. * User: WangShiKui * Date: 18-2-27 * Time: 上午10:19 */ namespace common\clients; use common\components\MicroServiceRequest; use common\models\pos\SeClassMembers; use Httpful\Mime; use Yii; class OrganizationService { /** * @var null */ private $uri = null; private $microServiceRequest = null; private $host = null; /** * TestMicroService constructor. */ public function __construct() { $this->uri = Yii::$app->params['microService']; $this->host = 'organization-service'; $this->microServiceRequest = new MicroServiceRequest($this->host); } /** * 创建班级 * @param int $userID * @param int $classNumber * @param int $departmentId * @param int $gradeId * @param int $joinYear * @param int $schoolID * @return \Httpful\Response */ public function CreateClass(int $userID, int $classNumber, int $departmentId, int $gradeId, int $joinYear, int $schoolID) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/create-class') ->body(http_build_query(['school-id' => $schoolID, 'department-id' => $departmentId, 'grade-id' => $gradeId, 'class-number' => $classNumber, 'join-year' => $joinYear, 'creator-id' => $userID])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 添加老师到班级(没有班级则创建) * @param int $userID * @param int $classNumber * @param int $departmentId * @param int $gradeId * @param int $joinYear * @param int $schoolID * @return array|object|string */ public function ClassAddTeacher(int $userID, int $classNumber, int $departmentId, int $gradeId, int $joinYear, int $schoolID) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/class-add-teacher') ->body(http_build_query(['school-id' => $schoolID, 'department-id' => $departmentId, 'grade-id' => $gradeId, 'class-number' => $classNumber, 'join-year' => $joinYear, 'creator-id' => $userID])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 封班 * @param string $classIds * @param int $schoolID * @return array|object|string */ public function CloseClass(string $classIds, int $schoolID) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/close-class') ->body(http_build_query(['school-id' => $schoolID, 'class-ids' => $classIds])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 踢出班级 * @param int $userID * @param int $classId * @param bool $ifCleanToken * @return array|object|string */ public function OutClass(int $userID, int $classId, bool $ifCleanToken = true) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/out-class') ->body(http_build_query(['class-id' => $classId, 'user-id' => $userID, 'if-clean-token' => $ifCleanToken])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 踢出学校 * @param int $userID * @return array|object|string */ public function OutSchool(int $userID) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/out-school') ->body(http_build_query(['user-id' => $userID])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 跨学校更新班级 * @param string $userIds * @param int $classId * @param int $departmentId * @param int $identity * @param int $schoolID * @param bool $ifCleanToken * @return array|object|string */ public function SpanSchoolUpdateClass(string $userIds, int $classId, int $departmentId, int $schoolID, int $identity = SeClassMembers::STUDENT, bool $ifCleanToken = true) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/span-school-update-class') ->body(http_build_query(['school-id' => $schoolID, 'department-id' => $departmentId, 'class-id' => $classId, 'identity' => $identity, 'user-ids' => $userIds, 'if-clean-token' => $ifCleanToken])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 老师更新班级信息 * @param int $userID * @param string $classIds * @param bool $ifOnlyAdd * @param bool $ifCleanToken * @return array|object|string */ public function ChangeTeacherClass(int $userID, string $classIds, bool $ifOnlyAdd = false, bool $ifCleanToken = true) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/change-teacher-class') ->body(http_build_query(['user-id' => $userID, 'class-ids' => $classIds, 'if-only-add' => $ifOnlyAdd, 'if-clean-token' => $ifCleanToken])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 学校升级 * @param int $departmentId * @param int $schoolID * @return array|object|string */ public function SchoolUpgrade(int $departmentId, int $schoolID) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/school-upgrade') ->body(http_build_query(['school-id' => $schoolID, 'department-id' => $departmentId])) ->sendsType(Mime::FORM) ->send(); return $result->body; } /** * 通过邀请码加入班级 * @param int $userID * @param string $inviteCode * @return array|object|string */ public function AddClass(int $userID, string $inviteCode) { $result = $this->microServiceRequest->post($this->uri . '/api/v2/organization/add-class') ->body(http_build_query(['invite-code' => $inviteCode, 'user-id' => $userID])) ->sendsType(Mime::FORM) ->send(); return $result->body; } }
true
0d34b90d6309d45d5faebba3a5eabcfcf90597a9
PHP
Kanta62/WEB-TECHNOLOGIES-KANTA
/Lab_Task_05/Lab_Task_05/Source Code/controller/addProductControler.php
UTF-8
551
2.65625
3
[]
no_license
<?php require_once ('../model/model.php'); $tableName = 'product'; if(isset($_POST['submit'])) { $data['Name'] = $_POST['name']; $data['BuyingPrice'] = $_POST['bprice']; $data['SellingPrice'] = $_POST['sprice']; if(empty($_POST['display'])){ $data['display'] = "No"; } else{ $data['display'] = $_POST['display']; } if (addProduct($tableName, $data)) { echo '<p>Product Successfully added!!</p><br>'; echo "<a href='../display.php'>Display Product</a>"; } } else { echo '<p>You are not allowed to access this page</p>'; } ?>
true
49564a245efa689345ab06f2147f2a4ab50acc9c
PHP
201732110125/github
/tp_blog/tp5.1/think/application/admin/controller/Index.php
UTF-8
2,260
2.609375
3
[ "Apache-2.0" ]
permissive
<?php namespace app\admin\controller; use think\Controller; class Index extends Controller { public function index() { $arr = ['a' => 'apple', 'b' => 'banana']; halt($arr); } //后台登陆 public function login() { if (request()->isAjax()) {//如果是Ajax请求,request()表示请求方式 $data = [ //接收数据用input()方法获取post传来的username和password //从post中抓取数据下来 'username' => input('post.username'), 'password' => input('post.password'), ]; //助手函数 //这个助手model()显示再admin模块下找common/model/Admin模型类,找不到就去application/model/common下找Admin模型类 //$result 保存了Admin模型类的login方法返回的数据 //从控制器中把抓取到的数据传给模型类进行判断处理 $result = model('Admin')->login($data); if ($result == 1) {//返回1,表示登陆成功了 //注意,当是ajax方法的时候,会自动的把error和success //当前请求为ajax请求(view页面上的jquery中的ajax请求) //返回的结果转化为json格式信息,给前台jquery的$.ajax $this->success("登陆成功"); } else {//返回的不是1 ,表示登陆不成功,或者此账号被禁用了 //把login方法返回的错误信息error一下 $this->error($result); } } return view(); } //后台注册 public function register() { if(request()->isAjax()){//如果有Ajax提交数据 //接收一下数据 $data=[ 'username'=>input('post.username'), 'password'=>input('post.password'), 'conpass'=>input('post.conpass'), 'nickname'=>input('post.nickname'), 'email'=>input('post.email') ]; //把数据传到Admin模型里面的register方法 $result=model("Admin")->register($data); } //显示注册模板 return view(); } }
true
13f356ac89eb86bce82c2e38868eea4958d4caaf
PHP
mrkekseek/book247
/database/migrations/2017_01_09_224806_add_profile_name_to_financial_profiles_table.php
UTF-8
749
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddProfileNameToFinancialProfilesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('financial_profiles', function (Blueprint $table) { $table->string('profile_name', 150); $table->unique('profile_name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('financial_profiles', function (Blueprint $table) { $table->dropUnique(['profile_name']); $table->dropColumn(['profile_name']); }); } }
true
a963de9293de3f542535be84c09dc7832d9eee4b
PHP
sudirmansyah1/kamus-bahasa-isyarat-kmp-boyermoore
/admin/authentication.php
UTF-8
1,815
2.65625
3
[]
no_license
<?php // mengaktifkan session php session_start(); // menghubungkan dengan koneksi include '../assets/config.php'; // menangkap data yang dikirim dari form $username = $_POST['username']; $password = $_POST['password']; $password2 = md5($password); // Untuk menjaga keamanan password maka password dilakukan enkripsi dengan md5, password yang tertera di database sudah berbentuk md5 sehingga untuk menyamakan maka dibutuhkan md5() // menyeleksi data admin dengan username dan password yang sesuai $data = mysqli_query($koneksi,"SELECT * FROM users WHERE (`username`='$username' OR `email`='$username') AND `password`='$password2'"); // menghitung jumlah data yang ditemukan $cek = mysqli_num_rows($data); if($cek > 0){ $row = mysqli_fetch_assoc($data); // Fungsi ini untuk menyimpan data admin sebagai session $_SESSION['id'] = $row['id']; $_SESSION['username'] = $row['username'];; $_SESSION['email'] = $row['email']; $_SESSION['photo'] = $row['photo']; $_SESSION['group'] = $row['group']; //------------------------------------------------------// // Fungsi ini untuk menyimpan aktifitas admin, admin yang login akan disimpan data kapan dia melakukan login. $date = new DateTime("now", new DateTimeZone('Asia/Jakarta') ); $tanggal = $date->format('d-m-Y H:i:s'); $photo_sess = $_SESSION["photo"]; $username_sess = $_SESSION["username"]; $group_sess = $_SESSION['group']; $activity = $username_sess." has been logged in as ".$group_sess; mysqli_query($koneksi, "INSERT INTO activity VALUES(NULL,'$tanggal','$photo_sess','$username_sess','$activity')"); //------------------------------------------------------// header("location:index.php"); }else{ header("location:login.php?status=gagal"); } ?>
true
43d218bdca63637fcf15c3fc9c14e99dd525ac7d
PHP
SinanDumandzha/Teknasyon-PHP-Bootcamp
/week-05/views/post-store.php
UTF-8
1,067
2.765625
3
[ "MIT" ]
permissive
<?php require_once '../autoloader.php'; require_once('../class/Post.class.php'); require_once('../class/Section.class.php'); $post = new Post; $section=new Section; if(isset($_POST['content'])) { $author=(string) $_POST["author"]; $content=(string) $_POST["content"]; if (isset($_GET["section"])){ $section_id = $_GET['section']; $fields = [ 'section_id'=>$section_id, 'author' => $author, 'content' => $content, ]; $section=$section->FindAll(["id"=>$section_id]); $book_id=$section[0]["book_id"]; } elseif (isset($_GET["book"])){ $book_id = $_GET['book']; $fields = [ 'book_id'=>$book_id, 'author' => $author, 'content' => $content, ]; } $post->addPost($fields); return header("Location: book.php?id=$book_id"); } else{ die("Post veri gönderim işlemi gereklidir."); }
true
2e4ec248ed5b9d4c95b8d3de37745f1cc6cc7c2b
PHP
xpeedstudio/mogo-portfolio-wordpress-themes
/framework-customizations/extensions/shortcodes/shortcodes/list/views/view.php
UTF-8
5,254
2.5625
3
[]
no_license
<?php if (!defined('FW')) { die('Forbidden'); /** * @var array $atts */ } ?> <?php $list = 'ul'; if ($atts['list_type']['selected_value'] == 'list-numbers') { $list = 'ol'; } ?> <div class="fw-list <?php echo esc_attr($atts['list_type']['selected_value']); ?> <?php echo esc_attr($atts['separator']); ?> <?php echo esc_attr($atts['class']); ?>"> <<?php echo $list; ?>> <?php if (!empty($atts['list_items'])) : ?> <?php foreach ($atts['list_items'] as $list_item) : ?> <?php if ($atts['list_type']['selected_value'] == 'list-icon') : ?> <li><i class="<?php echo $atts['list_type']['list-icon']['icon']; ?>"></i> <?php if ($list_item['link'] != '') { echo '<a href="' . esc_url($list_item['link']) . '" target="' . esc_attr($list_item['target']) . '">' . fw_theme_translate(esc_attr($list_item['item'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($list_item['item'])); } ?> <?php // begin sublist if (isset($list_item['sublist_items']) && !empty($list_item['sublist_items'])) : ?> <<?php echo $list; ?>> <?php foreach ($list_item['sublist_items'] as $sublist_item) : ?> <?php if ($atts['list_type']['selected_value'] == 'list-icon') : ?> <li><i class="<?php echo $atts['list_type']['list-icon']['icon']; ?>"></i> <?php if ($sublist_item['link'] != '') { echo '<a href="' . esc_url($sublist_item['link']) . '" target="' . esc_attr($sublist_item['target_subitem']) . '">' . fw_theme_translate(esc_attr($sublist_item['subitem'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($sublist_item['subitem'])); } ?> </li> <?php else : ?> <li><?php if ($sublist_item['link'] != '') { echo '<a href="' . esc_url($sublist_item['link']) . '" target="' . esc_attr($sublist_item['target_subitem']) . '">' . fw_theme_translate(esc_attr($sublist_item['subitem'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($sublist_item['subitem'])); } ?> </li> <?php endif; ?> <?php endforeach; ?> </<?php echo $list; ?>> <?php endif; // end sublist ?> </li> <?php else : ?> <li><?php if ($list_item['link'] != '') { echo '<a href="' . esc_url($list_item['link']) . '" target="' . esc_attr($list_item['target']) . '">' . fw_theme_translate(esc_attr($list_item['item'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($list_item['item'])); } ?> <?php // begin sublist if (isset($list_item['sublist_items']) && !empty($list_item['sublist_items'])) : ?> <<?php echo $list; ?>> <?php foreach ($list_item['sublist_items'] as $sublist_item) : ?> <?php if ($atts['list_type']['selected_value'] == 'list-icon') : ?> <li><i class="<?php echo $atts['list_type']['list-icon']['icon']; ?>"></i> <?php if ($sublist_item['link'] != '') { echo '<a href="' . esc_url($sublist_item['link']) . '" target="' . esc_attr($sublist_item['target_subitem']) . '">' . fw_theme_translate(esc_attr($sublist_item['subitem'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($sublist_item['subitem'])); } ?> </li> <?php else : ?> <li><?php if ($sublist_item['link'] != '') { echo '<a href="' . esc_url($sublist_item['link']) . '" target="' . esc_attr($sublist_item['target_subitem']) . '">' . fw_theme_translate(esc_attr($sublist_item['subitem'])) . '</a>'; } else { echo fw_theme_translate(esc_attr($sublist_item['subitem'])); } ?> </li> <?php endif; ?> <?php endforeach; ?> </<?php echo $list; ?>> <?php endif; // end sublist ?> </li> <?php endif; ?> <?php endforeach; ?> <?php endif; ?> </<?php echo $list; ?>> </div>
true
cf7c46ab78906ce6c45a04fb8432ef745e9306dd
PHP
h136799711/201506bbjie
/Application/Uclient/Model/OAuth2TypeModel.class.php
UTF-8
1,093
2.8125
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: hebidu * Date: 15/7/1 * Time: 16:11 */ namespace Uclient\Model; /** * 第三方账户登录\注册类型枚举 * Class OAuth2FromEnum * @package Uclient\Model */ class OAuth2TypeModel { /** * 来源QQ注册 */ const QQ = 1; /** * 来源微信注册 */ const WEIXIN = 2; /** * 来源百度注册 */ const SINA = 3; /** * 来源百度注册 */ const BAIDU = 4; /** * 来源淘宝注册 */ const TAOBAO = 5; /** * 来源其它应用登录 */ const OTHER_APP = 99; /** * 来源其它内部应用登录 */ const SELF = 0; /** * 检测类型是否合法 * @param $type * @return bool */ static public function checkType($type){ $type = intval($type); if(is_int($type)){ if($type >= 0 && $type < 5){ return true; } if($type == 99){ return true; } } return false; } }
true
182ede2b9c90192969ca4054c29e8192e6d14c70
PHP
eslamabdelbasset1/MagBuy
/utility/blocked_user.php
UTF-8
854
2.640625
3
[ "MIT" ]
permissive
<?php // Start Session if (session_status() == PHP_SESSION_NONE) { session_start(); } require_once 'autoloader.php'; if(isset($_SESSION['loggedUser']) ) { try { $userDao = \model\database\UserDao::getInstance(); if (!$userDao->checkEnabled($_SESSION['loggedUser'])){ $_SESSION['enabled'] = 0; } } catch (PDOException $e) { $message = date("Y-m-d H:i:s") . " " . $_SERVER['SCRIPT_NAME'] . " $e\n"; error_log($message, 3, '../errors.log'); header("Location: ../view/error/error_500.php"); die(); } // Check if user have session (if user is logged) if (isset($_SESSION['enabled']) && $_SESSION['enabled'] == 0) { session_destroy(); //Redirect to Main header('Location: ../../view/user/login.php?blocked'); die(); } }
true
9817ce8f14744bca7cf338a0668fcd2a2d6a25dc
PHP
alzerid/Arbitrage
/framework/cli/CCLIBaseApplication.class.php
UTF-8
322
2.71875
3
[]
no_license
<? abstract class CCLIBaseApplication { protected $_description; public function getApplicationDescription() { return $this->_description; } public function getApplicationName() { return strtolower(preg_replace('/Application$/', '', get_class($this))); } abstract public function getApplicationType(); } ?>
true
ea4d61da5d9c9bacf03a204ac8a8cef41b9ad3f2
PHP
maintaina-com/Service_Weather
/lib/Horde/Service/Weather/Forecast/Base.php
UTF-8
3,480
3
3
[]
permissive
<?php /** * This file contains the Horde_Service_Weather_Forecast class for abstracting * access to forecast data. Provides a simple iterator for a collection of * forecast periods. * * Copyright 2011-2017 Horde LLC (http://www.horde.org/) * * @author Michael J Rubinsky <mrubinsk@horde.org> * @license http://www.horde.org/licenses/bsd BSD * @category Horde * @package Service_Weather */ /** * Horde_Service_Weather_Current class * * @author Michael J Rubinsky <mrubinsk@horde.org> * @category Horde * @package Service_Weather */ abstract class Horde_Service_Weather_Forecast_Base implements IteratorAggregate { /** * The forecast properties as returned from the forecast request. * * @var array */ protected $_properties = array(); /** * Local cache of forecast periods * * @var array */ protected $_periods = array(); /** * Forecast type * * @var integer A Horde_Service_Weather::FORECAST_TYPE_* constant. */ protected $_type; /** * Maximum forecast length to return. Defaults to sufficiently high number * to ensure all available days returned by default. */ protected $_maxDays = 20; /** * Parent Weather driver. * * @var Horde_Service_Weather_Base */ public $weather; /** * Array of supported "detailed" forecast fields. To be populated by * concrete classes. * * @var array */ public $fields = array(); /** * Advertise how detailed the forecast period is. *<pre> * FORECAST_TYPE_STANDARD - Each Period represents a full day * FORECAST_TYPE_DETAILED - Each period represents either day or night. * FORECAST_TYPE_HOURLY - Each period represents a single hour. *</pre> * * @var integer */ public $detail = Horde_Service_Weather::FORECAST_TYPE_STANDARD; /** * Const'r * * @param array $properties Forecast properties. * @param Horde_Service_Weather_base $weather The base driver. * @param integer $type The forecast type. */ public function __construct( $properties, Horde_Service_Weather_Base $weather, $type = Horde_Service_Weather::FORECAST_TYPE_STANDARD) { $this->_properties = $properties; $this->weather = $weather; $this->_type = $type; } /** * Return the forecast for the specified ordinal day. * * @param integer $day The forecast day to return. * * @return Horde_Service_Weather_Period_Base */ public function getForecastDay($day) { return $this->_periods[$day]; } /** * Limit the returned number of forecast days. Used for emulating a smaller * forecast length than the provider supports or for using one, longer * request to supply two different forecast length requests. * * @param integer $days The number of days to return. */ public function limitLength($days) { $this->_maxDays = $days; } /** * Return the time of the forecast, in local (to station) time. * * @return Horde_Date The time of the forecast. */ abstract public function getForecastTime(); /** * Return an ArrayIterator * * @return ArrayIterator */ public function getIterator() { return new ArrayIterator(array_slice($this->_periods, 0, $this->_maxDays)); } }
true
432d4b7f46564cec77a9ff63c8c3ccd91b2f284a
PHP
Ju-Long/htdocs
/C203/P04CreateMyLyrics/doExercise2a.php
UTF-8
115
2.609375
3
[]
no_license
<?php $start = $_POST['start']; $end = $_POST['end']; for($i = $start; $i <= $end; $i++){ echo $i."<br>"; } ?>
true
db61e09aad3db785e8a99498ffe2ccccd6294185
PHP
elinoretenorio/php-headless-crud-for-movies-db
/src/Keyword/KeywordModel.php
UTF-8
1,218
3.140625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Movies\Keyword; use JsonSerializable; class KeywordModel implements JsonSerializable { private int $keywordId; private string $keywordName; public function __construct(KeywordDto $dto = null) { if ($dto === null) { return; } $this->keywordId = $dto->keywordId; $this->keywordName = $dto->keywordName; } public function getKeywordId(): int { return $this->keywordId; } public function setKeywordId(int $keywordId): void { $this->keywordId = $keywordId; } public function getKeywordName(): string { return $this->keywordName; } public function setKeywordName(string $keywordName): void { $this->keywordName = $keywordName; } public function toDto(): KeywordDto { $dto = new KeywordDto(); $dto->keywordId = (int) ($this->keywordId ?? 0); $dto->keywordName = $this->keywordName ?? ""; return $dto; } public function jsonSerialize(): array { return [ "keyword_id" => $this->keywordId, "keyword_name" => $this->keywordName, ]; } }
true
e73c62c4679d4744751d17e7ed7fa525a4e3ba2f
PHP
tk-wing/laravel-booklikes
/app/Models/Bookshelf.php
UTF-8
748
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Bookshelf extends Model { protected $table = 'bookshelves'; protected $primaryKey = 'id'; protected $fillable = ['user_id', 'title', 'auto']; public function user(){ return $this->belongsTo(User::class); } public function categories(){ return $this->belongsToMany(Category::class, 'bookshelves_has_categories'); } public function books(){ return $this->belongsToMany(Book::class, 'bookshelves_has_books'); } public function store($request, User $user) { $this->title = $request->title; $this->user_id = $user->id; $this->auto = $request->auto; $this->save(); } }
true
108cc1724eba73a55f6affa87b8054553f72d084
PHP
jfern01/klaus
/src/Objects/Account.php
UTF-8
2,591
2.84375
3
[ "MIT" ]
permissive
<?php namespace Ci\Klaus\Objects; use Ci\Klaus\Object; use JMS\Serializer\Annotation\AccessType; use JMS\Serializer\Annotation\SerializedName; use JMS\Serializer\Annotation\Type; use JMS\Serializer\Annotation\XmlElement; use JMS\Serializer\Annotation\XmlRoot; /** * @XmlRoot("Account") * @AccessType("public_method") */ class Account extends Object { /** * @var string * * @SerializedName("Name") * @Type("string") * @XmlElement(cdata=false) */ protected $name; /** * @var string * * @SerializedName("AccountingID") * @Type("string") * @XmlElement(cdata=false) */ protected $accountingId; /** * @var int * * @SerializedName("AccountType") * @Type("integer") */ protected $accountType; /** * @var string * * @SerializedName("Balance") * @Type("string") * @XmlElement(cdata=false) */ protected $balance; /** * Gets the value of name. * * @return string */ public function getName() { return $this->name; } /** * Sets the value of name. * * @param string $name the name * * @return self */ public function setName($name) { $this->name = $name; return $this; } /** * Gets the value of accountingId. * * @return string */ public function getAccountingId() { return $this->accountingId; } /** * Sets the value of accountingId. * * @param string $accountingId the accounting id * * @return self */ public function setAccountingId($accountingId) { $this->accountingId = $accountingId; return $this; } /** * Gets the value of accountType. * * @return int */ public function getAccountType() { return $this->accountType; } /** * Sets the value of accountType. * * @param int $accountType the account type * * @return self */ public function setAccountType($accountType) { $this->accountType = $accountType; return $this; } /** * Gets the value of balance. * * @return string */ public function getBalance() { return $this->balance; } /** * Sets the value of balance. * * @param string $balance the balance * * @return self */ public function setBalance($balance) { $this->balance = $balance; return $this; } }
true
155c3830a706aa843728b35970a2930e9579dbf7
PHP
mcbraga72/agradecaaqui
/app/Http/Controllers/UserAdminController.php
UTF-8
4,827
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\User; use App\Http\Requests\CompleteUserRegisterRequest; use Illuminate\Http\Request; use URL; class UserAdminController extends Controller { /** * User's list page * * @return Response */ public function listAll() { $countriesList = new \SplFileObject(URL::to('/') . '/paises.json'); while (!$countriesList->eof()) { $countries[] = trim($countriesList->fgets()); } return view('admin.user.list')->with('countries', $countries); } /** * Index page * * @return Response */ public function index(Request $request) { $users = User::orderBy('name')->paginate(10); $response = [ 'pagination' => [ 'total' => $users->total(), 'per_page' => $users->perPage(), 'current_page' => $users->currentPage(), 'last_page' => $users->lastPage(), 'from' => $users->firstItem(), 'to' => $users->lastItem() ], 'data' => $users ]; return response()->json($response); } /** * * Add new user to the database. * * @param Request $request * * @return Response * */ public function store(UserRequest $request) { $findUser = User::where('email', '=', $request->email)->first(); if($findUser == null) { $user = new User(); $user->name = $request->name; $user->surName = $request->surName; $user->gender = $request->gender; $user->dateOfBirth = $request->dateOfBirth; $user->telephone = $request->telephone; $user->city = $request->city; $user->state = $request->state; $user->email = $request->email; $user->password = bcrypt($request->password); $user->registerType = 'Padrão'; if($request->gender == 'Masculino') { $user->photo = '/images/male.png'; } else { $user->photo = '/images/female.png'; } $user->save(); return response()->json($user); } else { return false; } } /** * * Show user's data. * * @param int $id * * @return User $user * */ public function show($id) { $user = User::findOrFail($id); return $user; } /** * Update user's data * */ public function update(CompleteUserRegisterRequest $request, $id) { $user = User::find($id); $user->name = $request->name; $user->surName = $request->surName; if ($request->gender == 'Outro') { $user->gender = $request->otherGender; } else { $user->gender = $request->gender; } $user->dateOfBirth = $request->dateOfBirth; $user->telephone = $request->telephone; $user->city = $request->city; $user->state = $request->state; $user->country = $request->country; $user->email = $request->email; $user->education = $request->education; $user->profession = $request->profession; $user->maritalStatus = $request->maritalStatus; if ($request->religion == 'Outra') { $user->religion = $request->otherReligion; } else { $user->religion = $request->religion; } $user->income = $request->income; if (in_array('Outro(s)', $request->sport)) { $user->sport = $request->otherSport; } else { $user->sport = json_encode($request->sport); } if ($request->soccerTeam == 'Outro') { $user->soccerTeam = $request->otherSoccerTeam; } else { $user->soccerTeam = $request->soccerTeam; } $user->height = $request->height; $user->weight = $request->weight; $user->hasCar = $request->hasCar; $user->hasChildren = $request->hasChildren; $user->liveWith = $request->liveWith; if (in_array('Outro(s)', $request->pet)) { $user->pet = $request->otherPet; } else { $user->pet = json_encode($request->pet); } $user->save(); return response()->json($user); } /** * * Remove the user. * * @param int $id * * @return Response * */ public function destroy($id) { $delete = User::findOrFail($id)->delete(); return response()->json($delete); } }
true
884167cd2231d43f1832ba6a5e4e6a3f6786599b
PHP
flavius95/Licenta
/app/Topic.php
UTF-8
589
2.78125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Topic extends Model { protected $fillable = ['topic', 'word']; public $timestamps = false; public static function arrangeTopics(array $data) : array { $result = []; if (count($data)) { foreach ($data as $item) { if(!isset($result[$item['topic']])) { $result[$item['topic']] = [$item['word']]; } else { $result[$item['topic']][] = $item['word']; } } } return $result; } }
true
ab0d0dc1a2fdc8bc994d10cc8c7c2f41abddb9c7
PHP
rootlocal/yii2-crud
/src/components/ActionInterface.php
UTF-8
372
2.59375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace rootlocal\crud\components; /** * Interface ActionInterface * Base Action Interface * * @author Alexander Zakharov <sys@eml.ru> * @package rootlocal\crud\components */ interface ActionInterface { /** * @return string */ public function getViewName(); /** * @param string $viewName */ public function setViewName($viewName); }
true
d2d5eab9c5232cbb20eb0b85ebf892d864bd54eb
PHP
Sha-dow/ShadowStore
/users.php
UTF-8
1,736
2.921875
3
[]
no_license
<?php session_start(); include 'functions.php'; print_head("Users"); $role = ''; if (isset($_SESSION['username'])) { $firstname = $_SESSION['firstname']; $lastname = $_SESSION['lastname']; $role = $_SESSION['role']; } if ($role != 'A') { header('Location: index.php'); die(); } unset($_SESSION['sort']); $_SESSION['filter'] = 'all'; print_navigation($role, 'users'); ?> <!-- Main container includes two minor containers --> <div id="main-container"> <div id="container"> <h1>User listing</h1> <?php //Connect to DB $conn = connect_db(); //Query for selecting users $query = "select uid, firstname, lastname, email, phone, address from users;"; $resultset = mysqli_query($conn, $query); //If query fails print error and die if (!$resultset) { echo "FAILURE: Cant retrieve data from database"; die(); } //Print table of users echo "<table id='ordertable' class='ordertable'><tr>" . PHP_EOL; echo "<th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Address</th>" . PHP_EOL; $even = false; while ($data = mysqli_fetch_array($resultset, MYSQLI_ASSOC)) { if ($even) { echo "<tr class='even'>" . PHP_EOL; $even = false; } else { echo "<tr>"; $even = true; } echo "<td>" . $data['uid'] . "</td>" . PHP_EOL; echo "<td>" . $data['firstname'] . " " . $data['lastname'] ."</td>" . PHP_EOL; echo "<td>" . $data['email'] . "</td>" . PHP_EOL; echo "<td>" . $data['phone'] . "</td>" . PHP_EOL; echo "<td>" . $data['address'] . "</td>" . PHP_EOL; echo "</tr>"; } echo "</table>" . PHP_EOL; echo "</div>"; mysqli_free_result($resultset); //Close DB connection mysqli_close($conn); shopping_cart($firstname, $lastname); print_footer(); ?>
true
9743055733ccf5ce90f4bb6744767863a6d74ab8
PHP
hschulz/php-data-structures
/src/Queue/PriorityQueue.php
UTF-8
2,221
3.265625
3
[ "BSD-3-Clause" ]
permissive
<?php declare(strict_types=1); namespace Hschulz\DataStructures\Queue; use Serializable; use function serialize; use SplPriorityQueue; use function unserialize; /** * */ class PriorityQueue extends SplPriorityQueue implements Serializable { /** * The default priority value used when no priority is given. * @var int */ public const PIRORITY_DEFAULT = 1; /** * Iterates the queue and returns an array containing each item with * the data and priority set. * * @return array The array representation of the queue */ public function toArray(): array { /* Enable extraction of data and priority */ $this->setExtractFlags(self::EXTR_BOTH); /* Prepare output */ $data = []; /* Iterate yourself */ foreach ($this as $item) { $data[] = $item; } return $data; } /** * Allows inserting data into the queue without explicitly setting a * priority value. Inserts without a priority will use the PRIORITY_DEFAULT * value. * * @param mixed $data The data to insert * @param mixed $priority The priority * @return void */ public function insert($data, $priority = self::PIRORITY_DEFAULT): void { parent::insert($data, $priority); } /** * Serializes the queue by converting the queue into an array. * * @return string The serialized queue */ public function serialize(): string { return serialize($this->toArray()); } /** * Unserializes the queue. * * @param string $queue The serialized queue data * @return void */ public function unserialize($queue): void { foreach (unserialize($queue) as $item) { $this->insert($item['data'], $item['priority']); } } /** * Merges the given queue data into this queue. * * @param PriorityQueue $queue The queue to merge * @return void */ public function merge(self $queue): void { $data = $queue->toArray(); foreach ($data as $item) { $this->insert($item['data'], $item['priority']); } } }
true
b6b635cde0fef25b63fef651949cec035d727990
PHP
galadie/Caranille-RPG
/Design/support/Templates/Right.php
UTF-8
958
2.5625
3
[ "CC-BY-4.0" ]
permissive
<?php if(!function_exists('html_menu')) { function html_menu($title="Menu",$links = array(), $infos ="" ) { ?> <div> <span><a href="#" class="selected"><?php echo $title ?></a></span> </div> <ul> <li> <?php if(!empty($links)) { ?> <?php foreach($links as $link) { ?> <a href="<?php echo get_link($link[0],$link[1]) ?>"><?php echo $link[2] ?></a> <?php } ?> <?php } ?> </li> <?php if($infos!="") { ?><p><?php echo $infos ?></p><?php } ?> </ul> <?php } } ?> <div class="sidebar"> <?php if(verif_access("Admin",true) && $secteur_module === 'Admin')//Si le Access est Admin, afficher le menu de l'admin { call_menu_admin() ; } elseif (verif_access("Modo",true) && $secteur_module === 'Moderator')//Si le Access est Admin, afficher le menu de l'admin { call_menu_modo(); } ?> </div>
true
bfc1466af54aa3c8d728694295eb58b4e3e9d16d
PHP
dvsa/olcs-backend
/module/Api/src/Service/Document/Bookmark/CompanyStatus.php
UTF-8
1,112
2.53125
3
[ "MIT" ]
permissive
<?php namespace Dvsa\Olcs\Api\Service\Document\Bookmark; use Dvsa\Olcs\Api\Domain\Query\Bookmark\CompaniesHouseCompanyBundle as Qry; use Dvsa\Olcs\Api\Service\Document\Bookmark\Base\DynamicBookmark; use Dvsa\Olcs\Transfer\Query\QueryInterface; class CompanyStatus extends DynamicBookmark { /** * Get the data required for the bookmark */ public function getQuery(array $data): QueryInterface { return Qry::create(['id' => $data['licence'], 'bundle' => []]); } /** * Renders the data for the bookmark */ public function render(): ?string { return $this->formatCompanyStatus($this->data['companyStatus']); } private function formatCompanyStatus($companyStatus): ?string { $statuses = [ 'administration' => 'Administration', 'insolvency-proceedings' => 'Insolvency Proceedings', 'liquidation' => 'Liquidation', 'receivership' => 'Receivership', 'voluntary-arrangement' => 'Voluntary Arrangement', ]; return strtr($companyStatus, $statuses); } }
true
02e24b242dc21d5aad693e5e0ec24fdb48228e50
PHP
Trietptm-on-Coding-Algorithms/euler-4
/index.php
UTF-8
288
2.5625
3
[ "MIT" ]
permissive
<?php include("defines.php"); $problem=1; $problem = $_GET['prob']; $ausf_beginn = microtime(true); include("$problem.php"); $ausf_ende = microtime(true); ?> <hr> Execution time: <?php echo $ausf_ende - $ausf_beginn; ?> <hr> <?php highlight_file("$problem.php"); ?>
true
2ed6dfe69a07218e654f7e0fecdd67fc98343758
PHP
capirucho/Image-Gallery
/admin/includes/database.php
UTF-8
1,914
3.25
3
[]
no_license
<?php require_once("config.php"); class Database { public $connection; // use __construct() here to automatically call the open_db_connection // function once the class gets instantiated. // otherwise after instantiation you would have to call like this // $database->open_db_connection() function __construct() { $this->open_db_connection(); } public function open_db_connection() { //next line is outdate procedural way. Dont use //$this->connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME); //the more "object oriented" way of doing this is this next line: $this->connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if( $this->connection->connect_errno ) { die("Database connection failed badly" . $this->connection->connect_error); } } public function query($sql) { //$result = mysqli_query($this->connection, $sql); $result = $this->connection->query($sql); $this->confirm_query($result); return $result; } private function confirm_query($result) { if(!$result) { die("Query Failed by RONALD" . $this->connection->error); } } public function escape_string($string) { //$escaped_string = mysqli_real_escape_string($this->connection, $string); $escaped_string = $this->connection->real_escape_string($string); return $escaped_string; } public function the_insert_id() { return mysqli_insert_id($this->connection); } // public function the_insert_id() { // return $this->connection->insert_id; // } } // End of Class Database $database = new Database(); ?>
true
fdd486a524a3ac9e081d9ebaf507a8fa509c7bdb
PHP
MikeUpjohn/Mikeofmacc-Weather
/includes/printMLSFestivals.php
UTF-8
1,228
2.5625
3
[]
no_license
<?php $query = "SELECT * FROM specialevents_mlsfestivals"; $result = mysql_query($query); $currentNumberOfForecasts = mysql_num_rows($result); if(!$result) { echo "Error with forecast, please contact an administration,"; } else { if($currentNumberOfForecasts == 0) { echo "<h4><strong>Festivals of Music, Light and Sound Forecasts</strong></h4>"; echo "<p>No Festivals of Music, Light and Sound forecasts issued at present. Please check back later.</p>"; } else { while($row = mysql_fetch_array($result)) { echo "<h3><strong>" . $row['forecastDate'] . "</strong></h3><br/>"; echo "<h4><strong>#" . $row['forecastID'] . " - SPECIAL EVENT WEATHER FORECAST for " . $row['location'] . " and surrounding areas for '" . $row['event'] . "' issued at " . $row['issueTime'] . " on " . $row['issueDate'] . "." . $row['issueMonth'] . "." . $row['issueYear'] . "</strong></h4><br/>"; echo "<p><strong>Forecast for " . $row['location'] . ":</strong> " . $row['synopsis'] . "</p><br/>"; echo "<p><strong>Temperature: </strong>" . $row['forecastTemp'] . "&deg;C</p><br/>"; echo "<h5>" . $row['forecasterName'] . " for Mikeofmacc Weather</h5>"; echo "<div class='horizontal_rule'>"; echo "</div>"; } } } ?>
true
a3b447061721c754de2913982145f9d50475727d
PHP
eduardoborges/projeto-BD-pt2
/api/app/migrations/index.php
UTF-8
277
2.515625
3
[ "MIT" ]
permissive
<?php use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; $app->get('/', function(ServerRequestInterface $request, ResponseInterface $response){ $data = array('name' => 'Bob', 'age' => 40); return $response->withJson($data, 200); });
true
7611026f21c5e9ce81ba7ff5fa2cd3f85a98bf60
PHP
mmwny/xml-support-system
/models/Users.php
UTF-8
2,493
2.796875
3
[]
no_license
<?php class User { public function userAddTicket($catInput, $msgInput) { $doc = new DOMDocument; $doc->preserveWhiteSpace = false; $doc->formatOutput = true; $doc->load('xml/tickets.xml'); //get root tickets element $root = $doc->getElementsByTagName('tickets')->item(0); //creating id auto incrementer $ticketIdNum = $root->childNodes->length + 1; //create new ticket from form data $ticket = $doc->createElement('ticket'); //create <item> element $ticketId = $doc->createAttribute('id'); $ticketId->value = $ticketIdNum; $ticket->appendChild($ticketId); $ticketDate = $doc->createAttribute('date'); $ticketDate->value = date('Y-m-d'); $ticket->appendChild($ticketDate); $ticketStatus = $doc->createAttribute('status'); $ticketStatus->value = "Open"; $ticket->appendChild($ticketStatus); $category = $doc->createElement('category', $catInput); //value from dropdown $clientId = $doc->createElement('clientId', $_SESSION['userId'] /*VARIABLE STORING ID FROM SESSION */); $messages = $doc->createElement('messages'); $supportMsg = $doc->createElement('supportMsg', $msgInput); $userId = $doc->createAttribute('userId'); $userId->value = $_SESSION['userId']; //*VARAIBLE STORING ID FROM SESSION*/ $supportMsg->appendChild($userId); $dateTime = $doc->createAttribute('dateTime'); $dateTime->value = date('Y-m-d H:i:s'); $supportMsg->appendChild($dateTime); $messages->appendChild($supportMsg); $ticket->appendChild($category); $ticket->appendChild($clientId); $ticket->appendChild($messages); //add item to tickets $root->appendChild($ticket); $doc->save('xml/tickets.xml'); } public function loginUser($userInput, $passInput) { //Check if username and password match a users.xml item $xml = simplexml_load_file('xml/users.xml'); foreach ($xml->children() as $user) { if ($user->username == $userInput && $user->password == $passInput) { $_SESSION['loggedIn'] = true; $_SESSION['userId'] = (string)$user['id']; //USER ID for logged in user $_SESSION['userName'] = (string)$user->name->first; //USER FIRST NAME $_SESSION['role'] = (string)$user['role']; //client/support } } } } ?>
true
f22bcc5ae2a4877b685f1076b5c7c4dcfc5157a4
PHP
SaaSVenture/saas-resizer
/src/Saas/Resizer/helpers/File.php
UTF-8
613
3.171875
3
[]
no_license
<?php namespace Saas\Resizer\Helpers; class File { /** * Get a file MIME type by extension. * * @param string $extension * @return string */ public static function mime($ext) { $mime = ''; switch ($ext) { case 'jpg' : $mime = 'image/jpeg'; break; case 'gif' : $mime = 'image/gif'; break; case 'png' : $mime = 'image/png'; break; default : break; } return $mime; } /** * Extract the file extension from a file path. * * @param string $path * @return string */ public static function extension($path) { return pathinfo($path, PATHINFO_EXTENSION); } }
true
b484e8ddc33204b9ccec11665efb1a68be03244d
PHP
rafaelrosalessanch/ModuloInventario
/controladores/controladorAdicionarAtributosComputadora.php
UTF-8
6,156
2.640625
3
[]
no_license
<?php include_once '../modelo/ModeloLog.php'; $nombretipocpu =htmlspecialchars($_POST['nombretipocpu']); $nombrevelocidadcpu = htmlspecialchars($_POST['nombrevelocidadcpu']); $nombremarcahdd = htmlspecialchars($_POST['nombremarcahdd']); $nombrecapacidadhdd =htmlspecialchars($_POST['nombrecapacidadhdd']); $nombretiporam = htmlspecialchars($_POST['nombretiporam']); $nombrecapacidadram = htmlspecialchars($_POST['nombrecapacidadram']); validarAtributos($nombretipocpu, $nombrevelocidadcpu, $nombremarcahdd,$nombrecapacidadhdd,$nombretiporam,$nombrecapacidadram); function validarAtributos($nombretipocpu, $nombrevelocidadcpu, $nombremarcahdd,$nombrecapacidadhdd,$nombretiporam,$nombrecapacidadram){ $banderanombretipocpu=0; $banderanombrevelocidadcpu=0; $banderanombremarcahdd=0; $banderanombrecapacidadhdd=0; $banderanombretiporam=0; $banderanombrecapacidadram=0; $obj = new ModeloLog(); if ($nombretipocpu == NULL && $nombrevelocidadcpu == NULL && $nombremarcahdd == NULL&& $nombrecapacidadhdd == NULL&& $nombretiporam == NULL&& $nombrecapacidadram== NULL) { echo " <div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> <p style='color:red;' id='mensaje'><img src='/images/incorrecto.jpg' alt='' width='17' height='17' /><strong>Inserte almenos un atributo</strong></p>"; return FALSE; } if($nombretipocpu!=NULL){ $mostrarnombretipocpu=$obj->mostrar_tipocpu(); foreach ($mostrarnombretipocpu as $inombretipocpu){ if($inombretipocpu->nombretipocpu==$nombretipocpu){ $banderanombretipocpu=1; } } } else { $banderanombretipocpu=1; } if($nombrevelocidadcpu!=NULL){ $mostrarnombrevelocidadcpu=$obj->mostrar_velocidadcpu(); foreach ($mostrarnombrevelocidadcpu as $inombrevelocidadcpu){ if($inombrevelocidadcpu->nombrevelocidadcpu==$nombrevelocidadcpu){ $banderanombrevelocidadcpu=1; } } } else { $banderanombrevelocidadcpu=1; } if($nombremarcahdd!=NULL){ $mostrarnombremarcahdd=$obj->mostrar_marcahdd(); foreach ($mostrarnombremarcahdd as $inombremarcahdd){ if($inombremarcahdd->nombremarcahdd==$nombremarcahdd){ $banderanombremarcahdd=1; } } } else { $banderanombremarcahdd=1; } if($nombrecapacidadhdd!=NULL){ $mostrarnombrecapacidadhdd=$obj->mostrar_capacidadhdd(); foreach ($mostrarnombrecapacidadhdd as $inombrecapacidadhdd){ if($inombrecapacidadhdd->capacidadhdd==$nombrecapacidadhdd){ $banderanombrecapacidadhdd=1; } } } else { $banderanombrecapacidadhdd=1; } if($nombretiporam!=NULL){ $mostrarnombretiporam=$obj->mostrar_tiporam(); foreach ($mostrarnombretiporam as $inombretiporam){ if($inombretiporam->nombretiporam==$nombretiporam){ $banderanombretiporam=1; } } } else { $banderanombretiporam=1; } if($nombrecapacidadram!=NULL){ $mostrarnombrecapacidadram=$obj->mostrar_capacidadram(); foreach ($mostrarnombrecapacidadram as $inombrecapacidadram){ if($inombrecapacidadram->capacidadram==$nombrecapacidadram){ $banderanombrecapacidadram=1; } } } else { $banderanombrecapacidadram=1; } if($banderanombretipocpu==1){ $nombretipocpu=NULL; $ban=1; } if($banderanombrevelocidadcpu==1){ $nombrevelocidadcpu=NULL; $ban=1; } if($banderanombremarcahdd==1){ $nombremarcahdd=NULL; $ban=1; } if($banderanombrecapacidadhdd==1){ $nombrecapacidadhdd=NULL; $ban=1; } if($banderanombretiporam==1){ $nombretiporam=NULL; $ban=1; } if($banderanombrecapacidadram==1){ $nombrecapacidadram=NULL; $ban=1; } if ($obj->insertar_Atributos_Computadora($nombretipocpu, $nombrevelocidadcpu, $nombremarcahdd,$nombrecapacidadhdd,$nombretiporam,$nombrecapacidadram) == TRUE) { // if($nombreestado!=NULL&&$nombremarca==NULL&&$nombretipo==NULL){ // echo " //<div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> //<p style='color:green;' id='mensaje'><img src='/images/correcto.jpg' alt='' width='20' height='20' /><strong>Se inserto correctamente</strong></p>"; // // } // // if($nombreestado==NULL&&$nombremarca!=NULL&&$nombretipo==NULL){ // echo " //<div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> //<p style='color:green;' id='mensaje'><img src='/images/correcto.jpg' alt='' width='20' height='20' /><strong>Se inserto correctamente </strong></p>"; // // // } // if($nombreestado==NULL&&$nombremarca==NULL&&$nombretipo!=NULL){ // echo " //<div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> //<p style='color:green;' id='mensaje'><img src='/images/correcto.jpg' alt='' width='20' height='20' /><strong>Se inserto correctamente</strong></p>"; // // } // if(($banderaestado+$banderamarca+$banderatipo)==1){ // echo " //<div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> //<p style='color:green;' id='mensaje'><img src='/images/correcto.jpg' alt='' width='20' height='20' /><strong>Se inserto correctamente</strong></p>"; // // } // if(($banderaestado+$banderamarca+$banderatipo)==0){ echo " <div class='logo_img' ><img src='/images/logo.jpg' alt='' width='256' height='84' class='logo_img' /></div> <p style='color:green;' id='mensaje'><img src='/images/correcto.jpg' alt='' width='20' height='20' /><strong>Se inserto correctamente </strong></p>"; // } } } ?>
true
1e63f136247e62c4d6c29e31270cfa7829cc1aeb
PHP
devAsadNur/wedevs-assignment-wp-plugins
/assignment-01/posts-view/includes/Frontend/View.php
UTF-8
1,771
2.90625
3
[]
no_license
<?php namespace PostsView\Frontend; /** * Frontend view handler class */ class View { /** * Initializes the class */ public function __construct() { $this->pvc_counter_mechanism(); } /** * Post view counter mechanism * * @return void */ public function pvc_counter_mechanism() { add_filter( 'the_content', [ $this, 'pvc_set_post_view' ] ); add_filter( 'the_content', [ $this, 'pvc_get_post_view' ] ); } /** * Getting post view counter * * @param [string] $content * @return $content */ public function pvc_get_post_view($content) { global $post; if( $post->post_type === 'post' && is_single() ) { $post_id = $post->ID; $key = 'post_views_count'; $count = get_post_meta( $post_id, $key, true ); $msg = ''; $msg .= '<h3>Post Views: ' .'<'; $msg .= apply_filters( 'custom_html_tag', 'b'); $msg .= '>' . $count .'</'; $msg .= apply_filters( 'custom_html_tag', 'b'); $msg .= '>' . '</h3>'; echo $msg; } return $content; } /** * Setting post view counter * * @param [string] $content * @return $content */ public function pvc_set_post_view($content) { global $post; if( $post->post_type === 'post' && is_single() ) { $post_id = $post->ID; $key = 'post_views_count'; $count = (int) get_post_meta( $post_id, $key, true ); $count++; update_post_meta( $post_id, $key, $count ); } return $content; } }
true
187754543a335785d5e939cdcf3d513b6a2b8172
PHP
theallengroup/IntelNeo
/core/include/db/any.php
UTF-8
10,990
2.9375
3
[]
no_license
<?php global $is_connected_to_db,$global_link,$database_queries,$database_sql_queries,$database_query_count; /** * This is a wrapper for generic DB functionality, it allows us to use any database, as long as what's called is SQL92 * all database access whould be done trough here * */ class any_db extends common{ var $q2op_trim_length=40; //max length of SELECT name text in q2op var $dblink=null; var $dbdatabase='none'; //these constants are got from ./config.php, //make shure you include that somewhere var $db_field_colum_name='Field'; var $query_failed=0; // var $query_error=''; // var $dbhost='localhost'; var $dbname='root'; var $dbpwd=''; var $res=0; var $is_connected=0; /* code to run just after you connected (enviroment setup) */ function db_startup(){ } function sql_quote($a){ return("`$a`"); } function sql_quoted_single_comma(){ return("\'"); } function cast_as_string($field){ return($field); } function concat(){ $all = func_get_args(); if(is_array($all[0])){ $all=$all[0]; } return(implode(" || ",$all)); } /** * Class Constructor, connects to the database. * @param $c whether or not to connect to the database * */ function any_db($c=1){ global $config,$global_link,$is_connected_to_db; $this->dbdatabase=$config['database_name']; $this->dbhost=$config['database_host']; $this->dbname=$config['database_user']; $this->dbpwd=$config['database_password']; if($is_connected_to_db==1){ $this->dblink=$global_link; } if($c==1){ //this no longer connects } $this->db_connect(); $this->db_startup(); $this->common(); } /** * * */ function db_connect(){ $this->dblink=$this->cnn( $this->dbdatabase, $this->dbhost, $this->dbname, $this->dbpwd ); } /** * Returns the SQL necesary to paginate, since it's not standard SQL. * * I know that pagination is much more complex in other * systems, like oracle, where you have rownum, and let's not talk about * mssql, but at least its here, and not in std.php ! * */ function db_paginate_sql($page_number){ global $config; return("\n LIMIT ".$config['pagination_limit']." OFFSET ".($config['pagination_limit']*$page_number)." "); } /** * removes anything that could be used for SQL injection, * anything that comes from the user, should be filtered trough here first. * it also removes html attacks. * */ function remove_strange_chars($txt){ return(str_replace(array('<','>',"'",";","&","\\"),'',$txt)); } function remove_non_html($txt){ return(str_replace(array("'",";","\\"),'',$txt)); } function remove_html($txt){ return(str_replace(array("<",">"),'',$txt)); } /* * Returns a bi-dimensional array, with the result of the sql query, * in a suitable way for an input field, * it can be used, for instance, to get a list of values, name, value, from 2 fields, id and first varchar. * @param $sql a SQL query to be run * @param $f1 the first fields (acts as the ID) * @param $f2 the second field (ascts as the description field, like Name, for instance) * @param $trim can take two values, "no" and "trim" * * */ function q2op($sql,$f1='id',$f2='name',$trim='no'){ $q=$this->q2obj($sql); $r=array(); foreach($q as $k=>$row){ if($trim=='no'){ $v=$row[$f2]; }elseif($trim=='trim'){ $v=$this->cut($row[$f2],$this->q2op_trim_length); }else{ std::log_once('invalid parameter:$trim','ERROR'); $v=$row[$f2]; } $r[$row[$f1]]=$v; } return($r); } /** *returns "show databases", since it's not SQL92 * */ function database_list(){ return($this->q2obj("show databases")); } function real_connect($host1, $name1,$pwd1){ } function real_select($db){ return(true); } function real_error(){ return("error?"); } /** * This function connects you to the database. * altough the function might be called several times, by several objects that inherith this class or STD (which inheriths from DB), * the function only connects to the database once, and stopres the db link in $global_link * this is done to improve performance. * * @param $data1 database_name (usually in the config File) when the database is '', we just connect to the server, not to the database $data1 * */ function cnn($data1,$host1,$name1,$pwd1){ global $is_connected_to_db,$global_link; if(!$is_connected_to_db){ ///echo("Connection Trace".b2()); $link = $this->real_connect($host1, $name1,$pwd1) or die("error 1:" . $this->real_error()); $global_link = $link; $is_connected_to_db = 1; ///p2($global_link); }else{ $link=$global_link; } if($data1!=''){ $this->use_db($data1); } return($link); } /** * returns true or false depending on BD connectivity (but displays no error message), nor it die()s * follows the presime of "easier to ask for forgiveness rather than ask for permission" * so ill just apologize to the user, and log the error somewhere * */ function ping(){ $link = $this->real_connect($this->dbhost, $this->dbname, $this->dbpwd); if(!$link){ return(FALSE); } if($this->dbdatabase!=''){ if($this->real_select($this->dbdatabase)){ return(TRUE); } }else{ //no DB given, but server connect ok (.gen, _util, etc) return(TRUE); } return(FALSE); } /** maps to mysql_insert_id(), it's not SQL92 */ function last_id(){ return(-1); } /** Allows you to change the current database, for inter-database operability. */ function use_db($data1){ global $i18n_std; if(!$this->real_select($data1)){ echo('no db connection:'.$data1.' ('.$this->real_error().') engine='.$this->engine_name); //.'cwd='.getcwd() die(''); } } /** maps to sql.describe, i'm not sure about its compatibility w/ SQL92 */ function describe($table){ return(array()); } function table_list(){ return(array()); } function fetch(){ return(array()); } /* * Executes an SQL query, and returns a result-set, keep in mind that UPDATES, and INSERTS (among other) * don't return a valid result-set (since there isn't any) * */ function sql($sqlstring,$notes='',$allow_fail=0){ global $is_connected_to_db,$global_link,$main; //RESET ERROR STATE $this->query_failed=0; $this->query_error=''; #this function send a query to the db engine and returns the result. // echo('icdb='.$is_connected_to_db); if(!$is_connected_to_db){ $this->db_connect(); } global $database_queries,$database_query_count,$database_sql_queries; $q=explode(' ',$sqlstring); # if(DEBUG){ //THIS IS DBLOG; BUT CANNOT CALL DBLOG; SINCE IS OR ISNT STATIC! # $database_query_count++; # $database_queries.="<h2>--".$q[0]."</h2><hr/><pre>".$sqlstring.'</pre>'; # $database_sql_queries[]=$sqlstring; # } //p2($global_link); //echo("mysql_query Trace".b2()); $this->res = $this->real_sql($sqlstring,$this->dblink); if($this->res=='' && $allow_fail==1){ $this->query_failed=1; $this->query_error = "SQL error: " . htmlentities($this->real_error()); return("FAILED"); } if($this->res==''){ $database_query_count++; if(isset($_GET['__output_type']) && $_GET['__output_type']!='HTML'){ $err_text=htmlentities($this->real_error()); $err_text.=(DEBUG? ("\n\n".htmlentities($sqlstring)):'.'); }else{ $this->head();//ERROR? echo($this->get_log()); $err_text = "DEBUG=".DEBUG." SQL error: " . htmlentities($this->real_error()). ($txt .$txt2. "<br/><pre>".htmlentities($sqlstring)."</pre>"); } #$s = new std(); $this->error($err_text,'SQL001'); if(DEBUG){ $this->trace(); $this->foot(); } die(""); } return($this->res); } /** maps to mysql_affected_rows(), useful on insert,update,delete for successful execution checking */ function affected(){ return(0); } /** maps to mysql_num_rows(),useful for pagination, et al */ function rows($res){ return(0); } /** * returns a bi-dimentional array, with the rows in the form key=>value * * */ function dblog($sql,$result,$notes=''){ global $database_queries,$database_sql_queries,$database_query_count; $database_sql_queries[]=$sql; if(is_array($result[0])){ $titles=array_keys($result[0]); include_once(STD_LOCATION.'include/std_tab.php'); $t = new tab(); $t->name='sql'.rand(0,99999);//$database_query_count $t->add_tab('Null',$notes); $t->add_tab('Query',"<xmp>$sql</xmp>"); $t->add_tab('Trace',b2()); $t->add_tab('Results',common::table( $result, $titles, array( 'title'=>'Query Results', 'style'=>'db_result', 'border'=>1))); $database_queries.=$t->out(); } } /** returns an array of sql run for execution. * useful if you wish to save such SQl queries, or send them somewhere, etc * */ function queries_run(){ global $database_sql_queries; return($database_sql_queries); } function q2obj($sql,$notes='',$allow_fail=0){ if(DEBUG){ $mtime = microtime(); $mtime = explode(' ', $mtime); $mtime = $mtime[1] + $mtime[0]; $starttime = $mtime; } $r =$this->sql($sql,$notes,$allow_fail); if($this->query_failed==1 || $r =='FAILED' && $allow_fail==1){ return(array("FAIL"=>"QUERY FAILED")); } $result=array(); while($row=$this->fetch()){ $result[]=$row; } if(DEBUG){ $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = $mtime[1] + $mtime[0]; $endtime = $mtime; $totaltime = ($endtime - $starttime); $notes = $notes.' <br/>RUNS IN:' .$totaltime. ' seconds.'; $this->dblog($sql,$result,$notes); } return($result); } function q2js($all,$name,$idfield,$script_tag=1,$quote_values=0){ $dx6=''; $dx7=''; $q=""; $aa="[]"; if($quote_values==1){ $q="'"; $aa="{}"; } if($script_tag==1){ $dx6="<script>;"; $dx7=";</script>"; } $out="$dx6\n{$name}=$aa;"; foreach($all as $row){ $dx="\n{$name}[$q".$row[$idfield]."$q]="; $dx1=array(); foreach($row as $property_name=>$property_value){ $dx1[]="'$property_name':'".str_replace(array("\r","\n","'"),array("",'',''),$property_value)."'"; } $dx.='{'.implode(",",$dx1).'}'; $out.=$dx; } if($script_tag==1){ $out.=$dx7; } return($out); } /** returns all the SQL statements that were executed, VERY useful for debugging. */ function get_trace(){ global $database_queries,$database_query_count,$is_connected_to_db,$global_link; return("<div style='width:100%'></div>".$this->get_shadow("<h1>Mysql Trace information</h1>Note: this information s for debug purposes only, and will not be shown in the final product.<br/>Query Count:". 'db used:'.$this->dbdatabase.'<br/>Connected to Database:'.(int)$is_connected_to_db.'<br/>Link:'.$global_link.'<br/> Query Count: '. $database_query_count.'<br/>'.$database_queries,$this->default_style,'center','80%')); } /** prints all the SQL statements that were executed, VERY useful for debugging. */ function trace(){ echo($this->get_trace()/(1024*1024)." MB"); } } ?>
true
9a36a7d17a37b6dbae9352b763f864af8703e653
PHP
sbeng/luncher
/basic/models/Cart.php
UTF-8
762
2.65625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use yii\base\Model; use app\models\Item; /** * This is the model for shopping cart page * */ class Cart extends Model { public function rules() { return []; } public static function addItem($item) { \Yii::$app->cart->put($item, 1); return true; } public static function removeItem($item) { \Yii::$app->cart->remove($item); return true; } public static function getItemCount() { return \Yii::$app->cart->getCount(); } public static function getTotalPrice() { return \Yii::$app->cart->getCost(); } public static function getItems() { return \Yii::$app->cart->getPositions(); } }
true
93bb64d220f888a1a1d9d5784c02e5cb5220ac61
PHP
sonhai1088/Module2
/student-manager/student/update.php
UTF-8
2,053
2.859375
3
[]
no_license
<?php include_once '../DBconnect.php'; include_once '../Student.php'; include_once '../DBstudent.php'; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (!empty($_POST['name']) && !empty($_POST['email'])) { if (!empty($_GET['id'])) { $id = $_GET['id']; $name = $_POST['name']; $email = $_POST['email']; $studentDB = new DBstudent(); $studentDB->update($id, $name, $email); } } header('location: list.php', true); } else { if (!empty($_GET['id'])) { $id = $_GET['id']; $studentDB = new DBstudent(); $student = $studentDB->finById($id); if (is_string($student)) { echo $student . '<br>'; echo '<a href="list.php">Trở về</a>'; die(); } } } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Update info</title> </head> <body> <h2>Updata infomation</h2> <div class="table"> <form method="post" action=""> <table> <tr> <td>ID</td> <td> <?php if (isset($_GET['id'])) { $id = $_GET['id']; echo $id; } ?> </td> </tr> <tr> <td>Name</td> <td><input type="text" name="name" size="20" value="<?php echo $student->getName(); ?>"></td> </tr> <tr> <td>Email</td> <td><input type="text" name="email" size="20" value="<?php echo $student->getEmail(); ?>"></td> </tr> <tr> <td></td> <td> <button type="submit">Update</button> </td> </tr> </table> </form> </div> </body> </html>
true
87e67ce1e47c34f929dc1e07e6b1a4740200777a
PHP
motojouya/exam-wikipedia-tree-sugiyama
/app/Console/Commands/Search.php
UTF-8
1,865
3.171875
3
[ "MIT" ]
permissive
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Services\WikipediaAccess; use App\Services\Tree\Tree; class Search extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'command:search {keyword}'; /** * The console command description. * * @var string */ protected $description = 'Search Wikipedia'; /** * いくつのキーワードを取得するか * */ private $keywordLimit = 100; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Tree構造になっているキーワードを標準出力に出力する。 */ private function showKeywords($keywordTree, $level) { foreach ($keywordTree as $keyword => $belowTree) { foreach(range(0, $level) as $i) { echo " "; } if (!$belowTree) { echo "- $keyword\n"; } else if (is_string($belowTree)) { echo "- $keyword$belowTree\n"; } else { echo "- $keyword\n"; $this->showKeywords($belowTree, $level + 1); } } } /** * コマンドを実行する。 * 引数に与えられたキーワードから、再帰的にWikipediaにアクセスし、 * キーワードツリーを構築し、出力する。 * * @return mixed */ public function handle() { $argKeyword = $this->argument("keyword"); $keywordTree = Tree::build($argKeyword, $this->keywordLimit, function ($keyword) { sleep(1); return WikipediaAccess::getNextKeyword($keyword); }); if ($keywordTree[$argKeyword]) { $this->showKeywords($keywordTree, 0); } else { echo "入力されたキーワードはWikipediaに存在しないようです。\n"; } } }
true
8104984b291aebab9ba770c70284b501cfb0de10
PHP
SayenkoDesign/erickson
/wp-content/themes/sayenko-erickson/blocks/testimonials.php
UTF-8
4,564
2.703125
3
[]
no_license
<?php /* Block - Testimonials */ if( ! class_exists( 'Testimonials_Block' ) ) { class Testimonials_Block extends Element_Block { public function __construct( $data ) { parent::__construct( $data ); $fields['testimonials'] = get_field( 'testimonials' ); $this->set_fields( $fields ); /* $this->set_settings( 'padding', get_field( 'padding' ) ); $this->set_settings( 'margin', get_field( 'margin' ) ); */ // print the section $this->print_element(); } // Add default attributes to section protected function _add_render_attributes() { // use parent attributes parent::_add_render_attributes(); } // Add content public function render() { $testimonials = $this->get_testimonials(); if( empty( $testimonials ) ) { return false; } return sprintf( '<div class="grid-x grid-padding-x grid-padding-bottom"> <div class="cell">%s</div>', $testimonials ); } private function get_testimonials() { $posts = []; $post_ids = $this->get_fields( 'testimonials' ); if( empty( $post_ids ) ) { return false; } $args = array( 'post_type' => 'testimonial', 'order' => 'ASC', 'orderby' => 'post__in', 'post__in' => $post_ids, 'posts_per_page' => count( $post_ids ), 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false, 'fields' => 'ids' ); // Use $loop, a custom variable we made up, so it doesn't overwrite anything $loop = new WP_Query( $args ); // have_posts() is a wrapper function for $wp_query->have_posts(). Since we // don't want to use $wp_query, use our custom variable instead. if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); $posts[] = $this->get_testimonial(); endwhile; endif; wp_reset_postdata(); $buttons = '<div class="slick-arrows"> <button class="slick-prev slick-arrow" aria-label="Previous" type="button">Previous</button> <button class="slick-next slick-arrow" aria-label="Next" type="button">Previous</button> </div>'; if( ! empty( $posts ) ) { $quote_mark = sprintf( '<div class="quote-mark">%s</div>', get_svg( 'left-quote' ) ); return sprintf( '<div class="slider">%s<div class="slick">%s</div> %s </div>', $quote_mark, join( '', $posts ), $buttons ); } } private function get_testimonial() { $post_id = get_the_ID(); $quote = get_field( 'quote', $post_id ); if( empty( $quote ) ) { return false; } $name = _s_format_string( '- ' . get_field( 'name', $post_id ), 'h6' ); $quote = sprintf( '<div class="quote">%s%s</div>', $quote, $name ); $photo = get_the_post_thumbnail_url( $post_id, 'medium' ); if( ! empty( $photo ) ) { $photo = sprintf( '<div class="cell large-4"><div class="thumbnail" style="background-image: url(%s);"></div></div>', $photo ); } return sprintf( '<div class="slide"><div class="grid-x grid-padding-x grid-margin-bottom align-middle"> %s<div class="cell large-auto">%s</div></div></div>', $photo, $quote ); } } } new Testimonials_Block( $data );
true
c12b69ba964f52496b3985d81266aca40093a795
PHP
Yogranov/BetterLife-Web
/app/BetterLife/MailBox/Conversation.php
UTF-8
3,470
2.890625
3
[]
no_license
<?php namespace BetterLife\MailBox; use BetterLife\BetterLife; use BetterLife\Enum\Enum; use BetterLife\User\User; use BetterLife\MailBox\Message; use BetterLife\System\SystemConstant; use BetterLife\System\Encryption; class Conversation { const TABLE_NAME = "conversations"; const TABLE_KEY_COLUMN = "Id"; private $id; private $creator; private $recipient; private $subject; private $views = array(); private $createTime; private $messages = array(); public function __construct($id) { if(empty($id)) throw new \Exception("{0} is illegal Id!", null, $id); $data = BetterLife::GetDB()->where(self::TABLE_KEY_COLUMN, $id)->getOne(self::TABLE_NAME); if(empty($data)) throw new \Exception("Data empty, no message found!"); $this->id = $data["Id"]; $this->creator = User::getById($data["CreatorId"]); $this->recipient = User::getById($data["RecipientId"]); $this->subject = Encryption::Decrypt($data["Subject"]); $this->createTime = new \DateTime($data["CreateTime"]); if(!empty($data["Views"])) foreach (json_decode($data["Views"]) as $view) array_push($this->views, $view); $messagesDB = BetterLife::GetDB()->orderBy("CreateTime", "ASC")->where("ConversationId", $this->id)->get(Message::TABLE_NAME, null, "Id"); foreach ($messagesDB as $message) array_push($this->messages, new Message($message["Id"])); } public function newMessage(string $message, int $userId) { $dateTime = new \DateTime('now',new \DateTimeZone(SystemConstant::SYSTEM_TIMEZONE)); $data = [ "CreatorId" => $userId, "Content" => Encryption::Encrypt($message), "ConversationId" => $this->id, "CreateTime" => $dateTime->format("Y-m-d H:i:s") ]; $this->setView($userId, true); BetterLife::GetDB()->insert(Message::TABLE_NAME, $data); } public function clearViews() { BetterLife::GetDB()->where(self::TABLE_KEY_COLUMN, $this->id)->update(self::TABLE_NAME, ["Views" => json_decode(array())]); } public function setView($userId, $clear = false){ if($clear) $this->views = array(); if(in_array($userId, $this->views)) return; array_push($this->views, $userId); BetterLife::GetDB()->where(self::TABLE_KEY_COLUMN, $this->id)->update(self::TABLE_NAME, ["Views" => json_encode($this->views)]); } public function checkView(int $userId) { return in_array($userId, $this->views) ? true : false; } /** * @return mixed */ public function getId() { return $this->id; } /** * @return User */ public function getCreator(): User { return $this->creator; } /** * @return User */ public function getRecipient(): User { return $this->recipient; } /** * @return mixed */ public function getSubject() { return $this->subject; } /** * @return array */ public function getViews() { return $this->views; } /** * @return \DateTime */ public function getCreateTime(): \DateTime { return $this->createTime; } /** * @return Message[] */ public function getMessages(): array { return $this->messages; } }
true
12e6ff5766a8caf7460e61576cbbe5d320235a2d
PHP
0902matsumoto/Camp-Challenge
/challenge_2/2_9challenge.php
UTF-8
406
2.65625
3
[]
no_license
<!DOCTYPE HTML PUBLIC"-//WSC//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>PHP基礎</title> </head> <boby> <?php //9.以下の順で、連想配列を作成してください。 //    1に'AAA', 'hello'に'world', 'soeda'に33, 20に20 $x=array(1=>'AAA','hello'=>'world','soeda'=>'33',20=>20,); ?> </body> </html>
true
215637f6f5b6cb36669fda9ef6e71e281f2d21bc
PHP
Jeffersonss/TCC
/classes/usuario/Usuario.php
UTF-8
1,001
3.09375
3
[]
no_license
<?php class Usuario { public $idUsuario; public $nome; public $rg; public $cpf; public $perfil; function Usuario ($idUsuario=null, $nome=null, $rg=null,$cpf=null, $perfil=null) { $this->idUsuario = $idUsuario; $this->nome = $nome; $this->rg = $rg; $this->cpf = $cpf; $this->perfil = $perfil; } public function getIdUsuario() { return $this->idUsuario; } public function setIdUsuario($idUsuario) { $this->idUsuario = $idUsuario; } public function getNome() { return $this->nome; } public function setNome($nome) { $this->nome = $nome; } public function getRg() { return $this->rg; } public function setRg($rg) { $this->rg = $rg; } public function getCpf() { return $this->cpf; } public function setCpf($cpf) { $this->cpf = $cpf; } public function getPerfil() { return $this->perfil; } public function setPerfil($perfil) { $this->perfil = $perfil; } }
true
6afa7a59cc70965df8a22400d6fe053add2a7202
PHP
DMon777/barbellfans
/App/Models/Comments_Model.php
UTF-8
5,603
2.578125
3
[]
no_license
<?php namespace App\Models; class Comments_Model extends Abstract_Model { protected static $instance; public static function instance(){ if(self::$instance instanceof self) { return self::$instance; } return self::$instance = new self; } public function insert_comment($parent_id,$article_id,$text_comment,$user_login,$user_id,$email,$avatar){ return self::$db->pdo_insert('comments',['parent_id','article_id','text_comment','user_login','user_id','date','email','avatar'], [$parent_id,$article_id,$text_comment,$user_login,$user_id,time(),$email,$avatar]); } public function make_comments_tree($article_id,$start = 0){ $sql = "SELECT * FROM comments WHERE article_id=".$article_id." AND parent_id=".$start; $comments = self::$db->prepared_select($sql); $map = []; if(!empty($comments)){ foreach($comments as $comment) { $comment['children'] = $this->make_comments_tree($article_id,$comment['comment_id']); $map[] = $comment; } } return $map; } public function print_comments_map($map){ if(!empty($map)){ foreach($map as $val):?> <div class="comment"> <div class = "comment_avatar"> <img src="/images/avatars/<?=$val['avatar'];?>" class="user_avatar" alt = "avatar"> <?if($val['user_login'] != $_SESSION['auth']['user']):?> <span class="answer">ответить</span> <?endif;?> </div> <div class = "text_comment"> <span class = "user_login"> <?=$val['user_login'];?> </span> <span class="comment_date"> <?=date('d/m/Y',$val['date']);?></span> <p> <?=$val['text_comment'];?> </p> </div> <div class="answer_form"> <form method="post" action = ""> <textarea name = "text_comment" placeholder="Комментарий..."></textarea><br> <input type="hidden" name="parent_id" value="<?=$val['comment_id']?>"> <input type="hidden" name="user_login" value="<?=$val['user_login']?>"> <?if(!$_SESSION['auth']['user']):?> <input type="text" name = "email" placeholder = "e-mail"><br> <?endif;?> <input type="button" value = "опубликовать" name="send_comment" class="button"> </form> <p class="comment_error_message"></p> <img src = "/images/close_icon2.png" alt = "close" class="close_icon"> </div> <div class="clear"></div> <hr class="comment_separator"> <? $this->print_comments_map($val['children']); ?> </div> <?php endforeach; } else{ return false; } } public function print_admin_comments_map($map){ if(!empty($map)){ foreach($map as $val):?> <ul class="list-unstyled comments_list"> <li><?=$val['user_login'];?></li> <li><?=$val['text_comment'];?></li> <li class="text-right"> <button type="button" value="<?=$val['comment_id']?>" class="btn btn-default delete_comment" aria-label="Left Align"> <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> </button> </li> <hr> <li> <? $this->print_admin_comments_map($val['children']); ?></li> </ul> <?php endforeach; } else{ return false; } } public function delete_comment($comment_id){ self::$db->pdo_delete('comments',['comment_id'=>$comment_id]); $sql = "SELECT comment_id FROM comments WHERE parent_id=".(int)$comment_id; $comment_child = self::$db->prepared_select($sql)[0]; if($comment_child){ $this->delete_comment($comment_child['comment_id']); } } public function delete_comment_by_article_id($article_id){ self::$db->pdo_delete('comments',['article_id' => $article_id]); } public function change_avatar($new_avatar_name,$user_login){ self::$db->pdo_update('comments',['avatar'],[$new_avatar_name],['user_login' => $user_login]); } public function get_user_by_comment_id($comment_id){//метод скорее всего не понадобиться $sql = "SELECT user_login FROM comments WHERE comment_id=".$comment_id; $result = self::$db->prepared_select($sql)[0]; $user = User_Model::instance()->get_user($result['user_login']); return $user; } public function get_commentator_email($comment_id){ $sql = "SELECT email FROM comments WHERE comment_id=".$comment_id; return self::$db->prepared_select($sql)[0]['email']; } public function update_login($login,$user_id){ return self::$db->pdo_update('comments',['user_login',],[$login],['user_id' => $user_id]); } }
true
89ba99df9389cc66acf3ce5a09b97d2cb17e47c6
PHP
guidomachado/testeFPF
/models/SimularModel.php
UTF-8
756
2.6875
3
[]
no_license
<?php namespace app\models; use yii\base\Model; /** * This is the model class for table "projetos". * * @property int $Id Indice da tabela */ class SimularModel extends Model { /** * {@inheritdoc} */ public $Id; public $investimento; public $valor_de_retorno; /** * {@inheritdoc} */ public function rules() { return [ [['investimento'], 'required'], [['investimento','valor_de_retorno'], 'number'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'id', 'investimento' => 'Valor do Investimento', 'valor_de_retorno' => 'Valor de Retorno', ]; } }
true
af1c2fedab26db59c77afe59debd173774367525
PHP
jenskno/webprog-textsort
/textsort/test_input_from_console.php
UTF-8
389
2.59375
3
[]
no_license
<?php error_reporting(E_ALL); include_once 'processing_file.php'; if ($argv[1]){ $datei = trim($argv[1]);// ." ..."; } if (file_exists($datei)) { //echo $argv[1] . " gefunden"; $arr = mirror_content(file_get_contents($datei)); foreach ($arr as $key => $value) { echo "Wort: $key kommt $value mal vor\n"; } } else { echo $argv[1] . " nicht gefunden"; }
true
32d7f8b3794bbea28d0afcee0ac9d4232a8cba2f
PHP
yiisoft/yii2-redis
/tests/RedisSessionTest.php
UTF-8
2,676
2.640625
3
[]
permissive
<?php namespace yiiunit\extensions\redis; use yii\redis\Session; use yii\web\DbSession; /** * Class for testing redis session backend * @group redis * @group session */ class RedisSessionTest extends TestCase { public function testReadWrite() { $session = new Session(); $session->writeSession('test', 'session data'); $this->assertEquals('session data', $session->readSession('test')); $session->destroySession('test'); $this->assertEquals('', $session->readSession('test')); } /** * Test set name. Also check set name twice and after open * @runInSeparateProcess */ public function testSetName() { $session = new Session(); $session->setName('oldName'); $this->assertEquals('oldName', $session->getName()); $session->open(); $session->setName('newName'); $this->assertEquals('newName', $session->getName()); $session->destroy(); } /** * @depends testReadWrite * @runInSeparateProcess */ public function testStrictMode() { //non-strict-mode test $nonStrictSession = new Session([ 'useStrictMode' => false, ]); $nonStrictSession->close(); $nonStrictSession->destroySession('non-existing-non-strict'); $nonStrictSession->setId('non-existing-non-strict'); $nonStrictSession->open(); $this->assertEquals('non-existing-non-strict', $nonStrictSession->getId()); $nonStrictSession->close(); //strict-mode test $strictSession = new Session([ 'useStrictMode' => true, ]); $strictSession->close(); $strictSession->destroySession('non-existing-strict'); $strictSession->setId('non-existing-strict'); $strictSession->open(); $id = $strictSession->getId(); $this->assertNotEquals('non-existing-strict', $id); $strictSession->set('strict_mode_test', 'session data'); $strictSession->close(); //Ensure session was not stored under forced id $strictSession->setId('non-existing-strict'); $strictSession->open(); $this->assertNotEquals('session data', $strictSession->get('strict_mode_test')); $strictSession->close(); //Ensure session can be accessed with the new (and thus existing) id. $strictSession->setId($id); $strictSession->open(); $this->assertNotEmpty($id); $this->assertEquals($id, $strictSession->getId()); $this->assertEquals('session data', $strictSession->get('strict_mode_test')); $strictSession->close(); } }
true
5aee41ca7f13103acabf1235011fb1cb8473e916
PHP
OpenMageModuleFostering/ipg_pagseguro_transparente
/lib/Ipagare/PagSeguroDireto/Domain/Billing.php
UTF-8
638
2.875
3
[]
no_license
<?php /** * Shipping information */ class Ipagare_PagSeguroDireto_Domain_Billing { /** * Shipping address * @see Ipagare_PagSeguroDireto_Domain_Address */ private $address; /** * Sets the shipping address * @see Ipagare_PagSeguroDireto_Domain_Address * @param Ipagare_PagSeguroDireto_Domain_Address $address */ public function setAddress(Ipagare_PagSeguroDireto_Domain_Address $address) { $this->address = $address; } /** * @return Ipagare_PagSeguroDireto_Domain_Address the shipping Address * @see PagSeguroAddress */ public function getAddress() { return $this->address; } }
true
fd44940b59fec06268209c33d85bae36d4233ecb
PHP
Mdhesari/design-patterns
/app/NullObject/Person/Manager.php
UTF-8
401
3.21875
3
[]
no_license
<?php namespace App\NullObject\Person; class Manager extends Person { protected $employees = []; public function employ(Person ...$persons) { foreach ($persons as $person) { echo $person->getData(); $this->employees[] = $person; } } public function getData() { return "Manager [{$this->name} {$this->family}]"; } }
true
3f99daeb9614f65a54b229fbdb8184caa78b740b
PHP
loveorigami/shop_prototype
/tests/finders/SubcategorySeocodeFinderTests.php
UTF-8
2,947
2.5625
3
[]
no_license
<?php namespace app\tests\finders; use PHPUnit\Framework\TestCase; use app\finders\SubcategorySeocodeFinder; use app\tests\DbManager; use app\tests\sources\fixtures\SubcategoryFixture; use app\models\SubcategoryModel; /** * Тестирует класс SubcategorySeocodeFinder */ class SubcategorySeocodeFinderTests extends TestCase { private static $dbClass; public static function setUpBeforeClass() { self::$dbClass = new DbManager([ 'fixtures'=>[ 'subcategory'=>SubcategoryFixture::class ] ]); self::$dbClass->loadFixtures(); } /** * Тестирует свойства SubcategorySeocodeFinder */ public function testProperties() { $reflection = new \ReflectionClass(SubcategorySeocodeFinder::class); $this->assertTrue($reflection->hasProperty('seocode')); $this->assertTrue($reflection->hasProperty('storage')); } /** * Тестирует метод SubcategorySeocodeFinder::setSeocode * если передан параметр неверного типа * @expectedException TypeError */ public function testSetSeocodeError() { $seocode = null; $widget = new SubcategorySeocodeFinder(); $widget->setSeocode($seocode); } /** * Тестирует метод SubcategorySeocodeFinder::setSeocode */ public function testSetSeocode() { $seocode = 'seocode'; $widget = new SubcategorySeocodeFinder(); $widget->setSeocode($seocode); $reflection = new \ReflectionProperty($widget, 'seocode'); $reflection->setAccessible(true); $result = $reflection->getValue($widget); $this->assertInternalType('string', $result); } /** * Тестирует метод SubcategorySeocodeFinder::find * если пуст SubcategorySeocodeFinder::seocode * @expectedException ErrorException * @expectedExceptionMessage Отсутствуют необходимые данные: seocode */ public function testFindEmptySeocode() { $finder = new SubcategorySeocodeFinder(); $finder->find(); } /** * Тестирует метод SubcategorySeocodeFinder::find */ public function testFind() { $fixture = self::$dbClass->subcategory['subcategory_1']; $finder = new SubcategorySeocodeFinder(); $reflection = new \ReflectionProperty($finder, 'seocode'); $reflection->setAccessible(true); $reflection->setValue($finder, $fixture['seocode']); $result = $finder->find(); $this->assertInstanceOf(SubcategoryModel::class, $result); } public static function tearDownAfterClass() { self::$dbClass->unloadFixtures(); } }
true
3edaf13d4230332b9190dade9fd294ad16d53edf
PHP
cuongvv/koel
/tests/Integration/Models/SongTest.php
UTF-8
2,444
2.6875
3
[ "MIT" ]
permissive
<?php namespace Tests\Integration\Models; use App\Models\Song; use Aws\AwsClient; use Cache; use Mockery as m; use Tests\TestCase; class SongTest extends TestCase { protected function tearDown() { parent::tearDown(); m::close(); } /** @test */ public function it_returns_object_storage_public_url() { // Given there's a song hosted on Amazon S3 /** @var Song $song */ $song = factory(Song::class)->create(['path' => 's3://foo/bar']); $mockedURL = 'http://aws.com/foo/bar'; // When I get the song's object storage public URL $client = m::mock(AwsClient::class, [ 'getCommand' => null, 'createPresignedRequest' => m::mock(Request::class, [ 'getUri' => $mockedURL, ]), ]); Cache::shouldReceive('remember')->andReturn($mockedURL); $url = $song->getObjectStoragePublicUrl($client); // Then I should receive the correct S3 public URL $this->assertEquals($mockedURL, $url); } /** @test */ public function it_can_be_retrieved_using_its_path() { // Given a song with a path /** @var Song $song */ $song = factory(Song::class)->create(['path' => 'foo']); // When I retrieve it using the path $retrieved = Song::byPath('foo'); // Then the song is retrieved $this->assertEquals($song->id, $retrieved->id); } /** @test */ public function its_lyrics_has_all_new_line_characters_replace_by_br_tags() { // Given a song with lyrics contains new line characters /** @var Song $song */ $song = factory(Song::class)->create([ 'lyrics' => "foo\rbar\nbaz\r\nqux", ]); // When I retrieve its lyrics $lyrics = $song->lyrics; // Then I see the new line characters replaced by <br /> $this->assertEquals('foo<br />bar<br />baz<br />qux', $lyrics); } /** @test */ public function amazon_s3_parameters_can_be_retrieved_from_s3_hosted_songs() { // Given a song hosted on S3 /** @var Song $song */ $song = factory(Song::class)->create(['path' => 's3://foo/bar']); // When I check its S3 parameters $params = $song->s3_params; // Then I receive the correct parameters $this->assertEquals(['bucket' => 'foo', 'key' => 'bar'], $params); } }
true
e68e7353a0b67824b2454797b917444d5f1a2d61
PHP
carlosruesta/php-io
/aula05 - uso de contexto para acessar APIs ou ZIP com senha.php
UTF-8
1,026
2.734375
3
[]
no_license
<?php /** * Acessar uma API via stream definindo os metodos, headers e outros parametros da request * Sera utilizado os contexto de cada wrapper ou pelo protocolo */ $contexto = stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => [ "X-From: PHP", "Content-Type: text/plain", ], 'content' => 'Teste de corpo do request' ] ]); echo file_get_contents('http://httpbin.org/post', false, $contexto); /** * Testando contexto HTTP com metodo DELETE */ $contexto = stream_context_create([ 'http' => [ 'method' => 'DELETE', 'header' => [ "X-From: PHP", "Content-Type: text/plain", ] ] ]); echo file_get_contents('http://httpbin.org/delete', false, $contexto); /** * Para abrir um arquivo ZIP com senha */ $contexto = stream_context_create([ 'zip' => [ 'password' => '123456' ] ]); echo file_get_contents( 'zip://arquivos_com_senha.zip#lista-cursos.txt', false, $contexto );
true
a0441b2f6e1dc0e7e149a49ab3fce8be20237a9b
PHP
sviga/kattilera
/include/frontoffice_manager.class.php
UTF-8
26,267
2.625
3
[]
no_license
<?php /** * Основной класс, управляющий сайтом при просмотре его пользователями * * Решает следующие задачи: * <ul> * <li>Определение запрашиваемой страницы</li> * <li>Формирование страницы и вызов соответствующих модулей и их методов</li> * </ul> * * @name frontoffice_manager * @package Kernel * @copyright ArtProm (с) 2001-2012 * @version 3.0 */ class frontoffice_manager { /** * Конструктор объекта */ function __construct() { if (defined("GENERATE_STATISTIC") && GENERATE_STATISTIC) $this->session_tracking_set(); } /** * Устанавливает в сессии переменные, следящие за передвижениями пользователя по сайту * * Устанавливает следующие переменные в сессию: * <code> * $_SESSION['vars_kernel']['tracking']['enter_from'] Страница, с которой пришел посетитель * $_SESSION['vars_kernel']['tracking']['enter_from_domain'] Домен, с которого пришел посетитель * $_SESSION['vars_kernel']['tracking']['search_word'] Слово в поисковой системе, по которому пришел посетитель * $_SESSION['vars_kernel']['tracking']['enter_point'] Точка входа на сайт * $_SESSION['vars_kernel']['tracking']['enter_unixtime'] unixtime-время, в которое посетитель попал на сайт. * Служит для определения следующих параметров: * $_SESSION['vars_kernel']['tracking']['walking_path'][15] Страницы, которые посетил пользователь. * Последний индекс указывает через сколько времени от начала сессии он оказался на этой странице. * $_SESSION['vars_kernel']['tracking']['walking_time'] Время, которое пользователь провел на сайте в данный момент. * </code> * @access private * @return void */ function session_tracking_set() { // Устанавливаем точку входа и страницу, с которой пришли на сайт if (!isset($_SESSION['vars_kernel']['tracking'])) { require_once (dirname(dirname(__FILE__)) . "/admin/manager_stat.class.php"); $manager_stat = new manager_stat(); $user_array = $manager_stat->visitor_info_get(session_id()); $_SESSION['vars_kernel']['tracking']['enter_from'] = $user_array['referer']; $_SESSION['vars_kernel']['tracking']['enter_from_domain'] = $user_array['referer_domain']; $_SESSION['vars_kernel']['tracking']['search_word'] = $user_array['word']; $_SESSION['vars_kernel']['tracking']['enter_point'] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $_SESSION['vars_kernel']['tracking']['enter_unixtime'] = time(); } else { $_SESSION['vars_kernel']['tracking']['walking_path'][(time() - $_SESSION['vars_kernel']['tracking']['enter_unixtime'])] = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $_SESSION['vars_kernel']['tracking']['walking_time'] = time() - $_SESSION['vars_kernel']['tracking']['enter_unixtime']; } } public static function throw_404_error() { global $kernel; if (isset($_SERVER["HTTP_REFERER"]) && !empty($_SERVER["HTTP_REFERER"])) { //есть ли реферер? $mstat = new manager_stat(); $idSearch = $mstat->get_IDSearch_by_referer($_SERVER["HTTP_REFERER"]); if ($idSearch > 0) { $word = $mstat->get_word_by_referer($idSearch, $_SERVER["HTTP_REFERER"]); if ($word) { $webroot = dirname(dirname(__FILE__))."/"; if (file_exists($webroot.'modules/search/include/searcher.class.php')) { //модуль поиска существует, подключаем необходимые классы require_once $webroot.'modules/search/include/searcher.class.php'; require_once $webroot.'modules/search/include/searchdb.class.php'; require_once $webroot.'modules/search/include/htmlparser.class.php'; require_once $webroot.'modules/search/include/lingua_stem_ru.class.php'; require_once $webroot.'modules/search/include/indexator.class.php'; $searcher = new Searcher($kernel->pub_prefix_get() . "_search1"); $searcher->set_results_per_page(1); $searcher->set_doc_format('html'); $searcher->set_operation('and'); $results = $searcher->search($word); if (count($results) > 0) //что-то найдено $kernel->priv_redirect_301($results[0]['url']); } } } } if (defined("PAGE_FOR_404") && PAGE_FOR_404) $redirPage = PAGE_FOR_404; else $redirPage = "index"; $kernel->priv_redirect_301("/" . $redirPage); } /** * Точка входа * * Вызывается при получении непосредственно запроса от браузера. Запрашивает страницу, * подготавливает её к выводу и непосредственно выводит. * @return void */ function start() { global $kernel; //определим страницу, кторую запрашивают $uri = $_SERVER['REQUEST_URI']; $section_id = null; //Проверим корректность задания страницы if (isset($_GET['sitepage']) && $kernel->is_valid_sitepage_id($_GET['sitepage'])) //если задан параметр, какую страницу выдать, то выставим её в первую очередь $section_id = $_GET['sitepage']; elseif (preg_match("~^/([^\?]+)~i", $uri, $matches)) $section_id = $matches[1]; elseif (preg_match("'^/(\\?.*)?$'", $uri)) $section_id = "index"; else self::throw_404_error(); $section_id = strtolower($section_id); //Сразу проставим этустраницу в текущую, так как это влияет на карту сайта $kernel->priv_page_current_set($section_id, true); //Проверка на то, что эту страницу могут смотреть только авторизированные пользователи $only_auth = $kernel->pub_page_property_get($section_id, 'only_auth', false); if ($only_auth['isset'] && $only_auth['value'] && !$kernel->pub_user_is_registred()) //"Для просмотра необходима регестрация и (или) авторизация" self::throw_404_error(); //Проверим, может нужно перейти на какую-то другую страницу //При этом необходимо вытащить все параметры после вопроса и передать их дальше $id_other = $kernel->pub_page_property_get($section_id, 'link_other_page', false); if ($id_other['isset'] && !empty($id_other['value'])) { $query = ''; $pars_uri = parse_url($uri); if ((isset($pars_uri['query'])) && (!empty($pars_uri['query'])) && ($pars_uri['query'] !== "/")) $query = "?" . $pars_uri['query']; $str_url = "/" . trim($id_other['value']) . $query; $kernel->pub_redirect_refresh_global($str_url); } //Теперь, зная запрашиваемую страницу, надйдем её в базе //Проверяем, существует ли эта страница if (!$kernel->priv_page_exist($section_id)) self::throw_404_error(); //прежде всего шаблон, который она использует. $file_template = $kernel->pub_page_property_get($section_id, 'template'); if (!$file_template['isset']) { if (defined("SHOW_INT_ERRORE_MESSAGE") && SHOW_INT_ERRORE_MESSAGE) $kernel->priv_error_show('[#errore_message_isset_template#]'); die; } if (!file_exists($file_template['value'])) { if (defined("SHOW_INT_ERRORE_MESSAGE") && SHOW_INT_ERRORE_MESSAGE) $kernel->priv_error_show('[#errore_message_isset_file_template#]'); die; } //Сделаем запись в статиски сейчас вот таким способом if (defined('GENERATE_STATISTIC') && GENERATE_STATISTIC) { $stat = new manager_stat(); $stat->set_stat(); } $kernel->priv_session_vars_set(); //Получим заготовку для имени страницы в кэше $file_name_cache = $section_id; if (isset($_SERVER['REDIRECT_QUERY_STRING'])) $file_name_cache = $section_id . $_SERVER['REDIRECT_QUERY_STRING']; //Если производить кэширование, то проверим наличие этой страницы в кэше //и при её нахождение выведем её. if (defined("CACHED_PAGE") && CACHED_PAGE) { $file_name_cache = md5($file_name_cache); $file_name_cache = "cache/" . $file_name_cache . ".html"; if (file_exists($file_name_cache)) { $html = file_get_contents($file_name_cache); $kernel->priv_output($html, false, true); die; } } //Проверим, возможно есть вызов функции прямого модуля или метода //и тогда нам нужно его просто $this->priv_test_direct_run_metod(); //Теперь надо вызвать пару (пока одну) функцтию ядра и посмотреть, //может после вызова какого-то метода, произошли изменения и их надо учесть/ $new_name = $kernel->priv_page_template_get_da(); if (!($new_name === false)) $file_template['value'] = $new_name; //Производит непосредственное формирование страницы $html = file_get_contents($file_template['value']); //конвертируем шаблон из 1251, если такой тип указан в конфиге if (defined("IS_1251_TEMPLATES") && IS_1251_TEMPLATES) { $html = @iconv('cp1251', 'UTF-8//TRANSLIT', $html); //+заменяем кодировку в хидере $html = str_ireplace("windows-1251", "UTF-8", $html); } $kernel->priv_frontcontent_set($this->generate_html_template($html)); //Теперь нужно вытащить все метки с шаблона и узнать что соответсвует каждой метки $array_link = $kernel->priv_page_textlabels_get($kernel->priv_frontcontent_get()); $array_link = $array_link[1]; $array_link = array_flip($array_link); $array_link = $kernel->priv_page_real_link_get($array_link, $section_id, true); // Создаем массив с приоритетами выполнения модулей $priority_array = array(); // Ядру - самый низкий приоритет $priority_array['kernel'] = 1; // Устанавливаем приоритеты для модулей $modules = $kernel->db_get_list_simple("_modules", "parent_id IS NOT NULL", "id,parent_id"); foreach ($modules as $data) { // В будущем приоритеты можно будет брать из таблиц. Пока так. switch ($data['parent_id']) { case 'catalog': $priority_array[$data['id']] = 100; break; case 'waysite': $priority_array[$data['id']] = 50; break; case 'menu': $priority_array[$data['id']] = 55; break; case 'glossary': $priority_array[$data['id']] = 98; break; case 'newsi': //модуль должен отработать после kernel, т.к. меняет title $priority_array[$data['id']] = 110; break; case 'faq': //модуль должен отработать после kernel, т.к. меняет title $priority_array[$data['id']] = 120; break; default: $priority_array[$data['id']] = 99; } } // Приписываем приоритеты от модулей к действиям foreach ($array_link AS $key => $val) { if (!is_array($val)) continue; if ($val['id_mod']) { $prioritrt_metod = 0; //Здесь пока небольшое исключение для SAPE и Linkfeed //В дальнейшем это будет сделано уже для всех модулей if (preg_match("/^(sape|linkfeed)[0-9]+$/", $val['id_mod'])) { $tmp = unserialize($val['run']['param']); if (isset($tmp['num_for_sort'])) $prioritrt_metod = intval($tmp['num_for_sort']); } $array_link[$key]['priority'] = $priority_array[$array_link[$key]['id_mod']] + $prioritrt_metod; } else $array_link[$key]['priority'] = intval(100); } //И сортируем массив в соответствии с приоритетом uasort($array_link, array("frontoffice_manager", "compare_priority")); //Обходим массив меток, и создаем выходной итоговую страницу foreach ($array_link as $key => $val) { if (isset($val['isadditional'])) continue; $this->replace_labels_by_generated_content($key, $val); } //Второй проход (только оставшиеся метки), после отработки модулей, //чтобы заменить метки и в контенте, созданном модулями $gcontent = $this->generate_html_template($kernel->priv_frontcontent_get()); $kernel->priv_frontcontent_set($gcontent); $array_link = $kernel->priv_page_textlabels_get($kernel->priv_frontcontent_get()); $array_link = $array_link[1]; $array_link = array_flip($array_link); $array_link = $kernel->priv_page_real_link_get($array_link, $section_id, true); foreach ($array_link as $key => $val) { if (strpos($kernel->priv_frontcontent_get(), '[#' . $key . '#]') === false) continue; $this->replace_labels_by_generated_content($key, $val); } $html = $kernel->priv_frontcontent_get(); //Запишем в кэш страницу, если ведётся работа с кэшем. if (defined("CACHED_PAGE") && CACHED_PAGE) { $file = fopen($file_name_cache, "w+"); fwrite($file, $html); fclose($file); } $kernel->priv_output($html, false, true); } private function replace_labels_by_generated_content($label, $val) { global $kernel; $html_replace = ''; if (isset($val['id_mod']) && $val['id_mod']) { if ($val['id_mod'] == 'kernel') $html_replace = $this->run_metod_kernel($label, $val); else $html_replace = $this->run_metod_modul($val); $html_replace = $this->do_postprocessing($val, $html_replace); } $html = str_replace('[#' . $label . '#]', $html_replace, $kernel->priv_frontcontent_get()); //Теперь необходимо обновить этот контент в переменной ядра //что бы кто-то (модуль) мог иметь доступ к этому контенту и влиять на него. $kernel->priv_frontcontent_set($html); } private function do_postprocessing($labelData, $html) { global $kernel; $system_postprocessors = $kernel->get_postprocessors(); foreach ($labelData['postprocessors'] as $pp) { if (!array_key_exists($pp, $system_postprocessors)) //указанного постпроцессора нет в списке, возвращённом системой continue; include_once $kernel->get_postprocessors_dir() . "/" . $pp . ".php"; /** @var $ppobj postprocessor */ $ppobj = new $pp; $html = $ppobj->do_postprocessing($html); } return $html; } /** * Сравнивает приоритет двух модулей (действий) * * Возвращает "0" если приоритеты одинаковые, "-1" если приоритет $a больше $b, "1" если наоборот * @param array $a * @param array $b * @return int */ public function compare_priority($a, $b) { if ($a['priority'] == $b['priority']) return 0; return ($a['priority'] > $b['priority']) ? -1 : 1; } /** * Создает HTML шаблон, добавляя в него содержимое действий "редактора контента" * * Функция рекрсивная, а значит находит содержимое действий "редактора контента" не только * первого уровня, а всех, которые есть, как гы глубоко они не были "зарыты" * @param string $html_template * @param array $metki_exist Массив с метками, которые не нужно обрабатывать, так как они уже есть * @return string */ private function generate_html_template($html_template, $metki_exist = array()) { global $kernel; $curent_link = $kernel->priv_page_textlabels_get($html_template); $curent_link[0] = array_unique($curent_link[0]); $curent_link[1] = array_unique($curent_link[1]); //Узнаем значения ссылок с учетом наследования $link_in_page_real = $curent_link[1]; $link_in_page_real = array_flip($link_in_page_real); $link_in_page_real = $kernel->priv_page_real_link_get($link_in_page_real, $kernel->pub_page_current_get()); foreach ($link_in_page_real AS $metka => $massiv) { if (isset($metki_exist[$metka])) continue; if (($link_in_page_real[$metka]['id_mod'] == "kernel") && ($link_in_page_real[$metka]['run']['name'] == "priv_html_editor_start") && (is_file($kernel->priv_path_pages_content_get() . '/' . $link_in_page_real[$metka]['page'] . '_' . $kernel->pub_translit_string($metka) . '.html'))) { $metka_content = file_get_contents($kernel->priv_path_pages_content_get() . '/' . $link_in_page_real[$metka]['page'] . '_' . $kernel->pub_translit_string($metka) . '.html'); $metka_content = $this->generate_html_template($metka_content, $link_in_page_real); $metka_content = $this->do_postprocessing($massiv, $metka_content); $html_template = str_replace("[#" . $metka . "#]", $metka_content, $html_template); } } return $html_template; } /** * Осуществляет вызов метода кокртеного модуля * * Анализируя переданный в параметре массив определяет какой модуль * необходимо подключать и какой объект соответсвенно создавать. * После создания объект происходит вызов указанного метода. * Пример массива передаваемого в качестве параметра методу * <code> * [id_mod] => menu1 //Уникальное ID модуля, формирующего действие [id_action] => 3 //Уникальное ID дейсвтия [run] => Array ( [name] => pub_show_menu_static //Имя метода модуля, отвечающего за действие [param] => a:2:{s:13:"id_page_start";s:5:"index";s:16:"count_level_show";s:1:"1";} // Строчное представление массива с параметра метода ) * </code> * @param array $in Массив данных для вызова метода * @param boolean $direct_run * @return string */ private function run_metod_modul($in, $direct_run = false) { global $kernel; //Прежде всего узнаем родительский модуль $modul = new manager_modules(); $id_modul = $modul->return_info_modules($in['id_mod']); if ($id_modul === false) return false; $start_modul = trim($id_modul['parent_id']); if (empty($start_modul)) return false; //Теперь подключим класс этого модуля и установим переменную ядра с именем конкретного //модуля, производящего сейчас вызов $kernel->priv_module_for_action_set($in['id_mod']); if (isset($in['id_action'])) $kernel->set_current_actionid($in['id_action']); $modul = $kernel->priv_module_including_get($start_modul); if ($modul === false) { $str_file = "modules/" . $start_modul . "/" . $start_modul . ".class.php"; include_once($str_file); //Теперь можно создать объект //$run = $in['run']; $modul = new $start_modul(); $kernel->priv_module_including_set($start_modul, $modul); } //Узнаем имя модуля и его параметры и осуществим вызов этого метода $name_metod = $in['run']['name']; //Для прямого вызова надо проверить, а можем ли мы это вызывать $stop = false; if ($direct_run) { $open_action = $kernel->priv_da_metod_get(); if (!isset($open_action[$name_metod])) return false; $stop = ($open_action[$name_metod]); settype($stop, 'bool'); } $param = unserialize(stripslashes($in['run']['param'])); $html = call_user_func_array(array(&$modul, $name_metod), $param); $kernel->priv_module_for_action_set(''); $kernel->set_current_actionid(null); //Для прямого вызова вернём массив с флагом останвливаться или нет if (!$direct_run) return $html; else return array('stop' => $stop, 'content' => $html); } /** * Вызов основных функций ядра по фомрирвоанию контента для метки * * @param string $name_link Имя метода ядра, отвечающего за фомирование контенета * @param array $in * @return string */ private function run_metod_kernel($name_link, $in) { global $kernel; $name_metod = $in['run']['name']; $param = array($name_link); $html = call_user_func_array(array(&$kernel, $name_metod), $param); return $html; } private function priv_test_direct_run_metod() { global $kernel; //Определим, есть ли вообще прямой вызов $id_modul = $kernel->pub_httpget_get('da_modul'); $id_metod = $kernel->pub_httpget_get('da_metod'); if ((empty($id_modul)) || (empty($id_metod))) { $id_modul = $kernel->pub_httppost_get('da_modul'); $id_metod = $kernel->pub_httppost_get('da_metod'); } if ((empty($id_modul)) || (empty($id_metod))) return false; $in = array(); $in['id_mod'] = $id_modul; $in['run']['name'] = $id_metod; $in['run']['param'] = serialize(array()); $res = $this->run_metod_modul($in, true); if ($res['stop']) { $kernel->priv_output($res['content']); die; } return true; } }
true
5a8c6606d288ccef5b0049ae9cded19d9e7a767f
PHP
guymorin/football-predictions
/include/criterion.php
UTF-8
10,478
2.5625
3
[]
no_license
<?php function criterion($type,$data,$pdo){ $v=0; switch($type){ case "motivC1": if($data->motivation1!="") $v=intval($data->motivation1); else $v=1; // default is for home team break; case "motivC2": if($data->motivation2!="") $v=intval($data->motivation2); break; case "physicalC1": if($data->physicalForm1!="") $v=intval($data->physicalForm1); elseif(($_SESSION['matchdayNum']-1)>0){ $num = ($_SESSION['matchdayNum']-1); $req=" SELECT m.team_1 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_1 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_1 = :team_1 AND m.red1 > '0' AND s.id_championship = :id_championship AND s.id_season = :id_season UNION SELECT m.team_2 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_2 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_2 = :team_1 AND m.red2 > '0' AND s.id_championship = :id_championship AND s.id_season = :id_season;"; $r = $pdo->prepare($req,[ 'number' => $num, 'team_1' => $data->eq1, 'id_championship' => $_SESSION['championshipId'], 'id_season' => $_SESSION['seasonId'] ]); if($r == null) $v=0; else { $res = array(); foreach($r as $valTeam){ $res[] = $valTeam; } if(in_array($data->eq1,$res)) $v='-1'; } } break; case "physicalC2": if($data->physicalForm2!="") $v=intval($data->physicalForm2); elseif(($_SESSION['matchdayNum']-1)>0){ $num = ($_SESSION['matchdayNum']-1); // Did the team have a red card in the last matchday ? $req=" SELECT m.team_1 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_1 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_1 = :team_2 AND m.red1>'0' AND s.id_championship = :id_championship AND s.id_season = :id_season UNION SELECT m.team_2 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_2 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_2 = :team_2 AND m.red2 > '0' AND s.id_championship = :id_championship AND s.id_season = :id_season;"; $r = $pdo->prepare($req,[ 'number' => $num, 'team_2' => $data->eq2, 'id_championship' => $_SESSION['championshipId'], 'id_season' => $_SESSION['seasonId'] ]); if($r == null) $v=0; else { $res = array(); foreach($r as $valTeam){ $res[] = $valTeam; } if(in_array($data->eq2,$res)) $v='-1'; } } break; case "serieC1": if($data->currentForm1!="") $v=intval($data->currentForm1); elseif(($_SESSION['matchdayNum']-1)>0){ $num = ($_SESSION['matchdayNum']-1); $req=" SELECT m.team_1 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_1 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_1 = :team_1 AND m.result = '1' AND j.id_championship = :id_championship AND j.id_season = :id_season UNION SELECT m.team_2 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_2 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_2 = :team_1 AND m.result = '2' AND j.id_championship = :id_championship AND j.id_season = :id_season;"; $r = $pdo->prepare($req,[ 'number' => $num, 'team_1' => $data->eq1, 'id_championship' => $_SESSION['championshipId'], 'id_season' => $_SESSION['seasonId'] ]); if($r == null) $v=0; else { $res = array(); foreach($r as $valTeam){ $res[] = $valTeam; } if(in_array($data->eq1,$res)) $v=1; } } break; case "serieC2": if($data->currentForm2!="") $v=intval($data->currentForm2); elseif(($_SESSION['matchdayNum']-1)>0){ $num = ($_SESSION['matchdayNum']-1); // Did the team win in the last matchday ? $req=" SELECT m.team_1 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_1 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_1 = :team_2 AND m.result='1' AND j.id_championship = :id_championship AND j.id_season = :id_season UNION SELECT m.team_2 as team FROM matchgame m LEFT JOIN season_championship_team s ON s.id_team=m.team_2 LEFT JOIN matchday j ON j.id_matchday=m.id_matchday WHERE j.number = :number AND m.team_2 = :team_2 AND m.result = '2' AND j.id_championship = :id_championship AND j.id_season = :id_season;"; $r = $pdo->prepare($req,[ 'number' => $num, 'team_2' => $data->eq2, 'id_championship' => $_SESSION['championshipId'], 'id_season' => $_SESSION['seasonId'] ]); if($r == null) $v=0; else { $res = array(); foreach($r as $valTeam){ $res[] = $valTeam; } if(in_array($data->eq2,$res)) $v=1; } } break; case "trendTeam1": case "trendTeam2": if(isset($_SESSION['matchdayNum'])) $matchdayNum = $_SESSION['matchdayNum']; else $matchdayNum = $data->number; if($type=="trendTeam1") $v=trend($data->eq1,$pdo,$matchdayNum); else $v=trend($data->eq2,$pdo,$matchdayNum); break; case "v1": $v=value($data->eq1,$pdo); break; case "v2": $v=value($data->eq2,$pdo); break; case "predictionsHistoryHome": if(isset($data->Home)) $v=intval($data->Home); break; case "predictionsHistoryDraw": if(isset($data->Draw)) $v=intval($data->Draw); break; case "predictionsHistoryAway": if(isset($data->Away)) $v=intval($data->Away); break; } return $v; } function trend($team,$pdo,$matchdayNumber){ // Return the team championship results on the last three matches $val=0; $req="SELECT SUM(t.cnt) as trend FROM ( (SELECT CASE WHEN mg.result = '1' THEN '3' WHEN mg.result = 'D' THEN '1' ELSE '0' END as cnt FROM matchgame mg LEFT JOIN matchday md ON md.id_matchday=mg.id_matchday WHERE mg.team_1=:id_team AND md.number IN (:num1,:num2,:num3) AND md.id_season=:id_season AND md.id_championship=:id_championship) UNION ALL (SELECT CASE WHEN mg.result='2' THEN '3' WHEN mg.result='D' THEN '1' ELSE '0' END as cnt FROM matchgame mg LEFT JOIN matchday md ON md.id_matchday=mg.id_matchday WHERE mg.team_2=:id_team AND md.number IN (:num1,:num2,:num3) AND md.id_season=:id_season AND md.id_championship=:id_championship) ) t;"; $r = $pdo->prepare($req,[ 'id_team' => $team, 'id_season' => $_SESSION['seasonId'], 'id_championship' => $_SESSION['championshipId'], 'num1' => ($matchdayNumber - 3), 'num2' => ($matchdayNumber - 2), 'num3' => ($matchdayNumber - 1) ]); $val = $r->trend; return $val; } function value($team,$pdo){ // Select the market value of the team 1 $val = 0; $req="SELECT marketValue FROM marketValue WHERE id_team=:id_team AND id_season=:id_season;"; $r = $pdo->prepare($req,[ 'id_team' => $team, 'id_season' => $_SESSION['seasonId'] ]); $val = $r->marketValue; return $val; } ?>
true
acacbaa8cc49a9246d0bbbc12344dddd88c20064
PHP
linhongyou/uu
/protected/model/user.class.php
UTF-8
387
2.9375
3
[]
no_license
<?php class User extends Model{ private $id; private $username; private $password; function __construct(){ parent::__construct(); } private function __get($property_name) { if (isset ( $this->$property_name )) { return ($this->$property_name); } else { return (NULL); } } private function __set($property_name, $value) { $this->$property_name = $value; } } ?>
true
53845f4e04fb9a27ba7b3f7ca62a56c1c8f34067
PHP
tangping624/ql-laravel
/app/Repositories/Image.php
UTF-8
2,270
2.765625
3
[]
no_license
<?php namespace App\Repositories; use App\Models\Image as Model; use Illuminate\Http\UploadedFile; use Illuminate\Support\Str; use Auth; use Storage; class Image { /** * 上传图片 * * @param Illuminate\Http\UploadedFile $file 上传文件 * @return App\Models\Image */ public static function upload(UploadedFile $file) { $user = Auth::user(); // 生成文件名 do { $hashName = Str::random(40) . '.' . $file->guessExtension(); $path = 'up/' . substr($hashName, 0, 2) . '/' . substr($hashName, 2, 2) . '/' . substr($hashName, 4, 2); $filename = substr($hashName, 6); $fullName = $path . '/' . $filename; $realPath = storage_path('app/public/' . $fullName); } while (file_exists($realPath)); // 如果文件存在,重新生成文件名 $file->storeAs('public/' . $path, $filename); $imageSize = getimagesize($realPath); return Model::create([ 'user_id' => $user ? $user->id : 0, 'user_class' => get_class($user), 'md5' => md5_file($realPath), 'mime' => $file->getMimeType(), 'uri' => 'storage/' . $fullName, 'width' => $imageSize[0], 'height' => $imageSize[1], 'size' => $file->getClientSize(), 'created_at' => time(), ]); } /** * 根据 id 获取图片 * * @param array $ids * @return Illuminate\Database\Eloquent\Collection */ public static function getByIds($ids) { if (!is_array($ids)) { $ids = [$ids]; } return Model::whereIn('id', $ids)->get(); } /** * 删除多个图片 * * @param Illuminate\Database\Eloquent\Collection $images */ public static function destory($images) { // 删除图片文件 Storage::delete( $images ->pluck('uri') ->map(function ($item) { return str_replace('storage/', 'public/', $item); }) ->toArray() ); return Model::whereIn('id', $images->pluck('id'))->delete(); } }
true
488753d99d62ed7ab4060d7d6bc76412a634af55
PHP
josephldaigle/pl-project
/tests/Unit/Core/Data/Query/FindByGuidHandlerTest.php
UTF-8
1,615
2.5625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: joe * Date: 10/22/18 * Time: 4:01 PM */ namespace Test\Unit\Core\Data\Query; use PapaLocal\Core\Data\Query\FindByGuid; use PapaLocal\Core\Data\Query\FindByGuidHandler; use PapaLocal\Core\Data\RecordInterface; use PapaLocal\Core\Data\TableGatewayInterface; use PHPUnit\Framework\TestCase; /** * Class FindByGuidHandlerTest * * @package Test\Unit\Core\Data\Query */ class FindByGuidHandlerTest extends TestCase { public function testHandlerIsSuccess() { // set up fixtures $tableName = 'TestTableName'; $guid = '24c2aadf-8dc2-4a08-a020-3e99f979fdaa'; $queryMock = $this->createMock(FindByGuid::class); $queryMock->expects($this->once()) ->method('getTableName') ->willReturn($tableName); $queryMock->expects($this->once()) ->method('getGuid') ->willReturn($guid); $recordMock = $this->createMock(RecordInterface::class); $tableGatewayMock = $this->createMock(TableGatewayInterface::class); $tableGatewayMock->expects($this->once()) ->method('setTable') ->with($this->equalTo($tableName)); $tableGatewayMock->expects($this->once()) ->method('findByGuid') ->with($this->equalTo($guid)) ->willReturn($recordMock); $handler = new FindByGuidHandler($tableGatewayMock); // exercise SUT $result = $handler->__invoke($queryMock); // make assertions $this->assertEquals($recordMock, $result, 'unexpected result'); } }
true
c633e4d1ee699fd4ba5eb94b04f187427bcd3eb8
PHP
Yennhi2k/CONG_NGHE_WEB
/edit-education.php
UTF-8
3,364
2.671875
3
[]
no_license
<?php // kiểm tra id có tồn tại trên url hay k? if(!isset($_GET['id'])) { header("Location:education.php"); } //b1: kết nối với database require("config-csdl.php"); // lấy dữ liệu với id đã có trên csdl $id = $_GET['id']; $sql="select * from education where id_education=$id"; // echo $sql; $result=mysqli_query($conn,$sql); $bn= mysqli_fetch_array($result); // ktra xem ng dùng đã gửi dl lên chưa if( isset($_GET['year_school']) && isset($_GET['schools']) ){ $year_school = $_GET['year_school']; $schools = $_GET['schools']; //b2: truy vấn $sql= "update education set year_school='$year_school',schools='$schools' where id_education=$id"; // echo $sql; $result=mysqli_query($conn,$sql); if($result) { header("Location:education.php"); } } ?> <style> H2{ text-align: center; color: #007bff; margin-top:20px; margin-bottom:10px; }</style> <!doctype html> <html lang="en"> <head> <title>EDIT EDUCATION</title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"> </head> <body> <?php require('admin-header.php'); ?> <div class="container"> <h2>EDIT EDUCATION</h2> <form action=""> <!-- thêm id vao url --> <input type="hidden" name="id" value="<?php echo $bn['id'] ?>"> <div class="form-group"> <label for="id">id</label> <input type="text" name="id" id="id" class="form-control" placeholder=" " aria-describedby="helpId" disabled="disabled" value=" <?php echo $bn['id'] ?>"> </div> <div class="form-group"> <label for="year_school">year_school</label> <input type="text" name="year_school" id="year_school" class="form-control" placeholder="" aria-describedby="helpId" value=" <?php echo $bn['year_school'] ?>"> </div> <div class="form-group"> <label for="schools">schools</label> <input type="text" name="schools" id="schools" class="form-control" placeholder="" aria-describedby="helpId" value=" <?php echo $bn['schools'] ?>"> </div> <button class="btn btn-success" type="submit">Edit education</button> </form> <p><a href="education.php" class = "btn btn-success">Back</a></p> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
true
79f0abe39fba4ddd8a4a5ca4b4d425a3dcebfc30
PHP
jaromic/pansim
/src/Statistics.php
UTF-8
302
3.171875
3
[ "MIT" ]
permissive
<?php namespace Jarosoft; class Statistics { public static function randomIntNormalDistribution(float $mean, float $sd): float { $x = mt_rand() / mt_getrandmax(); $y = mt_rand() / mt_getrandmax(); return sqrt(-2 * log($x)) * cos(2 * pi() * $y) * $sd + $mean; } }
true
58e3aaa4bfb175560cb0543ef41473aa6799691e
PHP
bairwell/emojicalc
/src/Bairwell/Emojicalc/Container.php
UTF-8
2,683
3.34375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Bairwell\Emojicalc; /** * Simple PSR-11 inspired container. * @package Bairwell\Emojicalc */ class Container implements ContainerInterface { /** * The actual store. * @var array */ protected $store = []; /** * Container constructor. */ public function __construct() { $this->store = []; } /** * Get an item from the container store. * @param string $id * @return mixed * @throws \Exception */ public function get(string $id) { if (false === $this->has($id)) { throw new \RuntimeException('No entry was found for "' . $id . '" identifier.'); } return $this->store[$id]; } /** * Has this container got an item? * @param string $id Id of the item. * @return bool */ public function has(string $id) : bool { return array_key_exists($id, $this->store); } /** * Whether a offset exists * @link http://php.net/manual/en/arrayaccess.offsetexists.php * @param mixed $offset <p> * An offset to check for. * </p> * @return boolean true on success or false on failure. * </p> * <p> * The return value will be casted to boolean if non-boolean was returned. * @since 5.0.0 * @throws \RuntimeException If used. */ public function offsetExists($offset) : bool { throw new \RuntimeException('offsetExists on containers cannot be used directly. Use "has".'); } /** * Offset to retrieve * @link http://php.net/manual/en/arrayaccess.offsetget.php * @param mixed $offset The offset to retrieve. * @return mixed Can return all value types. * @since 5.0.0 * @throws \RuntimeException If used. */ public function offsetGet($offset) { throw new \RuntimeException('offsetGet on containers cannot be used directly. Use "get".'); } /** * Offset to set * @link http://php.net/manual/en/arrayaccess.offsetset.php * @param mixed $offset <p> * The offset to assign the value to. * </p> * @param mixed $value <p> * The value to set. * </p> * @return void * @since 5.0.0 */ public function offsetSet($offset, $value) { $this->store[$offset] = $value; } /** * Offset to unset * @link http://php.net/manual/en/arrayaccess.offsetunset.php * @param mixed $offset <p> * The offset to unset. * </p> * @return void * @since 5.0.0 */ public function offsetUnset($offset) { unset($this->store[$offset]); } }
true
114f9291845ed591bda695f7a4a744c0bdd7596e
PHP
NicolasGlassey/I133_calendar_teacher_kit
/calendarStep02/calendarStep02.php
UTF-8
1,187
2.640625
3
[]
no_license
<?php /** * Author : nicolas.glassey@cpnv.ch * Project : 133 - Calendar - Step 01 * Created : 09.12.2018 - 19h:30 * * Last update : [01.12.2018 author] * [add $logName in function setFullPath] * Git source : [link] */ //region global variables $title = "Calendar"; //html title page //endregion //region initialization //endregion //region entry point //endregion //region functions //endregion ?> <!--region gabarit--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> <?php echo $title; ?> </title> <link rel="stylesheet" href="style.css"> </head> <body> <!--region calendar--> <div class="month"> <ul> <li>August<br>2016</li> </ul> </div> <ul class="weekdays"> <li>Mo</li> <li>Tu</li> <li>We</li> <li>Th</li> <li>Fr</li> <li>Sa</li> <li>Su</li> </ul> <ul class="days"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li><span class="active">10</span></li> <li>11</li> </ul> <!--endregion--> </body> </html> <!--endregion-->
true
7d7182cee7d87943166cd8b37af50da6fd9950ce
PHP
LawrenceuSRprog/webPoweredPHP-PortraitTree
/C2_classBrickTester.php
UTF-8
3,887
2.96875
3
[]
no_license
<?php include 'autoload.php'; # This is a Test-Driver for BlockFind formerly:ToolBox class BrickTester { /* # #### #### #### #### #### #### #### ###### #### #### #### #### # # This BlockFind Holder assumes the CLASS BlockFind exists # see line 48 =============== # # #### #### #### #### #### #### #### ###### #### #### #### #### */ private $objFindBrick; private $pickFromLeft; private $pickFromRight; public function demoNudgingIn(){ $fink = $this->$objFindBrick; $apex = $fink->get_Orphans(); echo "<br><br>This apex is based on the ORPHANS:<br>"; foreach ($apex as $key => $apeMember) { echo(" APEX " . $apeMember . "<br>"); $memberList = $fink->spreadFromParent($apeMember); foreach ($memberList as $key => $member) { echo(" -- -- -- -- > " . $member . "<br>"); } } } # End Method public function demoChekingOut(){ $this->reportTheTrio($this->pickFromLeft); $runner = array("Lion","Witch","Wardrobe"); $this->reportTheTrio($runner); $this->reportTheTrio($this->pickFromRight); } # End Method function __construct() { $feed=$this->accepted_feed(); $fink = new FindBrick($feed,true); $this->$objFindBrick = $fink; $this->populateBoth($feed); echo "<br><br> ## ## ## ## ## ## ## ## ## ## ## ## ## <br><br>"; echo " # ## Code runs AFTER fink was CREATED ## # <br><br>"; echo " ## ## ## ## ## ## ## ## ## ## ## ## ## <br><br>"; } # End Construct of ToolBox Holder private function populateBoth($feed) { $this->pickFromLeft = []; $this->pickFromRight = []; foreach ($feed as $key => $twoPart) { array_push($this->pickFromRight, $twoPart[1]); $candidate = $twoPart[0]; $found = in_array($candidate, $this->pickFromLeft); if ($found==false) { array_push($this->pickFromLeft, $candidate); } # End If } # End Loop } # End func private function accepted_feed() { # return $this->afTinyForestData(); return $this->afWholeBodyData(); # return $this->afLetterData(); } # End func private function afTinyForestData() { return [ array('The Trees','Timber'), array('The Trees','Fruit'), array('The Trees','Artwork'),]; } // End Func private function afWholeBodyData() { return [ array('UpBody','RightArm'), array('UpBody','LeftArm'), array('UpBody','Chest'), array('Head','Face'), array('Head','Ears'), array('Head','Rest of Head'), array('Face','Nose'), array('Face','Eyes'), array('Face','Mouth'), array('MidBody','Center'), array('LowBody','LeftLeg'), array('LowBody','RightLeg')]; } // End Func private function afLetterData() { return [ array('a','ant'), array('a','adder'), array('b','brick'), array('b','banjo'), array('b','bank'), array('c','cello'), array('c','catcher'), array('c','candle'), array('c','coral'), array('c','cake'), array('ant','antler'), array('ant','ant thill'), array('adder','address'), array('adder','adding'), array('adder','addition')]; } // End Func private function reportTheTrio($runner){ $fink = $this->$objFindBrick; $spacer = " . . #### . . ||"; foreach ($runner as $key => $ran) { echo "<br>" . $fink->spyOnFLAG($ran) . $spacer . $ran; } # End For } # End Func private function trioCheckBox($a1,$a2,$a3){ $b1 = "[.]"; if ($a1) $b1="[#"; $b2 = "[.]"; if ($a2) $b2="[#"; $b3 = "[.]"; if ($a3) $b3="[#"; return "<br> ". $b1 . $ $b2 . $b3; }# End Func } # End class ?>
true
3a5eafe77f952881f3d97efefec58f4d495650bb
PHP
Fincallorca/HitchHikerApi
/src/Wsdl/v3_1_388_1/EnumType/TicketingTypeEnum.php
UTF-8
1,562
2.734375
3
[ "MIT" ]
permissive
<?php namespace Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\EnumType; /** * This class stands for TicketingTypeEnum EnumType * Meta informations extracted from the WSDL * - nillable: true * - type: tns:TicketingTypeEnum * @subpackage Enumerations */ class TicketingTypeEnum { /** * Constant for value 'None' * @return string 'None' */ const VALUE_NONE = 'None'; /** * Constant for value 'PaperTicketing' * @return string 'PaperTicketing' */ const VALUE_PAPER_TICKETING = 'PaperTicketing'; /** * Constant for value 'ElectronicTicketing' * @return string 'ElectronicTicketing' */ const VALUE_ELECTRONIC_TICKETING = 'ElectronicTicketing'; /** * Return true if value is allowed * @uses self::getValidValues() * @param mixed $value value * @return bool true|false */ public static function valueIsValid($value) { return ($value === null) || in_array($value, self::getValidValues(), true); } /** * Return allowed values * @uses self::VALUE_NONE * @uses self::VALUE_PAPER_TICKETING * @uses self::VALUE_ELECTRONIC_TICKETING * @return string[] */ public static function getValidValues() { return array( self::VALUE_NONE, self::VALUE_PAPER_TICKETING, self::VALUE_ELECTRONIC_TICKETING, ); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
true
982627fab716ffaa4bc8fdb55c9732d67a24233a
PHP
gilberg-vrn/php-lucene-analyzer
/src/analyses/FilteringTokenFilter.php
UTF-8
1,192
2.96875
3
[]
no_license
<?php namespace ftIndex\analyses; /** * Class FilteringTokenFilter * * @package ftIndex\analyses * @author Dmitrii Emelyanov <gilberg.vrn@gmail.com> * @date 9/9/19 1:47 PM */ abstract class FilteringTokenFilter extends TokenStream { private $skippedPositions; /** * Create a new {@link FilteringTokenFilter}. * * @param TokenStream $input the {@link TokenStream} to consume */ public function __construct(TokenStream $input) { parent::__construct($input); } /** Override this method and return if the current input token should be returned by {@link #incrementToken}. */ protected abstract function accept(): bool; public final function incrementToken(): bool { $this->skippedPositions = 0; while ($this->input->incrementToken()) { if ($this->accept()) { if ($this->skippedPositions != 0) { $this->posIncAttribute = $this->posIncAttribute + $this->skippedPositions; } return true; } $this->skippedPositions += $this->posIncAttribute; } // reached EOS -- return false return false; } }
true
f26b2aa5a055da89f9e979b11ede6ed671ae630c
PHP
mabrursatori/CI-toko-batik
/app/Models/GambarModel.php
UTF-8
701
2.65625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use CodeIgniter\Model; class GambarModel extends Model { protected $table = 'gambar'; protected $useTimestamps = true; protected $allowedFields = ['id', 'url', 'slug', 'ordinal']; protected $gambar; public function __construct() { $this->gambar = \Config\Database::connect()->table('gambar'); } public function getGambar($slug = false) { if ($slug) { return $this->where(['slug' => $slug])->get()->getRowArray(); } return $this->asArray()->findAll(); } public function getGambarUrlByID($id) { return $this->gambar->getWhere(['id' => $id])->getFirstRow()->url; } }
true
cb698c11853c3265ae9b8824797581ff546edb64
PHP
trint/flarum-s
/src/daemon/Service/StartCommand.php
UTF-8
876
2.609375
3
[ "MIT" ]
permissive
<?php namespace Flarum\Daemon\Service; use Flarum\Console\Flag; use Flarum\Console\Color; /** * Class StartComand * @package Flarum\Daemon\Service * @author <trint.dev@gmail.com> */ class StartCommand extends BaseCommand { /** * @var bool */ public $update; /** * @var bool */ public $daemon; public function main() { if ($pid = $this->getServicePid()) { (new Color)->println(sprintf(self::IS_RUNNING, $pid)); return; } $this->update = Flag::bool(['u', 'update'], false); $this->daemon = Flag::bool(['d', 'daemon'], false); $server = new \Flarum\Server\Httpd($this->path, $this->setting); if ($this->update) { $server->setting['max_request'] = 1; } $server->setting['daemonize'] = $this->daemon; $server->start(); } }
true
ded0dd34c10c29f4a1ab0b69880ae1712a425a3e
PHP
borisovmi/laravel-shop
/app/Order.php
UTF-8
1,758
2.75
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Session; use Cart; use Illuminate\Support\Facades\DB; class Order extends Model { /* save an order in DB after clicking on checkout button */ static public function SaveOrder() { $order = new self(); $order->uid = Session::get('user_id'); $order->total = 0; foreach (Cart::getContent()->toArray() as $item) { $order->total += $item['price'] * $item['quantity']; } $order->order_data = serialize(Cart::getContent()->toArray()); $order->status = "New"; $order->save(); $order_id = DB::table('orders')->latest()->first()->id; /* saving order_id in session, used to redirect the user to order details page on user page after submitting checkout */ Session::put('last_order', $order_id); /* clear cart, ready for a new order */ Cart::clear(); return true; } /* updating only order status: payed, delivered, etc */ static public function updateOrder($request, $id) { $order = self::find($id); $order->status = $request->status; $order->save(); if ($order->id) { return true; } return false; } /* get all user's order to show in CMS and also on user's personal page */ static public function getOrdersByUser($user_id) { $userOrders = DB::table('orders')->where('uid', $user_id)->get(); return $userOrders; } /* get order detailsn to show in CMS and also on user's personal page */ static public function getOrderById($order_id) { $order = DB::table('orders')->where('id', $order_id)->get(); return $order; } }
true
4895c12f894c19d4745353bf9419cb442d372928
PHP
fhp/unicorn
/src/Unicorn/UI/HTML/Attributes/SourceString.php
UTF-8
364
2.765625
3
[]
no_license
<?php namespace Unicorn\UI\HTML\Attributes; trait SourceString { use AttributeTrait; public function sourceString(): string { return $this->property("srcdoc"); } public function hasSourceString(): bool { return $this->hasProperty("srcdoc"); } public function setSourceString(string $value): void { $this->setProperty("srcdoc", $value); } }
true
090307f4e38b0ff77c7efd2d3e8224e856ebc751
PHP
WeLeetCoder/swoole
/App/Validate/RequestValidate.php
UTF-8
2,754
2.71875
3
[]
no_license
<?php namespace App\Validate; use App\Utils\Code; use EasySwoole\EasySwoole\Config; class RequestValidate extends BaseValidate { /** * 参数校验,需要哪些参数,哪些参数是必须的,可以列出。 */ /** * 通过 Access key 找到对应的 Secret key,然后再经过排序请求字段,签名即可 */ static function validate(): \Closure { /** * 模块是独立的吗? * 传输什么东西过来?做验证,然后验证完成之后怎么处理? 验证是否通过。 */ return function ($controller) { [ 'timestamp' => $ts, 'nonce' => $nonce, 'signature' => $sign, ] = $controller->params; $nowTimestamp = round(microtime(true), 3) * 1000; /** * 使用当前时间戳与传过来的时间戳对比, A - B > 60 second 说明有问题 */ if (Config::getInstance()->getConf('MODE') === 'DEV') { // 开发模式,不校验时间戳。 return true; } // 时间戳采用的是毫秒验证,所以此处,允许在60秒内的时间戳都是有效的。 if (abs($nowTimestamp - $ts) > 60 * 1000) { $controller->error('时间戳错误', Code::TIME_STAMP_ERROR); return false; } return true; }; } static function validateSign(): \Closure { return function ($controller) { $params = $controller->params; $sign = $params['signature']; unset($params['signature']); ksort($params); $signParams = []; foreach ($params as $key => $val) { array_push($signParams, "$key=$val"); } $signStr = implode('&', $signParams); $s = parent::sign($signStr); if ($s !== $sign) { /** * 开发模式,显示签名 */ $controller->error('签名不正确。', Code::SIGNATURE_ERROR, rawurlencode($s)); return false; } return true; }; } static function requireParamsCheck(array $paramKeys = []) { return function ($controller) use ($paramKeys) { foreach ($paramKeys as $paramKey) { if (!isset($controller->params[$paramKey])) { $controller->error("参数错误,缺少 $paramKey 参数。", Code::PARAM_MISS); // $controller->end(); return false; } } return true; }; } }
true
3d993d290d8154ae4712ccf9d9bdaa880339fd2c
PHP
CatherineCbl/WF3
/PHP/post/formulaire2.php
UTF-8
1,195
3.046875
3
[]
no_license
<?php if($_POST) { echo "ville : " . $_POST['ville'] . '<br>'; echo "cp : " . $_POST['cp'] . '<br>'; echo "adresse : " . $_POST['adresse'] . '<br>'; echo '<hr>'; //récupération des saisies via une boucle foreach ($_POST as $indice => $valeur) { echo $indice . ' : ' . $valeur . '<br>'; } } echo '<pre>'; print_r($_POST); echo '</pre>'; ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Formulaire2</title> <style> label{float: left; width: 95px; font-style: italic; font-family: Calibri;} h1 {margin: 0 0 10px 200px; font-family: Calibri;} </style> </head> <body> <h1>Formulaire</h1> <form class="" action="" method="post"> <label for="">Ville</label><br /> <input type="text" name="ville" value=""><br /> <label for="">Code Postal</label><br /> <input type="text" name="cp" value=""><br /> <label for="">Adresse</label><br /> <input type="text" name="adresse" value=""><br /> <label for=""></label> <input type="submit" name="" value="envois"><br /> </form> </body> </html>
true
6e6a6f8349fbb73cfe522e870105c0a3eb233500
PHP
a-abdi/shop
/app/Repositories/Eloquent/ExampleRepository.php
UTF-8
328
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Repositories\Eloquent; use App\Models\Example; use App\Contracts\Repositories\ExampleRepositoryInterface; class ExampleRepository extends BaseRepository implements ExampleRepositoryInterface { public function __construct(private Example $example) { parent::__construct($example); } }
true
8b0e0a56eaa095e867211c69730d2864c1997ad0
PHP
adrianomartino/CRUDo
/application/library/Data.php
UTF-8
1,185
2.828125
3
[]
no_license
<?php class Data{ private $to_save_in_cookies='user_email,site_lang,user_lang'; //list static function addToSession($data_name,$data_value){ $_SESSION[$data_name]=$data_value; } static function destroy($data){ if(isset($_COOKIE[$data])) setcookie($data); unset($_POST[$data],$_GET[$data],$_SESSION[$data],$_COOKIE[$data],$_REQUEST[$data]); } static function makeCookie($data_name,$data_value){ //memorize in session $_SESSION[$data_name]=$data_value; //memorize in cookie setcookie($data_name, $data_value, time()+60*60*24*30); //expires in 30 days } static function tryToGet($data){ /* Establish if a variable has been defined through the various possibilities */ if(isset($_POST[$data])) return $_POST[$data]; if(isset($_GET[$data])) return $_GET[$data]; if(isset($_SESSION[$data])) return $_SESSION[$data]; if(isset($_COOKIE[$data])) return $_COOKIE[$data]; return false; } }
true
83cb3094d3f8d2eacf8e5e43ab4db5f1aaf9cd7c
PHP
Lucatim/Domisep
/model/passerelle.php
UTF-8
3,179
2.890625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: franck.meyer * Date: 11/06/2018 * Time: 11:08 */ class passerelle { public static function recupererDonnees(){ $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, "http://projets-tomcat.isep.fr:8080/appService?ACTION=GETLOG&TEAM=002D"); curl_setopt($ch, CURLOPT_HEADER, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); curl_close($ch); //echo ("$data"); return $data; } public static function listeTrame($trameLog){ return str_split($trameLog,33); } public static function decouperTrame($listeTrame){ $listeTrameTraite=array(); foreach ($listeTrame as $trame){ $t = substr($trame,0,1); $o = substr($trame,1,4); $r=substr($trame,5,1); $c=substr($trame,6,1); $n=substr($trame,7,2); $v=substr($trame,9,4); $a=substr($trame,13,4); $x=substr($trame,17,2); $year=substr($trame,19,4); $month=substr($trame,23,2); $day=substr($trame,25,2); $hour=substr($trame,27,2); $min=substr($trame,29,2); $sec=substr($trame,31,2); $paramTrame=list($t, $o, $r, $c, $n, $v, $a, $x, $year, $month, $day, $hour, $min, $sec) = sscanf($trame,"%1s%4s%1s%1s%2s%4s%4s%2s%4s%2s%2s%2s%2s%2s"); $listeTrameTraite[]=$paramTrame; passerelle::traitementTrameBDD($paramTrame); /* foreach ($paramTrame as $param){ echo ("$param"); } */ //echo ("$paramTrame"); //var_dump($paramTrame); } //echo ("$listeTrameTraite"); //var_dump($listeTrameTraite); } public static function traitementTrame(){ $donneeTrame=passerelle::recupererDonnees(); $listeTrame=passerelle::listeTrame($donneeTrame); passerelle::decouperTrame($listeTrame); } public static function traitementTrameBDD($trameParam){ $date =mktime($trameParam[11],$trameParam[12],$trameParam[13],$trameParam[9],$trameParam[10],$trameParam[8]); $date=date("Y-m-d",$date); $date=(string)$date; echo("$date \n"); $idSensor="1"; $bdd=PdoDomisep::pdoConnectDB(); // Connexion à la BDD /* $req = $bdd->prepare('SELECT COUNT (*) FROM sensor_data WHERE id_sensor=? AND date_sensor=?'); $req->execute(array($idSensor,$date)); $req = $bdd->prepare('SELECT COUNT (*) FROM sensor_data WHERE id_sensor=?'); $req->execute(array($idSensor)); */ $req = $bdd->prepare('SELECT COUNT(*) FROM sensor_data WHERE id_sensor=? AND date_sensor=?'); $req->execute(array($idSensor,$date)); $val = $req->fetch(); var_dump($val); //$req->closeCursor(); //Verifier le numero de trame pour savoir quelle trame est déjà traité if($val[0]>0){ //Update } elseif ($val[0]==0){ //Insert } } }
true
cfadffcac90a0f63316a59b71d95b337c45f8d42
PHP
kirangun/1108
/load.php
UTF-8
1,086
2.921875
3
[]
no_license
<!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "test"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT vid_id, vid_name, vid_is_active ,vid_status FROM videos1"; $result = $conn->query($sql); if ($result->num_rows > 0) { echo "<table><tr><th>videoId</th><th>VideoName</th><th>video is active</th><th>video Status</th></tr>"; // output data of each row while($row = $result->fetch_assoc()) { echo "<tr><td>".$row["vid_id"]."</td><td>".$row["vid_name"]."</td><td>".$row["vid_is_active"]."</td><td>".$row["vid_status"]."</td></tr>"; } echo "</table>"; } else { echo "0 results"; } $conn->close(); ?> <input type="submit" value="Play" action="<?php echo"hello";?>"> <input type="submit" value="Play"> </body> </html>
true
e7dbd99076d987b8c1e2edf54a6e525ed277214d
PHP
hermesto/DB
/insert.php
UTF-8
613
2.765625
3
[]
no_license
<?php require_once('settings.config.php'); // Define db configuration arrays here require_once('DBConnection.php'); // Include this file $test3 = $_POST["nombre"]; echo $test3; $database = new DBConnection($localhost); // Create new connection by passing in your configuration array // $test3 = "hermest";s $sqlInsert = "insert into usurios(nombre) VALUES('".$test3."');"; // Insert/Update/Delete Statements: $count = $database->runQuery($sqlInsert); // Use this method to run inserts/updates/deletes echo "number of records inserted: " . $count; ?>
true
5ce3d496c148bee849d479791acb1b4bc2cb84c8
PHP
thierrysutter/siteClub
/ManagerEntrainement.class.php
ISO-8859-1
4,789
3.203125
3
[]
no_license
<?php class ManagerEntrainement { private $_db; public function __construct($db) { $this->setDb($db); } public function add($id, $libelle, $anneeDebut, $anneeFin, $login) { //echo "Ajout d'un nouveau article<br>"; // Prparation de la requte d'insertion. $q = $this->_db->query("INSERT INTO categorie (ID, LIBELLE, ANNEE_DEBUT, ANNEE_FIN, AUTEUR_MAJ, DERNIERE_MAJ) VALUES ('".$id."','".$libelle."','".$anneeDebut."','".$anneeFin."','".strtoupper($login)."',now())"); // Assignation des valeurs pour le nom du personnage. /*$q->bindValue(':login', $login); $q->bindValue(':password', $password); $q->bindValue(':email', $email); // Excution de la requte. $q->execute();*/ // Hydratation du article pass en paramtre avec assignation de son identifiant et des dgts initiaux (= 0). /*$article->hydrate(array( 'id' => $this->_db->lastInsertId(), 'degats' => 0, ));*/ } public function count() { // Excute une requte COUNT() et retourne le nombre de rsultats retourn. return $this->_db->query('SELECT COUNT(*) FROM entrainement')->fetchColumn(); } public function delete(Entrainement $entrainement) { // Excute une requte de type DELETE. $this->_db->exec('DELETE FROM entrainement WHERE id = '.$entrainement->getId()); } public function exists($jour) { // Si le paramtre est un string, c'est qu'on a fourni un nom. if (is_string($jour)) // On veut voir si tel sponsor ayant pour nom $nom existe. { // On excute alors une requte COUNT() avec une clause WHERE, et on retourne un boolean. return (bool) $this->_db->query("SELECT COUNT(*) FROM entrainement WHERE jour = '".$jour."'")->fetchColumn(); } return false; } public function get($jour) { // Si le paramtre est un entier, on veut rcuprer le sponsor avec son nom. // Sinon on renvoie null if (is_string($jour)) { // Excute une requte de type SELECT avec une clause WHERE, et retourne un objet Sponsor. $q = $this->_db->query("SELECT id, jour, heure_debut as heureDebut, heure_fin as heureFin, lieu FROM entrainement WHERE jour = '".$jour."'"); $donnees = $q->fetch(PDO::FETCH_ASSOC); return BoEntrainement($donnees); } else { return null; } } public function trouverEntrainementParCategorie($categorie) { // Si le paramtre est un entier, on veut rcuprer le sponsor avec son nom. // Sinon on renvoie null $entrainements = array(); if ($categorie > 0) { // Excute une requte de type SELECT avec une clause WHERE, et retourne un objet Sponsor. $q = $this->_db->query("SELECT id, jour, heure_debut as heureDebut, heure_fin as heureFin, lieu FROM entrainement WHERE categorie = '".$categorie."'"); while ($donnees = $q->fetch(PDO::FETCH_ASSOC)) { $entrainements[] = new BoEntrainement($donnees); } return $entrainements; } else { return null; } } public function getList() { // Retourne la liste des menus. // Le rsultat sera un tableau d'instances de Sponsor. $entrainements = array(); $q = $this->_db->query("SELECT id, jour, heure_debut as heureDebut, heure_fin as heureFin, lieu FROM entrainement"); //$q->execute(); while ($donnees = $q->fetch(PDO::FETCH_ASSOC)) { $entrainements[] = new BoEntrainement($donnees); } return $entrainements; } public function setDb(PDO $db) { $this->_db = $db; } public function ajouterEntrainement($categorie, $jour, $heureDebut, $heureFin, $lieu, $login) { // Prparation de la requte d'insertion. $sql = "INSERT INTO entrainement (CATEGORIE, JOUR, HEURE_DEBUT, HEURE_FIN, LIEU, AUTEUR_MAJ, DERNIERE_MAJ) "; $sql .= "VALUES (".$categorie.", ".$jour.", ".$heureDebut.", ".$heureFin.", ".$lieu.", '".strtoupper($login)."', now())"; $q = $this->_db->query($sql); } public function modifierEntrainement($id, $categorie, $jour, $heureDebut, $heureFin, $lieu, $login) { // Prparation de la requte d'insertion. $sql = "UPDATE entrainement "; $sql .= "SET CATEGORIE=".$categorie.", "; $sql .= "JOUR='".$jour."', "; $sql .= "HEURE_DEBUT='".$heureDebut."', "; $sql .= "HEURE_FIN='".$heureFin."', "; $sql .= "LIEU='".$lieu."', "; $sql .= "AUTEUR_MAJ='".strtoupper($login)."', "; $sql .= "DERNIERE_MAJ=now() "; $sql .= "WHERE id=".$id." "; $q = $this->_db->query($sql); } public function supprimerEntrainement(int $idEntrainement) { // Excute une requte de type DELETE. $this->_db->exec('DELETE FROM entrainement WHERE id = '.$idEntrainement); } } ?>
true
df93bbe6b84838ae76d39349d2f93ed251c49c6e
PHP
maedca/cursoPHPav
/colaboracion_objetos.php
UTF-8
2,113
2.875
3
[]
no_license
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php class Cabecera{ private $titulo; public function __construct($tit){ $this->titulo=$tit; } public function graficar(){ echo '<h1 style="text-align:center">'.$this->titulo.'</h1>'; } } class Cuerpo{ private $lineas=array(); public function insertarParrafo($li){ $this->lineas[]=$li; } public function graficar(){ for ($f=0; $f<count($this->lineas);$f++){ echo '<p>'.$this->lineas[$f].'</p>'; } } } class Pie{ private $titulo; public function __construct($perro){ $this->titulo=$perro; } public function graficar(){ echo '<h5 style="color:rojo">'.$this->titulo.'</h5>'; } } class Pagina{ private $cabecera; private $cuerpo; private $pie; public function __construct($texto1, $texto2){ $this->cabecera=new Cabecera($texto1); $this->cuerpo=new Cuerpo(); $this->pie=new Pie($texto2); } public function insertarCuerpo($texto){ $this->cuerpo->insertarParrafo($texto); } public function graficar(){ $this->cabecera->graficar(); $this->cuerpo->graficar(); $this->pie->graficar(); } } $pagina1=new Pagina('Titulo de la pagina' , 'pie de pagina'); $pagina1->insertarCuerpo('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum, quae, ea deserunt sequi velit impedit blanditiis suscipit quidem iusto voluptas facilis labore quas praesentium quaerat laborum. Sint facere adipisci dolores!'); $pagina1->insertarCuerpo('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid, labore, laboriosam, similique distinctio dicta nulla soluta neque alias vel autem illum modi ex reprehenderit est optio. Mollitia quae labore dignissimos.'); $pagina1->insertarCuerpo('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste, dignissimos, laborum ex dolor voluptas aliquam eos doloremque natus eligendi molestias numquam quisquam consectetur rem iure qui laudantium incidunt commodi vero.'); $pagina1->graficar(); ?> </body> </html>
true
037ae092be17eedadc0cf7948d61a0be0e73dc93
PHP
satthi/pawapuro-league
/src/Model/Entity/BasePlayer.php
UTF-8
3,575
2.609375
3
[]
no_license
<?php namespace App\Model\Entity; use Cake\ORM\Entity; /** * BasePlayer Entity * * @property int $id * @property string $name * @property string $name_short * @property bool $deleted * @property \Cake\I18n\Time $deleted_date * @property \Cake\I18n\Time $created * @property \Cake\I18n\Time $modified * * @property \App\Model\Entity\Player[] $players */ class BasePlayer extends Entity { /** * Fields that can be mass assigned using newEntity() or patchEntity(). * * Note that when '*' is set to true, this allows all unspecified fields to * be mass assigned. For security purposes, it is advised to set '*' to false * (or remove it), and explicitly make individual fields accessible as needed. * * @var array */ protected $_accessible = [ '*' => true, 'id' => false ]; protected function _getDisplayAvg() { if (!$this->_properties['dasu']) { return '-'; } return preg_replace('/^0/', '', sprintf('%0.3f', round($this->_properties['hit'] / $this->_properties['dasu'], 3))); } protected function _getObp() { if( $this->_properties['dasu'] == 0 && $this->_properties['walk'] == 0 && $this->_properties['deadball'] == 0 && $this->_properties['sacrifice_fly'] == 0 ) { $ratio = sprintf('%0.3f', round(0, 3)); } else { $ratio = sprintf('%0.3f', round(($this->_properties['hit'] + $this->_properties['walk'] + $this->_properties['deadball']) / ($this->_properties['dasu'] + $this->_properties['walk'] + $this->_properties['deadball'] + $this->_properties['sacrifice_fly']), 3)); } $ratio = preg_replace('/^0/', '', $ratio); return $ratio; } protected function _getSlg() { if( $this->_properties['dasu'] == 0 ) { $ratio = sprintf('%0.3f', round(0, 3)); } else { $ratio = sprintf('%0.3f', round(($this->_properties['hit'] + $this->_properties['base2'] + $this->_properties['base3'] * 2 + $this->_properties['hr']* 3 ) / ($this->_properties['dasu']), 3)); } $ratio = preg_replace('/^0/', '', $ratio); return $ratio; } protected function _getOps() { return preg_replace('/^0/', '', sprintf('%0.3f', $this->_getObp() + $this->_getSlg())); } protected function _getDisplayEra() { if (!$this->_properties['inning']) { return '-'; } return sprintf('%0.2f', round($this->_properties['jiseki'] / $this->_properties['inning'] * 27, 2)); } protected function _getDisplayWinRatio() { if (!$this->_properties['win'] && !$this->_properties['lose']) { return '-'; } return sprintf('%0.3f', round($this->_properties['win'] / ($this->_properties['win'] + $this->_properties['lose']), 3)); } protected function _getPAvg() { if($this->_properties['p_dasu'] == 0) { $ratio = sprintf('%0.3f', round(0, 3)); } else { $ratio = sprintf('%0.3f', round($this->_properties['p_hit'] / ($this->_properties['p_dasu']), 3)); } $ratio = preg_replace('/^0/', '', $ratio); return $ratio; } protected function _getSansinRitsu() { if (!$this->_properties['inning']) { return '-'; } return sprintf('%0.2f', round($this->_properties['get_sansin'] / $this->_properties['inning'] * 27, 2)); } }
true
a715573075f094cb84a85f7efed9f09b6ef827ac
PHP
enamba/janamesa
/application/models/Company.php
UTF-8
19,211
2.78125
3
[]
no_license
<?php /** * @author mlaug */ class Yourdelivery_Model_Company extends Default_Model_Base { /** * get all departments of company * @var SplObjectStorage */ protected $_departments = null; /** * store all employees as objects * @var SplObjectStorage */ protected $_employees = null; /** * returns an empty model if no id is given * @author mlaug * @param int $id * @return Yourdelivery_Model_Company */ function __construct($id = null) { //nothing is set so we return null if (is_null($id)) return $this; parent::__construct($id); } /** * get all customers from database * @author mlaug * @return SplObjectStorage */ public static function all() { $db = Zend_Registry::get('dbAdapter'); $result = $db->query('select id from companys')->fetchAll(); $companys = new SplObjectStorage(); foreach ($result as $c) { try { $company = new Yourdelivery_Model_Company($c['id']); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $companys->attach($company); } return $companys; } /** * get all email addresses of one certian company * @author mlaug * @param int $companyId * @return array */ public static function allEmployeesEmail($companyId = null) { if (is_null($companyId)) { return array(); } $db = Zend_Registry::get('dbAdapter'); return $db->query('select c.email from customers c inner join customer_company cc on c.id=cc.customerId where c.deleted=0 and cc.companyId=' . $companyId . ' order by c.email')->fetchAll(); } /** * get related table * @author mlaug * @return Yourdelivery_Model_DbTable_Company */ public function getTable() { if (is_null($this->_table)) { $this->_table = new Yourdelivery_Model_DbTable_Company(); } return $this->_table; } /** * Returns Customer_Company objects of all employees of this company * @author mlaug * @return splStorageObjects */ public function getEmployees() { if ( is_null($this->_employees) ){ $customers = $this->getTable()->getEmployees(); $objects = new splObjectStorage(); foreach ($customers AS $customer) { try { $ccust = new Yourdelivery_Model_Customer_Company($customer->customerId, $this->getId()); if ($ccust->isDeleted()) { continue; } } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $objects->attach($ccust); } $this->_employees = $objects; } return $this->_employees; } /** * Returns count of employees * @author mlaug * @return int */ public function getEmployeesCount() { return $this->getTable()->getEmployeesCount(); } /** * Returns the company name * @author mlaug * @return string */ public function getCompanyName() { return $this->getName(); } /** * Returns the contact Object of this company * @author mlaug * @return Yourdelivery_Model_Contact */ public function getContact() { try { return new Yourdelivery_Model_Contact($this->getContactId()); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { return null; } } /** * Returns the billing contact object if this company * @author mlaug * @return Yourdelivery_Model_Contact */ public function getBillingContact() { try { return new Yourdelivery_Model_Contact($this->getBillingContactId()); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { return null; } } /** * returns all budget objects of this company * @author mlaug * @return splStorageObjects */ public function getBudgets() { $table = new Yourdelivery_Model_DbTable_Company_Budgets(); $all = $table->fetchAll('companyId = ' . $this->getId()); $obj = new splObjectStorage(); foreach ($all AS $budget) { try { $budget = new Yourdelivery_Model_Budget($budget->id); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $obj->attach($budget); } return $obj; } /** * create new relation between company address and budget * @author mlaug * @param Yourdelivery_Model_Budget $budget * @param Yourdelivery_Model_Location $location * @return int */ public function addBudget($budget, $location) { if (!is_object($budget) || !is_object($location)) { return false; } $rel = new Yourdelivery_Model_DbTable_Company_Locations(); $row = $rel->createRow(); $row->budgetId = $budget->getId(); $row->locationId = $location->getId(); return $row->save(); } /** * return all admins of this company * @author mlaug * @return SplObjectStorage */ public function getAdmins() { $a = new SplObjectStorage(); $admins = $this->getTable()->getAdmins(); foreach ($admins as $admin) { try { $customer = new Yourdelivery_Model_Customer_Company($admin['id'], $this->getId()); $a->attach($customer); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } } return $a; } /** * returns all addresses of this company as RowSet * @author mlaug * @return Zend_Db_Rowset */ public function getAddresses() { $table = new Yourdelivery_Model_DbTable_Locations(); return $table->fetchAll('companyId = ' . $this->getId()); } /** * get locations associated to this company * * @author Felix Haferkorn <haferkorn@lieferando.de> * @since 21.03.2011 * @return SplObjectStorage */ public function getLocations(){ $table = new Yourdelivery_Model_DbTable_Locations(); $locationRows = $table->fetchAll(sprintf('companyId = %d AND deleted = 0' , $this->getId())); $locations = new SplObjectStorage(); foreach($locationRows as $locationRow){ try{ $loc = new Yourdelivery_Model_Location($locationRow['id']); $locations->attach($loc); }catch(Yourdelivery_Exception_Database_Inconsistency $e){ $this->logger->err(sprintf('Could not create location #', $locationRow['id'])); continue; } } return $locations; } /** * gets all Budgets that are related to a given address * @author mlaug * @param int $addressId * @return splStorageObjects */ public function getBudgetsByAddressId($addressId) { $nnTable = new Yourdelivery_Model_DbTable_Company_Location(); $all = $nnTable->fetchAll('locationId = "' . $addressId . '"'); $collector = new SplObjectStorage(); foreach ($all AS $budget) { try { $budget = new Yourdelivery_Model_Budget($budget->id); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $collector->attach($budget); } return $collector; } /** * gets all Billings of the Company filtered by $filter * @author mlaug * @param array $filter * @return splStorageObjects */ public function getBillings($filter = null) { $billingTable = new Yourdelivery_Model_DbTable_Billing(); $all = $billingTable->fetchAll('mode="company" AND refId="' . $this->getId() . '"'); $storage = new splObjectStorage(); foreach ($all AS $bill) { try { $bill = new Yourdelivery_Model_Billing($bill->id); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $storage->attach($bill); } return $storage; } /** * @author mlaug * @return Yourdelivery_Model_Billing_Balance */ public function getBalance() { $balance = new Yourdelivery_Model_Billing_Balance(); $balance->setObject($this); return $balance; } /** * get all departments assigned to company * @return SplObjectStorage */ public function getDepartments($onlyCostcenters = false) { $departments = new SplObjectStorage(); foreach ($this->getTable()->getDepartments() as $dep) { try { $department = new Yourdelivery_Model_Department($dep['id']); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $departments->attach($department); } $this->_departments = $departments; return $this->_departments; } /** * get all costcenters assigned to company * @author mlaug * @return SplObjectStorage */ public function getCostcenters() { return $this->getDepartments(true); } /** * get all project numbers * @author mlaug * @return SplObjectStorage */ public function getProjectNumbers($getDeletedToo = true) { $numbers = $this->getTable()->getProjectNumbers($getDeletedToo); $pnums = new SplObjectStorage(); foreach ($numbers as $number) { try { $num = new Yourdelivery_Model_Projectnumbers($number['id']); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { continue; } $pnums->attach($num); } return $pnums; } /** * Returns count of project numbers * @author alex * @return int */ public function getProjectNumbersCount($getDeletedToo = true) { return $this->getTable()->getProjectNumbersCount($getDeletedToo); } /** * add project number * @author mlaug * @param Yourdelivery_Model_Projectnumer $number * @param boolean $intern * @param string $comment */ public function addProjectNumber($number, $intern, $comment) { $pnum = new Yourdelivery_Model_Projectnumbers(); $pnum->setNumber($number); $pnum->setIntern($intern); $pnum->setComment($comment); $pnum->setCompany($this); $pnum->save(); } /** * check wether this company has a department or not * @author mlaug * @return boolean */ public function hasDepartments() { $deps = $this->getDepartments(); if ($deps->count() > 0) { return true; } return false; } /** * return bill interval * @author abril * @return int */ public function getBillMode() { return $this->getBillInterval(); } /** * @author mlaug * @return Yourdelivery_Model_Billing_Customized */ public function getBillingCustomizedData() { //set defaults $default = array( 'heading' => $this->getName(), 'street' => $this->getStreet(), 'hausnr' => $this->getHausnr(), 'zHd' => null, 'plz' => $this->getPlz(), 'city' => $this->getOrt()->getOrt(), 'showCostcenter' => $this->getCostcenters()->count() > 0 ? true : false, //deactivate by default, if no project or costcenter is available 'showProject' => $this->getProjectNumbersCount() > 0 ? true : false, 'showEmployee' => true, 'verbose' => true, 'projectSub' => false, 'costcenterSub' => false, 'template' => 'standard', 'reminder' => 14 ); //merge it with defaults $customized = array_merge($default, $this->getBillingCustomized()->getData()); return $customized; } /** * get customized billing data * @author mlaug * @since 02.10.2010 * @return Yourdelivery_Model_Billing_Customized */ public function getBillingCustomized() { $customized = new Yourdelivery_Model_Billing_Customized(); $cid = $this->getTable()->getBillingCustomized(); if ($cid === false) { $customized->setMode('comp'); } else { $customized->load($cid['id']); } $customized->setCompany($this); $customized->setRefId($this->getId()); return $customized; } /** * get next bill of this company * @author mlaug * @return Yourdelivery_Model_Billing_Company */ public function getNextBill($from = 0, $until=0, $test = 0) { $mode = $this->getBillMode(); return new Yourdelivery_Model_Billing_Company($this, $from, $until, $mode, $test); } /** * get ort object of location * @author mlaug * @return Yourdelivery_Model_City */ public function getOrt() { $cid = $this->getCityId(); try { return new Yourdelivery_Model_City($cid); } catch (Yourdelivery_Exception_Database_Inconsistency $e) { return null; } } /** * @author alex * @since 13.04.2011 * @return Yourdelivery_Model_City */ public function getCity() { if ($this->_city !== null) { return $this->_city; } $cid = (integer) $this->getCityId(); if ($cid <= 0) { throw new Yourdelivery_Exception_Database_Inconsistency('city id has not been set'); } return $this->_city = new Yourdelivery_Model_City($cid); } /** * returns all order objects of the company's employees * @author mlaug * @return splStorageObjects */ public function getOrders($filter = array()) { return $this->getTable()->getOrders(); } /** * get restaurants, having restriction on this company * any company assigned to restaurant is only allowed to order * @author alex * @return Zend_Db_Table_Rowset_Abstract */ public function getRestaurantRestrictions() { return $this->getTable()->getRestaurantRestrictions(); } /** * get restaurants, having restriction on this company * any company assigned to restaurant is only allowed to order * same as getRestaurantRestrictions, returning the array * @author alex * @return Zend_Db_Table_Rowset_Abstract */ public function getRestaurantsAssociations() { return $this->getTable()->getRestaurantsAssociations(); } /** * set restaurant, having restriction on this company * any company assigned to restaurant is only allowed to order * @author alex * @return int */ public function setRestaurantRestriction($restId, $exclusive=0) { return $this->getTable()->setRestaurantRestriction($restId, $exclusive); } /** * remove restriction relationship with this restaurant * @author alex * @param int $companyId * @return */ public function removeRestaurantRestriction($restId) { return $this->getTable()->removeRestaurantRestriction($restId); } /** * returns count of orders of the company's employees * @author alex * @return int */ public function getOrdersCount() { return $this->getTable()->getOrdersCount(); } /** * create html for tree ( recursive ) * @author mlaug * @param SplObjectStorage $elems * @return string */ private function _traverse($elems) { $html = ""; foreach ($elems as $elem) { $html .= "<li>" . $elem->getName(); if ($elem->getBilling() == 0) { $html .= $this->_appendDepartmentOptions($elem); } else { $html .= "( " . $elem->getIdentNr() . " )"; } if ($elem->hasChilds()) { $html .= "<ul>"; $html .= $this->_traverse($elem->getChilds()); $html .= "</ul>"; } $html . "</li>"; } return $html; } /** * * @param Yourdelivery_Model_Departments $department * @return string */ private function _appendDepartmentOptions($department) { $html = ' <a href="/company/department/id/' . $department->getId() . '" target="_top" title="Bearbeiten"> <img src="/media/images/yd-icons/pencil.png" alt="Bearbeiten" /> </a> <a href="/company/department/del/' . $department->getId() . '" target="_top" onclick="javascript:return confirm(\'Soll diese Abteilung wirklich gelöscht werden?\')"> <img src="/media/images/yd-icons/cross.png" alt="Abteilung löschen" /> </a> '; return $html; } /** * get company name as default string * @return string */ public function __toString() { $name = $this->getName(); if (!is_string($name)) { return ""; } return $name; } /** * @author Felix Haferkorn <haferkorn@lieferando.de> * @param int $budgetId * @return boolean */ public function hasBudgetGroup($budgetId = null) { $check = false; if (is_null($budgetId)) { return $check; } $budgets = $this->getBudgets(); foreach ($budgets as $budget) { if ($budget->getId() == $budgetId) { return true; } } return $check; } /** * @author mlaug * @return int */ public function getUnsendBillAmount() { return $this->getTable()->getUnsendBillAmount(); } /** * @author mlaug * @return int */ public function getUnpayedBillAmount() { return $this->getTable()->getUnpayedBillAmount(); } /** * @author mlaug * @return int */ public function getPayedBillAmount() { return $this->getTable()->getPayedBillAmount(); } /** * check, if company has address * @author Felix Haferkorn <haferkorn@lieferando.de> * @since 25.10.2010 * @param int $addrId * @return boolean */ public function hasAddress($addrId) { $table = new Yourdelivery_Model_DbTable_Locations(); return count($table->fetchAll('companyId = "' . $this->getId() . '" AND deleted = 0')) > 0; } /** * TODO * Refactor - only for backend * @author alex * @since 14.07.2011 */ public function getEditlink(){ return sprintf("<a href=\"/administration_company_edit/index/companyid/%s\">%s</a>", $this->getId(), $this->getName()); } }
true
333158ead8f48246eabd5d919e0a6625dab0079b
PHP
askovorodka/hotels
/src/AppBundle/Services/Geocoder/YandexGeocoder.php
UTF-8
7,208
2.765625
3
[ "MIT" ]
permissive
<?php namespace AppBundle\Services\Geocoder; use AppBundle\Services\Geocoder\Dto\AddressDto; use AppBundle\Services\Geocoder\Dto\MetroDto; use AppBundle\Services\Geocoder\ValueObjects\CoordinatesPoint; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; use Psr\Log\LoggerInterface; class YandexGeocoder implements GeocoderInterface { private const YANDEX_GEOCODER_URL = 'https://geocode-maps.yandex.ru/1.x/'; /** * @var ClientInterface */ private $httpClient; /** * @var LoggerInterface */ private $logger; /** * YandexGeocoder constructor. * * @param ClientInterface $httpClient * @param LoggerInterface $logger */ public function __construct(ClientInterface $httpClient, LoggerInterface $logger) { $this->httpClient = $httpClient; $this->logger = $logger; } /** * @inheritdoc */ public function findAddress(string $searchStr): AddressDto { $addressDto = new AddressDto(); try { $response = $this->httpClient->request('GET', self::YANDEX_GEOCODER_URL, [ 'query' => [ 'format' => 'json', 'results' => 1, 'geocode' => $searchStr, ], ]); } catch (GuzzleException $e) { $this->logger->error($e->getMessage()); return $addressDto; } $responseContent = $response->getBody()->getContents(); if (($statusCode = $response->getStatusCode()) !== 200) { $this->logger->error("Yandex geocoder response code: $statusCode", [ 'request_address' => $searchStr, 'response_content' => $responseContent, ]); return $addressDto; } $this->fillAddressDto($responseContent, $addressDto); return $addressDto; } /** * @inheritdoc */ public function findNearestMetro(CoordinatesPoint $point): MetroDto { $metroDto = new MetroDto(); try { $response = $this->httpClient->request('GET', self::YANDEX_GEOCODER_URL, [ 'query' => [ 'format' => 'json', 'kind' => 'metro', 'results' => 1, 'geocode' => $point->getLongitude() . ',' . $point->getLatitude(), ], ]); } catch (GuzzleException $e) { $this->logger->error($e->getMessage()); return $metroDto; } $responseContent = $response->getBody()->getContents(); if (($statusCode = $response->getStatusCode()) !== 200) { $this->logger->error("Yandex geocoder response code: $statusCode", [ 'request_address' => (string)$point, 'response_content' => $responseContent, ]); return $metroDto; } $this->fillMetroDto($responseContent, $metroDto); return $metroDto; } private function fillAddressDto(string $responseContent, AddressDto $addressDto): void { $data = json_decode($responseContent, true); if (json_last_error() !== JSON_ERROR_NONE) { $this->logger->error('Json decode error: ' . json_last_error_msg(), [ 'response_content' => $responseContent, ]); return; } $found = $data['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] ?? 0; if (!$found) { return; } $geoObject = $data['response']['GeoObjectCollection']['featureMember'][0]['GeoObject'] ?? []; $addressData = $geoObject['metaDataProperty']['GeocoderMetaData']['Address'] ?? []; if (!$addressData) { return; } $addressDto->postalCode = $addressData['postal_code'] ?? null; $addressComponents = $addressData['Components'] ?? []; foreach ($addressComponents as $addressComponent) { $kind = $addressComponent['kind'] ?? null; $value = $addressComponent['name'] ?? null; switch ($kind) { case 'country': $addressDto->country = $value; break; case 'province': $addressDto->administrativeArea = $value; break; case 'area': $addressDto->subAdministrativeArea = $value; break; case 'locality': $addressDto->locality = $value; break; case 'street': $addressDto->thoroughfare = $value; break; case 'house': $addressDto->premise = $value; break; default: break; } } $pointPos = $geoObject['Point']['pos'] ?? null; if ($pointPos && \is_string($pointPos)) { $coordinates = explode(' ', $pointPos); if (\count($coordinates) === 2) { [$longitude, $latitude] = $coordinates; //Яндекс геокодер возвращает в формате 'долгота широта' $coordinatesPoint = new CoordinatesPoint($latitude, $longitude); $addressDto->coordinates = (string)$coordinatesPoint; } } } private function fillMetroDto(string $responseContent, MetroDto $metroDto): void { $data = json_decode($responseContent, true); if (json_last_error() !== JSON_ERROR_NONE) { $this->logger->error('Json decode error: ' . json_last_error_msg(), [ 'response_content' => $responseContent, ]); return; } $found = $data['response']['GeoObjectCollection']['metaDataProperty']['GeocoderResponseMetaData']['found'] ?? 0; if (!$found) { return; } $geoObject = $data['response']['GeoObjectCollection']['featureMember'][0]['GeoObject'] ?? []; $addressData = $geoObject['metaDataProperty']['GeocoderMetaData']['Address'] ?? []; if (!$addressData) { return; } $addressComponents = $addressData['Components'] ?? []; foreach ($addressComponents as $addressComponent) { $kind = $addressComponent['kind'] ?? null; $value = $addressComponent['name'] ?? null; switch ($kind) { case 'country': $metroDto->country = $value; break; case 'province': $metroDto->province = $value; break; case 'locality': $metroDto->locality = $value; break; case 'route': $metroDto->route = $value; break; case 'metro': $metroDto->metro = $value; break; default: break; } } } }
true
11a13ecfbad87e1cd67cf3bdbbc1b53f4a707e1f
PHP
Born-in-moldova/school.loc
/app/core/mysql_driver.php
UTF-8
7,119
3.125
3
[]
no_license
<? class MYSQL_Driver{ private $connection; private $query; private $error = false; private $debug = false; private $columns; private $values; protected $table; protected $result; public function __construct(){ $this->debug = DEBUG; $this->connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); if($this->connection->connect_error) die($this->connection->connect_error); } private function execute(){ if($this->debug) echo '<!--' . $this->last_query() . '-->'; if(!$this->result = $this->connection->query($this->query)){ $this->error = $this->connection->error; if($this->debug) die($this->error); return false; } return true; } private function joins($assoc){ $joins = array(); $type = " JOIN "; if(empty($assoc)) return ''; foreach($assoc as $table => $condition){ if(is_array($condition)){ $joins[] = " " . $condition['type'] . " " . $table . " ON " . $condition['condition']; continue; } $joins[] = $type . $table . " ON " . $condition; } return implode(' ', $joins); } private function like($assoc){ foreach($assoc as $key => $value) if(is_array($value)) $result[] = $value['column'] . ' LIKE \'' . $value['filter'] . '\''; else $result[] = $value; return '(' . implode(' AND ', $result) . ')'; } private function where(array $assoc){ if(empty($assoc)) return ''; $conditions = array(); foreach($assoc as $key => $condition){ if($key === 'like'){ $conditions[] = $this->like($assoc['like']); continue; } if(is_int($key)) $conditions[] = $condition; else $conditions[] = $key . ' = ' . $condition; } return ' WHERE ' . implode(' AND ', $conditions); } private function set(array $assoc){ if(empty($assoc)) return ''; $columns = array(); foreach($assoc as $column => $value) if(is_int($column)) $columns[] = $value; else $columns[] = "`" . $column . "` = '" . $value . "'"; return ' SET ' . implode(' , ', $columns); } protected function select_one(array $assoc){ $columns = "*"; $limit = 1; $table = $this->table; //SELECT if(isset($assoc['columns'])) $columns = $assoc['columns']; $this->query = "SELECT " . $columns; //FROM if(isset($assoc['table'])) $table = $assoc['table']; $this->query .= " FROM " . $table; //JOINS if(isset($assoc['joins'])) $this->query .= $this->joins($assoc['joins']); //WHERE if(isset($assoc['where'])) $this->query .= $this->where($assoc['where']); //GROUP BY for select many //ORDER BY for select many //LIMIT //if($assoc['limit'] !== 'none') $this->query .= " LIMIT " . $limit; //die($this->query); if(!$this->execute()) return false; //echo '<pre>' . print_r($this->result->fetch_assoc(), true) . '</pre>'; return $this->result->fetch_assoc(); } protected function select_many(array $assoc){ $columns = "*"; $limit = 100; $table = $this->table; //SELECT if(isset($assoc['columns'])) $columns = $assoc['columns']; $this->query = "SELECT " . $columns; //FROM if(isset($assoc['table'])) $table = $assoc['table']; $this->query .= " FROM " . $table; //JOINS if(isset($assoc['joins'])) $this->query .= $this->joins($assoc['joins']); //WHERE if(isset($assoc['where'])) $this->query .= $this->where($assoc['where']); //GROUP BY for select many if(isset($assoc['group'])) $this->query .= ' GROUP BY '.$assoc['group']; //ORDER BY for select many if(isset($assoc['order'])) $this->query .= ' ORDER BY '.$assoc['order']; //LIMIT if(isset($assoc['limit'])) $limit = $assoc['limit']; $this->query .= " LIMIT " . $limit; //die($this->query); if(!$this->execute()) return false; while ($row = $this->result->fetch_assoc()) $data[] = $row; //echo '<pre>' . print_r($data, true) . '</pre>'; return $data; } protected function select_count(array $assoc){ $table = $this->table; //SELECT $this->query = 'SELECT COUNT(*) as counter '; //FROM if(isset($assoc['table'])) $table = $assoc['table']; $this->query .= 'FROM '.$table; //JOINS if(isset($assoc['joins'])) $this->query .= $this->joins($assoc['joins']); //WHERE if(isset($assoc['where'])) $this->query .= $this->where($assoc['where']); //GROUP BY for select many if(isset($assoc['group'])) $this->query .= ' GROUP BY '.$assoc['group']; //die($this->query); if(!$this->execute()) return false; $temp = $this->result->fetch_assoc(); return $temp['counter']; } protected function insert(array $entity){ $columns = "`" . implode("`,`" ,array_keys($entity)) . "`"; $values = "'" . implode("','" ,array_values($entity)) . "'"; //INTO $this->query = "INSERT INTO " . $this->table; //COLUMNS $this->query .= " (" . $columns . ") "; //VALUES $this->query .= "VALUES (" . $values . ")"; //die($this->query); if($this->execute()) return $this->connection->insert_id; return false; } protected function delete(array $assoc){ //TABLE if(isset($assoc['table'])) $this->table = $assoc['table']; $this->query = "DELETE FROM `".$this->table."`"; //WHERE if(!isset($assoc['where'])) return false; $this->query .= $this->where($assoc['where']); //die($this->query); return $this->execute(); } protected function update(array $entity, array $conditions){ //UPDATE TABLE $this->query = "UPDATE " . $this->table; //SET $this->query .= $this->set($entity); //WHERE $this->query .= $this->where($conditions['where']); //die($this->query); return $this->execute(); } } ?>
true
cc1853192ba3712414d9acaa4088e5784db47fe8
PHP
decole/planka-php-sdk
/src/Actions/Attachment/AttachmentCreateAction.php
UTF-8
1,472
2.625
3
[]
no_license
<?php declare(strict_types=1); namespace Planka\Bridge\Actions\Attachment; use Planka\Bridge\Contracts\Actions\ResponseResultInterface; use Planka\Bridge\Contracts\Actions\AuthenticateInterface; use Symfony\Component\Mime\Part\Multipart\FormDataPart; use Planka\Bridge\Contracts\Actions\ActionInterface; use Planka\Bridge\Exceptions\FileExistException; use Planka\Bridge\Traits\AttachmentHydrateTrait; use Planka\Bridge\Traits\AuthenticateTrait; use Symfony\Component\Mime\Part\DataPart; final class AttachmentCreateAction implements ActionInterface, AuthenticateInterface, ResponseResultInterface { use AuthenticateTrait, AttachmentHydrateTrait; /** * @throws FileExistException */ public function __construct( private readonly string $cardId, private readonly string $file, string $token ) { $this->setToken($token); if (!file_exists($file) || !is_readable($file)) { throw new FileExistException("File not exist {$file}"); } } public function url(): string { return "api/cards/{$this->cardId}/attachments"; } public function getOptions(): array { $formFields = [ 'file' => DataPart::fromPath($this->file), ]; $formData = new FormDataPart($formFields); return [ 'headers' => $formData->getPreparedHeaders()->toArray(), 'body' => $formData->bodyToIterable(), ]; } }
true
709eaa4f926e2e9176bde0db202f32cd9c600367
PHP
bev-designs/ldl-http-router
/src/LDL/Http/Router/Handler/Exception/ExceptionHandlerInterface.php
UTF-8
649
2.578125
3
[]
no_license
<?php declare(strict_types=1); namespace LDL\Http\Router\Handler\Exception; use LDL\Framework\Base\Contracts\NameableInterface; use LDL\Http\Router\Router; use LDL\Type\Collection\Types\Classes\ClassCollection; interface ExceptionHandlerInterface extends NameableInterface { /** * @param string $exceptionClass * @return bool */ public function canHandle(string $exceptionClass) : bool; /** * @return ClassCollection */ public function getHandledExceptions(): ClassCollection; /** * @param \Exception $e * * @return int|null */ public function handle(\Exception $e) : ?int; }
true
f6883243b4950fb68b172dc21cab382f208ccdb9
PHP
dnirmalasari18/simkp-mamet
/app/Http/Controllers/UserController.php
UTF-8
5,872
2.578125
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\User; use RealRashid\SweetAlert\Facades\Alert; class UserController extends Controller { /** * Display user list. * * @return Response */ public function index(){ $users = User::all(); $dosen = User::where('role','!=','mahasiswa')->orderBy('fullname')->get(); $mahasiswa = User::where('role','mahasiswa')->orderBy('username')->get(); $tendik = User::where('role','tendik')->orderBy('username')->get(); return view('user.index')->with('dosen',$dosen)->with('mahasiswa',$mahasiswa)->with('tendik', $tendik)->with('users', $users); } /** * Show the form for creating a new resource. * * @return Response */ public function create(){ return view('user.create'); } /** * Store a user in storage via coordinator * * @return Response */ public function store(Request $request){ $this->validate($request, [ 'username' => 'required', 'fullname' => 'required', 'phone_number' => 'required', 'password' => 'required|confirmed', 'role' => 'required', ],$message=[ 'required'=>'Atribut di atas perlu diisi', 'confirmed'=>'Atribbt pada password dan konfirmasi password tidak boleh berbeda' ]); User::create([ 'username' => request('username'), 'fullname' => request('fullname'), 'phone_number' => request('phone_number'), 'password' => bcrypt(request('password')), 'role' => request('role'), ]); Alert::success('Success', 'Data telah tersimpan'); return redirect()->route('user.index'); } /** * Update user information * * @return Response */ public function update(Request $request){ // dd($request); $this->validate($request, [ 'id' => 'required', 'username' => 'required', 'fullname' => 'required', 'phone_number' => 'required', ]); $user = User::find(request('id')); $user->username = request('username'); $user->fullname = request('fullname'); $user->phone_number = request('phone_number'); if($request->password != null){ $this->validate($request, [ 'password' => 'required|confirmed' ]); $user->password = bcrypt(request('password')); } $user->save(); Alert::success('Success', 'Data telah tersimpan'); return redirect()->route('user.index'); } /** * Delete user. * * @return Response */ public function destroy(Request $request){ $user = User::find($request->id); $user->delete(); Alert::success('Success', 'Akun telah berhasil dihapus'); return redirect()->route('user.index'); } /** * User login. * * @return Response */ public function login(Request $request){ $this->validate($request, [ 'username' => 'required', 'password' => 'required', ]); if(Auth::attempt(['username' => request('username'), 'password' => request('password')])){ Alert::success('Success', 'Berhasil login'); $user = Auth::user(); if($user->role == 'tendik'){ return redirect()->route('cover_letter.index'); } else return redirect()->route('group.index'); } else { return redirect()->back()->withErrors([ 'approve' => 'Username atau password yang anda masukkan salah',]); } } /** * Store a student in storage. * * @return Response */ public function register(Request $request){ $this->validate($request, [ 'username' => 'required', 'fullname' => 'required', 'phone_number' => 'required', 'password' => 'required|min:6|confirmed', ],$messages=[ 'required' => 'Atribut di atas perlu diisi', 'min' => 'Atribut perlu diisi minimal :min karakter', 'confirmed' => 'Atribut pada password dan konfirmasi password tidak boleh berbeda' ]); User::create([ 'username' => request('username'), 'fullname' => request('fullname'), 'phone_number' => request('phone_number'), 'password' => bcrypt(request('password')), 'role' => 'mahasiswa', ]); Alert::success('Success', 'Selamat datang di SimKP'); return redirect()->route('login'); } /** * Display reset password form. * * @return Response */ public function reset(){ return view('auth.passwords.reset'); } /** * Reset password * * @return Response */ public function doReset(Request $request){ $this->validate($request, [ 'password_old' => 'required', 'password' => 'required|min:6|confirmed', ],$messages = [ 'required' => 'Atribut di atas perlu diisi', 'min' => 'Atribut perlu diisi minimal :min karakter', 'confirmed' => 'Atribut pada password dan konfirmasi password tidak boleh berbeda' ]); $user = Auth::user(); if ($user->password == bcrypt(request('password_old'))){ $user->password = bcrypt(request('password')); $user->save(); Alert::success('Success', 'Password berhasil diganti'); } else { Alert::error('Error', 'Password lama salah'); } return redirect()->route('reset'); } }
true
f1e28b5a0e7d50018621ec1b666734dc9f32e47e
PHP
honewatson/config_test
/api/router_page.php
UTF-8
3,968
2.625
3
[]
no_license
<?php namespace api; /* class */ class router_page { public $page_folder; public $route_bits; public $factory; public $request; public $class_name; public $request_type = null; public $route_bits_size = null; public $routes = null; public $routes_location = null; public $params = null; public function __construct($config){ $this->page_folder = $config['page_folder']; $this->route_bits = $config['sub_route_bits']; $this->factory = $config['factory']; $this->request = $config['request']; $this->set_request_type(); if($config['class_name'] !== null) $this->class_name = $this->request_type."_{$config['class_name']}"; else $this->class_name = $this->request_type."_index"; } public function route(){ if($this->route_bits_size = sizeof($this->route_bits)) return $this->parse_params(); else return $this->return_config( $this->page_folder, $this->get_class_name_namespace()); } public function return_config($page_folder, $class_name, $params = array(), $config_class = 'api\folder_params'){ return array('class' => $class_name , "config" => new $config_class( $page_folder, $params, $this->class_name) ); } public function parse_params() { $this->set_route_location(); $this->set_routes(); $this->set_class_name(); $this->set_params(); return $this->return_config( $this->page_folder, $this->get_class_name_namespace(), $this->params ); } public function get_params(){ if($this->params === null) $this->set_params(); return $this->params; } public function set_params(){ $routes = $this->routes; $route_bits = $this->route_bits; if(isset($routes[$this->class_name])) { $params = $routes[$this->class_name]; if(sizeof($params) < $this->route_bits_size) { $this->params = array("404" => "Array of Request URI has more parameters than is set in routes config for this page."); } else { $count = 0; $parsed_params = new \stdClass; foreach($route_bits as $value) { $parsed_params->{$params[$count]} = $value; $count++; } $this->params = $parsed_params; } } else { $this->params = array("404" => "$this->class_name is not in $this->page_folder get_routes"); } } public function get_class_name_namespace(){ return "$this->page_folder\controllers\\$this->class_name"; } public function set_class_name(){ $route_bits = $this->route_bits; $routes = $this->routes; $class_name_or_main = $this->request_type."_".array_shift($route_bits); if(isset($routes[$class_name_or_main])) $this->class_name = $class_name_or_main; else $this->class_name = $this->request_type."_main"; } public function set_routes(){ $this->routes = $this->factory->get_loader()->load_array($this->routes_location); } public function set_route_location(){ $request_type = $this->request_type; $this->routes_location = "$this->page_folder\\{$request_type}_routes"; } public function set_request_type(){ $request = $this->request; if(sizeof($request::$_post)) $this->request_type = 'post'; else $this->request_type = 'get'; } }
true
b251f8078cf781e0c9636ac6df94edb267c79d96
PHP
sschepis-zuul/xchain
/app/Handlers/XChain/Network/Bitcoin/BitcoinBlockEventBuilder.php
UTF-8
1,327
2.53125
3
[]
no_license
<?php namespace App\Handlers\XChain\Network\Bitcoin; use Nbobtc\Bitcoind\Bitcoind; use Tokenly\LaravelEventLog\Facade\EventLog; use \Exception; /* * BitcoinBlockEventBuilder */ class BitcoinBlockEventBuilder { public function __construct(Bitcoind $bitcoind) { $this->bitcoind = $bitcoind; } public function buildBlockEventData($block_hash) { try { // get the full block data from bitcoind $block = $this->bitcoind->getblock($block_hash, true); if (!$block) { throw new Exception("Block not found for hash $block_hash", 1); } // convert to array $block = json_decode(json_encode($block), true); // create the event data $event_data = []; $event_data['network'] = 'bitcoin'; $event_data['hash'] = $block['hash']; $event_data['height'] = $block['height']; $event_data['previousblockhash'] = $block['previousblockhash']; $event_data['time'] = $block['time']; $event_data['tx'] = $block['tx']; return $event_data; } catch (Exception $e) { EventLog::logError('block', $e, ['hash' => $block_hash]); throw $e; } } }
true
ab6452b8768cae7d96a3b0a276daca845a40c0b0
PHP
renandoring/aula5-conceito-heranca
/Pessoa.class.php
UTF-8
410
3.5625
4
[]
no_license
<?php class Pessoa{ public $nome; public $idade; public $telefone; public $endereco; function __construct($nome,$idade,$telefone,$endereco){ $this->nome = $nome; $this->idade = $idade; $this->telefone = $telefone; $this->endereco = $endereco; } public function andar(){ $this->nome; $this->idade; $this->telefone; $this->endereco; echo $this->nome. ", esta andando."."\n"; } } ?>
true
08d532e89bc594d899bc158cff66b4f815bfb14e
PHP
elyasnoui/PC_Potion_Project
/PC Potion Project/contact.php
UTF-8
14,962
2.53125
3
[]
no_license
<?php // Start the session session_start(); $_SESSION['fnameErr'] = $_SESSION['lnameErr'] = $_SESSION['phoneErr'] = $_SESSION['emailErr'] = $_SESSION['rUsernameErr'] = $_SESSION['rPasswordErr'] = $_SESSION['lUsernameErr'] = $_SESSION['lPasswordErr'] = $_SESSION['dateErr'] = $_SESSION['timeErr'] = ""; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="description" content= "Highly specialised custom water-cooled PCs. Build the PC of your dreams!"> <meta name="keywords" content="Gaming, PC, Custom Loop, Water Cooling, Loop, Water"> <meta name="author" content="Elyas Noui"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" type="image/x-icon" href="logo.ico"> <link rel="stylesheet" href="styleSheet.css?v=<?php echo time(); ?>"> <title>PC Potion</title> </head> <body id="contact"> <?php require_once "connection.php"; $usernameErr = $_SESSION['cUsernameErr']; $emailErr = $_SESSION['cEmailErr']; $topicErr = $_SESSION['topicErr']; $messageErr = $_SESSION['messageErr']; $username = $email = $topic = $message = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $_SESSION['cUsernameErr'] = $_SESSION['cEmailErr'] = $_SESSION['topicErr'] = $_SESSION['messageErr'] = ""; $errors = 0; $username = test_input($_POST['username']); if (empty($_POST["username"]) || !preg_match("/^[a-zA-Z0-9-_]{5,20}$/",$username)) { $_SESSION['cUsernameErr'] = "Must be only numbers and letters with no spaces"; $errors++; } $email = test_input($_POST['email']); if (empty($_POST["email"]) || !preg_match("/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/",$email)) { $_SESSION['cEmailErr'] = "Must be in email format"; $errors++; } $topic = test_input($_POST['topic']); if (empty($_POST["topic"]) || !preg_match("/[^\r\n]+((\r|\n|\r\n)[^\r\n]+)*/g",$topic) && !(strlen($topic) >= 5 && strlen($topic) <= 20)) { $_SESSION['topicErr'] = "Must be only numbers and letters with no spaces (5-20)"; $errors++; } $message = test_input($_POST['message']); if (empty($_POST["message"]) || !preg_match("/[^\r\n]+((\r|\n|\r\n)[^\r\n]+)*/g",$message) && !(strlen($message) >= 20 && strlen($message) <= 500)) { $_SESSION['messageErr'] = "Must be only numbers and letters with no spaces (20-500)"; $errors++; } if ($errors > 0) { header('Location: '.$_SERVER['REQUEST_URI']); exit(); } $query = "SELECT username FROM Users WHERE username = '$username'"; $result = $db->query($query); if ($result->num_rows == 0) { $_SESSION['cUsernameErr'] = $username." does not exist"; $errors++; } else { if (isset($_SESSION['username'])) { if ($username != $_SESSION['username']) { $_SESSION['cUsernameErr'] = $username." does not match your username"; $errors++; } } else { $_SESSION['cUsernameErr'] = "You are not logged in"; $errors++; } } if ($errors > 0) { header('Location: '.$_SERVER['REQUEST_URI']); exit(); } $sendTo = "elyas.noui@city.ac.uk"; $headers[] = 'MIME-Version: 1.0'; $headers[] = 'Content-type: text/html; charset=iso-8859-1'; $headers[] = 'To: PC Potion <'.$sendTo.'>'; $headers[] = 'From: '.$username.' <'.$email.'>'; //Help using: https://www.php.net/manual/en/function.mail.php if (mail($sendTo, $topic, $message, implode("\r\n", $headers))) echo "<script>alert('Email sent!');</script>"; else echo "<script>alert('Not sent.');</script>"; } //IN1010 Session 6 page 66 function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <div class="container" id="top"> <div class="header"> <!-- Logo: https://www.freelogodesign.org/ --> <a href="index.php"><img class="logo" src="logo.png" alt="Logo"></a> <a href="index.php"><img class="business-name" src="title.png" alt="Business Name"></a> </div> <div class="nav"> <br> <a class="in-nav" href="index.php">Home</a> <a class="in-nav" href="about.php">About</a> <a class="in-nav" href="contact.php" id="selected">Contact</a> <div class="booking"><a class="in-nav" href="booking.php">Booking</a></div> <div class="nav-list"> <button onclick="drop()">&#9776;</button> <div class="in-list" id="dropdown"> <a href="index.php">Home</a> <a href="about.php">About</a> <a href="contact.php">Contact</a> <div class="booking"><a href="booking.php">Booking</a></div> </div> </div> <a href="login.php" class="nav-login">Login</a> <a href="account.php" class="nav-user"></a> </div> </div> <div class="article" id="contact"> <img id="hero-img" src="contact_img.png"> <h1 id="img-text">CONTACT</h1> </div> <div class="container"><p id="contact">Fill out the contact form to get in touch with us. By submitting a form, you will automatically book an appointment for one of our team members to get in touch to discuss further. We aim to respond to general enquires in 1-2 business days.</p></div> <div class="container" id="contact-form"> <div class="c-info"> <h3>Info</h3> <p2>Address: Northampton Square, Clerkenwell, London, EC1V 0HB</p2> <br> <br> <p2>Email: elyas.noui@city.ac.uk</p2> <br> <br> <p2>Phone: 020 7040 5060</p2> <br> <br> <p2>Opening Hours:</p2> <br> <p2>Mon-Sat: 9am-6pm</p2> </div> <div class="c-form"> <div class="div-form"> <h3>Contact</h3> <div class="errors"> <p class="alert" id="username-guide">*Usernames must be 5-15 characters long.</p> <br> <p class="alert" id="email-guide">*Please enter a valid email.</p> <br> <p class="alert-topic">*Topics must be 5-20 characters long</p> <p class="alert-topic">with no special characters.</p> <br> <p class="alert-message">*Messages must be 20-500 characters long</p> <p class="alert-message">with no special characters.</p> </div> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" onsubmit="return valCon()"> <span class="error" id="php"><?php echo $usernameErr;?></span><br>Username:<br><input class="validate" type="text" name="username" maxlength="15" value=""><span class="error">*</span><p class="alert" id="username"><i>Invalid Entry</i></p> <br> <br> <span class="error" id="php"><?php echo $emailErr;?></span><br>Email:<br><input class="validate" type="text" name="email" maxlength="50" value=""><span class="error">*</span><p class="alert" id="email"><i>Invalid Entry</i></p> <br> <br> <span class="error" id="php"><?php echo $topicErr;?></span><br>Topic:<br><input class="validate" type="text" name="topic" maxlength="20" value=""><span class="error">*</span><p class="alert" id="topic"><i>Invalid Entry</i></p> <br> <br> <span class="error" id="php"><?php echo $messageErr;?></span><br>Message:<br><textarea class="validate" type="text" name="message" maxlength="500"></textarea><span class="error">*</span><p class="alert" id="message"><i>Invalid<br>Entry</i></p> <br> <br> <input class="button" type="submit" value="Submit"> <p>Haven't signed in?</p> <p><a href="login.php" class="p-link">LOGIN</a>/<a href="register.php" class="p-link">REGISTER</a> </form> </div> </div> </div> <div class="container" id="contact"> <div class="footer"> <p>Copyright © 2020 PC Potion</p> <p><strong>Follow us on Social Media!</strong></p> <!-- FB Icon: https://www.flaticon.com/free-icon/instagram_733558?term=instagram&page=1&position=2 --> <a href="https://www.facebook.com/" target="_blank"><img src="facebook.png" style="width:4vw; min-width: 25px; max-width: 35px; padding: 1%;"></a> <!-- Twitter Icon: https://www.flaticon.com/free-icon/twitter_2111688?term=twitter&page=1&position=25 --> <a href="https://twitter.com/" target="_blank"><img src="twitter.png" style="width:4vw; min-width: 25px; max-width: 35px; padding: 1%;"></a> <!-- Instagram Icon: https://www.flaticon.com/free-icon/facebook_733547?term=facebook&page=1&position=1 --> <a href="https://www.instagram.com/" target="_blank"><img src="instagram.png" style="width:4vw; min-width: 25px; max-width: 35px; padding: 1%;"></a> <p><u>DISCLAIMER</u>: PC Potion is a fictitious brand created solely for the purpose of the assessment of IN1010 module at City, University of London, UK. All products and people associated with PC Potion are also fictitious. Any resemblance to real brands, products, or people is purely coincidental. Information provided about the product is also fictitious and should not be construed to be representative of actual products on the market in a similar product category. </p> <p>Author: Elyas Noui 190053026</p> <br> </div> </div> </body> <script> var arr = document.getElementsByClassName("validate"); var errorList = document.querySelectorAll(".errors p"); //Email Regex: https://stackoverflow.com/questions/7635533/validate-email-address-textbox-using-javascript/7635734 var email = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/; function drop() { var menu = document.getElementById('dropdown'); if (menu.style.display == 'none') menu.style.display = 'block'; else menu.style.display = 'none'; } function valCon() { this.val = true; for (i=0; i<this.errorList.length; i++) this.errorList[i].style.display = 'none'; for (i=0; i<this.arr.length; i++) { if (this.arr[i].name == "username" && !/^[a-zA-Z0-9-]{5,20}$/.test(this.arr[i].value)) { document.getElementById("username-guide").style.display = "block"; document.getElementById(this.arr[i].name).style.display = "inline"; this.val = false; } //Alert if not in email format if (this.arr[i].name == "email" && (!email.test(this.arr[i].value) || this.arr[i].value.length > 50)) { document.getElementById("email-guide").style.display = "block"; document.getElementById(this.arr[i].name).style.display = "inline"; this.val = false; } if (this.arr[i].name == "topic" && !/[^\r\n]+((\r|\n|\r\n)[^\r\n]+)*/g.test(this.arr[i].value) && !(this.arr[i].value.length >= 5 && this.arr[i].value.length <= 20)) { document.getElementsByClassName("alert-topic")[0].style.display = "block"; document.getElementsByClassName("alert-topic")[1].style.display = "block"; document.getElementById(this.arr[i].name).style.display = "inline"; this.val = false; } if (this.arr[i].name == "message" && !this.arr[i].value.match(/[^\r\n]+((\r|\n|\r\n)[^\r\n]+)*/g) && !(this.arr[i].value.length >= 5 && this.arr[i].value.length <= 500)){ document.getElementsByClassName("alert-message")[0].style.display = "block"; document.getElementsByClassName("alert-message")[1].style.display = "block"; document.getElementById(this.arr[i].name).style.display = "inline"; this.val = false; } } return this.val; } function signedIn(username) { document.getElementsByClassName("nav-login")[0].style.display = "none"; document.getElementsByClassName("nav-user")[0].style.display = "inline"; document.getElementsByClassName("nav-user")[0].innerHTML = username; document.getElementsByClassName("booking")[0].style.display = "inline"; document.getElementsByClassName("booking")[1].style.display = "inline"; } </script> <?php if (isset($_SESSION['username'])) { $username = $_SESSION['username']; echo "<script> signedIn('$username'); </script>"; } ?> </html>
true
7ebc00dd22dc701462612a403771b016ed0e0706
PHP
cornejong/blackdoor-util
/src/Traits/MagicObjectAccessWithGettersAndSetters.php
UTF-8
2,993
3.296875
3
[]
no_license
<?php /* * File: MagicObjectAccess.php * Project: Blackdoor\Util\Traits * File Created: Tuesday, 24th March 2020 8:55:52 pm * Author: Corné de Jong (corne@tearo.eu) * ------------------------------------------------------------ * Copyright 2019 - 2020 SouthCoast */ namespace Blackdoor\Util\Traits; /** * Trait implementing a simple version of __get,__set, __isset & __unset * * Required is to specify a container pointer: * - protected $containerPointer = '{The name of the variable that you want to access}'; * * Also it will check if there are getters or setters defined for the offset. * Additionally it will check for 'has{Offset}' and 'unset{Offset}' methods in __isset and __unset respectively */ trait MagicObjectAccessWithGettersAndSetters { // protected $containerPointer; /** * Get a data by offset * * @param string The key data to retrieve * @access public */ public function __get($offset) { if (empty($this->containerPointer ?? null)) { throw new \Exception('No container pointer provided!', 1); } $getter = 'get' . ucfirst($offset); if (method_exists($this, $getter)) { return call_user_func([$this, $getter]); } return $this->{$this->containerPointer}[$offset] ?? null; } /** * Assigns a value to the specified data * * @param string The data key to assign the value to * @param mixed The value to set * @access public */ public function __set($offset, $value) { if (empty($this->containerPointer ?? null)) { throw new \Exception('No container pointer provided!', 1); } $setter = 'set' . ucfirst($offset); if (method_exists($this, $setter)) { return call_user_func([$this, $setter], $value); } return $this->{$this->containerPointer}[$offset] = $value; } /** * Whether or not an data exists by key * * @param string An data key to check for * @access public * @return boolean */ public function __isset($offset) { if (empty($this->containerPointer ?? null)) { throw new \Exception('No container pointer provided!', 1); } $method = 'has' . ucfirst($offset); if (method_exists($this, $method)) { return call_user_func([$this, $method]); } return isset($this->{$this->containerPointer}[$offset]); } /** * Unsets an data by key * * @param string The key to unset * @access public */ public function __unset($offset) { if (empty($this->containerPointer ?? null)) { throw new \Exception('No container pointer provided!', 1); } $method = 'unset' . ucfirst($offset); if (method_exists($this, $method)) { return call_user_func([$this, $method]); } unset($this->{$this->containerPointer}[$offset]); } }
true
51e2f69221acf0c27212ac741807da389771ecfa
PHP
l396635210/study
/htdocs/src/AppBundle/Entity/Category.php
UTF-8
590
2.53125
3
[]
no_license
<?php namespace AppBundle\Entity; use DBAL\ORM\Entity; class Category extends Entity{ protected $title = ['type'=>'char', 'length'=>40, 'comment'=>'标题']; protected $status = ['type'=>'bool', 'comment'=>'状态']; protected $descr = ['type'=>'varchar', 'comment'=>'描述']; protected $createTime = ['type'=>'timestamp', 'comment'=>'创建时间']; protected $createUser = ['type'=>'int', 'comment'=>'创建人']; protected $updateTime = ['type'=>'timestamp', 'comment'=>'修改时间']; protected $updateUser = ['type'=>'int', 'comment'=>'修改人']; }
true
3aed7c1c70cc47896009767cab00f381303b393f
PHP
ciampa-davide/php-snacks-blocco-1
/PHP-snack-1.php
UTF-8
2,058
2.890625
3
[]
no_license
<!-- PHP Snack 1: Creiamo un array 'matches' contenente altri array i quali rappresentano delle partite di basket di un’ipotetica tappa del calendario. Ogni array della partita avrà una squadra di casa e una squadra ospite, punti fatti dalla squadra di casa e punti fatti dalla squadra ospite. Stampiamo a schermo tutte le partite con questo schema: Olimpia Milano - Cantù | 55 - 60 --> <?php $matches = [ "03-01-2021" => [ "firstMatch" =>[ "casa" => "Milano", "ospite"=>"Roma", "puntiCasa"=> 80, "puntiOspite"=> 84 ], "secondMatch" =>[ "casa"=>"Napoli", "ospite"=>"Bari", "puntiCasa"=>75, "puntiOspite"=>96 ], "thirdMatch" =>[ "casa" => "Cagliari", "ospite" => "Torino", "puntiCasa" => 54, "puntiOspite" => 36 ] ] ]; ?> <!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>Snack 1</title> </head> <body> <h1>Partite del 03/01/2021</h1> <p>Prima partita</p> <p><?php echo $matches["03-01-2021"]["firstMatch"]["casa"]." - ".$matches["03-01-2021"]["firstMatch"]["ospite"]." | ". $matches["03-01-2021"]["firstMatch"]["puntiCasa"]." - ".$matches["03-01-2021"]["firstMatch"]["puntiOspite"]; ?></p> <p>Seconda Partita</p> <p><?php echo $matches["03-01-2021"]["secondMatch"]["casa"]." - ".$matches["03-01-2021"]["secondMatch"]["ospite"]." | ". $matches["03-01-2021"]["secondMatch"]["puntiCasa"]." - ".$matches["03-01-2021"]["secondMatch"]["puntiOspite"]; ?></p> <p>Terza Partita</p> <p><?php echo $matches["03-01-2021"]["thirdMatch"]["casa"]." - ".$matches["03-01-2021"]["thirdMatch"]["ospite"]." | ". $matches["03-01-2021"]["thirdMatch"]["puntiCasa"]." - ".$matches["03-01-2021"]["thirdMatch"]["puntiOspite"]; ?></p> </body> </html>
true
687dc37c9855409bd927894b8f4b7ba7e32cda79
PHP
Saadique/AOMS_Oasis_back_end
/app/Services/Service.php
UTF-8
1,200
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Services; use App\Mail\PasswordIssuer; use App\Traits\ApiResponser; use DateTime; use Illuminate\Support\Facades\Mail; class Service { use ApiResponser; // protected $serviceGateway; /** * Service constructor. */ // public function __construct(ServiceGateway $serviceGateway) // { // $this->serviceGateway = $serviceGateway; // } public function TimeIsBetweenTwoTimes($from, $till, $input) { $f = DateTime::createFromFormat('H:i:s', $from); $t = DateTime::createFromFormat('H:i:s', $till); $i = DateTime::createFromFormat('H:i:s', $input); if ($f > $t) $t->modify('+1 day'); return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t); } public function check_time_overlap($start_time1, $end_time1, $start_time2, $end_time2) { return (($start_time1) <= ($end_time2) && ($start_time2) < ($end_time1) ? true : false); } public function sendPasswordMail($email,$username, $password) { $data = [ 'username'=> $username, 'password'=>$password ]; Mail::to($email)->send(new PasswordIssuer($data)); } }
true
7686b4468a231fcd265e931cd11ad1be9edf1460
PHP
AlchemicA/MateriaArchive
/Data/Collection.php
UTF-8
491
3
3
[]
no_license
<?php namespace Materia\Data; /** * Collection interface * * @package Materia.Data * @author Filippo "Pirosauro" Bovo * @link http://lab.alchemica.it/materia/ **/ interface Collection extends \Iterator, \Countable { /** * Returns collection's type * * @return string class name or NULL if not defined (empty collection) **/ public function getType(); /** * Reverse the order of the elements **/ public function reverse(); }
true
556c72577ed3321f09fe40f0c96a291ec971c610
PHP
camachogfelipe/imaginamos
/incolacteos/business/model/Dbform_news.db.php
UTF-8
1,080
2.578125
3
[]
no_license
<?php /* * @file : Dbform_news.db.php * @brief : Clase para la interaccion con la tabla form_news * @version : 3.3 * @ultima_modificacion: 2013-07-11 * @author : Ruben Dario Cifuentes Torres * @generated : Generador DAO vercion 1.1 * * @class: Dbform_news * @brief: Clase para la interaccion con la tabla form_news */ class Dbform_news extends DbDAO { public $id = NULL; protected $nombre = NULL; protected $correo = NULL; protected $suscripcion = NULL; public function setid($mData = NULL) { if ($mData === NULL) { $this->id = NULL; } $this->id = StripHtml($mData); } public function setnombre($mData = NULL) { if ($mData === NULL) { $this->nombre = NULL; } $this->nombre = StripHtml($mData); } public function setcorreo($mData = NULL) { if ($mData === NULL) { $this->correo = NULL; } $this->correo = StripHtml($mData); } public function setsuscripcion($mData = NULL) { if ($mData === NULL) { $this->suscripcion = NULL; } $this->suscripcion = StripHtml($mData); } } ?>
true
508cba5021eb5ef922b89fa92a483bd6ffde4bc9
PHP
rollerworks-graveyard/datagrid
/src/Column/CompoundColumn.php
UTF-8
1,505
2.578125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /* * This file is part of the RollerworksDatagrid package. * * (c) Sebastiaan Stok <s.stok@rollerscapes.net> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Rollerworks\Component\Datagrid\Column; use Rollerworks\Component\Datagrid\DatagridView; use Rollerworks\Component\Datagrid\Exception\BadMethodCallException; class CompoundColumn extends Column { private $columns = []; public function createHeaderView(DatagridView $datagrid): HeaderView { if (!$this->locked || !$this->columns) { throw new BadMethodCallException( 'Cannot be create a headerView, the Column is not properly configured.' ); } return parent::createHeaderView($datagrid); } public function createCellView(HeaderView $header, $object, $index): CellView { if (!$this->locked || !$this->columns) { throw new BadMethodCallException( 'Cannot be create a cellView, the Column is not properly configured.' ); } return parent::createCellView($header, $object, $index); } /** * @param ColumnInterface[] $columns */ public function setColumns(array $columns) { $this->columns = $columns; $this->locked = true; } /** * @return ColumnInterface[] */ public function getColumns(): array { return $this->columns; } }
true
0bd7890d5df4acf96e6a86ffccd26d9d0c4e44bc
PHP
netphonetech/WeeklyReport
/user_activation.php
UTF-8
1,001
2.546875
3
[]
no_license
<?php require_once('dbconnection.php'); print_r($user); $message = ''; $type = ''; if (isset($_POST['id']) && $_POST['id']!='') { $id = $_POST['id']; if ($id == $user['Id']) { $message = 'You can\'t disable your account!'; $type = 'fail'; } else{ if (isset($_POST['activate'])) { $sql = "UPDATE user SET status=1 WHERE Id='$id'"; if ($mysqli->query($sql)) { $message = 'Successful activated user'; $type = 'success'; } else { $message = 'Something went wrong, refresh and try again!'; $type = 'fail'; } }else if(isset($_POST['deactivate'])) { $sql = "UPDATE user SET status=0 WHERE Id='$id'"; if ($mysqli->query($sql)) { $message = 'Successful deactivated user'; $type = 'success'; } else { $message = 'Something went wrong, refresh and try again!'; $type = 'fail'; } } } } else{ $message = 'Something went wrong, refresh and try again!'; $type = 'fail'; } return header("location: viewUsers.php?message=$message&type=$type");
true
bcb6c19b47ea33a9241f1db3ea40677750097661
PHP
milyass/Camagru
/www/app/models/User.php
UTF-8
8,090
2.9375
3
[ "MIT" ]
permissive
<?php class User { private $db; public function __construct(){ $this->db = new Database; } // Regsiter user public function register($data){ $hash = md5(rand(0,1000)); $this->db->query('INSERT INTO users (name, email, password, token) VALUES(:name, :email, :password, :token)'); // Bind values $this->db->bind(':name', strtolower($data['name'])); $this->db->bind(':email', strtolower($data['email'])); $this->db->bind(':password', $data['password']); $this->db->bind(':token', $hash); // sendig verif email $to = $data['email']; $subject = 'Signup verification'; $message = ' <center> <h1 style="font-family:verdana;">Welcome To '.SITENAME.'</h1> <p style="font-family:verdana;"> Hello Thanks for signing up <b> Mr '.strtolower($data['name']).'</b> Your account has been created<br> you can login with your credentials after you have activated your account clicking the url below:<br> <a target="_blank" style="color:#46C6C6" href="'.URLROOT.'/users/verify?hash='.$hash.'">Click here</a> </p> </center>'; $headers = 'From:noreply@camagru.ma'."\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; // Execute if($this->db->execute() && mail($to,$subject,$message,$headers)){ return true; } else { return false; } } // Login User public function login($email, $password){ $this->db->query('SELECT * FROM users WHERE email = :email'); $this->db->bind(':email', $email); $row = $this->db->single(); $hashed_password = $row->password; if(password_verify($password, $hashed_password)){ return $row; } else { return false; } } // Find user by email public function findUserByEmail($email){ $this->db->query('SELECT * FROM users WHERE email = :email'); // Bind value $this->db->bind(':email', $email); $row = $this->db->single(); // Check row if($this->db->rowCount() > 0){ return true; } else { return false; } } // find user by name public function findUserByName($name){ $this->db->query('SELECT * FROM users WHERE name = :name'); // Bind value $this->db->bind(':name', $name); $row = $this->db->single(); // Check row if($this->db->rowCount() > 0){ return true; } else { return false; } } // verification email public function verify($hash){ /// verify in database token == hash $this->db->query('SELECT id, token FROM users WHERE token=:token AND active = 0'); $this->db->bind(':token',$hash); if($row = $this->db->fetcher()){ $this->db->query('UPDATE users SET active = 1, token = 0 WHERE id=:id'); $this->db->bind(':id',$row['id']); if($this->db->execute()){ return true; } else { return false; } } else return false; } // reset mail request public function reset($email){ $hash = md5(rand(0,1000)); $this->db->query('UPDATE users SET reset=:hash WHERE email=:email'); $this->db->bind(':email',$email); $this->db->bind(':hash',$hash); if($this->db->execute()){ $to = $email; $subject = 'Reset password request'; $message = ' <center> <h1 style="font-family:verdana;">Reset Password</h1> <p style="font-family:verdana;"> Hello You have Requested a password reset<br> if you ignore this message your password wont be changed<br> if you want to reset your password follow the link below:<br> <a target="_blank" style="color:#46C6C6" href="'.URLROOT.'/users/forgot/'.$hash.'">Click here</a> </p> </center>'; $headers = 'From:noreply@camagru.ma'."\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; if(mail($to,$subject,$message,$headers)){ return true; } else return false; } else return false; } // check if user active by email public function isActive($email){ $this->db->query('SELECT * FROM users WHERE email = :email'); $this->db->bind(':email', $email); if($row = $this->db->fetcher()){ if($row['active'] == 1){ return true; }else{ return false; } } else return false; } // verify user by hash and see if hes active public function verifyUserbyHash($hash){ $this->db->query('SELECT * FROM users WHERE reset=:hash'); $this->db->bind(':hash', $hash); if($row = $this->db->fetcher()){ if($row['active'] == 1){ return true; }else{ return false; } } else return false; } // forgot password => changing password public function forgot($data){ // $this->db->query('UPDATE users SET password=:password WHERE reset=:token'); $this->db->bind(':token', $data['hash']); $this->db->bind(':password', $data['password']); // Execute if($this->db->execute()){ return true; } else{ return false; } } // edit user info public function editinfo($data,$id){ //UPDATE users SET name=:name, email=:email WHERE id=:id $this->db->query("UPDATE users SET name=:name, email=:email WHERE id=:id"); $this->db->bind(':name', $data['name']); $this->db->bind(':email', $data['email']); $this->db->bind(':id', $id); if($this->db->execute()){ return true; } else{ return false; } } public function chpwd($data,$id){ $this->db->query('UPDATE users SET password=:newpwd WHERE id=:id'); $this->db->bind(':newpwd', $data['Newpassword']); $this->db->bind(':id', $id); $to = $data['email']; $subject = 'Password Change'; $message = ' <center> <h1 style="font-family:verdana;">Hello from '.SITENAME.'</h1> <p style="font-family:verdana;"> Hello '.$data['name'].'</b> Your Password has been changed<br> you can login with your new password right now if it was not you please reset password using the link bellow<br> <a target="_blank" style="color:#46C6C6" href="'.URLROOT.'/users/reset">Click here</a> </p> </center>'; $headers = 'From:noreply@camagru.ma'."\r\n"; $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n"; if($this->db->execute() && mail($to,$subject,$message,$headers)){ return true; } else{ return false; } } public function findUserByid($id){ $this->db->query("SELECT name FROM users WHERE id = :id"); $this->db->bind(':id', $id); $results = $this->db->resultSet(); return $results; } // toggle notication public function isNotified($uid){ $this->db->query("SELECT notification FROM users WHERE id=:id"); $this->db->bind(':id',$uid); if($row = $this->db->fetcher()){ if($row['notification'] == 1) return true; else return false; } else return false; } public function notify($uid,$value){ $this->db->query("UPDATE users SET notification = :value WHERE id=:id"); $this->db->bind(':id',$uid); $this->db->bind(':value',$value); if($this->db->execute()) return true; else return false; } public function isDark($uid){ $this->db->query("SELECT darkmode FROM users WHERE id=:id"); $this->db->bind(':id',$uid); if($row = $this->db->fetcher()){ if($row['darkmode'] == 1) return true; else return false; } else return false; } public function Dark($uid,$value){ $this->db->query("UPDATE users SET darkmode = :value WHERE id=:id"); $this->db->bind(':id',$uid); $this->db->bind(':value',$value); if($this->db->execute()) return true; else return false; } //END }
true
ac143d102cc86cc94815ae642e6346183bee4833
PHP
syzngroup/json-api
/src/Contracts/Repositories/ErrorsRepositoryInterface.php
UTF-8
327
2.546875
3
[]
no_license
<?php namespace Syzn\JsonApi\Contracts\Repositories; use Syzn\JsonApi\Contracts\EncodableJsonApiStructureInterface; use Syzn\JsonApi\Contracts\ErrorInterface; interface ErrorsRepositoryInterface extends EncodableJsonApiStructureInterface { public function all(): array; public function add(ErrorInterface $error); }
true
169f4aa2ad789c4f61c34762e535a615a2567b62
PHP
devBPI/WebService-InterfaceTest
/utils/xmlUtils.php
UTF-8
1,074
2.875
3
[]
no_license
<?php function xmlEscape($string) { return str_replace(array('&', '<', '>', '\'', '"'), array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;'), $string); } function array_to_xml($data, &$xml_data) { foreach($data as $key => $value) { if(is_numeric($key)) { $key = 'item'.$key; //dealing with <0/>..<n/> issues } if(is_array($value)) { $subnode = $xml_data->addChild($key); array_to_xml($value, $subnode); } else { $xml_data->addChild("$key",htmlspecialchars("$value")); } } } function array_to_xml_main($mainname, $data) { if(!$mainname || $mainname=="") return NULL; /*$xml_data = new SimpleXMLElement('<?xml version="1.0"?><'.$mainname.'></'.$mainname.'>');*/ $xml_data = new SimpleXMLElement('<'.$mainname.'></'.$mainname.'>'); array_to_xml($data,$xml_data); return $xml_data; } function xml_adopt($root, $new) { $node = $root->addChild($new->getName(), (string) $new); foreach($new->attributes() as $attr => $value) { $node->addAttribute($attr, $value); } foreach($new->children() as $ch) { xml_adopt($node, $ch); } }
true
cdb2f0cea1d550f89ddd3a74a61795a0910f9f15
PHP
phpmathan/zampphp
/plugins/Zamp/Request.php
UTF-8
28,146
2.8125
3
[ "MIT" ]
permissive
<?php namespace Zamp; class Request extends Base { const CONTENT_TYPE_URL = 1; const CONTENT_TYPE_STRING = 2; const CONTENT_TYPE_IMAGE = 3; // Character set public $charset = 'UTF-8'; // Random Hash for protecting URLs protected $_xss_hash; // Generates the XSS hash if needed and returns it public function xssHash() { if($this->_xss_hash === null) $this->_xss_hash = bin2hex(random_bytes(16)); return $this->_xss_hash; } // Do Never Allowed protected function _doNeverAllowed($str) { $neverAllowedStr = [ 'document.cookie' => '[removed]', '(document).cookie' => '[removed]', 'document.write' => '[removed]', '(document).write'=> '[removed]', '.parentNode' => '[removed]', '.innerHTML' => '[removed]', '-moz-binding' => '[removed]', '<!--' => '&lt;!--', '-->' => '--&gt;', '<![CDATA[' => '&lt;![CDATA[', '<comment>' => '&lt;comment&gt;', '<%' => '&lt;&#37;' ]; $neverAllowedRegex = [ 'javascript\s*:', '(\(?document\)?|\(?window\)?(\.document)?)\.(location|on\w*)', 'expression\s*(\(|&\#40;)', // CSS and IE 'vbscript\s*:', // IE, surprise! 'wscript\s*:', // IE 'jscript\s*:', // IE 'vbs\s*:', // IE 'Redirect\s+30\d', "([\"'])?data\s*:[^\\1]*?base64[^\\1]*?,[^\\1]*?\\1?" ]; $str = str_replace(array_keys($neverAllowedStr), $neverAllowedStr, $str); foreach($neverAllowedRegex as $regex) $str = preg_replace('#'.$regex.'#is', '[removed]', $str); return $str; } // Compact Exploded Words. Remove whitespace from things like 'j a v a s c r i p t' protected function _compactExplodedWords($matches) { return preg_replace('/\s+/s', '', $matches[1]).$matches[2]; } /** * XSS Clean * * Sanitizes data so that Cross Site Scripting Hacks can be * prevented. This method does a fair amount of work but * it is extremely thorough, designed to prevent even the * most obscure XSS attempts. Nothing is ever 100% foolproof, * of course, but I haven't been able to get anything passed * the filter. * * Note: Should only be used to deal with data upon submission. * It's not something that should be used for general runtime processing. */ public function xssClean($str, $contentType=1) { // Is the string an array? if((array) $str === $str) { while(list($key) = each($str)) $str[$key] = $this->xssClean($str[$key], $contentType); return $str; } if($str === null || $str === true || $str === false) return $str; // Remove Invisible Characters $str = Security::removeInvisibleCharacters($str); /* * URL Decode * * Just in case stuff like this is submitted: * * <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a> * * Note: Use rawurldecode() so it does not remove plus signs */ if($contentType === self::CONTENT_TYPE_URL && (stripos($str, '%') !== false)) { do { $oldstr = $str; $str = rawurldecode($str); $str = preg_replace_callback('#%(?:\s*[0-9a-f]){2,}#i', [$this, '_urlDecodeSpaces'], $str); } while($oldstr !== $str); unset($oldstr); } /* * Convert character entities to ASCII * * This permits our tests below to work reliably. * We only convert entities that are within tags since * these are the ones that will pose security problems. */ $str = preg_replace_callback("/[^a-z0-9>]+[a-z0-9]+=([\'\"]).*?\\1/si", [$this, '_convertAttribute'], $str); if($contentType !== self::CONTENT_TYPE_STRING) $str = preg_replace_callback('/<\w+.*/si', [$this, '_decodeEntity'], $str); // Remove Invisible Characters Again! $str = Security::removeInvisibleCharacters($str); /* * Convert all tabs to spaces * * This prevents strings like this: ja vascript * NOTE: we deal with spaces between characters later. * NOTE: preg_replace was found to be amazingly slow here on * large blocks of data, so we use str_replace. */ $str = str_replace("\t", ' ', $str); // Capture converted string for later comparison $converted_string = $str; // Remove Strings that are never allowed $str = $this->_doNeverAllowed($str); /* * Makes PHP tags safe * * Note: XML tags are inadvertently replaced too: * * <?xml * * But it doesn't seem to pose a problem. */ if($contentType === self::CONTENT_TYPE_IMAGE) { // Images have a tendency to have the PHP short opening and // closing tags every so often so we skip those and only // do the long opening tags. $str = preg_replace('/<\?(php)/i', '&lt;?\\1', $str); } else { $str = str_replace(['<?', '?'.'>'], ['&lt;?', '?&gt;'], $str); } /* * Compact any exploded words * * This corrects words like: j a v a s c r i p t * These words are compacted back to their correct state. */ $words = [ 'javascript', 'expression', 'vbscript', 'jscript', 'wscript', 'vbs', 'script', 'base64', 'applet', 'alert', 'document', 'write', 'cookie', 'window', 'confirm', 'prompt', 'eval' ]; foreach($words as $word) { $word = implode('\s*', str_split($word)).'\s*'; // We only want to do this when it is followed by a non-word character // That way valid stuff like "dealer to" does not become "dealerto" $str = preg_replace_callback('#('.substr($word, 0, -3).')(\W)#is', [$this, '_compactExplodedWords'], $str); } /* * Remove disallowed Javascript in links or img tags * We used to do some version comparisons and use of stripos(), * but it is dog slow compared to these simplified non-capturing * preg_match(), especially if the pattern exists in the string * * Note: It was reported that not only space characters, but all in * the following pattern can be parsed as separators between a tag name * and its attributes: [\d\s"\'`;,\/\=\(\x00\x0B\x09\x0C] * ... however, Security::removeInvisibleCharacters() above already strips the * hex-encoded ones, so we'll skip them below. */ do { $original = $str; if(preg_match('/<a/i', $str)) $str = preg_replace_callback('#<a(?:rea)?[^a-z0-9>]+([^>]*?)(?:>|$)#si', [$this, '_jsLinkRemoval'], $str); if(preg_match('/<img/i', $str)) $str = preg_replace_callback('#<img[^a-z0-9]+([^>]*?)(?:\s?/?>|$)#si', [$this, '_jsImgRemoval'], $str); if(preg_match('/script|xss/i', $str)) $str = preg_replace('#</*(?:script|xss).*?>#si', '[removed]', $str); } while($original !== $str); unset($original); /* * Sanitize naughty HTML elements * * If a tag containing any of the words in the list * below is found, the tag gets converted to entities. * * So this: <blink> * Becomes: &lt;blink&gt; */ $pattern = '#' .'<((?<slash>/*\s*)((?<tagName>[a-z0-9]+)(?=[^a-z0-9]|$)|.+)' // tag start and name, followed by a non-tag character .'[^\s\042\047a-z0-9>/=]*' // a valid attribute character immediately after the tag would count as a separator // optional attributes .'(?<attributes>(?:[\s\042\047/=]*' // non-attribute characters, excluding > (tag close) for obvious reasons .'[^\s\042\047>/=]+' // attribute characters // optional attribute-value .'(?:\s*=' // attribute-value separator .'(?:[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*))' // single, double or non-quoted value .')?' // end optional attribute-value group .')*)' // end optional attributes group .'[^>]*)(?<closeTag>\>)?#isS'; // Note: It would be nice to optimize this for speed, BUT // only matching the naughty elements here results in // false positives and in turn - vulnerabilities! do { $old_str = $str; $str = preg_replace_callback($pattern, [$this, '_sanitizeNaughtyHtml'], $str); } while($old_str !== $str); unset($old_str); /* * Sanitize naughty scripting elements * * Similar to above, only instead of looking for * tags it looks for PHP and JavaScript commands * that are disallowed. Rather than removing the * code, it simply converts the parenthesis to entities * rendering the code un-executable. * * For example: eval('some code') * Becomes: eval&#40;'some code'&#41; */ $str = preg_replace( '#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', '\\1\\2&#40;\\3&#41;', $str ); $str = preg_replace( '#(alert|prompt|confirm|cmd|passthru|eval|exec|expression|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)`(.*?)`#si', '\\1\\2&#96;\\3&#96;', $str ); // Final clean up // This adds a bit of extra precaution in case // something got through the above filters $str = $this->_doNeverAllowed($str); /* * Images are Handled in a Special Way * - Essentially, we want to know that after all of the character * conversion is done whether any unwanted, likely XSS, code was found. * If not, we return TRUE, as the image is clean. * However, if the string post-conversion does not matched the * string post-removal of XSS, then it fails, as there was unwanted XSS * code found and removed/changed during processing. */ if($contentType === self::CONTENT_TYPE_IMAGE) return $str === $converted_string; return $str; } // Sanitize Naughty HTML protected function _sanitizeNaughtyHtml($matches) { static $naughty_tags = [ 'alert', 'area', 'prompt', 'confirm', 'applet', 'audio', 'basefont', 'base', 'behavior', 'bgsound', 'blink', 'body', 'embed', 'expression', 'form', 'frameset', 'frame', 'head', 'html', 'ilayer', 'iframe', 'input', 'button', 'select', 'isindex', 'layer', 'link', 'meta', 'keygen', 'object', 'plaintext', 'style', 'script', 'textarea', 'title', 'math', 'video', 'svg', 'xml', 'xss' ]; static $evil_attributes = [ 'on\w+', 'style', 'xmlns', 'formaction', 'form', 'xlink:href', 'FSCommand', 'seekSegmentTime' ]; // First, escape unclosed tags if(empty($matches['closeTag'])) return '&lt;'.$matches[1]; // Is the element that we caught naughty? If so, escape it elseif(in_array(strtolower($matches['tagName']), $naughty_tags, true)) return '&lt;'.$matches[1].'&gt;'; // For other tags, see if their attributes are "evil" and strip those elseif(isset($matches['attributes'])) { // We'll store the already fitlered attributes here $attributes = []; // Attribute-catching pattern $attributes_pattern = '#' .'(?<name>[^\s\042\047>/=]+)' // attribute characters // optional attribute-value .'(?:\s*=(?<value>[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))' // attribute-value separator .'#i'; // Blacklist pattern for evil attribute names $is_evil_pattern = '#^('.implode('|', $evil_attributes).')$#i'; // Each iteration filters a single attribute do { // Strip any non-alpha characters that may preceed an attribute. // Browsers often parse these incorrectly and that has been a // of numerous XSS issues we've had. $matches['attributes'] = preg_replace('#^[^a-z]+#i', '', $matches['attributes']); if(!preg_match($attributes_pattern, $matches['attributes'], $attribute, PREG_OFFSET_CAPTURE)) { // No (valid) attribute found? Discard everything else inside the tag break; } if( // Is it indeed an "evil" attribute? preg_match($is_evil_pattern, $attribute['name'][0]) // Or does it have an equals sign, but no value and not quoted? Strip that too! || (trim($attribute['value'][0]) === '') ) { $attributes[] = 'xss=removed'; } else { $attributes[] = $attribute[0][0]; } $matches['attributes'] = substr($matches['attributes'], $attribute[0][1] + strlen($attribute[0][0])); } while($matches['attributes'] !== ''); $attributes = empty($attributes) ? '' : ' '.implode(' ', $attributes); return '<'.$matches['slash'].$matches['tagName'].$attributes.'>'; } return $matches[0]; } // HTML Entity Decode Callback protected function _decodeEntity($match) { // Protect GET variables in URLs // 901119URL5918AMP18930PROTECT8198 $match = preg_replace('|\&([a-z\_0-9\-]+)\=([a-z\_0-9\-/]+)|i', $this->xssHash().'\\1=\\2', $match[0]); // Decode, then un-protect URL GET vars return str_replace( $this->xssHash(), '&', $this->entityDecode($match, $this->charset) ); } // URL-decode taking spaces into account protected function _urlDecodeSpaces($matches) { $input = $matches[0]; $nospaces = preg_replace('#\s+#', '', $input); return ($nospaces === $input) ?$input :rawurldecode($nospaces); } /** * HTML Entities Decode * * A replacement for html_entity_decode() * * The reason we are not using html_entity_decode() by itself is because * while it is not technically correct to leave out the semicolon * at the end of an entity most browsers will still interpret the entity * correctly. html_entity_decode() does not convert entities without * semicolons, so we are left with our own little solution here. Bummer. */ public function entityDecode($str, $charset=null) { if(strpos($str, '&') === false) return $str; static $_entities; if(!isset($charset)) $charset = $this->charset; $flag = ENT_COMPAT | ENT_HTML5; if(!isset($_entities)) $_entities = array_map('strtolower', get_html_translation_table(HTML_ENTITIES, $flag, $charset)); do { $str_compare = $str; // Decode standard entities, avoiding false positives if(preg_match_all('/&[a-z]{2,}(?![a-z;])/i', $str, $matches)) { $replace = []; $matches = array_unique(array_map('strtolower', $matches[0])); foreach($matches as &$match) { if(($char = array_search($match.';', $_entities, true)) !== false) { $replace[$match] = $char; } } $str = str_replace(array_keys($replace), array_values($replace), $str); } // Decode numeric & UTF16 two byte entities $str = html_entity_decode( preg_replace('/(&#(?:x0*[0-9a-f]{2,5}(?![0-9a-f;])|(?:0*\d{2,4}(?![0-9;]))))/iS', '$1;', $str), $flag, $charset ); } while($str_compare !== $str); return $str; } // Filters tag attributes for consistency and safety protected function _filterAttributes($str) { $out = ''; if(preg_match_all('#\s*[a-z\-]+\s*=\s*(\042|\047)([^\\1]*?)\\1#is', $str, $matches)) { foreach($matches[0] as $match) { $out .= preg_replace('#/\*.*?\*/#s', '', $match); } } return $out; } /** * JS Link Removal * * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in * PHP 5.2+ on link-heavy strings. */ protected function _jsLinkRemoval($match) { return str_replace( $match[1], preg_replace( '#href=.*?(?:(?:alert|prompt|confirm)(?:\(|&\#40;)|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|d\s*a\s*t\s*a\s*:)#si', '', $this->_filterAttributes($match[1]) ), $match[0] ); } /** * JS Image Removal * * This limits the PCRE backtracks, making it more performance friendly * and prevents PREG_BACKTRACK_LIMIT_ERROR from being triggered in * PHP 5.2+ on image tag heavy strings. */ protected function _jsImgRemoval($match) { return str_replace( $match[1], preg_replace( '#src=.*?(?:(?:alert|prompt|confirm|eval)(?:\(|&\#40;)|javascript:|livescript:|mocha:|charset=|window\.|document\.|\.cookie|<script|<xss|base64\s*,)#si', '', $this->_filterAttributes($match[1]) ), $match[0] ); } // Attribute Conversion protected function _convertAttribute($match) { return str_replace(array('>', '<', '\\'), array('&gt;', '&lt;', '\\\\'), $match[0]); } // Fetch the IP Address public function ipAddress(&$proxyIp=null) { if(isset($this->ipAddress)) { $proxyIp = $this->ipAddress['proxyIp']; return $this->ipAddress['realIp']; } $ipSourceList = [ 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_X_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR' ]; foreach($ipSourceList as $ip) { if(isset($_SERVER[$ip])) { $matched = $ip; $realIp = $_SERVER[$ip]; break; } } $proxyIp = $_SERVER['REMOTE_ADDR']; if($realIp == $proxyIp) $proxyIp = null; else { $realIp = str_replace(';', ',', $realIp); $realIp = explode(',', $realIp); $temp = []; foreach($realIp as $ip) { $ip = trim($ip); if(!$ip || !filter_var($ip, FILTER_VALIDATE_IP)) continue; $temp[$ip] = 1; } $realIp = key($temp); unset($temp[$realIp]); if($temp) { $temp[$proxyIp] = 1; $proxyIp = implode(', ', array_keys($temp)); } } $this->ipAddress = [ 'realIp' => $realIp, 'proxyIp' => $proxyIp ]; return $realIp; } // Is ajax request public function isAjax() { return ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ); } // Is request from CLI public function isCli() { return NEXT_LINE != '<br/>'; } // Is post request? public function isPost() { return $_SERVER['REQUEST_METHOD'] === 'POST'; } // Return clients user agent information public function userAgent() { if(isset($this->userAgent)) return $this->userAgent; $this->userAgent = isset($_SERVER['HTTP_USER_AGENT']) ?$this->xssClean($_SERVER['HTTP_USER_AGENT']) :''; return $this->userAgent; } // This is a helper function to retrieve values from global arrays private function _grubGlobalArray(&$array, $name='', $xssClean=false, $contentType=1) { if(!isset($array[$name])) return; if($xssClean) return $this->arrayXssClean($array[$name], $contentType); return $array[$name]; } // Apply XSS filter for parsed input public function arrayXssClean($data, $contentType=1) { if((array) $data === $data) { $new_data = []; foreach($data as $key => $value) $new_data[$key] = ((array) $value === $value) ?$this->arrayXssClean($value, $contentType) :$this->xssClean($value, $contentType); return $new_data; } else return $this->xssClean($data, $contentType); } // Fetch an item from the COOKIE array public function cookie($name='', $xssClean=true) { if($name) { if(!isset($_COOKIE[$name])) return null; if(!$xssClean) return $_COOKIE[$name]; if(!isset($this->cookie_data[$name])) $this->cookie_data[$name] = $this->_grubGlobalArray($_COOKIE, $name, $xssClean); return $this->cookie_data[$name]; } else { if(!$xssClean) return $_COOKIE; $this->cookie_data = $this->arrayXssClean($_COOKIE); return $this->cookie_data; } } // Fetch an item from the POST array public function post($name='', $xssClean=true) { if($name) { if(!isset($_POST[$name])) return null; if(!$xssClean) return $_POST[$name]; if(!isset($this->post_data[$name])) $this->post_data[$name] = $this->_grubGlobalArray($_POST, $name, $xssClean, self::CONTENT_TYPE_STRING); return $this->post_data[$name]; } else { if(!$xssClean) return $_POST; $this->post_data = $this->arrayXssClean($_POST, self::CONTENT_TYPE_STRING); return $this->post_data; } } private function _server($name) { $replaceBack = []; if( $name == 'REQUEST_URI' || $name == 'QUERY_STRING' || $name == 'HTTP_REFERER' ) { $replaceBack = [ '%26' => '~26', // & '%2B' => '~2B', // + '%3F' => '~3F', // ? '%2F' => '~2F', // / '%7E' => '~7E', // ~ '%3A' => '~3A', // : '%5C' => '~5C', // \ '%3D' => '~3D', // = '%40' => '~40', // @ '%23' => '~23', // # ]; $replaceBack = [array_keys($replaceBack), $replaceBack]; } $serverData = $_SERVER[$name]; if($serverData !== null) { $patterns = [ '~([\?\&]?)%0[aAdD][^&\?]*~' => '\\1', '~\?&+~' => '?', '~&{2,}~' => '&', ]; $serverData = preg_replace(array_keys($patterns), $patterns, $serverData); if($replaceBack) $serverData = str_replace($replaceBack[0], $replaceBack[1], $serverData); $serverData = $this->xssClean($serverData, self::CONTENT_TYPE_URL); if($replaceBack) $serverData = str_replace($replaceBack[1], $replaceBack[0], $serverData); } return $this->server_data[$name] = $serverData; } // Fetch an item from the SERVER array public function server($name='', $xssClean=true) { if($name) { if(!isset($_SERVER[$name])) return null; if(!$xssClean) return $_SERVER[$name]; if(isset($this->server_data[$name])) return $this->server_data[$name]; return $this->_server($name); } else { if(!$xssClean) return $_SERVER; foreach($_SERVER as $name => $value) $this->_server($name); return $this->server_data; } } // Fetch an item from the GET array public function get($name=null) { $query = Core::system()->bootInfo('query'); if($name !== null) return $query[$name] ?? null; else return $query; } // Get request body public function body() { return file_get_contents('php://input'); } // Set get method data dynamically public function setGet($name, $value) { $query = $this->get(); $query[$name] = $value; Core::system()->bootInfoSet('query', $query); } // Fetch an item from either the POST or GET public function getParam($name='', $xssClean=true) { if(!isset($_POST[$name])) return $this->get($name); else return $this->post($name, $xssClean); } // Get get query url with or without numeric index public function getQueryUrl($includeNumericIndex=true, $argSeparator="&", $getData=[]) { $getQueryUrl = ''; if(!$getData) $getData = $this->get(); if((array) $getData === $getData) { ksort($getData, SORT_STRING); $queryParams = []; foreach($getData as $k => $v) { if(!is_numeric($k)) $queryParams[$k] = $v; elseif($includeNumericIndex) $getQueryUrl .= "$v/"; } $getQueryUrl = rtrim($getQueryUrl, '/'); if($queryParams) $getQueryUrl .= '?'.http_build_query($queryParams, '', $argSeparator); } return $getQueryUrl; } } /* END OF FILE */
true