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
3a699b6b041115048856521b3ff18ae643941644
PHP
vakata/database
/tests/DB.php
UTF-8
9,377
2.71875
3
[ "MIT" ]
permissive
<?php namespace vakata\database\test; use vakata\database\DB as DBI; abstract class DB extends \PHPUnit\Framework\TestCase { protected static $db = null; abstract protected function getConnectionString(); protected function getDB() { if (!static::$db) { $connection = $this->getConnectionString(); static::$db = new DBI($connection); $this->importFile(static::$db, __DIR__ . '/data/' . basename(explode('://', $connection)[0]) . '.sql'); } return static::$db; } protected function importFile(DBI $dbc, string $path) { $sql = file_get_contents($path); $sql = str_replace("\r", '', $sql); $sql = preg_replace('(--.*\n)', '', $sql); $sql = preg_replace('(\n+)', "\n", $sql); $sql = explode(';', $sql); foreach (array_filter(array_map("trim", $sql)) as $q) { $dbc->query($q); } } public function testDriver() { $db = new DBI($this->getConnectionString()); $this->assertEquals(true, $db->test()); $db = new DBI('mysql://user:invalid@unknown/error'); $this->assertEquals(false, $db->test()); } public function testCreate() { $this->assertEquals(true, $this->getDB() instanceof DBI); } public function testInsertId() { $this->assertEquals(1, $this->getDB()->query('INSERT INTO log (lvl) VALUES(?)', ['error'])->insertID()); $this->assertEquals(2, $this->getDB()->query('INSERT INTO log (lvl) VALUES(?)', ['warning'])->insertID()); } public function testAffected() { $this->assertEquals(1, $this->getDB()->query('INSERT INTO log (lvl) VALUES(?)', ['debug'])->affected()); $this->assertEquals(2, $this->getDB()->query('UPDATE log SET lvl = ?', ['debug'])->affected()); $this->assertEquals(1, $this->getDB()->query('DELETE FROM log WHERE id = ?', [3])->affected()); } public function testCount() { $this->assertEquals(2, count($this->getDB()->query('SELECT * FROM log'))); $this->assertEquals(1, count($this->getDB()->query('SELECT * FROM log WHERE id = 2'))); $this->assertEquals(0, count($this->getDB()->query('SELECT * FROM log WHERE id = 3'))); } public function testExpand() { $this->assertEquals(2, count($this->getDB()->query('SELECT * FROM log WHERE id IN (??)', [[1,2,3]]))); $this->assertEquals(1, count($this->getDB()->query('SELECT * FROM log WHERE id IN (??)', [1,3]))); $this->assertEquals( 2, count($this->getDB()->query('SELECT * FROM log WHERE id > ? AND id IN (??) AND id < ?', [0, [1,2,3], 4])) ); $this->assertEquals( 2, count( $this->getDB()->query( 'SELECT * FROM log WHERE id > ? AND (id IN (??) OR id IN (??)) AND id < ?', [0, [1,2,3], [1,2,3], 4] ) ) ); } public function testPrepare() { $q1 = $this->getDB()->prepare('SELECT id FROM log WHERE id = ?'); $q2 = $this->getDB()->prepare('SELECT lvl FROM log WHERE id = ?'); $q3 = $this->getDB()->prepare('INSERT INTO log (lvl) VALUES (?)'); $q4 = $this->getDB()->prepare('UPDATE log SET lvl = ? WHERE id = ?'); $q5 = $this->getDB()->prepare('DELETE FROM log WHERE id = ?'); $this->assertEquals('debug', $q2->execute([1])->toArray()[0]['lvl']); $this->assertEquals(4, $q3->execute(['error'])->insertID()); $this->assertEquals(1, $q4->execute(['error', 1])->affected()); $this->assertEquals(5, $q3->execute(['error'])->insertID()); $this->assertEquals(1, $q1->execute([1])->toArray()[0]['id']); $this->assertEquals(2, $q1->execute([2])->toArray()[0]['id']); $this->assertEquals('error', $q2->execute([4])->toArray()[0]['lvl']); $this->assertEquals(1, $q4->execute(['warning', 5])->affected()); $this->assertEquals(0, $q5->execute([10])->affected()); $this->assertEquals(1, $q5->execute([4])->affected()); } public function testToArray() { $this->assertEquals( [], $this->getDB()->query('SELECT * FROM log WHERE id IN (??)', [[10,20]])->toArray() ); $this->assertEquals( [['id' => 1, 'lvl' => 'error']], $this->getDB()->query('SELECT id, lvl FROM log WHERE id IN (??)', [[1]])->toArray() ); $this->assertEquals( [['id' => 1, 'lvl' => 'error'], ['id' => 2, 'lvl' => 'debug']], $this->getDB()->query('SELECT id, lvl FROM log WHERE id IN (??)', [[1, 2]])->toArray() ); $this->assertEquals( [['id' => 1], ['id' => 2]], $this->getDB()->query('SELECT id FROM log WHERE id IN (??)', [[1, 2]])->toArray() ); } public function testAll() { $this->assertEquals( [], $this->getDB()->all('SELECT * FROM log WHERE id IN (??)', [[10,20]]) ); $this->assertEquals( [['id' => 1, 'lvl' => 'error']], $this->getDB()->all('SELECT id, lvl FROM log WHERE id IN (??)', [[1]]) ); $this->assertEquals( [['id' => 1, 'lvl' => 'error'], ['id' => 2, 'lvl' => 'debug']], $this->getDB()->all('SELECT id, lvl FROM log WHERE id IN (??)', [[1, 2]]) ); $this->assertEquals( [ 1 => ['id' => 1, 'lvl' => 'error'], 2 => ['id' => 2, 'lvl' => 'debug']], $this->getDB()->all('SELECT id, lvl FROM log WHERE id IN (??)', [[1, 2]], 'id') ); $this->assertEquals( [1 => 'error', 2 => 'debug'], $this->getDB()->all('SELECT id, lvl FROM log WHERE id IN (??)', [[1, 2]], 'id', true) ); $this->assertEquals( [1, 2], $this->getDB()->all('SELECT id FROM log WHERE id IN (??)', [[1, 2]]) ); $this->assertEquals( [['id' => 1 ], ['id' => 2]], $this->getDB()->all('SELECT id FROM log WHERE id IN (??)', [[1, 2]], null, false, false) ); } public function testOne() { $this->assertEquals( null, $this->getDB()->one('SELECT * FROM log WHERE id IN (??)', [[10,20]]) ); $this->assertEquals( ['id' => 1, 'lvl' => 'error'], $this->getDB()->one('SELECT id, lvl FROM log WHERE id IN (??)', [[1]]) ); $this->assertEquals( ['id' => 1, 'lvl' => 'error'], $this->getDB()->one('SELECT id, lvl FROM log WHERE id IN (??)', [[1, 2]]) ); $this->assertEquals( 1, $this->getDB()->one('SELECT id FROM log WHERE id IN (??)', [[1, 2]]) ); $this->assertEquals( ['id' => 1 ], $this->getDB()->one('SELECT id FROM log WHERE id IN (??)', [[1, 2]], false) ); } public function testMode() { $connection = $this->getConnectionString(); $connection .= (strpos($connection, '?') ? '&' : '?') . 'mode=strtoupper'; $this->assertEquals( [ ['ID' => 1 ], ['ID' => 2] ], (new DBI($connection))->all('SELECT id FROM log WHERE id IN (??)', [[1, 2]], null, false, false) ); } public function testGet() { $data = $this->getDB()->get('SELECT id, lvl FROM log WHERE id IN (??)', [1,2], 'id', true); $cnt = 0; foreach ($data as $k => $v) { $cnt ++; } $this->assertEquals(2, $cnt); $cnt = 0; foreach ($data as $k => $v) { $cnt ++; } $this->assertEquals(2, $cnt); $this->assertEquals(2, count($data)); $this->assertEquals(true, isset($data[1])); $this->assertEquals(false, isset($data[10])); $this->assertEquals('error', $data[1]); } public function testGetSingle() { $temp = []; foreach (self::$db->get('SELECT id FROM log WHERE id IN (1,2)') as $v) { $temp[] = $v; } $this->assertEquals([1,2], $temp); } public function testTransaction() { $this->getDB()->begin(); $this->assertEquals(6, $this->getDB()->query('INSERT INTO log (lvl) VALUES(?)', ['debug'])->insertID()); $this->getDB()->rollback(); $this->assertEquals(true, $this->getDB()->one('SELECT MAX(id) FROM log') < 6); $this->getDB()->begin(); $this->assertEquals(true, $this->getDB()->query('INSERT INTO log (lvl) VALUES(?)', ['debug'])->insertID() > 5); $this->getDB()->commit(); $this->assertEquals(true, $this->getDB()->one('SELECT MAX(id) FROM log') > 5); } public function testSerialize() { // no exception should be thrown $data = $this->getDB()->get('SELECT * FROM grps'); json_encode($data); $this->assertEquals(true, strlen(serialize($data)) > 0); } public function testStream() { $handle = fopen('php://memory', 'w'); fwrite($handle, 'asdf'); rewind($handle); $id = $this->getDB()->query('INSERT INTO log (lvl, request) VALUES(??)', ['debug', $handle])->insertID(); fclose($handle); $this->assertEquals('asdf', self::$db->one('SELECT request FROM log WHERE id = ?', $id)); } }
true
8b513ec41fcc29d55d46ab97704cbfdb70c72b91
PHP
heidelpay/woocommerce-heidelpay
/vendor/heidelpay/php-payment-api/tests/Helper/Constraints/ArraysMatchConstraint.php
UTF-8
3,249
2.953125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Heidelpay\Tests\PhpPaymentApi\Helper\Constraints; use PHPUnit\Util\InvalidArgumentHelper; class ArraysMatchConstraint extends \PHPUnit_Framework_Constraint { /** * @var array */ protected $value; /** * @var boolean */ protected $strict; /** * @var bool */ private $count; /** @var string $failureMessage */ private $failureMessage; /** * @param array $value * @param bool $count * @param bool $strict * * @throws \PHPUnit\Framework\Exception */ public function __construct($value, $count = false, $strict = false) { parent::__construct(); if (!\is_array($value)) { throw InvalidArgumentHelper::factory(1, 'array'); } if (!\is_bool($count)) { throw InvalidArgumentHelper::factory(2, 'boolean'); } if (!\is_bool($strict)) { throw InvalidArgumentHelper::factory(3, 'boolean'); } $this->value = $value; $this->strict = $strict; $this->count = $count; } /** * Evaluates the constraint for parameter $other. Returns true if the * constraint is met, false otherwise. * * This method can be overridden to implement the evaluation algorithm. * * @param mixed $other Value or object to evaluate. * * @return bool */ public function matches($other) { if (!is_array($other)) { return false; } foreach ($this->value as $key => $value) { if (!array_key_exists($key, $other)) { $this->failureMessage = "Expected key: '" . $key . "' " . 'is missing'; return false; } $keys_match = true; if ($this->strict) { if ($other[$key] !== $value) { $keys_match = false; } } else { /** @noinspection TypeUnsafeComparisonInspection */ if ($other[$key] != $value) { $keys_match = false; } } if (!$keys_match) { $this->failureMessage = "Key: '" . $key . "' => '" . $other[$key] . "' " . "does not match expected value: '" . $value . "'"; return false; } } if ($this->count) { $diff = array_diff_key($other, $this->value); if (count($diff) > 0) { $this->failureMessage = 'The array contains the following key/s, which is/are not expected: ' . implode(', ', array_keys($diff)); return false; } } return true; } /** * Returns a string representation of the object. * * @return string */ public function toString() { $ret_val = 'matches expected Array ('; foreach ($this->value as $key => $value) { $ret_val .= "\n\t '" . $key . " => '" . $value . "'"; } $ret_val .= "\n]"; if (!empty($ret_val)) { $ret_val .= "\n" . $this->failureMessage; } return $ret_val; } }
true
60db30cd6baefc9e69f58b191c477a8910126ca1
PHP
EdmilsonFerreiraF/Rede-IMA
/uploads/newpub.php
UTF-8
761
2.53125
3
[]
no_license
<?php $file_error = false; $title = $_GET['title']; $content = $_GET['content']; // Get input data and add to body.php //$ok = file_put_contents('body.php', $resultado, FILE_APPEND); ob_start(); echo "<h2 class='sections-4__title'>".$title."</h2><br/>"; echo "<p class='sections__text'>".$content."</p><br/></div>"; if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "<img src='".$target_file."' class='sections__image'><br/></div>"; } $resultado = ob_get_contents(); $ok = file_put_contents('../body.php', $resultado, FILE_APPEND); if ($ok) { print 'O arquivo foi salvo com sucesso.<br>'; } else { print 'Ocorreu um erro. Verifique as permissões. <br/>'; } header("refresh:5;url=../../profile.php?"); ?> <div> </div>
true
f3f22ee340244b1b775a06436ea744dfc102e1cb
PHP
Dukecz/Nubium
/webroot/nubium/app/authenticators/DatabaseAuthenticator.php
UTF-8
879
2.984375
3
[]
no_license
<?php declare(strict_types=1); namespace App\authenticators; use Nette\Database\Context; use Nette\Security\AuthenticationException; use Nette\Security\IAuthenticator; use Nette\Security\Identity; use function password_verify; class DatabaseAuthenticator implements IAuthenticator { /** @var Context */ private $database; public function __construct(Context $database) { $this->database = $database; } public function authenticate(array $credentials): Identity { list($username, $password) = $credentials; $row = $this->database->table('users') ->where('username', $username)->fetch(); if (!$row) { throw new AuthenticationException('User not found.'); } if (!password_verify($password, $row->password)) { throw new AuthenticationException('Invalid password.'); } return new Identity($row->id, null, ['username' => $row->username]); } }
true
2353a1d060ce2d7a13f7ca4dd667dd59629ebf4c
PHP
htmlacademy-yii/1415187-task-force-1
/frontend/models/SignupForm.php
UTF-8
2,795
2.625
3
[]
permissive
<?php namespace frontend\models; use Yii; use app\models\User; use yii\base\Model; /** * Signup form */ class SignupForm extends Model { public $name; public $email; public $city; public $password; public function attributeLabels(): array { return [ 'email' => 'Электронная почта', 'name' => 'Ваше имя', 'city' => 'Город проживания', 'password' => 'Пароль' ]; } public function rules(): array { return [ [['email', 'name', 'city', 'password'], 'safe'], [['email'], 'required', 'message' => 'Введите Ваш адрес электронной почты'], [['name'], 'required', 'message' => 'Введите Ваши имя и фамилию'], [['city'], 'required', 'message' => 'Укажите город, чтобы находить подходящие задачи'], [['password'], 'required', 'message' => 'Введите Ваш пароль'], ['email', 'trim'], ['email', 'email', 'message' => 'Введите валидный адрес электронной почты'], ['email', 'string', 'max' => User::MAX_STRING_LENGTH], ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'Пользователь с таким email уже существует'], ['name', 'string', 'max' => self::MAX_STRING_LENGTH], ['password', 'string', 'min' => \Yii::$app->params['user.passwordMinLength'], 'tooShort' => 'Длина пароля от 8 символов до ' . User::MAX_PASSWORD_LENGTH . ' символов'], ['password', 'string', 'max' => User::MAX_PASSWORD_LENGTH, 'tooLong' => 'Длина пароля от 8 символов до ' . User::MAX_PASSWORD_LENGTH . ' символов'], ]; } public function signup(): ?bool { if (!$this->validate()) { return null; } $user = new User(); $user->name = $this->name; $user->email = $this->email; $user->city_id = $this->city; $user->password = Yii::$app->security->generatePasswordHash($this->password); return $user->save(); } protected function sendEmail($user): bool { return Yii::$app ->mailer ->compose( ['html' => 'emailVerify-html', 'text' => 'emailVerify-text'], ['user' => $user] ) ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot']) ->setTo($this->email) ->setSubject('Account registration at ' . Yii::$app->name) ->send(); } }
true
4bf51d074ac06196e2d5920a08c2240012b8cec9
PHP
10yung/ADB-project2
/app/Repository/AdminRepo.php
UTF-8
274
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Repository; use Illuminate\Support\Facades\DB; class AdminRepo { public static function getAdminByUserID($userID){ $admin = DB::table('Admin') ->where('userID', '=',$userID) ->first(); return $admin; } }
true
8d7f32a3aaffda1b122f7b774f722a2d688901cf
PHP
firebao/weidomall
/application/index/model/Area.php
UTF-8
4,493
2.546875
3
[ "Apache-2.0" ]
permissive
<?php // +---------------------------------------------------------------------- // | WeiDo // +---------------------------------------------------------------------- // | Copyright (c) 2015 All rights reserved. // +---------------------------------------------------------------------- // | @Author: 围兜工作室 <318348750@qq.com> // +---------------------------------------------------------------------- // | @Version: v1.0 // +---------------------------------------------------------------------- // | @Desp: Area模型模块 // +---------------------------------------------------------------------- namespace app\index\model; use think\Model; use think\Request; use think\Config; use think\Session; class Area extends Model{ protected $table = "tp_area"; /** * 定位所在城市 * @access public * @return integer $areaID2 */ public function getDefaultCity() { //请求信息中是否包含所在城市id,如没有默认为0 $request = Request::instance(); $areaId2 = $request->post('city/d', 0); //保存的会话信息中是否包含所在城市id if($areaId2 == 0) { $areaId2 = $request->session('areaId2/d'); } //检验城市有效性 if($areaId2 > 0) { $map['isShow'] = 1; $map['areaFlag'] = 1; $map['areaType'] = 1; $map['areaId'] = $areaId2; $result = $this->where($map)->field('areaId')->find(); if ($result['areaId'] == '') { $areaId2 = 0; } } else { $areaId2 = $request->cookie('areaId2/d'); } //还未获得所在城市id,从网站配置中得到默认城市id if($areaId2 == 0) { $areaId2 = (int)Config::get('site.defaultCity'); } //保存所在城市id到session Session::set('areaId2', $areaId2); return $areaId2; } /** * 获取区域信息 * @access public * @param integer $areaId区域ID * @return object 区域信息 */ public function getArea($areaId) { $map['areaFlag'] = 1; $map['isShow'] = 1; $map['areaId'] = $areaId; return $this->where($map)->find()->getData(); } /** * 获取省份列表 * @access public * @param * @return array 区域信息 */ public function getProvinceList() { $result = array(); $map['isShow'] = 1; $map['areaFlag'] = 1; $map['areaType'] = 0; //0表示省份 $list = $this->where($map)->cache('WEIDO_CACHE_CITY_001', 31536000)->field('areaId,areaName')->order('parentId, areaSort')->select(); foreach ($list as $value){ $result[$value->getData('areaId')] = $value->getData(); } return $result; } /** * 获取所有城市,根据字母分类 * @access public * @param * @return array 分类城市信息 */ public function getCityGroupByKey() { $result = array(); $map['isShow'] = 1; $map['areaFlag'] = 1; $map['areaType'] = 1; //1表示城市 $list = $this->where($map) ->cache('WEIDO_CACHE_CITY_000', 31536000) ->field('areaId,areaName,areaKey') ->order('areaKey, areaSort') ->select(); foreach ($list as $value){ $result[$value->getData('areaKey')][] = $value->getData(); } return $result; } /** * 通过省份获取城市列表 * @access public * @param $provinceId 0 省份ID * @return array 所属省份的城市信息 */ public function getCityListByProvince($provinceId = 0) { $result = array(); $map['isShow'] = 1; $map['areaFlag'] = 1; $map['areaType'] = 1; $map['parentId'] = $provinceId; $list = $this->where($map) ->cache('WEIDO_CACHE_CITY_002'.$provinceId, 31536000) ->field('areaId,areaName') ->order('parentId,areaSort') ->select(); foreach ($list as $value){ $result[] = $value->getData(); } return $result; } }
true
ee4037cec2b10f9fcf5dd233577e3afedaca8666
PHP
lyrixx/twitter-sdk
/Twitter/Tests/OAuthTest.php
UTF-8
4,109
2.640625
3
[ "MIT" ]
permissive
<?php namespace Lyrixx\Twitter\Tests; use Lyrixx\Twitter\OAuth; /** * OAuthTest. * * All results and fixture values come from * https://dev.twitter.com/docs/auth/creating-signature * * @author Grégoire Pineau <lyrixx@lyrixx.info> */ class OAuthTest extends \PHPUnit_Framework_TestCase { private $method; private $url; private $parameters; private $oauth; public function setUp() { $this->method = 'POST'; $this->url = 'https://api.twitter.com/1/statuses/update.json'; $this->parameters = array( 'status' => 'Hello Ladies + Gentlemen, a signed OAuth request!', 'include_entities' => true, 'oauth_nonce' => 'kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg', // Have to harcode it because it's a generated random value 'oauth_timestamp' => '1318622958', // Have to harcode it because it's a generated timed value ); $consumerKey = 'xvz1evFS4wEEPTGEFPHBog'; $accessToken = '370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb'; $consumerSecret = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw'; $accessTokenSecret = 'LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE'; $this->oAuth = new OAuth($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret); } public function testGenerateAuthorizationHeader() { $result = $this->oAuth->generateAuthorizationHeader($this->method, $this->url, $this->parameters); $expected = 'OAuth oauth_consumer_key="xvz1evFS4wEEPTGEFPHBog", oauth_nonce="kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg", oauth_signature="tnnArxj06cWHq44gCs1OSKk%2FjLY%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318622958", oauth_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb", oauth_version="1.0"'; $this->assertSame($expected, $result); } public function testGenerateSignature() { $object = new \ReflectionObject($this->oAuth); $method = $object->getMethod('generateSignature'); $method->setAccessible(true); $result = $method->invokeArgs($this->oAuth, array($this->method, $this->url, $this->parameters)); $expected = 'tnnArxj06cWHq44gCs1OSKk/jLY='; $this->assertSame($expected, $result); } public function testGenerateSigninKey() { $object = new \ReflectionObject($this->oAuth); $method = $object->getMethod('generateSigningKey'); $method->setAccessible(true); $result = $method->invokeArgs($this->oAuth, array()); $expected = 'kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw&LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE'; $this->assertSame($expected, $result); } public function testGenerateSigningString() { $object = new \ReflectionObject($this->oAuth); $method = $object->getMethod('generateSigningString'); $method->setAccessible(true); $result = $method->invokeArgs($this->oAuth, array($this->method, $this->url, $this->parameters)); $expected = 'POST&https%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&include_entities%3Dtrue%26oauth_consumer_key%3Dxvz1evFS4wEEPTGEFPHBog%26oauth_nonce%3DkYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1318622958%26oauth_token%3D370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb%26oauth_version%3D1.0%26status%3DHello%2520Ladies%2520%252B%2520Gentlemen%252C%2520a%2520signed%2520OAuth%2520request%2521'; $this->assertSame($expected, $result); } public function testEncodeParameters() { $object = new \ReflectionObject($this->oAuth); $method = $object->getMethod('encodeParameters'); $method->setAccessible(true); $result = $method->invokeArgs($this->oAuth, array($this->parameters)); $expected = 'include_entities=true&oauth_consumer_key=xvz1evFS4wEEPTGEFPHBog&oauth_nonce=kYjzVBB8Y0ZFabxSWbWovY3uYSQ2pTgmZeNu2VS4cg&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1318622958&oauth_token=370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMZeS9weJAEb&oauth_version=1.0&status=Hello%20Ladies%20%2B%20Gentlemen%2C%20a%20signed%20OAuth%20request%21'; $this->assertSame($expected, $result); } public function tearDown() { $this->method = null; $this->url = null; $this->parameters = null; $this->oAuth = null; } }
true
58452c2dc55497bca4d7c12cab7129aff36c5e43
PHP
82crisbar/MaFormationWF3
/PHPoo version Prof/06-surcharge-abstraction-finalisation-interface-trait/abstraction.php
UTF-8
1,068
3.25
3
[]
no_license
<?php //06-surcharge-abstraction-finalisation-interface-trait/abstraction.php abstract class Joueur { public function seConnecter(){ return $this -> etreMajeur(); } abstract public function etreMajeur(); // On fonction abstraite n'a pas corps ! } //-------------- class JoueurFr extends Joueur { public function etreMajeur(){ return 18; } } //------------------------ class JoueurUs extends Joueur { public function etreMajeur(){ return 21; } } //------------ //$joueur = new Joueur; /* Commentaires: - Une classe abstraite ne peut pas être instanciée - Les méthodes abstraites n'ont pas de contenu - Les méthodes abstraites sont OBLIGATOIREMENT dans une classe abstraite - Lorsqu'on hérite d'une classe abstraite on DOIT OBLIGATOIREMENT redéfinir les méthodes abstraites - Une classe abstraite peut contenir des méthodes normales. Le développeur qui écrit une classe abstraite est souvent au coeur de l'application. Il va obliger les autres dev' à redéfinir des méthodes. CECI EST UNE BONNE CONTRAINTE ! */
true
378338b345e12079445bc77c4046243917e893b4
PHP
Hkevin25/s07-php-sql-quiz
/src/Utils/Database.php
UTF-8
7,796
3.390625
3
[]
no_license
<?php namespace App\Utils; use PDO; use App\Interfaces\ActiveRecordModel; /** * Handles all communication with the database */ class Database { /** * Single and only instance of Database * @var Database * @static */ private static Database $instance; /** * Instance of PHP database interface * @var PDO */ private PDO $databaseHandler; /** * Create new database handler * * Made private to prevent any instanciation from outside processes as part of the Singleton design pattern */ private function __construct() { } /** * Get single and only instance of Database * * @return Database * @static */ public static function getInstance(): Database { // S'il n'existe pas encore d'instance de Database en mémoire, en crée une if (!isset(self::$instance)) { self::$instance = new Database(); } // Renvoyer l'unique instance de Database en mémoire return self::$instance; } /** * Set up the database handler * * @param string $name The database name * @param string $host The database server * @param string $username Login credentials: user name * @param string $password Login credentials: password * @return void */ public function setupDatabaseHandler(string $name, string $host, string $username, string $password): void { $this->databaseHandler = new PDO("mysql:dbname=$name;host=$host", $username, $password); $this->databaseHandler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } /** * Fetch resource from database based on ID * * @param string $className Class to return objects as * @param integer $id ID of the resource to fetch */ public function fetchFromTableById(string $className, int $id) { // Récupère l'ensemble des enregistrements ayant l'ID demandé en bas e de données $result = $this->fetchFromTableWhere($className, [ 'id' => $id ]); // Si aucun enregistrement ne correspond, renvoie null if (empty($result)) { return null; } // Sinon, puisque les ID sont uniques, il ne peut y avoir qu'un seul résultat: // renvoie ce résultat return $result[0]; } /** * Fetch collection of resources from database based on criteria * * @param string $className Class to return objects as * @param array $criteria Criteria to be satisfied as collection of key/values * @return array */ public function fetchFromTableWhere(string $className, array $criteria): array { $tableName = $className::getTableName(); // Construit la requête préparée avec le nom de la table... $query = 'SELECT * FROM `' . $tableName . '` '; // ...puis tous les critères de filtrage foreach ($criteria as $key => $value) { $query .= 'WHERE `' . $key . '` = :' . $key; } // Prépare la requête $statement = $this->databaseHandler->prepare($query); // Exécute la requête en remplaçant tous les champs variables par leur valeur foreach ($criteria as $key => $value) { $params [':' . $key]= $value; } $statement->execute($params); // Récupère tous les résultats de la requête sous forme d'objets // de la classe spécifiée en paramètres $result = $statement->fetchAll(PDO::FETCH_FUNC, function (...$params) use ($className) { return new $className(...$params); } ); // Renvoie le gestionnaire de requête return $result; } /** * Fetch all resources from database * * @param string $className Class to return objects as * @return array */ public function fetchAllFromTable(string $className) : array { $tableName = $className::getTableName(); $query = 'SELECT * FROM `'. $tableName .'`'; $statement = $this->databaseHandler->query($query); $result = $statement->fetchAll( PDO::FETCH_FUNC, function (...$params) use ($className) { return new $className(...$params); } ); return $result; } /** * Create new record based on current object state * * @param ActiveRecordModel $instance The object from which to create a new record * @return integer */ public function insertIntoTable(ActiveRecordModel $instance): int { // Récupère le nom de la table sur laquelle envoyer la requête $className = get_class($instance); $tableName = $className::getTableName(); // Construit la requête à partir du nom de la table et de la liste des propriétés $properties = $instance->getProperties(); $query = 'INSERT INTO `' . $tableName . '` ('; foreach (array_keys($properties) as $propertyName) { $propertyNames []= '`' . $propertyName . '`'; $valueNames []= ':' . $propertyName; } $query .= join(', ', $propertyNames); $query .= ') '; $query .= 'VALUES ('; $query .= join(', ', $valueNames); $query .= ');'; // Exécute la requête en remplaçant tous les champs variables par les valeurs correspondantes $statement = $this->databaseHandler->prepare($query); foreach ($properties as $key => $value) { $params [':' . $key]= $value; } $statement->execute($params); // Renvoie l'ID de l'objet qui vient d'être créé return $this->databaseHandler->lastInsertId(); } /** * Update existing record based on current object state * * @param ActiveRecordModel $instance The object from which to update existing record * @return void */ public function updateTable(ActiveRecordModel $instance): void { // Récupère le nom de la table sur laquelle envoyer la requête $className = get_class($instance); $tableName = $className::getTableName(); // Construit la requête à partir du nom de la table et de la liste des propriétés $properties = $instance->getProperties(); $query = 'UPDATE `' . $tableName . '` SET '; foreach (array_keys($properties) as $propertyName) { $sets []= '`' . $propertyName . '` = :' . $propertyName; } $query .= join(', ', $sets); $query .= ' WHERE `id` = :id'; // Exécute la requête en remplaçant tous les champs variables par les valeurs correspondantes $statement = $this->databaseHandler->prepare($query); foreach ($properties as $key => $value) { $params [':' . $key]= $value; } $params [':id'] = $instance->getId(); $statement->execute($params); } /** * Delete record associated with a given object from database * * @param ActiveRecordModel $instance The object associated with the record to be deleted * @return void */ public function deleteFromTable(ActiveRecordModel $instance): void { // Récupère le nom de table du modèle $className = get_class($instance); $tableName = $className::getTableName(); // Envoie une requête de suppression en base de données $statement = $this->databaseHandler->prepare('DELETE FROM `'. $tableName . '` WHERE `id` = :id'); $statement->execute([ ':id' => $instance->getId() ]); } public function query(string $sqlQuery): \PDOStatement { return $this->databaseHandler->query($sqlQuery); } }
true
2b7e5feae6ecc62f4d763a0ce7e1d42f0f82fbaf
PHP
TLDevW/Group-project
/Meteo/CtrlMeteo.php
UTF-8
710
2.5625
3
[]
no_license
<?php class CtrlMeteo { private $view; private $model; public function __construct() { $this->view = new ViewMeteo(); $this->model = new ModelMeteo(); } public function getMeteo($ville) { $data = $this->model->getDataMeteo($ville); $this->view->afficherMeteo($data); } public function widgetMeteo() { $heure = date('G') . "H00"; if (!isset($_SESSION['meteo'])) { echo ""; } else { $ville = $_SESSION['meteo']['city_info']['name']; $data = $_SESSION['meteo']['fcst_day_0']['hourly_data'][$heure]; $this->view->afficherWidget($ville, $data); } } }
true
180dff78b301cb0fcaaf843c21f1b7d0505c96cf
PHP
AhmedMedDev/MVC-Blog
/app/models/User.php
UTF-8
1,062
3.046875
3
[]
no_license
<?php //namespace MVC\Models; /* * Model User Class * Register User * Login User * Find User By ID */ class User extends Model{ public function register($username,$email,$password,$img) { $sql = "INSERT INTO user (username, email, password, img) VALUES (?, ?, ?, ?);"; $stmt = $this->Connection->prepare($sql); $stmt->execute([$username,$email,$password,$img]); } public function login($username, $password) { $sql = "SELECT * FROM user WHERE username = ? AND password = ?"; $stmt = $this->Connection->prepare($sql); $stmt->execute([$username,$password]); $count = $stmt->rowCount(); $row = $stmt->fetch(PDO::FETCH_ASSOC); return ($count > 0) ? $row : false; } public function getUserByID($ID){ $sql = "SELECT * FROM user WHERE id = ?"; $stmt = $this->Connection->prepare($sql); $stmt->execute([$ID]); $row = $stmt->fetch(PDO::FETCH_ASSOC); return $row; } }
true
e869509359fa33c9e92adf18e22f15d3b85004e9
PHP
marmot-cn/marmot-framework
/src/Command/Cache/SaveCacheCommand.php
UTF-8
1,191
2.75
3
[]
no_license
<?php namespace Marmot\Framework\Command\Cache; use Marmot\Basecode\Command\Cache\SaveCacheCommand as BaseSaveCacheCommand; use Marmot\Framework\Classes\Transaction; use Marmot\Framework\Observer\CacheObserver; /** * 添加cache缓存命令 * @author chloroplast1983 */ class SaveCacheCommand extends BaseSaveCacheCommand { protected $transaction; public function __construct($key, $data, $time = 0) { parent::__construct($key, $data, $time); $this->transaction = Transaction::getInstance(); $this->attachedByObserver(); } public function __destruct() { parent::__destruct(); unset($this->transaction); } protected function getTransaction() : Transaction { return $this->transaction; } protected function attachedByObserver() : bool { $transaction = $this->getTransaction(); if ($transaction->inTransaction()) { return $transaction->attachRollBackObserver(new CacheObserver($this)); } return false; } public function execute() : bool { $this->attachedByObserver(); return parent::execute(); } }
true
a619e47402a35edda08848debbd02cdde45be2e3
PHP
MadhuSingh/Statistics_Database
/Statistics-master/delete_year_selected.php
UTF-8
574
2.5625
3
[]
no_license
<?php include('connect_to_shady_grove.php'); // Connects to your Database $mydate = $_GET['year']; $mydate = trim($mydate,"\\'"); $time = strtotime($mydate); $year = date('Y',$time); $mydate1 = $year."-01-01"; $mydate2 = $year."-12-31"; $query1 = "DELETE FROM daily_data WHERE d_date BETWEEN \"$mydate1\" AND \"$mydate2\""; $result1 = @mysqli_query ($dbc, $query1); $query2 = "DELETE FROM monthly_data WHERE m_year = $year"; $result2 = @mysqli_query ($dbc, $query2); if($result1 && $result2) { header('Location:home.php'); } ?>
true
a5644102aa0d50ce925674e1d7e39a5ec067df87
PHP
astropatelshubh/Students-Grade
/students.php
UTF-8
3,114
2.5625
3
[]
no_license
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Student's Grade</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> </head> <style> body { font-family: times; } * { box-sizing: border-box; } button { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; opacity: 0.9; } button:hover { opacity:1; } .cancelbtn { float: left; width: 50%; padding: 14px 20px; background-color: #f44336; } .container { padding: 16px; } hr { border: 1px solid #f1f1f1; margin-bottom: 25px; } @media screen and (max-width: 300px) { .cancelbtn { width: 100%; } } </style> <body> <form name="student" action="students.html"> <div class="container"> <h1>PHP-701 Grades for Fall 2018</h1> <hr> <?php $error_msg = ""; if (empty($_POST['name'])) { $error_msg .= "<p>You must enter your name.</p>\n"; } if (empty($_POST['id'])) { $error_msg .= "<p>You must enter your id #.</p>\n"; } else if (!is_numeric($_POST['id'])) { $error_msg .= "<p>Your id # must be a whole number.</p>\n"; } else if ($_POST['id'] < 1) { $error_msg .= "<p>Your id # must be a whole number.</p>\n"; } if (empty($_POST['grade'])) { $error_msg .= "<p>You must enter your grade (enter 0 if you don't have one).</p>\n"; } else if (!is_numeric($_POST['grade'])) { $error_msg .= "<p>Your grade must be a whole number.</p>\n"; } else if (($_POST['grade'] < 0) || ($_POST['grade'] > 4)) { $error_msg .= "<p>Your grade must be between 0 and 4.0.</p>\n"; } if (strlen($error_msg) > 0) { echo $error_msg; echo "<p>Click on the button below to return at Student's Grade form and fix these errors.</p>\n"; } else { $Name = addslashes($_POST['name']); $RegistrationFile = fopen("students.txt", "ab"); if (is_writeable("students.txt")) { if (fwrite($RegistrationFile, $Name . ", " . $_POST['id'] . ", " . $_POST['grade'] . "\n")) { echo "<p>Student's Name: " . $_POST['name'] . "</p>\n"; echo "<p>Student's ID: " . $_POST['id'] . "</p>\n"; echo "<p>Grade: " . $_POST['grade'] . "</p>\n"; echo "<p>Thank you for registering!</p>\n\n"; } else { echo "<p>Cannot store your information.</p>\n"; } } else { echo "<p>Cannot write to the file.</p>\n"; } fclose($RegistrationFile); } ?> <hr> <div class="clearfix"> <button onclick="students.html" class="cancelbtn">Another Student</button> </div> </div> </form> </body> </html>
true
e494a206cca62db4f94294e126aa051c2f002ed4
PHP
dev-websites/uni-documentation
/config/http.php
UTF-8
1,230
3.125
3
[]
no_license
<?php /** * ------------------------------------------------------------------------- * Estrutura URL * ------------------------------------------------------------------------- * * Monta a estrutura da URL utilizando como parâmetros o protocolo, o host, * a porta(caso exista) e nome do projeto do desenvolvedor. * * @param type $redirect */ function url($redirect = NULL) : string { // SERVER_PROTOCOL | http $server_protocol = strtolower(preg_replace('/[^a-zA-Z\$]/', '', filter_input(INPUT_SERVER, 'SERVER_PROTOCOL'))); // SERVER_NAME | localhost ou 127.0.0.1 $server_name = filter_input(INPUT_SERVER, 'SERVER_NAME'); // SERVER_PORT | :8080 ou :80 $server_port = filter_input(INPUT_SERVER, 'SERVER_PORT') === '80' ? '' : ':' . filter_input(INPUT_SERVER, 'SERVER_PORT'); // SCRIPT_NAME | nome do diretório do projeto $script_name = str_replace('/index.php', '', filter_input(INPUT_SERVER, 'SCRIPT_NAME')); // Estrutura da URL return "{$server_protocol}://{$server_name}{$server_port}{$script_name}{$redirect}"; }
true
26f1f30320da7447270d6eee313acd5018a7d0c8
PHP
KiRealo/TestHub
/classWork.php
UTF-8
854
3.703125
4
[]
no_license
<?php declare(strict_types=1); class Person { protected string $name; protected string $surname; protected string $middlename; public function __construct(string $name, string $surname, string $middlename) { $this->name = $name; $this->surname=$surname; $this->middlename=$middlename; } public function middlname():string { return $this->middlename.PHP_EOL; } public function ekoName() { return $this->name.PHP_EOL.$this->middlename.PHP_EOL.$this->surname.PHP_EOL; } } $person=new Person('Vasjka','Pupkins','Petrovich'); $person2=new Person('Karlis','Zenofs','Peteris'); $person3=new Person('John','Doe','Michael'); echo $person->ekoName()." ".$person->middlname(); echo $person2->ekoName()." ".$person2->middlname(); echo $person3->ekoName()." ".$person3->middlname();
true
1fa26b16c60ce71d8a911cf9a3259286246fa087
PHP
hjpbarcelos/gd-wrapper
/src/Action/ResizeMode/Exact.php
UTF-8
1,839
3.234375
3
[ "MIT" ]
permissive
<?php /** * Defines the Exact resizing mode. * @author Henrique Barcelos */ namespace Hjpbarcelos\GdWrapper\Action\ResizeMode; use Hjpbarcelos\GdWrapper\Geometry\Point; /** * Represents an exact resizing. That is, no matter which are the original * dimensions of an image file, the new dimensions should be exaclty as * they are told to be. */ class Exact implements Mode { /** * @var int The width of the resized image. */ private $width; /** * @var int The height of the resized imaged. */ private $height; /** * Creates an exact resizing mode. * * @param int $width The desired width of the image. * @param int $height The desired height of the image. */ public function __construct($width, $height) { $this->setWidth($width); $this->setHeight($height); } /** * Sets the desired width of the image. * * @param int $width * @return void */ public function setWidth($width) { $this->width = (int) $width; } /** * Gets the desired width of the image. * * @return int */ public function getWidth() { return $this->width; } /** * Sets the desired width of the image. * * @param int $height * @return void */ public function setHeight($height) { $this->height = (int) $height; } /** * Gets the desired height of the image. * * @return int */ public function getHeight() { return $this->height; } /** * {@inheritdoc} * * @see Hjpbarcelos\GdWrapper\Action\ResizeMode\Mode::getNewDimensions() */ public function getNewDimensions($width, $height) { return new Point($this->width, $this->height); } }
true
9e33348a78763652597ba82ad57d2377598b456d
PHP
tsubono/makuou
/app/Http/Controllers/Auth/RegisterController.php
UTF-8
3,013
2.609375
3
[]
no_license
<?php namespace App\Http\Controllers\Auth; use App\Models\User; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; /** * Where to redirect users after registration. * * @var string */ protected $redirectTo = '/register/thanks'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } public function showRegistrationForm() { return view('front.register.index'); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'lastName' => 'required|string', 'firstName' => 'required|string', 'lastNameKana' => 'required|string', 'firstNameKana' => 'required|string', 'email' => 'required|string|email|max:255|unique:users', 'mobileOne' => '', 'mobileTwo' => '', 'mobileThree' => '', 'telOne' => '', 'telTwo' => '', 'telThree' => '', 'zipCodeOne' => ['required', 'regex:/^[0-9]{3}$/'], 'zipCodeTwo' => ['required', 'regex:/^[0-9]{4}$/'], 'prefecture' => 'required|numeric|between:0,47', 'addressOne' => 'required', 'addressTwo' => '', 'password' => 'required', ]); } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\Models\User */ protected function create(array $data) { return User::create([ 'name' => $data['lastName'] .$data['firstName'], 'name_kana' => $data['lastNameKana'] .$data['firstNameKana'], 'zip_code' => $data['zipCodeOne'] .$data['zipCodeTwo'], 'pref_id' => $data['prefecture'], 'address1' => $data['addressOne'], 'address2' => $data['addressTwo']||'', 'tel' => $data['mobileOne'] .$data['mobileTwo'] .$data['mobileThree'], 'fax' => $data['telOne'] .$data['telTwo'] .$data['telThree'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); } }
true
6f5273fefda79642a82a8fc183e346e486e4a0fc
PHP
sasin91/fluen-bnet
/app/Http/Controllers/Api/MailController.php
UTF-8
1,403
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api; use Illuminate\Contracts\Mail\Mailer; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Mail\Message; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Mail; class MailController extends Controller { /** * @var Mailer */ protected $mailer; /** * MailController constructor. * * * @param Mailer $mailer */ public function __construct(Mailer $mailer) { $this->mailer = $mailer; } /** * Dispatches a welcome mail to the new User. * * * @return void */ public function sendWelcomeMail() { $user = Auth::user(); $this->mailer->send('user.welcome', compact('user'), function (Message $message) use($user) { $message ->to($user->email) ->subject('Welcome! hope you enjoy your stay. :)'); }); } /** * Dispatches a goodbye mail to the leaving User. * * * @return void */ public function sendGoodbyeMail() { $user = Auth::user(); $this->mailer->send('user.goodbye', compact('user'), function (Message $message) use($user) { $message ->to($user->email) ->subject('Sorry to see you leave...'); }); } }
true
80664449b5049271ffaea680c659afe505ed2f5d
PHP
nielsdegroot789/schoolbib
/backend/src/lib/Controller/UserController.php
UTF-8
13,929
2.84375
3
[]
no_license
<?php namespace skoolBiep\Controller; use Exception; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use skoolBiep\Entity\User; use skoolBiep\Util\CreateJWT; use skoolBiep\DB; $data = array(); class UserController { private $user; protected $container; protected $response; public function __construct(\Psr\Container\ContainerInterface $container) { $this->container = $container; } public function login(Request $request, Response $response, array $args): Response { $data = json_decode(file_get_contents("php://input"), true); try { $formEmail = $data["email"]; if (!$formEmail) { throw new Exception('Email not filled in correctly'); } $formPassword = $data["password"]; if (!$formPassword) { throw new Exception('Password not filled in correctly'); } } catch (Exception $e) { $response->getBody()->write('Caught exception: ' . $e->getMessage() . "\n"); return $response->withStatus(401); } try { $user = $this->validateUser($formEmail, $formPassword); $jwt = new CreateJWT($user); $token = $jwt(); $response->getBody()->write($token); return $response->withHeader('Authorization', 'Bearer: ' . $token); } catch (Exception $e) { $response->getBody()->write('Caught exception: ' . $e->getMessage() . "\n"); return $response->withStatus(401); } } public function validateUser(String $formEmail, String $formPassword): array { $user = null; $db = $this->container->get('db'); $user = $db->getUserByEmail($formEmail); if ($user) { if (password_verify($formPassword, $user['password'])) { $this->setUser($user); return $user; } } throw new Exception("Combination not found"); } public function resetPassword(Request $request, Response $response, array $args) { try{ $data = json_decode(file_get_contents("php://input"), true); $db = $this->container->get('db'); $address = $data["email"]; $result = $db->checkAdress($address); $token = $result['token']; $name = $result['name']; if(!$token) { throw new Exception('Email is not registered'); } $body = $this->container->get('twig')->render('twig.twig', ['token' => $token, 'name' => $name]); $subject = "Password reset"; $this->container->get('mailer')->sendMail($address, $body, $subject); return $response; } catch(Exception $e){ $response->getBody()->write('Caught exception: ' . $e->getMessage() . "\n"); return $response->withStatus(401); } } public function setUser(array $user) { $this->user = $user; } public function getUser(): array { return $this->user; } public function saveReservationsUser(Request $request, Response $response, array $args) { $data = json_decode(file_get_contents("php://input"), TRUE); $this->response = $response; $db = new DB(); // Reworked Benno's reservation to an atleast presentable demo, not working fully. // The reservation of actual books does not work. (only book metas) $usersId = $data['params']["usersId"]; $booksId = $data['params']["booksId"]; $reservationDateTime = $data['params']["reservationDateTime"]; $accepted = 0; $data = $db->saveReservationsUser($usersId, $booksId, $reservationDateTime, $accepted); $response->getBody()->write($data); return $response; } public function saveCheckouts(Request $request, Response $response, array $args) { $data = json_decode(file_get_contents("php://input"), TRUE); $this->response = $response; $db = new DB(); $usersId = $data["usersId"]; $booksId = $data["booksId"]; $checkoutDateTime = $data["checkoutDateTime"]; $maxAllowedDate = $data["maxAllowedDate"]; $data = $db->saveCheckouts($usersId,$booksId,$checkoutDateTime,$maxAllowedDate); $mailData = $db->getEmailData($usersId, $booksId); $name = $mailData[0]['surname']; $email= $mailData[0]['email']; $title = $mailData[0]['title']; $author = $mailData[0]['author']; $body = $this->container->get('twig')->render('confirmation.twig', ['name' => $name, 'title' => $title, 'author' => $author]); $subject = "Confirmation book"; $this->container->get('mailer')->sendMail($email, $body, $subject); $response->getBody()->write($data); return $response; } public function returnCheckouts(Request $request, Response $response, array $args) { $data = json_decode(file_get_contents("php://input"), TRUE); $this->response = $response; $db = new DB(); $id = $data["id"]; $returnDateTime = $data["returnDateTime"]; $data = $db->returnCheckouts($id, $returnDateTime); $response->getBody()->write($data); return $response; } public function getReservations(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $arguments = json_decode(file_get_contents("php://input"), true); $id = isset($arguments["id"]) ? '%' . $arguments["id"] : "%"; $usersId = isset($arguments["usersId"]) ? '%' . $arguments["usersId"] : "%"; $booksId = isset($arguments["booksId"]) ? $arguments["booksId"] : "%"; $reservationDateTime = isset($arguments["reservationDateTime"]) ? '%' .$arguments["reservationDateTime"] :"%"; $accepted = isset($arguments["accepted"]) ? '%' .$arguments["accepted"] : "%"; $limitNumber = isset($arguments["limit"]) ? $arguments["limit"] : 20; $offsetNumber = isset($arguments["offset"]) ? $arguments["offset"] : 0; $data = $db->getReservations($limitNumber, $offsetNumber,$reservationDateTime, $accepted, $booksId, $usersId, $id); $payload = json_encode($data); $response->getBody()->write($payload); return $response ->withHeader('Content-Type', 'application/json'); } public function getCheckouts(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $arguments = json_decode(file_get_contents("php://input"), true); $id = isset($arguments["id"]) ? '%' . $arguments["id"] : "%"; $usersId = isset($arguments["usersId"]) ? '%' . $arguments["usersId"] : "%"; $booksId = isset($arguments["booksId"]) ? $arguments["booksId"] : "%"; $checkoutDateTime = isset($arguments["checkoutDateTime"]) ? '%' .$arguments["checkoutDateTime"] :"%"; $returnDateTime = isset($arguments["returnDateTime"]) ? '%' .$arguments["returnDateTime"] : "%"; $maxAllowedDate = isset($arguments["maxAllowedDate"]) ? '%' .$arguments["maxAllowedDate"] : '%'; $fine = isset($arguments["fine"]) ? '%' .$arguments["fine"] : '%'; $isPaid = isset($arguments["isPaid"]) ? '%' .$arguments["isPaid"] : '%'; $limitNumber = isset($arguments["limit"]) ? $arguments["limit"] : 20; $offsetNumber = isset($arguments["offset"]) ? $arguments["offset"] : 0; $data = $db->getCheckouts($limitNumber, $offsetNumber,$id, $usersId,$booksId,$checkoutDateTime,$returnDateTime,$maxAllowedDate, $fine, $isPaid); $payload = json_encode($data); $response->getBody()->write($payload); return $response ->withHeader('Content-Type', 'application/json'); } public function getCheckoutUser(Request $request, Response $response, array $args) { $payloadData = $_GET['data']; $json = json_decode($payloadData); $id = $json->id; $this->response = $response; $db = new DB(); $data = $db->getCheckoutUser($id); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function getReservationUser(Request $request, Response $response, array $args) { $payloadData = $_GET['data']; $json = json_decode($payloadData); $id = $json->id; $this->response = $response; $db = new DB(); $data = $db->getReservationUser($id); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function deleteReservationUser(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $contents = json_decode(file_get_contents('php://input'), true); $resId = $contents['userId']; $db->deleteFavoriteBooks($resId); $response->getBody()->write($contents); return $response; } public function getFavoriteBooks(Request $request, Response $response, array $args) { $payloadData = $_GET['data']; $json = json_decode($payloadData); $id = $json->id; $this->response = $response; $db = new DB(); $data = $db->getFavoriteBooks($id); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function deleteFavoriteBooks(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $contents = json_decode(file_get_contents('php://input'), true); $resId = $contents['userId']; $db->deleteFavoriteBooks($resId); $response->getBody()->write($contents); return $response; } public function getFavoriteAuthors(Request $request, Response $response, array $args) { $payloadData = $_GET['data']; $json = json_decode($payloadData); $id = $json->id; $this->response = $response; $db = new DB(); $data = $db->getFavoriteAuthors($id); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function deleteFavoriteAuthors(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $contents = json_decode(file_get_contents('php://input'), true); $resId = $contents['userId']; $db->deleteFavoriteAuthors($resId); $response->getBody()->write($contents); return $response; } public function getProfilePageData(Request $request, Response $response, array $args) { $payloadData = $_GET['data']; $json = json_decode($payloadData); $id = $json->id; $this->response = $response; $db = new DB(); $data = $db->getProfilePageData($id); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function saveProfileData(Request $request, Response $response, array $args) { $this->response = $response; $contents = json_decode(file_get_contents('php://input'), true); $id = $contents['currentUser']; if($id) { $firstName = $contents['firstName']; $lastName = $contents['lastName']; $email = $contents['email']; $db = new DB(); $db->saveProfileData($id,$firstName,$lastName,$email); } else { $firstName = $contents['firstName']; $lastName = $contents['lastName']; $email = $contents['email']; $db = new DB(); $db->createProfileData($firstName,$lastName,$email); //send email telling person to select forgot password option $address = $email; $body = $this->container->get('twig')->render('newAccount.twig'); $subject = "Active acount"; $this->container->get('mailer')->sendMail($address, $body, $subject); } return $response; } public function getAllUsers(Request $request, Response $response, array $args) { $this->response = $response; $db = new DB(); $data = $db->getAllUsers(); $payload = json_encode($data); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function checkToken(Request $request, Response $response, array $args) { $this->response = $response; $token = $_REQUEST[0]; $db = new DB(); $checkAnswer = $db->checkToken($token); $payload = json_encode($checkAnswer); $response->getBody()->write($payload); return $response->withHeader('Content-Type', 'application/json'); } public function updatePassword(Request $request, Response $response, array $args) { $this->response = $response; $contents = json_decode(file_get_contents('php://input'), true); $id = $contents['id']; $newPassword = $contents['password']['password']; $hashed_pass = password_hash($newPassword, CRYPT_SHA256); $db = new DB(); $db->updatePassword($hashed_pass, $id); return $response; } }
true
4c993b7a187fd381db379c112f131fa101d04350
PHP
cviccaro/jpa-admin
/app/Sluggable.php
UTF-8
572
2.65625
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Http\Request; trait Sluggable { function __construct() { if (isset($this->appends)) { $this->appends[] = 'uri'; } else { $this->appends = ['uri']; } } public function getUriAttribute() { $title = false; if (isset($this->attributes['title'])) { $title = $this->attributes['title']; } elseif (isset($this->attributes['name'])) { $title = $this->attributes['name']; } return !$title ?: str_slug($title); } }
true
f3afcb1e174e24e1b9c3f4dd31fd5343c1d7e6ab
PHP
rishad1234/inspect
/inspect/app/models/Job.php
UTF-8
222
2.71875
3
[]
no_license
<?php class Job{ public static function getAllJobs(){ $database = new Database; $database->query('select * from job_posts order by created_at desc'); return $database->resultSet(); } }
true
705d158b7d5a84f07dfb08ab3fa441f30dc8b5bd
PHP
Fiacco/chamada-PHP_Fundamentos
/PHP_Fundamentos/operadores.php
ISO-8859-1
336
3.640625
4
[]
no_license
<?php $x=9; $y=3; $z; $a="programao"; $b="PHP"; // REALIZANDO TESTE $z= $x + $y; echo "soma=$z \n"; $z= $x - $y; echo "subtrao = $z \n"; $z= $x * $y; echo "multiplicao = $z \n"; $z= $x / $y; echo "diviso = $z \n "; $z = $x % $y; echo " mdulo = $z \n"; $z = ($x + $y + 12)/3; echo "mdia = $z \n"; echo $a . $b ?>
true
646db33732bf0e625e99bf251e9b387c7966956c
PHP
Cyecize/Jesterous
/src/AppBundle/Service/ArticleAsMessageManager.php
UTF-8
3,636
2.78125
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: ceci * Date: 9/25/2018 * Time: 1:29 PM */ namespace AppBundle\Service; use AppBundle\BindingModel\ArticleAsMessageBindingModel; use AppBundle\Constants\Config; use AppBundle\Contracts\IArticleAsMessageManager; use AppBundle\Contracts\IArticleDbManager; use AppBundle\Entity\Article; use AppBundle\Exception\ArticleNotFoundException; use AppBundle\Util\YamlParser; use AppBundle\ViewModel\ArticleAsMessageViewModel; class ArticleAsMessageManager implements IArticleAsMessageManager { private const FILE_PATH = "../app/config/article_as_message.yml"; private const SUBSCRIBE_REWARD = "subscribe_reward"; private const SUBSCRIBE_MESSAGE = "subscribe_message"; private const BINDING_MODEL_NAME_DELIMITER = "__"; /** * @var IArticleDbManager */ private $articleService; private $settings; public function __construct(IArticleDbManager $articleDb) { $this->settings = YamlParser::getFile(self::FILE_PATH); $this->articleService = $articleDb; } public function saveSettings(ArticleAsMessageBindingModel $bindingModel): void { $settings = $this->extractSettingsFromBindingModel($bindingModel); YamlParser::saveFile($settings, self::FILE_PATH); } public function getSubscribeReward(string $localeName): Article { return $this->getArticle($this->extractArticleId(self::SUBSCRIBE_REWARD, $localeName)); } public function getSubscribeMessage(string $localeName): Article { return $this->getArticle($this->extractArticleId(self::SUBSCRIBE_MESSAGE, $localeName)); } /** * @return ArticleAsMessageViewModel[] */ public function getArticleSettings(): array { $res = array(); foreach ($this->settings as $sectionName => $options) { $res[] = new ArticleAsMessageViewModel($sectionName, $options); } return $res; } //Private logic /** * @param string $section * @param $localeName * @return int * @throws ArticleNotFoundException */ private function extractArticleId(string $section, $localeName): int { $sectionArr = $this->settings[$section]; $articleLocale = $this->getArticleName($localeName); if (!array_key_exists($articleLocale, $sectionArr)) throw new ArticleNotFoundException(); return intval($sectionArr[$articleLocale]); } private function getArticle(int $id) : Article{ $article = $this->articleService->findOneById($id, true); if($article == null) throw new ArticleNotFoundException(); return $article; } private function getArticleName(string $locale): string { switch ($locale) { case Config::COOKIE_BG_LANG: return "bg_article"; case Config::COOKIE_EN_LANG: return "en_article"; default: return "bg_article"; } } private function extractSettingsFromBindingModel(ArticleAsMessageBindingModel $bindingModel): array { $reflection = new \ReflectionObject($bindingModel); $res = array(); foreach ($reflection->getProperties() as $property) { $property->setAccessible(true); $settingNameTokens = explode(self::BINDING_MODEL_NAME_DELIMITER, $property->getName()); if (count($settingNameTokens) != 2) continue; $res[$settingNameTokens[0]][$settingNameTokens[1]] = $property->getValue($bindingModel); } return $res; } }
true
2b8cd1668782d4209c54ac3c3e31227a5cb2d67d
PHP
DimitriLeandro/Pumas
/Core/php/classes/ciclo.Class.php
UTF-8
2,536
3.15625
3
[]
no_license
<?php /* * Essa classe é a progenitora das classes Paciente, Triagem e Diagnostico * Os atributos protegidos são aqueles que foram repetidos nas respectivas tabelas no banco de dados * usuarioRegistro -> nas três tabelas do banco esse atributo serve para informar quem foi o funcionário que realizou um determinado registro * ubs -> informa em qual ubs o registro foi feito * data e hora -> tem nessas três tabelas também. * O usuarioRegistro está numa $_SESSION do próprio userspice. Para receber esse valor será usada outra classe que será instanciada no método construtor. */ require_once 'conexao.Class.php'; require_once 'usuario.Class.php'; abstract class Ciclo { protected $cdUsuarioRegistro; protected $cdUbs; protected $dtRegistro; protected $hrRegistro; protected $db_maua; //não tem get nem set protected $attr; //isso é um array que serve para os métodos de selecionar() //não tem get nem set public function __construct() { //fazendo a conexão com o banco para que todas as classes filhas não precisem fazer isso novamente $obj_conn = new Conexao(); $this->db_maua = $obj_conn->get_db_maua(); //atribuindo um valor ao atributo usuarioRegistro $obj_usuario = new Usuario(); $this->cdUsuarioRegistro = $obj_usuario->getId(); //atribuindo valor ao $cdUbs //cdUbs é diferente de cdUbsReferencia. O cdUbs é a ubs onde o sistema está sendo rodado e cdUbsReferencia é onde o paciente deveria ir $this->setCdUbs($obj_conn->getCdUbs()); //dizendo que $attr é um array $this->attr = array(); } abstract function cadastrar(); abstract function selecionar($id); abstract function atualizar($id); //----------------------------FUNÇÕES GET E SET -- menos getset pro $db_maua e set pro cdUsuarioRegistro function getCdUsuarioRegistro() { return $this->cdUsuarioRegistro; } function getCdUbs() { return $this->cdUbs; } function getDtRegistro() { return $this->dtRegistro; } function getHrRegistro() { return $this->hrRegistro; } function setCdUsuarioRegistro($cdUsuarioRegistro) { $this->cdUsuarioRegistro = $cdUsuarioRegistro; } function setCdUbs($cdUbs) { $this->cdUbs = $cdUbs; } function setDtRegistro($dtRegistro) { $this->dtRegistro = $dtRegistro; } function setHrRegistro($hrRegistro) { $this->hrRegistro = $hrRegistro; } } ?>
true
0e0c497f8f8ddef2efd4449502cc19abe864f971
PHP
Paola0210/PeliculasMovieflix
/application/libraries/MailApi.php
UTF-8
1,895
2.53125
3
[]
no_license
<?php if(!defined('BASEPATH')) exit('No direct script access allowed'); require_once dirname(__FILE__) . '/vendor_mail/autoload.php'; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; class MailApi { public function __construct() { } public function send_mail($para,$nueva_contrasena){ $mail = new PHPMailer(true); try { //Server settings //$mail->SMTPDebug = SMTP::DEBUG_SERVER; //Enable verbose debug output $mail->isSMTP(); //Send using SMTP $mail->Host = 'smtp.gmail.com'; //Set the SMTP server to send through $mail->SMTPAuth = true; //Enable SMTP authentication $mail->Username = 'eugeniapesca322@gmail.com'; //SMTP username $mail->Password = '23725856'; //SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; //Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; $mail->SMTPSecure = 'tls'; //TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom('eugeniapesca322@gmail.com', 'Mailer'); $mail->addAddress($para, 'Cliente'); //Add a recipient //Content $mail->isHTML(true); //Set email format to HTML $mail->Subject = 'Clave temporal Movieflix'; $mail->Body = 'Su contraseña temporal es <b>'.$nueva_contrasena.'</b>'; $mail->AltBody = 'Su contraseña temporal es '.$nueva_contrasena; $mail->send(); echo 'Message has been sent'; } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } } }
true
299f980ea47f2fbc746b6d0a14fcede003fab891
PHP
Azalius/betisier
/classes/Ville.class.php
UTF-8
655
3.28125
3
[]
no_license
<?php class Ville{ private $num; private $nom; public function __construct($valeurs = array()) { if(!empty($valeurs)){ $this->affecte($valeurs); } } public function affecte($donnees){ foreach($donnees as $attribut => $valeur){ switch($attribut){ case 'vil_num' : $this->setNum($valeur);break; case 'vil_nom' : $this->setNom($valeur);break; } } } public function setNum($num){ $this->num = $num; } public function setNom($num){ $this->nom = $num; } public function getNom(){ return $this->nom; } public function getNum(){ return $this->num; } } ?>
true
434c5a58be34a372d7a624c4baf2cf0140c9de65
PHP
endemio/cv-test-jokes
/app/tests/AbstractMiscServiceTest.php
UTF-8
3,499
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Tests; use App\Exceptions\ErrorDuringResponseToGetCategories; use App\Service\AbstractMiscService; use PHPUnit\Framework\TestCase; class AbstractMiscServiceTest extends TestCase { protected $newAbstractMiscService; protected function setUp(): void { $this->newAbstractMiscService = new class extends AbstractMiscService { public function returnThis() { return $this; } }; } public function testAbstractMiscService() { $this->assertInstanceOf( AbstractMiscService::class, $this->newAbstractMiscService->returnThis() ); } public function testSendResponse() { $url = 'https://httpbin.org/status/404'; $this->expectException(\Exception::class); $this->newAbstractMiscService->sendResponse($url); } public function testSendResponse2() { $url = 'https://httpbin.org/status/503'; $this->expectException(\Exception::class); $this->newAbstractMiscService->sendResponse($url); } public function testSendResponse3() { $url = 'https://httpbin.org/status/304'; $this->expectException(ErrorDuringResponseToGetCategories::class); $this->newAbstractMiscService->sendResponse($url); } public function testSendResponse4() { $url = 'https://httpbin.org/anything/bla'; $this->assertIsString($this->newAbstractMiscService->sendResponse($url)); } public function testGetResultFromResponse(){ $result = $this->newAbstractMiscService->getResultFromResponse('{"test":4}'); $this->assertEquals(4,$result['test']); $result = $this->newAbstractMiscService->getResultFromResponse('{"bla":55}'); $this->assertEquals(55,$result['bla']); $this->expectException(\Exception::class); $this->newAbstractMiscService->getResultFromResponse('{\'bla":55}'); } public function testGetResult(){ $test_array = ['type'=>'success','value'=>['one','two','three','four'=>['five','six']]]; $this->assertEquals('one',$this->newAbstractMiscService->getResult($test_array)[0]); $this->assertEquals('two',$this->newAbstractMiscService->getResult($test_array)[1]); $this->assertEquals('three',$this->newAbstractMiscService->getResult($test_array)[2]); $this->assertIsArray($this->newAbstractMiscService->getResult($test_array)['four']); // Exceptions $test_array = ['type'=>'false','value'=>['one','two','three','four'=>['five','six']]]; $this->expectException(ErrorDuringResponseToGetCategories::class); $this->assertEquals('one',$this->newAbstractMiscService->getResult($test_array)); $test_array = ['type'=>'success','not_value'=>['one','two','three','four'=>['five','six']]]; $this->expectException(ErrorDuringResponseToGetCategories::class); $this->assertEquals('one',$this->newAbstractMiscService->getResult($test_array)); $test_array = ['type'=>'success','value'=>'text']; $this->expectException(ErrorDuringResponseToGetCategories::class); $this->assertEquals('one',$this->newAbstractMiscService->getResult($test_array)); $test_array = ['type'=>'success']; $this->expectException(ErrorDuringResponseToGetCategories::class); $this->assertEquals('one',$this->newAbstractMiscService->getResult($test_array)); } }
true
08828248a96b2b6b09cc64cf02c45a045daebb7c
PHP
tkotosz/functions-playground
/inc/function_autoload.php
UTF-8
699
2.609375
3
[]
no_license
<?php /** * @param string $module * * @return callable[] */ function requirefm(string $module): array { static $cache; if (!isset($cache[$module])) { $path = 'inc/' . $module . '/index.php'; $cache[$module] = (static function() use ($path) { return require($path); })(); } return $cache[$module]; } /** * @param string[] $functionNames * @param string $module * * @return callable[] */ function import(array $functionNames, string $module): array { $module = requirefm($module); $result = []; foreach ($functionNames as $functionName) { $result[] = $module[$functionName]; } return $result; }
true
379e991fed9f660e8eb63149a4f7f468f2aba3ea
PHP
WordPress/wordpress.org
/wordpress.org/public_html/wp-content/plugins/trac-notifications/trac-notifications-http-server.php
UTF-8
1,002
2.84375
3
[]
no_license
<?php /** * Sits on the Trac server and responds to calls from Trac_Notifications_HTTP_Client. */ class Trac_Notifications_HTTP_Server { function __construct( Trac_Notifications_DB $db, $secret ) { $this->db = $db; $this->secret = $secret; } function serve_request() { $this->serve( $_GET['call'], $_GET['secret'], json_decode( $_POST['arguments'], true ) ); } function serve( $method, $secret, $arguments ) { if ( ! method_exists( 'Trac_Notifications_DB', $method ) || $method[0] === '_' ) { header( ( $_SERVER["SERVER_PROTOCOL"] ?: 'HTTP/1.0' ) . ' 404 Method Not Found', true, 404 ); exit; } if ( ! hash_equals( $this->secret, $secret ) ) { header( ( $_SERVER["SERVER_PROTOCOL"] ?: 'HTTP/1.0' ) . ' 403 Forbidden', true, 403 ); exit; } if ( $arguments ) { $result = call_user_func_array( array( $this->db, $method ), $arguments ); } else { $result = call_user_func( array( $this->db, $method ) ); } echo json_encode( $result ); exit; } }
true
9baf386d532953c0a5ea5bffbc0c091132401577
PHP
sparrrky/arrays_loops_tasks
/22/22_while.php
UTF-8
302
3.015625
3
[]
no_license
<?php /* Нарисуйте пирамиду, как показано на рисунке, используя цикл for или while. xx xxxx xxxxxx xxxxxxxx xxxxxxxxxx [17 баллов] */ //Цикл while: $str = ''; $i = 0; while ($i <= 4) { $i++; $str .= 'xx'; echo $str.'<br>'; } ?>
true
8b90a5c3af9174f3d45d3b1bbef65922070c5224
PHP
thinhtd1995/shop_db
/backend/models/News.php
UTF-8
2,855
2.546875
3
[]
no_license
<?php namespace backend\models; use Yii; use yii\data\Pagination; use backend\services\BaseService; date_default_timezone_set("Asia/Vientiane"); /** * This is the model class for table "news". * * @property int $id * @property string $title * @property string $slug * @property string $description * @property string $content * @property string $images * @property int $cat_id * @property int $user_id * @property string $desc_seo * @property string $title_seo * @property int $status * @property int $public * @property string $created_at * @property string $updated_at */ class News extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'news'; } /** * {@inheritdoc} */ public function rules() { return [ [['title', 'slug', 'description', 'content', 'images', 'cat_id', 'status', 'type'], 'required'], [['description', 'content', 'desc_seo', 'title_seo','key_seo'], 'string'], [['cat_id', 'user_id', 'status', 'type'], 'integer'], [['created_at', 'updated_at'], 'safe'], [['title', 'slug', 'images'], 'string', 'max' => 255], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'title' => 'Tiêu đề', 'slug' => 'Đường dẫn tĩnh', 'description' => 'Mô tả', 'content' => 'Nội dung', 'images' => 'Hình ảnh', 'cat_id' => 'Danh mục cha', 'user_id' => 'Tài khoản đăng ký', 'desc_seo' => 'Mô tả seo', 'title_seo' => 'Tiêu đề seo', 'key_seo' => 'Keyword seo', 'status' => 'Trạng thai', 'type' => 'Kiều tin', 'created_at' => 'Ngày tạo', 'updated_at' => 'Ngày cập nhật', ]; } public function saveData($model, $post) { $base = new BaseService(); if ($model->images != null && $model->images != "") { $string_img = $post["News"]["images"]; $filename = $base->uploadBase64("uploads/images/", $string_img, 555, 415); if ($filename) { $model->images = $filename; } } return 0; } public function getNewnames(){ return $this->hasOne(Category::className(),['id' => 'cat_id']); } public function getNameuser(){ return $this->hasOne(User::className(),['id' => 'user_id']); } public function checkslug($slug){ $model = News::findOne(['slug'=>$slug]); while (isset($model)) { $slug = $model->slug.'-'.'1'; $model = News::findOne(['slug'=>$slug]); } return $slug; } }
true
54b7ef4a77197443f8bc74cc192fd068ed066304
PHP
artaxmax/worker-manager
/src/WorkerManager/Service/ActionFileManager.php
UTF-8
4,373
2.890625
3
[]
no_license
<?php namespace WorkerManager\Service; use Symfony\Component\Process\Process; /** * WorkerManager\Service\ActionFileManager */ class ActionFileManager { const TYPE_PID = 'pid'; const TYPE_ACTION = 'action'; /** * @var string */ static public $pidFile; /** * @var string */ static public $actionFile; /** * @var string */ protected $processName; /** * @var int */ protected $processPid; /** * @var string */ protected $actionFilePath; /** * @param string $processName * @param int $processPid * @param string $actionFilePath */ public function __construct( $processName, $processPid = null, $actionFilePath = null ) { $this->processName = (string) $processName; $this->actionFilePath = $actionFilePath ?: dirname(dirname(dirname(__DIR__))); $this->processPid = $processPid ?: getmypid(); } /** * @return bool */ public function flushPid() { file_put_contents($this->buildPidPath(), $this->processPid); return true; } /** * @param string $action * * @return bool */ public function flushAction($action) { file_put_contents($this->buildActionPath(), (string) $action); return true; } /** * @return string */ public function loadAction() { return file_get_contents($this->buildActionPath()); } /** * @param array $node * * @return bool */ public function pingNode(array $node) { $process = new Process( sprintf( 'ssh %s "cat %s"', $node['ssh'], $this->buildPidPath($node['action_file_path'], $node['name']) ) ); $nodePid = $error = null; $process->run( function ($out, $line) use (&$nodePid, &$error) { if ($out === 'out') { $nodePid = $line; } else { $error = $line; } } ); if ($nodePid) { $process = new Process( sprintf( 'ssh %s ps aux | grep "%s" | grep -v grep', $node['ssh'], $nodePid ) ); $response = $error = null; $process->run( function ($out, $line) use (&$response, &$error) { if ($out === 'out') { $response = $line; } else { $error = $line; } } ); return strpos($response, $nodePid) !== false; } return false; } /** * @param string $actionFilePath * @param string $processName * * @return string */ protected function buildPidPath($actionFilePath = null, $processName = null) { $actionFilePath = $actionFilePath ?: $this->actionFilePath; $processName = $processName ?: $this->processName; return sprintf('%s/worker-monitoring-%s.pid', $actionFilePath, $processName); } /** * @return string */ protected function buildActionPath() { return sprintf('%s/worker-monitoring-%s.action', $this->actionFilePath, $this->processName); } /** * init tmp files * * @deprecated */ static public function init() { static::$pidFile = static::$pidFile ?: dirname(dirname(dirname(__DIR__))).'/worker-monitoring.pid'; static::$actionFile = static::$actionFile ?: dirname(dirname(dirname(__DIR__))).'/worker-monitoring.action'; } /** * @param int $pid * * @deprecated */ static public function updatePid($pid = null) { $pid = $pid ?: getmypid(); file_put_contents(static::$pidFile, $pid); } /** * @param string $action * * @deprecated */ static public function updateAction($action) { file_put_contents(static::$actionFile, $action); } /** * @return string * * @deprecated */ static public function getAction() { return file_get_contents(static::$actionFile); } }
true
5e4161ef6060ef7e37b56ab0d47fa32b70f6fe38
PHP
mayakaconard/college_clearance_portal_codeigniter
/application/models/Sections_model.php
UTF-8
12,224
2.734375
3
[]
no_license
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Sections_model extends CI_Model { //Clearance system Dashboard data management // Function to register A student into the system public function registerStudent($newStudent) { $qry = $this->db->insert('users', $newStudent); if ($qry) { return true; } else { return false; } } //Add new Announcement public function new_Announcement($newAnnouncement) { $query=$this->db->insert('announcements',$newAnnouncement); if ($query) { return true; } else { return false; } } //Get schools to selectmenu in Student view public function getSchools(){ $sql="SELECT * FROM schools"; $query=$this->db->query($sql); return $query->result_array(); } //Get Departments to selectmenu in Student view public function getDepartments(){ $sql="SELECT * FROM departments"; $query=$this->db->query($sql); return $query->result_array(); } //Get programmes to selectmenu in Student view public function getProgrammes() { $sql="SELECT * FROM programmes"; $query=$this->db->query($sql); return $query->result_array(); } //Get Clearance Sections to selectmenu in Sections view public function getSections() { $sql="SELECT * FROM sections"; $query=$this->db->query($sql); return $query->result_array(); } //Get Announcements to the Dashboard public function getAnnouncements() { $sql = "SELECT * FROM announcements"; $query=$this->db->query($sql); return $query->result_array(); } public function get_school() { $sql = "SELECT * FROM schools"; $query = $this->db->query($sql); return $query->result_array(); } public function get_department($sch_id) { $sql = "SELECT * FROM departments WHERE sch_id=?"; $query = $this->db->query($sql,array($sch_id)); return $query->result_array(); } public function get_program($dept_id) { $sql = "SELECT * FROM programmes WHERE department_id=?"; $query = $this->db->query($sql,$dept_id); return $query->result_array(); } //New clearance dates function public function new_Clearance($date_id,$newdates) { $this->db->where('date_id',$date_id); $qry=$this->db->update("clearance_dates", $newdates); if ($qry) { return true; } else { return false; } } //fetch clearance dates from db public function get_dates() { $sql="SELECT clearance_dates.*, status.status FROM clearance_dates, status WHERE clearance_dates.status=status.status_id"; $query=$this->db->query($sql); return $query->result_array(); } //fetch student to the arares view public function getStudent() { $sql="SELECT * FROM users WHERE role_id=2"; $query=$this->db->query($sql); return $query->result_array(); } /*==================POST ARARES TO DB VIA THE MODEL=========================*/ public function newArares($arares) { $qry = $this->db->insert('section_arares', $arares); if ($qry) { //$this->form_validation->set_message('New Student', 'New student successfully registered.'); return '<div class="alert alert-success">New student details Captured! </div>'; } else { return false; } } /*==================GET STUDENTS WITH ARARES IN VARIOUS SECTIONS OF THE INSTITUTION=========================*/ public function getStudentArares($id) { $this->db->select('*'); $this->db->from('section_arares a'); $this->db->join('users u','u.user_id=a.student','left'); $this->db->join('programmes p','p.prog_id=u.program','left'); $this->db->join('departments d','d.dept_id=p.department_id','left'); $this->db->join('schools s','s.sch_id=d.sch_id','left'); $this->db->join('status t','t.status_id=a.status_id','left'); $this->db->join('sections c','c.section_id=a.section_id'); $this->db->where('a.status_id',2); $this->db->where('a.section_id',$id); $query=$this->db->get(); return $query->result_array(); } public function Deleteid($arare_id) { $this->db->where('arares_id',$arare_id); return $this->db->delete('section_arares'); } public function deleteArareSweet($id) { $sql="DELETE FROM section_arares WHERE arares_id=?"; $qry = $this->db->query($sql,$id); if ($qry) { return true; } else { return false; } } // Deletes a STUDENT WITH ARARES FROM DATABASE public function deleteArare($id) { $this->db->where('arares_id', $id); $qry = $this->db->delete('section_arares'); if ($qry) { return true; } else { return false; } } // UPDATES STUDENT WITH ARARES IN DATABASE public function updateArares($status){ $sql="UPDATE section_arares SET status_id=1 WHERE arares_id=?"; $query=$this->db->query($sql,$status); if($query){ return true; } else{ return false; } } // OPENS CLEARANCE PROCESS public function OpenClearance($status){ $sql="UPDATE clearance_dates SET status=5 WHERE date_id=?"; $query=$this->db->query($sql,$status); if($query){ return '<div class="alert alert-success">New student details Captured! </div>'; return true; } else{ return false; } } // CLOSE CLEARANCE PROCESS public function CloseClearance($status){ $sql="UPDATE clearance_dates SET status=4 WHERE date_id=?"; $query=$this->db->query($sql,$status); if($query){ return true; } else{ return false; } } // Logs in the Administrator into the portal public function Login($params) { $data = array( 'email' => $params['email'], 'password' => $params['password'] ); $qry = $this->db->get_where('users', $data); if ($qry->num_rows() == 1) { return $qry->row('role_id'); } else { return false; } } public function getUserName($email) { $data = array( 'email' => $email ); $qry = $this->db->get_where('users', $data); if ($qry) { return $qry->result_array(); } } /* Return Section_id */ public function getSectionId($email) { $sql="SELECT * FROM users WHERE email=?"; $query=$this->db->query($sql,$email); if($query->num_rows()==1){ return $query->row('section_id'); } else{ return false; } //return $query->result_array(); } // UPDATE ANNOUNCEMENTS public function updateAnnouncement($id,$edit){ // $sql="UPDATE announcements SET title=?, subject=? WHERE date_id=?"; //$id=$edit['ann_id']; $data = array( 'title'=>$edit['title'], 'subject'=>$edit['subject'] ); $this->db->where('ann_id',$id); $query= $this->db->update('announcements',$data); //$query=$this->db->query($sql,$status); if($query){ return true; } else{ return false; } } public function deleteAnnouncement($id) { $sql="DELETE FROM announcements WHERE ann_id=?"; $query=$this->db->query($sql,$id); if($query){ return true; } else { return false; } } //count registered students public function CountStudents($id){ $this->db->select('*')->from('section_arares')->where('section_id',$id)->count_all(); $query=$this->db->get(); return $query->num_rows(); } //count students with arares public function UnclearedStudents($id){ $this->db->select('*')->from('section_arares')->where('status_id',2)->where('section_id',$id)->count_all(); $query=$this->db->get(); return $query->num_rows(); } //count cleared students public function ClearedStudents($id) { $this->db->select('*')->from('section_arares')->where('status_id',1)->where('section_id',$id)->count_all(); $query=$this->db->get(); return $query->num_rows(); /* $sql="SELECT * FROM clearance"; $query=$this->db->query($sql); return $query->num_rows();*/ } /************************************GET SCHOOL DEANS FROM THE DATABASE*****************************/ public function Deans() { $sql="SELECT school_deans.*,schools.* FROM school_deans,schools WHERE school_deans.school_id=schools.sch_id"; $query=$this->db->query($sql); return $query->result_array(); } public function add_dean($dean) { $qry = $this->db->insert('school_deans', $dean); if ($qry) { return true; } else { return false; } } // upload passport public function upload_passport($pass, $email) { $this->db->where('email', $email); $qry = $this->db->update('users', $pass); if ($qry) { return true; } else { return false; } } public function get_passport($email) { $sql="SELECT passport FROM users WHERE email=?"; $query=$this->db->query($sql,$email); return $query->result_array(); } /* FETCH IMPORTED DATA */ function select() { $this->db->order_by('id', 'DESC'); $query = $this->db->get('students'); } /* FUNCTION TO INSERT THE IMPORTED DATA FROM A CSV FILE TO THE DATABASE */ function insert($data) { $this->db->insert_batch('users', $data); } /* get student bank details*/ public function get_bankDetails() { $this->db->select('first_name,middle_name, surname, school_name, department,b.reg_number,bank_name,bank_branch, bank_account,amount'); $this->db->from('users u', 'left'); $this->db->join('programmes p','p.prog_id=u.program','left'); $this->db->join('departments d','d.dept_id=p.department_id','left'); $this->db->join('schools s','s.sch_id=d.sch_id','left'); $this->db->join('bank_details b','b.reg_number=u.reg_number'); $query=$this->db->get(); return $query->result_array(); } } ?>
true
5546d54d38979cce2a85dfe0275ff144aeb67676
PHP
bigster322/Tasks
/Задачки с UniLecs/Число Смита/index.php
UTF-8
2,140
3.21875
3
[]
no_license
<?php // Задача: просматривая свою телефонную книжку в 1982 году, математик Альберт Вилански обратил внимание на то, // что телефонный номер его зятя Гарольда Смита (493-7775) обладал интересным свойством: // сумма его цифр равнялась сумме цифр всех его простых сомножителей (единица не в счёт). // // Число 4 937 775 раскладывается на простые сомножители следующим образом: // // 4 937 775 = 3 × 5 × 5 × 65 837. // // Сумма цифр телефонного номера равна 4 + 9 + 3 + 7 + 7 + 7 + 5 = 42, и сумма цифр его разложения на простые сомножители также равна 3 + 5 + 5 + 6 + 5 + 8 + 3 + 7 = 42. Вилански назвал такой тип чисел по имени своего зятя. Так как этим свойством обладают все простые числа, Вилански не включил их в определение. // // Найдите 3 числа Смита, следующие за телефонным номером зятя этого математика. function factoringOut($n) { $c = 0; $del = 0; while($c <= ($n / 2)) { $c++; if ($n % $c == 0) { $del = $n / $c; $max_del = $c; } if ($c == $del) break; } if ($max_del == 1) { return $n; } else { return strval($del) . strval(factoringOut($max_del)); } } function sumOfNums($numStr) { $sum = 0; for ($i = 0; $i < strlen($numStr); $i++) { $sum += intval($numStr[$i]); } return $sum; } function compare($num) { if (sumOfNums(factoringOut($num)) === sumOfNums(strval($num))) return $num; return false; } function check($n) { $c = 0; $num = $n; while ($c <= 2) { $num++; if (compare($num)){ $c++; echo $num . '<br />'; } } } check(4937775);
true
c94df3ea4e7629a9652343ecf46cd538d58069cd
PHP
naumanshahid007/Acadmy_Management_system
/app/class/update_class.php
UTF-8
3,748
2.609375
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
<?php include("../includes/header.php"); // get specific class id $id=$_GET["class_id"]; // fetch class against specific class id $query = "SELECT * FROM classes WHERE class_id = $id "; $res = mysqli_query($con,$query); $row=mysqli_fetch_assoc($res); // get specific branch id $branch_id = $row['branch_id']; // fetch branches name not against specific branch id $branches = "SELECT * FROM branches WHERE branch_id != $branch_id AND delete_status = 1 "; $allbranches = mysqli_query($con,$branches); $branchesname = mysqli_fetch_array($allbranches); //fetch branch name against specific branch id $branch = "SELECT * FROM branches WHERE branch_id = $branch_id AND delete_status = 1 "; $onebranch = mysqli_query($con,$branch); $branchname = mysqli_fetch_array($onebranch); ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Main content --> <div class="container-fluid"> <h3 class="well well-sm" style="border-radius:10px;font-weight: bolder; background-color:#00c0ef; color: white; text-align: center;">Update Class</h3><br> <form method="POST" enctype="multipart/form-data" class="well" style="border-top:1px solid #00c0ef;"> <div class="row"> <div class="col-md-4 form-group"> <label>Branch Name</label> <select name="branch_id" class="form-control"> <option value="<?php echo $branchname["branch_id"]; ?>"><?php echo $branchname["branch_name"]; ?></option> <option value="<?php echo $branchesname["branch_id"]; ?>"><?php echo $branchesname['branch_name']; ?> </select> </div> <div class="col-md-4 form-group"> <label for="">class Name</label> <input type="text" name="class_name" class="form-control" placeholder="Enter Name of class" value="<?php echo$row['class_name']; ?>" required="" > </div> <div class="col-md-4 form-group"> <label for="">class Description </label> <textarea name="class_description" required="" class="form-control" placeholder=" class Description " rows="1"> <?php echo $row["class_description"]; ?></textarea> </div> </div> <br> <div class="row"> <div class="col-md-4"> <button type="submit" class="btn btn-primary" name="submit"><i class="glyphicon glyphicon-ok"></i> Update</button>&nbsp; <a href="index.php" title="Go to main page" class="btn btn-danger"><i class="fa fa-times"></i> Cancel</a> </div> </div> </form> </div> <?php if(isset($_POST["submit"])){ $branch_id = $_POST["branch_id"]; $class_name = $_POST["class_name"]; $class_description = $_POST["class_description"]; $query_update = "UPDATE classes SET branch_id = '$branch_id', class_name = '$class_name', class_description = '$class_description', updated_by ='$user' WHERE class_id = '$id'"; $result = mysqli_query($con,$query_update); if($result) { echo "<script type='text/javascript'>window.location='index.php'</script>"; } } ?> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="pull-right hidden-xs"> <b>Version</b> 2.4.0 </div> <strong>Copyright &copy; 2014-2016 <a href="http://dexdevs.com/">DEXDEVS</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <!-- /.control-sidebar --> <!-- Add the sidebar's background. This div must be placed immediately after the control sidebar --> <div class="control-sidebar-bg"></div> </div> <!-- ./wrapper --> <!-- jQuery 3 --> <?php include"../includes/footer.php"; ?>
true
6793e9211421428e85422318000165c57be0b54a
PHP
jasonmarkbeaton/SMSGyan
/update/locality_upd.php
UTF-8
1,105
2.703125
3
[ "MIT" ]
permissive
<?php include 'configdb2.php'; $query = "select locality,id from snapdeal_locality"; $result = mysql_query($query); while ($row = mysql_fetch_array($result)) { $srch_word = $row["locality"]; $locality_id = $row["id"]; $srch_word = trim(preg_replace("~\b(nagar|road|Street|Layout|Bazar|Town|Lane|Colony|Palya|Circle|City|block|junction|cross|Quarters|&|Gali|Temple|high)\b~i", " ", $srch_word)); $srch_word = trim(preg_replace("~\.|\-|,~", " ", $srch_word)); $srch_word = trim(preg_replace("~[\s]+~", " ", $srch_word)); $srch_word=srchstring($srch_word); $q = "update snapdeal_locality set srch='" . mysql_real_escape_string($srch_word) . "' where id =" . $locality_id; if (mysql_query($q)) { echo "<br>Record updated"; } } function srchstring($mystring) { $words = explode(" ", $mystring); $ret = $words[0]; for ($i = 1; $i < count($words); $i++) { if (strlen($words[$i - 1]) == 1 && strlen($words[$i]) == 1) { $ret .= $words[$i]; } else { $ret .= " " . $words[$i]; } } return $ret; } ?>
true
e232a847b07d38a28462b02cef14da62dd6a0546
PHP
repomaster/maju-mundurApp
/app/Http/Requests/ApiRegisterFormRequest.php
UTF-8
900
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class ApiRegisterFormRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rules = [ 'role' => 'required|string', 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'phone' => 'required|string', 'address' => 'required|string', 'password' => 'required|string|min:8|confirmed', ]; if ($this->role == 1) { $rules['shop_name'] = 'required|string|unique:users'; } return $rules; } }
true
ea3e1545a2e0cab04dcc48687818da92e70e8f82
PHP
mw185/CMDBox
/pwaendern.php
UTF-8
4,579
2.84375
3
[]
no_license
<html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width" initial-scale=1.0 /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link href="profil.css" rel="stylesheet"> <link href="pwaendern.css" rel="stylesheet"> <title>Passwort ändern</title> </head> <?php session_start(); include 'connection.php'; #Datenbankverbindung wird hergestellt, indem connection.php aufgerufen wird if(!isset($_SESSION['userid'])) { #es wird geprüft ob eingelogt, ansonsten wird auf login.php weitergeleitet header("location: login.php"); } ?> <body> <div class="extrainfo"> <img src="CMDBox.png" width="250px" alt="Logo"/> </div> <ul><li><img src="<?php echo 'Profilbild/'.$_SESSION ['userid'].'.jpg';?>" width="285px" alt="Profilbild"/></li></ul> <div> <div class="nav"> <div class="container"> <ul class="pull-right"> <li><a href="upload.php">CMD Upload</a></li> <li><a href="pwaendern.php">Passwort ändern</a></li> <li><a href="profilbild.php">Profilbild ändern</a></li> <li><a href="logout.php">Logout</a></li> </ul> </div> </div> </div> <?php $showFormular = true; #Die Variable ShowFormular wird auf true gesetzt-> Formular wird angezeigt $statement = $db->prepare("SELECT * FROM person WHERE username = :username"); #mit der Variable $statement alle usernames in der Datenbank 'person' vorbereiten $result = $statement->execute(array('username' => $username)); #eingegebenen username mit username aus Datenbank abgleichen $user = $statement->fetch(); #variable user erstellen mit dem entsprechenden username aus $statement und aus der DB holen if (isset($_SESSION['userid'])){ #Wenn der Nutzer in der Session angemeldet ist, wird eine userid übergeben $username = $_SESSION['userid']; #der userid wird die Variable $username zugewiesen } if (isset($_GET['password'])) { #eingegebene Daten werden aus Formular ausgelesen $error = false; #Die Variable $error wird auf false gesetzt $passwort_alt = $_POST['passwort_alt']; $passwort_neu = $_POST['passwort_neu']; $passwort_neu2 = $_POST['passwort_neu2']; if ($passwort_neu != $passwort_neu2) { #Es wird geprüft, ob die neuen Passwörter überein stimmen, ansonsten wird eine Fehlermeldung ausgegeben echo '<p>Die neuen Passwörter stimmen nicht überein!</p>'; #und die Variable $error auf true gesetzt -> Änderung wird nicht ausgeführt $error = true; } if ($passwort_neu == $passwort_alt) { #prüft, ob das neue und das alte Passwort überein stimmen, wenn ja -> wie oben. echo '<p>Das neue Passwort ist unverändert!</p>'; $error = true; } if (password_verify($passwort_alt, $user['password'])) { echo '<p>Das alte Passwort ist nicht korrekt!</p>'; #und die Variable $error auf true gesetzt -> Änderung wird nicht ausgeführt $error = true; } # Kein Error, Passwort kann jetzt geändert werden if (!$error) { $passwort_hash = password_hash($passwort_neu, PASSWORD_DEFAULT); #Das neue Passwort wird gehasht $statement = $db->prepare("UPDATE person SET password = :password WHERE username = :username"); #SQL Statement Updated das Passwort in der DB $result = $statement->execute(array('password' => $passwort_hash, 'username' => $username)); if ($result) { # Wenn das Statement ausgeführt wurde und das Passwort geändert wurde, $showFormular = false; #wird das Formular ausgeblendet echo '<h3>Dein Passwort wurde erfolgreich geändert!</h3>'; #und eine Bestätigungsnachricht ausgegeben ?> <a href=upload.php><h4>Zurück</h4></a> <?php } } } if($showFormular) { #Das wird angezeigt, wenn $showFormular = true ist ?> <br/><br/><br/><br/><br/> <br/><br/> <form action="pwaendern.php?password=1" method="post"> <input type="password" size="40" maxlength="250" name="passwort_alt" placeholder="Altes Passwort"><br> <input type="password" size="40" maxlength="250" name="passwort_neu" placeholder = "Neues Passwort"><br> <input type="password" size="40" maxlength="250" name="passwort_neu2" placeholder = "Passwort wiederholen"><br><br> <button type="submit">Passwort ändern</button> <button type="reset">Eingaben zurücksetzen</button> </form> <?php } ?> </body> </html>
true
a018b3c2e518f45df9dc33b5ae98042e47aabab3
PHP
camarama/BabaCoolCar
/src/Entity/Adresse.php
UTF-8
2,033
2.578125
3
[]
no_license
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\AdresseRepository") */ class Adresse { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $lieudepart; /** * @ORM\Column(type="string", length=255) */ private $lieudestination; /** * @ORM\OneToMany(targetEntity="App\Entity\Etape", mappedBy="adresse") */ private $etapes; public function __construct() { $this->etapes = new ArrayCollection(); } public function getId() { return $this->id; } public function getLieudepart(): ?string { return $this->lieudepart; } public function setLieudepart(string $lieudepart): self { $this->lieudepart = $lieudepart; return $this; } public function getLieudestination(): ?string { return $this->lieudestination; } public function setLieudestination(string $lieudestination): self { $this->lieudestination = $lieudestination; return $this; } /** * @return Collection|Etape[] */ public function getEtapes(): Collection { return $this->etapes; } public function addEtape(Etape $etape): self { if (!$this->etapes->contains($etape)) { $this->etapes[] = $etape; $etape->setAdresse($this); } return $this; } public function removeEtape(Etape $etape): self { if ($this->etapes->contains($etape)) { $this->etapes->removeElement($etape); // set the owning side to null (unless already changed) if ($etape->getAdresse() === $this) { $etape->setAdresse(null); } } return $this; } }
true
ad1aab789cb40649028a1d5751c9a9cd668b5d6c
PHP
bjuppa/fluent-html
/src/HtmlBuilder.php
UTF-8
10,758
3.1875
3
[ "MIT" ]
permissive
<?php namespace FewAgency\FluentHtml; use Illuminate\Contracts\Support\Htmlable; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Support\Collection; /** * Builds HTML string representations of elements from parameters. */ class HtmlBuilder { /** * Available attribute quote characters " and ' */ const ATTRIBUTE_QUOTE_CHARS = '"\''; // This const can be made into an array on PHP >= 5.6 /** * Constants to use for readability with the $escape_contents parameter */ const DO_ESCAPE = true; const DONT_ESCAPE = false; /** * The html elements that have no closing element * @var array */ public static $void_elements = [ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', 'track', 'wbr' ]; // This static array can be made into a const on PHP >= 5.6 /** * Build an HTML string from parameters describing a single element and its children. * * @param string $tag_name * @param array|Arrayable $attributes * @param array|Arrayable|string|Htmlable $contents * @param bool $escape_contents defaults to true * @param string $attribute_quote_char to use for quotes around attribute values, can be either ' or default " * @return string */ public static function buildHtmlElement( $tag_name, $attributes = [], $contents = [], $escape_contents = true, $attribute_quote_char = '"' ) { $tag_name = self::escapeHtml($tag_name); $tag_parts['opening'] = "<$tag_name"; $tag_parts['opening'] .= self::buildAttributesString($attributes, $attribute_quote_char); $tag_parts['opening'] .= ">"; $tag_parts['content'] = self::buildContentsString($contents, $escape_contents); if (strlen($tag_parts['content']) or !in_array($tag_name, self::$void_elements)) { $tag_parts['closing'] = "</$tag_name>"; } $tag_parts = array_filter($tag_parts, 'strlen'); $glue = ''; if (strlen(implode($tag_parts)) > 80 or (isset($tag_parts['content']) and str_contains($tag_parts['content'], "\n")) ) { $glue = "\n"; } return implode($glue, $tag_parts); } /** * Build a string of html contents * * @param string|Htmlable|array|Arrayable $contents If a key is a valid string, it will be used for content if the corresponding value is truthy * @param bool $escape_contents can be set to false to not html-encode content strings * @return string */ public static function buildContentsString($contents, $escape_contents = true) { return self::flatten(self::evaluate($contents))->transform(function ($item, $key) use ($escape_contents) { if (is_object($item)) { if ($item instanceof FluentHtmlElement) { return $item->branchToHtml(); } elseif ($item instanceof Htmlable) { return $item->toHtml(); } elseif (method_exists($item, '__toString')) { $item = strval($item); } else { //This object couldn't safely be converted to string return false; } } if (is_string($key) and trim($key) and $item) { //This key is valid as content and its value is truthy $item = $key; } $item = trim($item); if ($escape_contents) { return self::escapeHtml($item); } else { return $item; } })->filter(function ($item) { //Filter out empty strings and booleans return isset($item) and !is_bool($item) and '' !== $item; })->implode("\n"); } /** * Build an attribute string starting with space, to put after html tag name * * @param array|Arrayable $attributes * @param string $attribute_quote_char to use for quotes around attribute values, can be ' or default " * @return string */ public static function buildAttributesString($attributes = [], $attribute_quote_char = '"') { $attribute_quote_char = self::getAttributeQuoteChar($attribute_quote_char); $attributes = self::flattenAttributes(self::evaluate($attributes)); $attributes_string = ''; foreach ($attributes as $attribute_name => $attribute_value) { if (is_object($attribute_value) and !method_exists($attribute_value, '__toString')) { $attribute_value = false; } $attribute_value = self::flattenAttributeValue($attribute_name, $attribute_value); if (isset($attribute_value) and $attribute_value !== false) { $attributes_string .= ' ' . self::escapeHtml($attribute_name); if ($attribute_value !== true) { $attributes_string .= '=' . $attribute_quote_char . self::escapeHtml($attribute_value) . $attribute_quote_char; } } } return $attributes_string; } /** * Flatten out contents of any numeric attribute keys * * @param array|Arrayable $attributes * @return array */ protected static function flattenAttributes($attributes) { $attributes = Collection::make($attributes); $flat_attributes = []; foreach ($attributes as $attribute_name => $attribute_value) { if (is_int($attribute_name)) { if (self::isArrayable($attribute_value)) { $flat_attributes = array_merge($flat_attributes, self::flattenAttributes($attribute_value)); } else { $flat_attributes[$attribute_value] = true; } } else { $flat_attributes[$attribute_name] = $attribute_value; } } return $flat_attributes; } /** * If any attribute's value is an array, its contents will be flattened * into a comma or space separated string depending on type. * * @param string $attribute_name * @param mixed $attribute_value * @return string */ public static function flattenAttributeValue($attribute_name, $attribute_value) { if (self::isArrayable($attribute_value)) { //This attribute is a list of several values, check each value and build a string from them $attribute_value = self::flatten($attribute_value); $values = []; foreach ($attribute_value as $key => $value) { if ($value) { if (is_int($key)) { //If the key is numeric, the value is put in the list $values[] = $value; } else { //If the key is a string, it'll be put in the list when the value is truthy $values[] = $key; } } else { // if the value is falsy, the key will be removed from the list $values = array_diff($values, [$key]); } } if (count($values) < 1) { return null; } $attribute_value = implode($attribute_name == 'class' ? ' ' : ',', $values); } return $attribute_value; } /** * Make sure returned attribute quote character is valid for use * * @param $attribute_quote_char * @return string A valid attribute quote character */ protected static function getAttributeQuoteChar($attribute_quote_char = '"') { if (!in_array($attribute_quote_char, str_split(self::ATTRIBUTE_QUOTE_CHARS))) { $attribute_quote_char = '"'; } return $attribute_quote_char; } /** * Escape HTML characters * * @param Htmlable|string $value * @return string */ public static function escapeHtml($value) { return e($value); } /** * Alias for escape() * * @param Htmlable|string $value * @return string */ public static function e($value) { return self::escapeHtml($value); } /** * Check if parameter can be used as array. * * @param $value * @return bool */ public static function isArrayable($value) { return is_array($value) or $value instanceof Arrayable; } /** * Determine if the given value is callable, but not a string nor a callable object-method array pair. * * @param mixed $value * @return bool */ public static function useAsCallable($value) { return !is_string($value) and !is_array($value) and is_callable($value); } /** * Recursively evaluates input value if it's a callable, or returns the original value. * * @param mixed $value to evaluate, any contained callbacks will be invoked. * @return mixed Evaluated value, guaranteed not to be a callable. */ protected static function evaluate($value) { if (self::useAsCallable($value)) { return self::evaluate(call_user_func($value)); } if (self::isArrayable($value)) { $collection = $value instanceof Collection ? $value->make($value) : new Collection($value); return $collection->transform(function ($value) { return self::evaluate($value); }); } return $value; } /** * Flatten multidimensional arrays to a one level Collection, preserving keys. * * @param mixed $collection,... * @return Collection */ public static function flatten($collection) { $flat_collection = $collection instanceof Collection ? $collection->make() : new Collection(); $collection = func_get_args(); // This can use ... instead of func_get_args() on PHP >= 5.6 http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list array_walk_recursive($collection, function ($item, $key) use (&$flat_collection) { if ($item instanceof Arrayable) { $flat_collection = $flat_collection->merge(self::flatten($item->toArray())); } elseif (is_int($key)) { $flat_collection->push($item); } else { $flat_collection->put($key, $item); } }); return $flat_collection; } }
true
04b514728f48651b039c189a53d4ababe8b85aaf
PHP
intellehub/permissible-ng
/src/Permission.php
UTF-8
1,309
2.78125
3
[ "MIT" ]
permissive
<?php namespace Shahnewaz\PermissibleNg; use Shahnewaz\PermissibleNg\Role; use Illuminate\Database\Eloquent\Model; class Permission extends Model { public $timestamps = false; protected $fillable = ['type', 'name']; /** * @param $permission * @return array */ public static function getPermissionParts($permission) { $parts = explode('.', $permission); $params = [ 'type' => isset($parts[0]) ? $parts[0] : null, 'name' => isset($parts[1]) ? $parts[1] : null ]; return $params; } public function roles () { return $this->belongsToMany(Role::class, 'role_permission'); } /** * Creates a Permission passed in the form `type.name` * * @param $permission * @return \App\Permission */ public static function createPermission($permission) { $params = self::getPermissionParts($permission); return static::updateOrCreate($params); } /** * Finds a Permission passed in the form `type.name` * * @param $permission * @return \App\Permission | null */ public static function getPermission($permission) { $params = self::getPermissionParts($permission); return static::where($params)->first(); } }
true
435cb4409b849e44d6fe3e8c81cae99f87135dfa
PHP
Mino5531/scrum-project
/assets/php/site.php
UTF-8
1,865
2.625
3
[]
no_license
<?php session_start(); $controller = $_GET["controller"]; include_once("inc.php"); switch ($controller) { case "balance": BalanceController(); break; case "user": UserController(); break; case "authorization": AuthorizationController(); break; } // controller function BalanceController(){ global $conn; $userId = $_SESSION["user-id"]; $sql = "SELECT Kontostand FROM User WHERE UserID = $userId"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) == 1){ $row = mysqli_fetch_assoc($result); $balance = $row["Kontostand"]; $sql = "SELECT Datum, Betrag, Typ FROM PaymentHistory WHERE UserID = $userId ORDER BY Datum DESC LIMIT 3"; $result = mysqli_query($conn, $sql); $history = []; if(mysqli_num_rows($result) > 0){ while($row = mysqli_fetch_assoc($result)){ $payment = ["date"=>$row["Datum"], "amount"=>$row["Betrag"], "type"=>$row["Typ"]]; $history[] = $payment; } $data = ["balance"=>$balance, "history"=>$history]; echo json_encode($data); } else{ $data = ["balance"=>$balance]; echo json_encode($data); } } } function UserController(){ global $conn; $userId = $_SESSION["user-id"]; $sql = "SELECT Username, Profilbild FROM User WHERE UserID=$userId"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) == 1){ $row = mysqli_fetch_assoc($result); $username = $row["Username"]; $imagedb = $row["Profilbild"]; if ($imagedb == null){ $image = null; } else{ $image = base64_encode($imagedb); } $array = ["username"=>$username, "img"=>$image]; echo json_encode($array); } // Falls Profilbilder eingebaut werden sollen müssen sie in dieser Funktion noch ergänzt werden } function AuthorizationController(){ $userId = $_SESSION['user-id']; if ($userId == 0 || $userId == null){ echo false; } else{ echo true; } }
true
f1be0c60c9b2e813614661417bcdbcf27dd1e649
PHP
jbatson/Code
/Location.php
UTF-8
1,382
3.109375
3
[]
no_license
<?php /* * Class Location * @version 1.0 * @date 07/15/10 * @compatibility: PHP 4, PHP 5 */ class Location { public $mapCoordinates; function Location($map_key, $location_address) { $ch = curl_init("http://maps.google.com/maps/geo?key=".$map_key."&output=xml&q=".urlencode($location_address)); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $resp = curl_exec($ch); curl_close ($ch); $pattern = '/<coordinates>?.*<\/coordinates>/is'; @preg_match($pattern, $resp, $matched_content); $get_coords = str_replace("<coordinates>","",$matched_content[0]); $get_coords = str_replace("</coordinates>","",$get_coords); $get_coords = explode(",", $get_coords); $longitude = $get_coords[0]; $latitude = $get_coords[1]; $coordinates = array('latitude' => $latitude, 'longitude' => $longitude); $this->setMapCoordinates($coordinates); return $this->getMapCoordinates(); } /** * Returns $mapCoordinates. * @see Location::$mapCoordinates */ function getMapCoordinates() { return $this->mapCoordinates; } /** * Sets $mapCoordinates. * @param object $mapCoordinates * @see Location::$mapCoordinates */ function setMapCoordinates($mapCoordinates) { $this->mapCoordinates = $mapCoordinates; } } ?>
true
e9bc87bffec935011097ebb03044cc584d3f7569
PHP
ScarZa/supply
/class/read_conn.php
UTF-8
302
2.859375
3
[]
no_license
<?php class Read_DB{ public $read; public function Read_Text(){ $myfile = fopen("$this->read", "r") or die("Unable to open file!"); // Output one line until end-of-file while(!feof($myfile)) { $conn_db[]= fgets($myfile); } fclose($myfile); return $conn_db; } } ?>
true
87749159ab22b406711bfae9b02d96c2f9a99d7e
PHP
rcleozier/screenshot-maker
/images.php
UTF-8
2,447
2.703125
3
[]
no_license
<?php include 'imageresize.php'; use \Eventviva\ImageResize; Class Cropper { private $devices = [ 'iPhone_35_portrait' => [640, 920, 'iphone'], 'iPhone_35_landscape' => [960, 640, 'iphone'], 'iPhone_47_portrait' => [640, 1136, 'iphone'], 'iPhone_47_landscape' => [1136, 640, 'iphone'], 'iPhone_55_portrait' => [750, 1334, 'iphone'], 'iPhone_55_plus_portrait' => [1242, 2208, 'iphone'], 'ipad_portrait' => [768, 1024, 'ipad'], 'ipad_landscape' => [1024, 768, 'ipad'], 'ipad_hires_portrait' => [1536, 2048, 'ipad'], 'ipad_hires_landscape' => [2048, 1536, 'ipad'], 'kindle_portrait_1' => [800, 480, 'kindle'], 'kindle_portrait_2' => [1280, 800, 'kindle'], 'kindle_portrait_3' => [1920, 1200, 'kindle'], 'kindle_portrait_3' => [2560, 1600, 'kindle'], ]; private $rootDir; public function crop($images) { $this->makeRootDirectory(); foreach($images as $image) { foreach ($this->devices as $key => $value) { $img = new ImageResize($image); $img->crop($value[0], $value[1], false); $this->saveImage($img, $key, $image, $value[2]); unset($img); } } $directoryFullPath = "downloads/$this->downloadDir"; $this->zipDirectory($directoryFullPath); $this->cleanUp($directoryFullPath); return $this->downloadDir; } private function makeRootDirectory() { $this->downloadDir = $this->generateRandomString(25); $this->rootDir = "downloads/" . $this->downloadDir; mkdir($this->rootDir); } private function saveImage($img, $key, $image, $dir) { if (!is_dir("{$this->rootDir}/{$dir}")) { mkdir("{$this->rootDir}/{$dir}"); } $image = str_replace("temp/", "", $image); $img->save("{$this->rootDir}/{$dir}/" . $key . "_" . $image, IMAGETYPE_PNG, 5); } private function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } private function zipDirectory($destination) { exec("zip -r '$destination.zip' {$destination}"); } private function cleanUp($destination) { exec("rm -rf {$destination}"); } } ?>
true
622b820848812c075e8117ee0b3a1e2e50558153
PHP
mywikipro/queue-manager
/src/MyWikiPRO/Component/QueueManager/Consumer/Response/MessageInterface.php
UTF-8
659
3
3
[]
no_license
<?php namespace MyWikiPRO\Component\QueueManager\Consumer\Response; /** * Менеджер очередей / Интерфейс отладочного сообщения консьюмера * * Interface MessageInterface * @package MyWikiPRO\Component\QueueManager\Consumer\Response */ interface MessageInterface { const TYPE_INFO = 'info'; const TYPE_WARNING = 'warning'; const TYPE_ERROR = 'error'; /** * Тип сообщения * * @return string */ public function getType(); /** * Текст сообщения * * @return string */ public function getMessage(); }
true
670c0729f8c4a792a455ebb4396cf6eb1e72154e
PHP
AugCat50/keyburner50
/DomainObjectAssembler/Collections/old examples/example____VenueCollection.php
UTF-8
1,060
2.828125
3
[]
no_license
<?php /** * Коллекция для объектов типа Venue */ namespace DomainObjectAssembler\Collections; use DomainObjectAssembler\DomainModel\VenueModel; class VenueCollection extends Collection { /** * Возвращает имя класса модели * Используется для проверки, дочерняя коллекция соответстует конкретному типу модели и может содержать только объекты её типа * * @return string */ public function targetClass(): string { return VenueModel::class; } /** * Возвращает имя класса фабрики моделей * Используется для проверки, дочерняя коллекция должна получить фабрику для своего типа моделей * * @return string */ public function targetFactoryClass(): string { return VenueObjectFactory::class; } }
true
1b2ac5d5832c5fd140bcc3d7fb15928582eb5317
PHP
yingyezhufeng/phan
/src/Phan/Language/Element/GlobalConstant.php
UTF-8
2,056
2.8125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Phan\Language\Element; use Phan\CodeBase; use Phan\Language\Context; use Phan\Language\FQSEN; use Phan\Language\FQSEN\FullyQualifiedGlobalConstantName; use Phan\Language\Type; use Phan\Language\UnionType; class GlobalConstant extends AddressableElement implements ConstantInterface { use ConstantTrait; /** * Override the default getter to fill in a future * union type if available. * * @return UnionType */ public function getUnionType() : UnionType { if (null !== ($union_type = $this->getFutureUnionType())) { $this->getUnionType()->addUnionType($union_type); } return parent::getUnionType(); } /** * @return FullyQualifiedGlobalConstantName * The fully-qualified structural element name of this * structural element */ public function getFQSEN() : FullyQualifiedGlobalConstantName { \assert(!empty($this->fqsen), "FQSEN must be defined"); return $this->fqsen; } /** * @param CodeBase $code_base * @param string $name * The name of a builtin constant to build a new GlobalConstant structural * element from. * * @return GlobalConstant * A GlobalConstant structural element representing the given named * builtin constant. */ public static function fromGlobalConstantName( CodeBase $code_base, string $name ) : GlobalConstant { if (!defined($name)) { throw new \InvalidArgumentException(sprintf("This should not happen, defined(%s) is false, but the constant was returned by get_defined_constants()", var_export($name, true))); } $value = constant($name); $constant_fqsen = FullyQualifiedGlobalConstantName::fromFullyQualifiedString( '\\' . $name ); return new self( new Context(), $name, Type::fromObject($value)->asUnionType(), 0, $constant_fqsen ); } }
true
b77a3f9bf030ee06e5aed77e2232792bbf97fb48
PHP
aymen7/blog
/php/functions.php
UTF-8
639
2.921875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: user * Date: 21/09/2017 * Time: 12:02 */ function connectDb($host,$db,$username,$password){ try{ $conn = new PDO("mysql:host=$host;dbname=$db", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } catch(PDOException $e){ echo "failed to execute the query ".$e->getMessage(); } } //validate the data function validate_data($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
true
6dc712efe9df105012e3fe7bb9b669647fecc378
PHP
hazydazyart/OSU
/CS494/Assignment5/src/loopback.php
UTF-8
619
2.875
3
[]
no_license
<?php echo "<!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>Loopback</title> </head> <body>"; header('Content-Type: text/plain'); $myArr = array(); $type = array( 'Type' => '' ); $parameters = array(); $myArr['Type'] = $_SERVER['REQUEST_METHOD']; if($myArr['Type'] == 'GET') { foreach($_GET as $key => $value) { $parameters[$key] = $value; } } if($myArr['Type'] == 'POST') { foreach($_POST as $key => $value) { $parameters[$key] = $value; } } if(empty($_GET) || empty($_POST)) { $myArr[] = null; } $myArr['parameters'] = $parameters; echo JSON_encode($myArr); echo "</body> </html>"; ?>
true
256c394ffb628b2fa76897ce61daf35eb048d159
PHP
loilo/contao-illuminate-database-bundle
/src/Database/QueryBuilderFactory.php
UTF-8
1,879
2.671875
3
[ "MIT" ]
permissive
<?php namespace Loilo\ContaoIlluminateDatabaseBundle\Database; use Illuminate\Database\Capsule\Manager as Capsule; class QueryBuilderFactory { /** * @var Capsule */ protected $capsule; /** * @var array */ protected $defaultConfig; /** * @var array */ protected $configuredConnections = []; public function __construct($host, $port, $database, $user, $password) { $this->defaultConfig = [ 'driver' => 'mysql', 'host' => $host . ':' . $port, 'database' => $database, 'username' => $user, 'password' => $password, 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => 'tl_', ]; $this->capsule = new Capsule(); $this->capsule->addConnection($this->defaultConfig); } public function create(array $config = []): QueryBuilder { if (empty($config)) { $connection = $this->capsule->getConnection(); } else { // Store configured connections with their index as connection name $index = (string) array_search($config, $this->configuredConnections); if (strlen($index) === 0) { $index = (string) sizeof($this->configuredConnections); $this->configuredConnections[] = $config; $this->capsule->addConnection( array_merge($this->defaultConfig, $config), $index ); } $connection = $this->capsule->getConnection($index); } return new QueryBuilder($connection); } public function getCapsule() { return $this->capsule; } public function setCapsule(Capsule $capsule) { $this->capsule = $capsule; } }
true
19bffa5843df1f5c0530db3276223bcabcae605d
PHP
ice-devel/formation-mi2-js-php-2021
/2-php/10-qualite/1-tests/1-probleme.php
UTF-8
290
3.1875
3
[]
no_license
<?php require 'src/Slugger.php'; /* * Faire ça c'est déjà un début mais c'est pas pratique : * utilisons un outil de tests comme PHPUnit */ $slugger = new Slugger(); $str = "Test de slug"; $slug = $slugger->slug($str); if ($slug !== "test-de-slug") { throw new Exception(); }
true
bab518ddfbb91b17bcca9f0c6ce260ede97de292
PHP
shakilahammad/mayaapaapis
/app/Classes/MakeResponse.php
UTF-8
890
2.53125
3
[]
no_license
<?php namespace App\Classes; class MakeResponse { public static function successResponse($data, $status = 'success', $errorCode = 0, $errorMessage = '') { return response()->json([ 'status' => $status, 'data' => $data, 'error_code' => $errorCode, 'error_message' => $errorMessage ]); } public static function errorResponse($errorMessage) { return response()->json([ 'status' => 'failure', 'data' => null, 'error_code' => 0, 'error_message' => $errorMessage ]); } public static function errorResponseOperator($status, $errorMessage) { return response()->json([ 'status' => $status, 'data' => null, 'error_code' => 0, 'error_message' => $errorMessage ]); } }
true
647e1a77938db2cc0989ed490ec52e6daaf4ea87
PHP
Eric-Daniel/web2018
/config.php
UTF-8
858
2.671875
3
[]
no_license
<?php define('db_host', 'localhost'); define('db_user', 'root'); define('db_password', ''); define('db_name', 'amlsdb'); class db_connect{ public $host = db_host; public $user = db_user; public $password = db_password; public $dbname = db_name; public $conn; public $error; public function __construct() { $this->connect(); } public function connect(){ $this->conn = new mysqli($this->host, $this->user, $this->password, $this->dbname); if(!$this->conn){ $this->error = "Fatal Error: Can't connect to database" . $this->connect->connect_error(); return false; } return $this->conn; } public function db_query($sql){ $result = $this->conn->query($sql); return $result; } public function escape_string($value){ return $this->conn->real_escape_string($_POST["query"]); } } ?>
true
3987bac7418a28a909261a0080e88c70aa6d74af
PHP
dmitriyltw/CheckOrder-magento2
/Model/OrderProvider.php
UTF-8
1,334
2.609375
3
[]
no_license
<?php namespace Litvinov\CheckOrder\Model; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Exception\NotFoundException; class OrderProvider { /** @var OrderRepositoryInterface */ protected $orderRepository; /** @var SearchCriteriaBuilder */ protected $searchCriteriaBuilder; /** * Initialize dependencies. * * @param OrderRepositoryInterface $orderRepository * @param SearchCriteriaBuilder $searchCriteriaBuilder */ public function __construct( OrderRepositoryInterface $orderRepository, SearchCriteriaBuilder $searchCriteriaBuilder) { $this->orderRepository = $orderRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; } /** * @param $fieldValue * Get orders with filter. * @return \Magento\Sales\Api\Data\OrderInterface[] */ public function getOrderByIncrementId($fieldValue) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('increment_id', $fieldValue, 'eq')->create(); $orders = $this->orderRepository->getList($searchCriteria)->getItems(); if (!$orders){ throw new NotFoundException(__('Parameter is incorrect.')); } return array_shift($orders); } }
true
e41bbab47e9e5de446476a776ce7ca376635e9ff
PHP
FrankCastle04/presidenciaV2
/app/Http/Controllers/EmpleadoController.php
UTF-8
4,234
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\empleado; use Illuminate\Http\Request; //use App\Http\Requests\CreateEmpleadoRequest; use App\Http\Requests\SaveEmpleadoRequest; class EmpleadoController extends Controller { public function __construct() { $this->middleware('auth')->except('index', 'show'); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $emplead = empleado::orderBy('apellidos', 'ASC')->paginate(); return view('empleados.index', compact('emplead')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('empleados.create', [ 'empleadItem' => new empleado ]); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(SaveEmpleadoRequest $request) { // $fields = request()->validate([ // 'noempleado' => 'required', // 'nombre' => 'required', // 'apellidos' => 'required', // 'ine' => 'required', // 'curp' => 'required', // 'cargo' => 'required', // 'rfc' => 'required', // 'calle' => 'required', // 'colonia' => 'required', // 'cp' => 'required', // 'municipio' => 'required', // 'correo' => 'required', // 'nocelular' => 'required', // ]); //empleado::create($fields); //empleado::create( $request->validated() ); empleado::create( request()->all()); return redirect()->route('empleados.index')->with('status', 'El empleado fue agregado con exito'); //return request(); // empleado::create( $request->validated() ); // return redirect()->route('empleados.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Empleado $emplea) { return view('empleados.show',[ // 'project => Project::find($id' 'empleadItem' => $emplea //Empleado::findOrFail($id) ]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit(Empleado $emplea) { return view('empleados.edit',[ // 'project => Project::find($id' 'empleadItem' => $emplea //Empleado::findOrFail($id) ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Empleado $emplea, SaveEmpleadoRequest $request) { //$emplea->updateOrInsert( $request->validated() ); $emplea->update([ 'noempleado' => request('noempleado'), 'nombre' => request('nombre'), 'apellidos' => request('apellidos'), 'ine' => request('ine'), 'curp' => request('curp'), 'areaadscr' => request('areaadscr'), 'cargo' => request('cargo'), 'rfc' => request('rfc'), 'calle' => request('calle'), 'colonia' => request('colonia'), 'cp' => request('cp'), 'municipio' => request('municipio'), 'noext' => request('noext'), 'noint' => request('noint'), 'correo' => request('correo'), 'nocasa' => request('nocasa'), 'nocelular' => request('nocelular'), ]); return redirect()->route('empleados.show', $emplea)->with('status', 'La informacion fue actualizada con exito'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Empleado $emplea) { $emplea->delete(); return redirect()->route('empleados.index')->with('status', 'El empleado fue eliminado con exito'); } }
true
e31a51d92e55761fcce4173d9a56c9a7e7de04c9
PHP
CarlosPorta77/z--DH-old-repo
/app/Http/Controllers/Admin/CategoryController.php
UTF-8
4,532
2.53125
3
[]
no_license
<?php namespace App\Http\Controllers\Admin; use App\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use File; use Intervention\Image\Facades\Image; class CategoryController extends Controller { public function index() { $categories = Category::orderBy('id')->paginate(5); return view('admin.categories.index')->with(compact('categories')); //listado } public function create() { return view('admin.categories.create'); //formulario de creación } public function store(Request $request) { //validar $this->validate($request, Category::$rules, Category::$messages); $category = new Category(); //if ($request->hasFile('image')) { // // guardar la imagen en el server // //$path = public_path() . '/images/categories/'; // $path = 'images/categories/'; // $fileName = uniqid() . '-' . $request->file('image')->getClientOriginalName(); // //$img = Image::make($request->file('image')); // Obtengo la imagen // $img = Image::make($request->file('image')); // Obtengo la imagen // $img->resize(1024, // null, // function ($constraint) { // le cambio el tamaño a width: 1024, heigh: auto // $constraint->aspectRatio(); // mantengo el ratio de la imagen // $constraint->upsize(); // no dejo que escale para arriba // }); // $img->save($path . $fileName, 85); // $category->image = $fileName; //} if ($request->hasFile('image')) { // guardar la imagen en el server //$path = public_path() . '/images/categories/'; $path = public_path('/images/categories/'); $fileName = uniqid() . '-' . $request->file('image')->getClientOriginalName(); //$img = Image::make($request->file('image')); // Obtengo la imagen echo '$request->file(\'image\')->getRealPath(): ' . $request->file('image')->getRealPath() . '<br>'; echo '$path: ' . $path . '<br>'; echo '$fileName: ' . $fileName . '<br>'; $img = Image::make($request->file('image')->getRealPath()); // Obtengo la imagen echo 'pasé el make'; $img->resize(1024, null, function ($constraint) { // le cambio el tamaño a width: 1024, heigh: auto $constraint->aspectRatio(); // mantengo el ratio de la imagen $constraint->upsize(); // no dejo que escale para arriba }); echo '$path'; dump($path); echo '$fileName'; dump($fileName); $img->save($path . $fileName, 85); $category->image = $fileName; } $category->name = $request->name; $category->description = $request->description; $category->save(); $msgSuccess = 'Se insertó la categoría exitosamente'; return back()->with(compact('msgSuccess')); } public function edit(Category $category) { return view('admin.categories.edit', compact('category')); //formulario de edición } public function update(Request $request, Category $category) { //validar $this->validate($request, Category::$rules, Category::$messages); if ($request->hasFile('image')) { // guardar la imagen en el server $path = public_path() . '/images/categories/'; $fileName = uniqid() . '-' . $request->file('image')->getClientOriginalName(); $img = Image::make($request->file('image')); // Obtengo la imagen $img->resize(1024, null, function ($constraint) { // le cambio el tamaño a width: 1024, heigh: auto $constraint->aspectRatio(); // mantengo el ratio de la imagen $constraint->upsize(); // no dejo que escale para arriba }); $img->save($path . $fileName, 85); // Me guardo el path a la imagen anterior $previousPath = $path . '/' . $category->image; $category->image = $fileName; } $category->name = $request->name; $category->description = $request->description; $saved = $category->save(); // Si actualicé OK, borro la imagen anterior if ($saved) { File::delete($previousPath); } $msgSuccess = 'Modificación exitosa'; return back()->with(compact('msgSuccess')); } public function destroy(Category $category) { $previousPath = '/images/categories/' . $category->image; $deleted = $category->delete(); if ($deleted) { File::delete($previousPath); } $msgSuccess = 'Eliminación exitosa'; return back()->with(compact('msgSuccess')); } }
true
78c1ed4001206de64ec129b687595193eda934b2
PHP
HenrivantSant/henri
/Framework/Model/Entity/Entity.php
UTF-8
16,497
2.59375
3
[]
no_license
<?php /** * Created by Buro26. * Author: Henri * Date: 13-12-2019 17:09 */ namespace Henri\Framework\Model\Entity; use Doctrine\Common\Annotations\AnnotationReader; use Exception; use Henri\Framework\Database\DatabaseDriver; use Henri\Framework\Model\Entity\Helper\Query; use Henri\Framework\Model\Entity\Helper\Translate; abstract class Entity { /** * @var DatabaseDriver $database */ protected $database; /** * @var AnnotationReader $annotationReader Doctrine Annotation Reader */ protected $annotationReader; /** * @var Translate $helperTranslate */ protected $helperTranslate; /** * @var Query $helperQuery */ protected $helperQuery; /** * @var \ReflectionClass $reflectionClass Reflection of this class */ protected $reflectionClass; /** * @var string $primaryKey the primary key in the table */ protected $primaryKey; /** * @var array $propertyMap map of properties and their belonging name in the table */ protected $propertyMap = array(); /** * @var array $propertyActions actions to related to properties */ protected $propertyActions = array(); /** * @var array $propertyProps properties and their props/settings */ protected $propertyProps = array(); /** * @var string $tableName table name without prefix */ protected $tableName; /** * @var string $tableNamePrefixed prefixed version of the table name */ protected $tableNamePrefixed; /** * Entity constructor. * * @param DatabaseDriver $databaseDriver * @param AnnotationReader $annotationReader * @param Translate $helperTranslate * @param Query $helperQuery * * @throws \ReflectionException */ public function __construct( DatabaseDriver $databaseDriver, AnnotationReader $annotationReader, Translate $helperTranslate, Query $helperQuery ) { $this->database = $databaseDriver; $this->annotationReader = $annotationReader; $this->helperTranslate = $helperTranslate; $this->helperQuery = $helperQuery; $this->reflectionClass = new \ReflectionClass(get_class($this)); $this->setTable(); $this->mapProperties(); } /** * Method to populate object state * * @param array|\stdClass $state state values to populate * @param bool $autoload whether to try to autoload the object based on the given data * * @return void */ public function populateState($state, bool $autoload) : void { if (!is_array($state)) { $state = (array) $state; } foreach ($state as $propertyName => $value) { // Check if property is mapped for db usage if (!$this->hasProperty($propertyName)) { continue; } $this->{$propertyName} = $value; } if ($autoload) { $this->load(); } } /** * Method to populate state from db values * * @param $state * * @return void */ public function populateStateFromDB($state) : void { if (!is_array($state)) { $state = (array) $state; } foreach ($state as $key => $value) { $property = array_search($key, $this->propertyMap); if ($property && property_exists($this, $property)) { $value = $this->onAfterLoad($value, $property); $this->{$property} = $value; } } } /** * Method to load state from db based on populated properties * * @param array $keys keys to load * @param array $loadBy keys to use a reference for load * * @return bool true on succes. false on not found */ public function load(array $keys = array(), array $loadBy = array()) : bool { $query = $this->database->select('[*]')->from('[' . $this->tableNamePrefixed . ']'); $where = ''; foreach ($this->propertyMap as $propertyName => $dbKey) { if (!isset($this->{$propertyName})) { continue; } $value = $this->onBeforeSave($this->{$propertyName}, $propertyName); $query->where($dbKey . ' = %s', $value); } $result = $query->fetch(); if (is_null($result)) { return false; } $result = $result->toArray(); if (empty($result)) { return false; } $this->populateStateFromDB($result); return true; } /** * Method to save/update based on the current state * * @return bool * @throws \Dibi\Exception */ public function save() : bool { // Check if record is new $isNew = isset($this->{$this->primaryKey}) && $this->{$this->primaryKey} ? false : true; if ($isNew) { // Insert $this->database->query('INSERT INTO ' . $this->tableNamePrefixed, $this->getValuesForDatabase()); if ($this->database->getInsertId()) { $this->{$this->primaryKey} = $this->database->getInsertId(); } } else { // Update $this->database->query( 'UPDATE ' . $this->tableNamePrefixed . ' SET', $this->getValuesForDatabase(), 'WHERE ' . $this->primaryKey . ' = ?', $this->{$this->primaryKey} ); } return true; } /** * Method to delete a row from the database * * @return bool * @throws \Dibi\Exception */ public function delete() : bool { if (!isset($this->{$this->primaryKey}) || !$this->{$this->primaryKey}) { throw new Exception('No item found to remove', 500); } $this->database->query( 'DELETE FROM ' . $this->tableNamePrefixed . ' WHERE ' . $this->primaryKey . ' = ' . $this->{$this->primaryKey} ); return true; } /** * Method to get all properties as array * * @return array */ public function getValuesAsArray(bool $preparedForSave = false) : array { $values = array(); foreach ($this->propertyMap as $propertyName => $dbBinding) { $value = $preparedForSave && $this->{$propertyName} ? $this->onBeforeSave($this->{$propertyName}, $propertyName) : $this->{$propertyName}; $values[$propertyName] = $value; } return $values; } /** * @param string $name * @param array $args * * @return \stdClass */ public function getValuesAsObject(bool $preparedForSave = false) : \stdClass { $values = new \stdClass(); foreach ($this->propertyMap as $propertyName => $dbBinding) { $value = $preparedForSave && $this->{$propertyName} ? $this->onBeforeSave($this->{$propertyName}, $propertyName) : $this->{$propertyName}; $values->{$propertyName} = $value; } return $values; } /** * Method to get all properties as array with db bindings as key * * @return array */ protected function getValuesForDatabase() : array { $values = array(); foreach ($this->propertyMap as $propertyName => $dbBinding) { $value = $this->{$propertyName}; $value = $this->onBeforeSave($value, $propertyName); $values[$dbBinding] = $value; } return $values; } /** * On before save event * * @param $value * @param $propertyName * * @return mixed * @throws Exception */ protected function onBeforeSave($value, $propertyName) { if (array_key_exists($propertyName, $this->propertyActions['translate'])) { foreach ($this->propertyActions['translate'][$propertyName] as $action) { if (!method_exists($this->helperTranslate, $action)) { throw new Exception('Method ' . $action . ' not found in ' . get_class($this->helperTranslate), 500); } $value = $this->helperTranslate->{$action}($value, true); } } return $value; } /** * On after load event * * @param $value * @param $propertyName * * @return mixed * @throws Exception */ protected function onAfterLoad($value, $propertyName) { if (strlen($value) && array_key_exists($propertyName, $this->propertyActions['translate'])) { foreach ($this->propertyActions['translate'][$propertyName] as $action) { if (!method_exists($this->helperTranslate, $action)) { throw new Exception('Method ' . $action . ' not found in ' . get_class($this->helperTranslate), 500); } $value = $this->helperTranslate->{$action}($value, false); } } return $value; } /** * Method to get property where clause * * @param string $propertyName name of the property to get * * @return array * @throws Exception */ public function getPropertyWhereClause(string $propertyName) : array { if (!$this->hasProperty($propertyName)) { throw new Exception('Property ' . $propertyName . ' not found', 500); } return array( 'prepare' => $this->propertyMap[$propertyName] . ' = %s ', 'value' => $this->{$propertyName} ); } /** * Method to validate if a property is available * * @param string $property * * @return bool */ public function hasProperty(string $property) : bool { return array_key_exists($property, $this->propertyMap); } /** * Method to get property from object * * @param string $property * * @return mixed * @throws Exception */ public function get(string $property) { // Only this class itself or EntityManager are allowed access $calling_class = debug_backtrace(1, 1)[0]['class']; if (!is_a($calling_class, 'Henri\Framework\Model\Entity\EntityManager', true) && !is_a($calling_class, 'Henri\Framework\Model\Entity\Entity', true)) { throw new Exception('Access to method not allowed', 500); } if (!property_exists($this, $property)) { throw new Exception('Property not found', 500); } return $this->{$property}; } /** * Method to get property's db name * * @param string $property * * @return string * @throws Exception */ public function getPropertyDBName(string $property) : string { // Only this class itself or EntityManager are allowed access $calling_class = debug_backtrace(1, 1)[0]['class']; if (!is_a($calling_class, 'Henri\Framework\Model\Entity\EntityManager', true) && !is_a($calling_class, 'Henri\Framework\Model\Entity\Entity', true)) { throw new Exception('Access to method not allowed', 500); } if (!$this->hasProperty($property)) { throw new Exception('Property ' . $property . ' does not exist for ' . get_class($this), 500); } return $this->propertyMap[$property]; } /** * Method to set table * * @return void */ protected function setTable() : void { $annotation = $this->annotationReader->getClassAnnotation($this->reflectionClass, 'Henri\Framework\Annotations\Annotation\DB'); if ($annotation && isset($annotation->table)) { $this->tableName = $annotation->table; $this->tableNamePrefixed = $this->database->getPrefix() . $this->tableName; } } /** * Method to get table name * * @return string */ public function getTableName(bool $prefixed = true) : string { return $prefixed ? $this->tableNamePrefixed : $this->tableName; } /** * Method to map object properties to table columns * * @return void */ protected function mapProperties() : void { $this->propertyActions['translate'] = array(); $properties = $this->reflectionClass->getProperties(); foreach ($properties as $property) { $annotation = $this->annotationReader->getPropertyAnnotation($property, 'Henri\Framework\Annotations\Annotation\DBRecord'); if (isset($property->name) && $annotation && isset($annotation->name)) { $this->propertyMap[$property->name] = $annotation->name; $propertyProps = new \stdClass(); $propertyProps->name = $annotation->name; $propertyProps->type = isset($annotation->type) && !empty($annotation->type) ? $annotation->type : 'text'; $propertyProps->length = $annotation->length; $propertyProps->primary = $annotation->primary; $propertyProps->translate = $annotation->translate; $propertyProps->empty = $annotation->empty; $propertyProps->unique = $annotation->unique ?? false; $this->propertyProps[$property->name] = $propertyProps; } if (isset($property->name) && $annotation && isset($annotation->translate) && !empty($annotation->translate)) { // Set translate actions $this->propertyActions['translate'][$property->name] = $annotation->translate; } // Check for primary key if (isset($property->name) && $annotation && isset($annotation->primary)) { if ($annotation->primary && isset($this->primaryKey)) { throw new Exception('Multiple primary keys found', 500); } if ($annotation->primary) { $this->primaryKey = $property->name; } } } } /** * Method to get property name by db name * * @param string $dbName * * @return string|null */ private function getPropertyNameByDbName(string $dbName) : ?string { $property = array_search($dbName, $this->propertyMap); if ($property && property_exists($this, $property)) { return $property; } return null; } /** * Method to reset properties */ public function reset() : void { foreach ($this->propertyMap as $propertyName => $dbName) { $this->{$propertyName} = null; } } /** * Method to create entity table * * @param bool $dropTableIfExists * * @return bool * @throws \Dibi\Exception */ public function createTable(bool $dropTableIfExists = false) : bool { if ($dropTableIfExists) { $this->database->query('DROP TABLE if EXISTS ' . $this->tableNamePrefixed); } $query = 'CREATE TABLE ' . $this->tableNamePrefixed . ' ('; $count = 1; foreach ($this->propertyProps as $propertyProp) { $query .= $this->helperQuery->getCreateQueryForProperty($propertyProp); $query .= $count < count($this->propertyProps) ? ',' : ''; $count++; } if ($this->primaryKey) { $query .= ',PRIMARY KEY (' . $this->propertyMap[$this->primaryKey] . ')'; } $query .= ' );'; $this->database->query($query); return true; } /** * Method to update a table by entity properties * * @param bool $removeNonExistingColumns * @param bool $dropTableIfExists * * @return array Array of non properties which only exist in the database and are not present as properties. * If $removeNonExistingColumns = true, then will have been dropped from the table. * Mind this is dangerous in a production environment! * @throws \Dibi\Exception */ public function updateTable(bool $removeNonExistingColumns, bool $dropTableIfExists) : array { $currentColumns = $this->getTableColumns(); $nonExistingColumns = array(); if (is_null($currentColumns)) { // Table does not exist yet $this->createTable(false); throw new Exception('Table ' . $this->tableNamePrefixed . ' did not exist yet. It has been created.'); } if (!is_null($currentColumns) && $dropTableIfExists) { // Table dropped and newly created $this->createTable(false); throw new Exception('Table ' . $this->tableNamePrefixed . ' has been dropped and recreated.'); } $query = 'ALTER TABLE ' . $this->tableNamePrefixed . ' '; $count = 1; foreach ($this->propertyProps as $propertyProp) { if (array_key_exists($propertyProp->name, $currentColumns)) { // Column already present, create update query $query .= $this->helperQuery->getUpdateQueryForProperty($propertyProp, true); } else { // Column is new, create add query $query .= $this->helperQuery->getUpdateQueryForProperty($propertyProp, false); } $query .= $count < count($this->propertyProps) ? ',' : ''; $count++; } foreach ($currentColumns as $column) { $propertyName = $this->getPropertyNameByDbName($column->COLUMN_NAME); if (!$propertyName || !$this->hasProperty($propertyName)) { // Column present in database but not in entity array_push($nonExistingColumns, $column->COLUMN_NAME); if ($removeNonExistingColumns) { $query .= ',' . $this->helperQuery->getRemoveQueryForProperty($column->COLUMN_NAME); } } } $this->database->query($query); return $nonExistingColumns; } /** * Method to get table columns for entity * * @return array|null associative array of columns, null when table does not exist * @throws \Dibi\Exception */ private function getTableColumns() : ?array { $query = 'SELECT column_name, data_type, column_type FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N\'' . $this->tableNamePrefixed . '\''; $columns = $this->database->query($query); $columnsArr = array(); foreach ($columns as $column) { if (property_exists($column, 'COLUMN_NAME')) { $columnsArr[$column->COLUMN_NAME] = $column; } if (property_exists($column, 'column_name')) { $column->COLUMN_NAME = $column->column_name; $columnsArr[$column->COLUMN_NAME] = $column; } } return !empty($columnsArr) ? $columnsArr : null; } }
true
cf41412948564f5e3daf18dd0269bbc115cc1c50
PHP
Mrnt/mrnt-asscn
/controller/admin/mrnt-asscn-install.php
UTF-8
3,150
2.75
3
[]
no_license
<?php /** * Class for installing and uninstalling this plugin * On install sets up tables, on uninstall cleans up all the data it created including options. * * @author Maurent Software ${date.year} */ class MrntAsscnInstall { var $db_version = MRNT_ASSCN_DB_VERSNUM; var $messages = ''; function __construct() { } function activate() { global $wpdb; // trap any errors in the error log ob_start(); require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // create the roles table $table_name = $wpdb->prefix . 'mrnt_asscn_roles'; // NB need two spaces between KEY and name of field for dbDelta $sql = "CREATE TABLE $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, ranking mediumint(9) NOT NULL, title tinytext NOT NULL, subrole tinytext NOT NULL, description tinytext NOT NULL, UNIQUE KEY id (id) ) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;"; @dbDelta($sql); if (!$wpdb->get_var( "SELECT COUNT(*) FROM $table_name" )) { // add some starter values $wpdb->insert( $table_name, array( 'ranking' => 1, 'title' => 'President' ) ); $wpdb->insert( $table_name, array( 'ranking' => 2, 'title' => 'Secretary' ) ); } // create data tables $sql = file_get_contents(MRNT_ASSCN_PATH . '/data/install.mysql'); $sql = str_replace('mrnt_asscn', $wpdb->prefix.'mrnt_asscn', $sql); $this->_batchquery($sql); $sql = file_get_contents(MRNT_ASSCN_PATH . '/data/import.mysql'); $sql = str_replace('mrnt_asscn', $wpdb->prefix.'mrnt_asscn', $sql); $this->_batchquery($sql); add_option(MRNT_ASSCN_DB_VERSION, $this->db_version); $message = ob_get_flush(); mrnt_asscn_log_message($message); if (defined('PMPRO_DIR')) { mrnt_asscn_log_message('You will find an option to add and configure members roles in the menu under "Memberships"->"Member Roles".'); } else { mrnt_asscn_log_message('You will find an option to add and configure members roles in the menu under "Users"->"Member Roles".'); } } function uninstall() { global $wpdb; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); // drop roles table $table = $wpdb->prefix . 'mrnt_asscn_roles'; $wpdb->query("DROP TABLE IF EXISTS $table"); // cleanup user meta $table = $wpdb->prefix . 'usermeta'; $wpdb->query("DELETE FROM $table WHERE meta_key LIKE 'mrnt_asscn_%'"); // remove data tables $sql = file_get_contents(MRNT_ASSCN_PATH . '/data/uninstall.mysql'); $sql = str_replace('mrnt_asscn', $wpdb->prefix.'mrnt_asscn', $sql); $this->_batchquery($sql); //Delete any options that stored also? delete_option(MRNT_ASSCN_DB_VERSION); delete_option(MRNT_ASSCN_ADMIN_NOTICE); } function _batchquery($sql) { $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $mysqli->set_charset('utf8'); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); die; } if ($mysqli->multi_query($sql)) { $i = 0; do { $i++; } while ($mysqli->next_result()); } if ($mysqli->errno) { echo "Batch execution prematurely ended on statement $i.\n"; var_dump($statements[$i], $mysqli->error); } } }
true
ec2d7cf03008f673130dec80fac416da75f86daf
PHP
joelrf/php
/projects/ejercicio2.php
UTF-8
286
3.484375
3
[]
no_license
<?php echo "<table border=\"1\">"; $numero1 =8; for($i = 1; $i <= 10; $i++){ $resultado = $numero1 * $i; echo"<tr>"; echo "<td>$numero1</td>"; echo "<td> x </td>"; echo "<td> $i </td>"; echo "<td> = </td>"; echo "<td>$resultado </td>"; echo "</tr>"; } ?>
true
c0d2d54cd957a3dc8db00bd36e24f73c572c5f4c
PHP
KernelFolla/KFIBackupBundle
/Command/MySqlImportCommand.php
UTF-8
4,847
2.5625
3
[]
no_license
<?php namespace KFI\BackupBundle\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Process\Process; /** * Command that dumps * * based on {@link https://github.com/ABMundi/DatabaseCommands/blob/master/Command/DatabaseDumpCommand.php ABMundi/DatabaseCommands} */ class MySqlImportCommand extends Base { const COMMAND_NAME = 'kfi_backup:mysql_import'; const DEFAULT_FILENAME = 'import.sql.bz2'; const DEFAULT_DIRECTORY = 'app/backup/mysql'; protected $filename; protected $download; protected $clear; /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName(self::COMMAND_NAME) ->setDescription('This task dump the database in a file') ->addOption( 'clear', 'c', InputOption::VALUE_NONE, 'clear the existing tables' )->addOption( 'download', 'w', InputOption::VALUE_REQUIRED, 'download the file' )->addOption( 'filename', 'f', InputArgument::OPTIONAL, 'define a filename', self::DEFAULT_FILENAME )->addOption( 'directory', 'd', InputArgument::OPTIONAL, 'define a directory', self::DEFAULT_DIRECTORY ); } /** * {@inheritDoc} */ protected function init() { $this->download = $this->input->getOption('download'); $this->directory = $this->input->getOption('directory'); $this->filename = $this->input->getOption('filename'); $this->clear = $this->input->getOption('clear'); } /** * {@inheritDoc} */ protected function dispatch() { $time = new \DateTime(); $o = $this->output; $c = $this->getContainer(); try { if(!empty($this->download)) $this->downloadFile($this->download,$this->filename); if(!empty($this->clear)) $this->clearTables( $c->getParameter('database_host'), $c->getParameter('database_name'), $c->getParameter('database_user'), $c->getParameter('database_password') ); $this->mysqlimport( $c->getParameter('database_host'), $c->getParameter('database_name'), $c->getParameter('database_user'), $c->getParameter('database_password'), $this->filename ); $o->writeln(sprintf( "<info>imported from %s in %s seconds</info>", $this->filename, $time->diff($time = new \DateTime())->s )); $o->writeln('<info>MISSION ACCOMPLISHED</info>'); } catch (ProcessException $e) { $o->writeln('<error>Nasty error happened :\'-(</error>'); $o->writeln(sprintf('<error>%s</error>', $e->getMessage())); } } /** * Run MysqlDump * * @throws ProcessException */ protected function mysqlimport($host, $name, $user, $password, $file) { if (!file_exists($file)) { throw new ProcessException(sprintf('<info>File %s don\'t exists</info>', $file)); } $this->executeCode(sprintf( 'bunzip2 < %s | mysql -h %s -u %s --password=%s %s', $file, $host, $user, $password, $name )); $this->output->writeln(sprintf('<info>Database %s imported succesfully</info>', $name)); } protected function clearTables($host, $name, $user, $password) { $this->output->writeln(sprintf('<info>clearing tables of %s</info>', $name)); $command = 'mysql -h {host} --user={user} --password="{password}" -Nse "show tables" {name} | while read table; do mysql -h {host} --user={user} --password={password} -e "SET FOREIGN_KEY_CHECKS = 0; drop table $table" {name}; done'; foreach(array('host','name','user','password') as $k){ $command = str_replace(sprintf('{%s}',$k),$$k,$command); } $this->executeCode($command); $this->output->writeln(sprintf('<info>database %s cleared succesfully</info>', $name)); } protected function downloadFile($from, $to){ $this->output->writeln(sprintf('<info>downloading %s, please wait</info>', $from)); $this->executeCode(sprintf('wget -O %s %s', $to, $from)); } }
true
232bc9740dfd48482ad8538a777c59102fce949a
PHP
marscore/hhvm
/hphp/test/slow/ext_array/array_multisort.php
UTF-8
842
3.234375
3
[ "Zend-2.0", "PHP-3.01", "MIT" ]
permissive
<?php function a() { $ar1 = array(10, 100, 100, 0); $ar2 = array(1, 3, 2, 4); array_multisort(&$ar1, &$ar2); var_dump($ar1); var_dump($ar2); } function b() { $ar0 = array("10", 11, 100, 100, "a"); $ar1 = array(1, 2, "2", 3, 1); $asc = SORT_ASC; $string = SORT_STRING; $numeric = SORT_NUMERIC; $desc = SORT_DESC; array_multisort(&$ar0, &$asc, &$string, &$ar1, &$numeric, &$desc); $ar = array( $ar0, $ar1, ); var_dump($ar); } function c() { $array = array("Alpha", "atomic", "Beta", "bank"); $array_lowercase = array_map("strtolower", $array); $asc = SORT_ASC; $string = SORT_STRING; array_multisort(&$array_lowercase, &$asc, &$string, &$array); var_dump($array); } <<__EntryPoint>> function main_array_multisort() { a(); b(); c(); }
true
537d7344b242e398f68b3638a47fd52f1826af79
PHP
Lezzyy/Exo_POO
/test.php
UTF-8
1,894
3.78125
4
[]
no_license
<?php //la class définit ce qu'il y a à l'intérieur d'un objet // class Product { // public $title = 'Retour vers le futur'; //propriété // //constructeur // function __construct($title){ // $this->title=$title; // // } // function getTitle(){ //méthode // return $title; // } // } // // $p = new Product('Retour vers le futur'); // $p->getTitle(); // class Person { // public $Firstname = "Bill"; // public $LastName = "Murphy"; // public $Age = 29; // } // // $bill = new Person(); // Nous créons une classe « Personnage ». class Personnage { private $_force; private $_localisation; private $_experience; private $_degats; public function __construct($force){ echo 'voici le constructeur'; $this->setForce($force); $this->_experience=1; } // Nous déclarons une méthode dont le seul but est d'afficher un texte. public function gagnerExperience() { echo $this->_experience=$this->_experience+1; //$this->_experience+=1; //$this->_experience++; } public function force() { return $this->_force; } public function frapper(Personnage $perso) { return $perso->_degats += $this->_force; } public function setForce($force) { if (!is_int($force)) { trigger_error('Valeur incorrect, entrez un nombre', E_USER_WARNING); return; } if ($force>100) { trigger_error('Entrez une valeur inférieur à 100', E_USER_WARNING); return; } $this->_force=$force; } } $perso1 = new Personnage(60); $perso2 = new Personnage(100); // // $perso1->setForce(10); // $perso2->setForce(20); $perso1->frapper($perso2); $perso1->frapper($perso2); $perso2->frapper($perso1); echo 'le perso1 a ', $perso1->force(), ' de force, alors que le perso2 a ', $perso2->force(),' de force.';
true
5b49113bcd02f161863c24b009031caf84b6ebed
PHP
hector-valdivia/movi_task
/app/Http/Controllers/GenreController.php
UTF-8
2,040
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Genre; use App\Http\Requests\GenreRequest; use Illuminate\Http\Request; use Illuminate\Http\Response; class GenreController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function index() { return view('genre.genre_index', [ 'genres' => Genre::all() ]); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return view('genre.genre_create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return Response */ public function store(GenreRequest $request) { $genre = Genre::create($request->validated()); session()->flash('success', 'Genre '. $genre->name .' was created'); return redirect()->route('genre.index'); } /** * Show the form for editing the specified resource. * * @param \App\Genre $genre * @return Response */ public function edit(Genre $genre) { return view('genre.genre_edit', [ 'genre' => $genre ]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Genre $genre * @return Response */ public function update(GenreRequest $request, Genre $genre) { $genre->fill($request->validated()); $genre->save(); session()->flash('success', 'Genre '. $genre->name .' was updated'); return redirect()->route('genre.index'); } /** * Remove the specified resource from storage. * * @param \App\Genre $genre * @return Response */ public function destroy(Genre $genre) { $genre->delete(); session()->flash('success', 'Genre '. $genre->name .' was deleted'); return redirect()->route('genre.index'); } }
true
49ed02f5e4da5f472b05200e4105b1454014db2e
PHP
ManarAhmed/GreenTravel
/application/forms/Addpost.php
UTF-8
916
2.546875
3
[]
no_license
<?php class Application_Form_Addpost extends Zend_Form { public function init() { $this->setMethod('POST'); $this->setAttrib('class','form-horizontal'); $title= new Zend_Form_Element_Text("title"); $title->setLabel("Title : "); $title->setAttrib('class','form-control'); $content= new Zend_Form_Element_Textarea("content"); $content->setLabel("Post Content: "); $title->setRequired(); $content->setRequired(); $content->setAttrib('class','form-control'); $content->setAttribs(array('cols'=>'5', 'rows'=>'10')); $submit=new Zend_Form_Element_Submit("submit"); $submit->setValue("Add Experience"); $submit->setAttrib('class','btn btn-success'); $this->addElements( array( $title, $content, $submit ) ); } }
true
6a90f61ebfffc55efa25f435a2e1b6085086883c
PHP
stekel/laravel-bench
/src/Assessment.php
UTF-8
2,130
2.96875
3
[ "MIT" ]
permissive
<?php namespace stekel\LaravelBench; abstract class Assessment implements AssessmentContract { public const GLOBAL_ROUTE = 'performance'; /** * Path to execute the test against * - If null, create route via slug for execution */ public ?string $path = null; /** * Number of requests to send at a time */ public int $concurrency = 1; /** * Number of total requests to send */ public int $requests = 1; /** * Slug to use for reference */ public string $slug = 'default'; /** * Assessment result */ public ?Result $result = null; /** * Custom route execution via slug * Note: this is only enabled if $path is null * Route: /performance/{$slug} * * @return mixed */ public function route() { } /** * Is the current test within the given thresholds? */ public function isValidThreshold(Result $result): void { } /** * Return the assessment as an array */ public function toArray(): array { return [ 'slug' => $this->slug, 'path' => $this->getPath(), 'concurrency' => $this->concurrency, 'requests' => $this->requests, ]; } /** * Execute the test */ public function execute(): Result { if (is_null($this->path)) { $this->path = $this->getPath(); } $this->result = $this->viaApacheBench(); $this->isValidThreshold($this->result); return $this->result; } /** * Use ApacheBench for test execution */ private function viaApacheBench(): Result { return (new ApacheBench()) ->ignoreLengthErrors() ->noPercentageTable() ->noProgressOutput() ->concurrency($this->concurrency) ->requests($this->requests) ->url(url($this->path)) ->execute(); } private function getPath(): string { return $this->path ?? self::GLOBAL_ROUTE.'/'.$this->slug; } }
true
53a121da96796b7f3aed876319d76f5f3c02e3c6
PHP
chenjundong/php-bitbucket-api
/lib/Bitbucket/Client.php
UTF-8
2,817
2.71875
3
[]
no_license
<?php namespace Bitbucket; use Buzz\Client\Curl; use Buzz\Client\ClientInterface; use Bitbucket\HttpClient\HttpClientInterface; use Bitbucket\HttpClient\HttpClient; /** * @property HttpClient $httpClient Description */ class Client { private $options = array( 'base_url' => 'https://api.bitbucket.org/1.0/', 'user_argent' => 'php-bitbucket-api', 'timeout' => 10, 'api_limit' => 5000, ); private $httpClient; public function __construct(HttpClientInterface $httpClient = null) { if (!is_null($httpClient)) { $this->httpClient = $httpClient; } } public function api($name) { switch (strtolower($name)) { case "user": case "users": $api = new Api\User($this); break; case "repo": case "repos": case "repository": case "repositories": $api = new Api\Repositories($this); break; case "email": $api = new Api\Email($this); break; case "group": case "groups": $api = new Api\Groups($this); break; case "group_privileges": case "group-privileges": $api = new Api\GroupPrivileges($this); break; default: throw new \InvalidArgumentException(sprintf('Undefined api instance called: "%s"', $name)); } return $api; } public function authenticate($username,$password) { if (is_null($username) || is_null($password)) { throw new \InvalidArgumentException('You need to specify authentication method!'); } $this->getHttpClient()->authenticate($username, $password); return $this; } public function base64Authenticate($base64) { if (is_null($base64)) { throw new \InvalidArgumentException('You need to specify authentication method!'); } $this->getHttpClient()->base64Authenticate($base64); return $this; } /** * * @return HttpClient\HttpClient */ public function getHttpClient() { if (is_null($this->httpClient)) { $this->httpClient = new HttpClient($this->options); } return $this->httpClient; } public function setHttpClient(HttpClientInterface $httpClient) { $this->httpClient = $httpClient; } public function clearHeaders() { $this->getHttpClient()->clearHeaders(); return $this; } public function setHttpHeaders(array $headers) { $this->getHttpClient()->setHeaders($headers); return $this; } public function getOption($key) { if (is_null($key)) { throw new InvalidArgumentException('Undefined option called: null'); } if (!isset($this->options[$key])) { throw new InvalidArgumentException(sprintf('Undefined option called: "%s"', $key)); } return $this->options[$key]; } public function setOption($key, $value) { if (!isset($this->options[$key])) { throw new InvalidArgumentException(sprintf('Undefined option called: "%s"', $key)); } $this->options[$key] = $value; return $this; } }
true
30bfd3a1dbd69f4e81268fcadbbd45ae1417d7af
PHP
ngocsang1599/mypham
/controllers/frontend/productController.php
UTF-8
2,017
2.59375
3
[]
no_license
<?php //include file productModel de su dung class productModel include "models/frontend/productModel.php"; class productController extends Controller{ //su dung class productModel use productModel; public function category(){ $id = isset($_GET["id"]) && is_numeric($_GET["id"]) ? $_GET["id"]:0; //quy định số bản ghi trên một trang $recordPerPage = 15; //---- //phân trang //tính thông số bản ghi $total = $this->model_total(); //tính tổng số trang $numPage = ceil($total/$recordPerPage);//ham ceil de lay tran //lấy biến p truyển từ url -> biến này thể hiện là đang ở trang mấy $p = isset($_GET["p"])&&is_numeric($_GET["p"])? $_GET["p"]-1:0; $fromRecord = $p*$recordPerPage; //---- //goi ham model_get() trong class productModel de lay du lieu $data = $this->model_get($fromRecord,$recordPerPage); $this->renderHTML("views/frontend/productCategoryView.php", array("data"=>$data,"numPage"=>$numPage,"id"=>$id)); } //chi tiết sản phẩm public function detail(){ $record = $this->model_detail(); $this->renderHTML("views/frontend/productDetailView.php",array("record"=>$record)); } //test 1 cho nhieu public function getProductInHome($category_id){ $data = $this->getProductInHomeModel($category_id); //sử dungj chung 1 form View product $this->renderHTML("views/frontend/formProductView.php",array("data"=>$data)); } //san pham danh muc ngang Form2 public function sanphamdanhmucLuoi($category_id){ $data = $this->getProductInHomeModel($category_id); //sử dungj chung 1 form View product $this->renderHTML("views/frontend/formProductView2.php",array("data"=>$data)); } //san pham danh muc ngang Form3 public function sanphamdanhmucDoc($category_id){ $data = $this->getProductInHomeModel($category_id); //sử dungj chung 1 form View product $this->renderHTML("views/frontend/formProductView3.php",array("data"=>$data)); } } ?>
true
ee625b44a63b8ced571f741e9ddc72a2980434ca
PHP
klausetgeton/esales-gtk
/app/model/Log.class.php
UTF-8
469
2.671875
3
[]
no_license
<?php /** * Log Active Record * @author <your-name-here> */ class Log extends TRecord { const TABLENAME = 'public.log'; const PRIMARYKEY= 'id'; const IDPOLICY = 'serial'; // {max, serial} /** * Constructor method */ public function __construct($id = NULL, $callObjectLoad = TRUE) { parent::__construct($id, $callObjectLoad); parent::addAttribute('tabela'); parent::addAttribute('sql'); } }
true
576268536e8d618b398f3ae92df8654bda32c1d7
PHP
giosifelis/php-docs-api
/apiFunctions.php
UTF-8
2,064
2.828125
3
[ "MIT" ]
permissive
<?php require_once 'utils.php'; function login($userName, $password){ if ($userName === USERNAME && sha1($password) === PASSWORD_HASHED) { $_SESSION['isLoggedIn'] = true; $jsonRes = json_encode(responseMessage(false, LOGIN_SUCCESS)); echo $jsonRes; exit; } else { $jsonRes = json_encode(responseMessage(true, LOGIN_ERROR)); echo $jsonRes; exit; } } function logout(){ unset($_SESSION['isLoggedIn']); session_unset(); $jsonRes = json_encode(responseMessage(false, LOGOUT_SUCCESS)); echo $jsonRes; exit; } function readDirectory(){ $jsonFileContents = file_get_contents(DOCS_FILE_STRUCTURE); return array( 'error' => false, 'msg' => READ_DIR_SUCCESS, 'data' => json_decode($jsonFileContents, true) ); } function updateDirectory( $newContent=false ){ checkSession($_SESSION['isLoggedIn']); if(is_file(DOCS_FILE_STRUCTURE) && file_put_contents(DOCS_FILE_STRUCTURE, $newContent)){ return responseMessage(false, UPDATE_DIR_SUCCESS); } else { return responseMessage(true, UPDATE_DIR_ERROR); } } function createFile( $fileName=false ){ checkSession($_SESSION['isLoggedIn']); $filePath = createFilePath($fileName); if( !is_file($filePath) && copy(TEMPLATE_FILE, $filePath) ) { return responseMessage(false, FILE_CREATED); } else { return responseMessage(true, FILE_NOT_CREATED); } } function updateFile( $fileName=false, $newContent=false ){ checkSession($_SESSION['isLoggedIn']); $filePath = createFilePath($fileName); if(is_file($filePath) && file_put_contents($filePath, $newContent)){ return responseMessage(false, FILE_UPDATED); } else { return responseMessage(true, FILE_NOT_UPDATED); } } function deleteFile( $fileName=false ){ checkSession($_SESSION['isLoggedIn']); $filePath = createFilePath($fileName); if(is_file($filePath) && unlink($filePath) ){ return responseMessage(false, FILE_DELETED); } else { return responseMessage(true, FILE_NOT_DELETED); } }
true
ba230453789b50ce1b38bf8dfe1149890375206e
PHP
smsloverss/sms99
/your-project/app/Services/Messagehub.php
UTF-8
1,818
2.921875
3
[ "MIT" ]
permissive
<?php namespace App\Services; use GuzzleHttp\Client; /** * Class Messagehub * @package App\Services */ class Messagehub { /** * @var Client */ protected $client; /** * @var null */ protected $auth = NULL; /** * Messagehub constructor. */ public function __construct() { $this->client = new Client([ 'base_uri' => 'https://app.messagehub.nl/apis/' ]); $this->getAuthToken(); } /** * @return |null */ private function getAuthToken() { if (!is_null($this->auth)) return $this->auth; $response = $this->client->post('auth', [ 'json' => [ 'type' => 'access_token', 'username' => env('MESSAGEHUB_USERNAME'), 'password' => env('MESSAGEHUB_PASSWORD'), ] ]); $data = json_decode($response->getBody()->getContents()); if (property_exists($data, 'payload')) $this->auth = $data->payload->access_token; return $this->auth; } public function sendSingleMessage($from, $to, $message) { $response = $this->client->post('sms/mt/v2/send', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->getAuthToken(), ], 'json' => [[ 'to' => $to, 'from' => $from, 'message' => $message, ]] ]); return $response->getBody()->getContents(); } public function getBalance() { $response = $this->client->get('sms/mt/v2/balance', [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->auth, ] ]); var_dump($response->getBody()->getContents()); } }
true
4465e2de09b61d31a676a5045069c76347eaa606
PHP
Adamiko/magicrainbowadventure
/application/tests/MagicRainbowAdventure/Tests/Mocks/AuthDriverMock.php
UTF-8
605
2.703125
3
[ "MIT", "LicenseRef-scancode-dco-1.1" ]
permissive
<?php /** * Auth Driver Mock Class * * Always authenticates and returns a new User instance. * * @author Joseph Wynn <joseph@wildlyinaccurate.com> */ namespace MagicRainbowAdventure\Tests\Mocks; class AuthDriverMock extends \Laravel\Auth\Drivers\Driver { /** * Log In * * @param array $arguments * @return void * @author Joseph Wynn <joseph@wildlyinaccurate.com> */ public function attempt($arguments = array()) { return $this->login(1, false); } /** * Get a user entity * * @param int $id * @return \Entity\User * @author Joseph Wynn <joseph@wildlyinaccurate.com> */ public function retrieve($id) { return new \Entity\User; } }
true
50940124c9ae90038ecedacf6b5fb4de037a556b
PHP
phindmarsh/zm-tracker
/public/update.php
UTF-8
2,526
2.625
3
[]
no_license
<?php define ('NOW_PLAYING_URL', 'http://zmonline.com/PlNowPlayingData/'); define ('DEBUG', true); require_once 'simplehtmldom_1_5/simple_html_dom.php'; require_once 'db.inc.php'; file_put_contents('lastupdate', time()); // get the latest five songs and store them $feed = file_get_html(NOW_PLAYING_URL); $items = $feed->find('li'); $count_back = count($items); if(isset($_GET['cron'])) write_log('Checking '.$count_back.' songs via cron'); else { include 'header.php'; ?> <div class="pull-right"> <a href="index.php" class="btn btn-primary"><i class="icon-download-alt icon-white"></i> List</a> </div> <h2>Updating recently played</h2> <pre class="well" style="margin-top:2em;"> <?php } $play_history = get_recent_plays($count_back + 5); $updated_songs = array(); foreach($items as $container){ $title = $container->find('div.songTitle', 0)->plaintext; $artist = $container->find('div.songArtist', 0)->plaintext; $song = load_song($title, $artist); if(!isset($updated_songs[$song['song_id']]) && !isset($play_history[$song['song_id']])){ $updated_songs[$song['song_id']] = $song; create_play($song); } } function load_song($title, $artist){ write_log("Loading song $title by $artist", true); $result = DB::select('SELECT * FROM song WHERE title = "'.DB::escape($title).'" AND artist = "'.DB::escape($artist).'"'); if(empty($result)){ write_log("Creating $title by $artist"); DB::query('INSERT INTO song (title, artist) VALUES ("'.DB::escape($title).'", "'.DB::escape($artist).'")'); $result = array('song_id' => DB::last_insert_id(), 'title' => $title, 'artist' => $artist); } else { $result = array_pop($result); } return $result; } function create_play($song, $time = null){ if($time === null) $time = time(); $timestamp = date('Y-m-d H:i:00', $time); if(empty($play)){ write_log("Creating play for {$song['title']} at $timestamp"); DB::query('INSERT INTO play (song_id, timestamp) VALUES ('.$song['song_id'].', "'.$timestamp.'")'); } } function write_log($message, $verbose = false){ if(!$verbose || isset($_GET['verbose'])){ DB::query('INSERT INTO log (message) VALUES ("'.DB::escape($message).'")'); if(DEBUG) echo "$message\n"; } } function get_recent_plays($limit = 6){ $plays = DB::select('SELECT * FROM play ORDER BY timestamp DESC LIMIT '.$limit); $results = array(); foreach($plays as $play) $results[$play['song_id']] = $play; return $results; } if(isset($_GET['cron'])) exit(); ?> </pre> <?php include 'footer.php'; ?>
true
b071d2c3ba2e5fa07125cf6da258018aa2740366
PHP
nazmulpcc/php-socks
/src/PeerCollection.php
UTF-8
935
3.09375
3
[]
no_license
<?php declare(strict_types=1); namespace Nazmul\Socks; class PeerCollection { /** * Collection of peers * * @var Peer[] */ protected array $peers = []; public function __construct(protected Server &$server) { // } /** * Add a new Peer created from the given $fd * * @param int $fd * @return Peer */ public function add(int $fd) { $this->peers[$fd] = new Peer($this->server, $fd); return $this->peers[$fd]; } /** * Get the Peer with the given $fd * * @param int $fd * @return Peer */ public function get(int $fd): Peer { return $this->peers[$fd] ?? $this->add($fd); } public function has(int $fd) { return isset($this->peers[$fd]); } public function forget(int $fd) { $this->get($fd)->close(); unset($this->peers[$fd]); } }
true
d19ce6846c37d206af46e86657312998cebfeedf
PHP
sanmiguella/coding_and_ctf
/Web_dev/PHP/Web/Practice/functions.php
UTF-8
2,057
3.640625
4
[]
no_license
<?php include "db.php"; function list_items() { // $connection is a global scope variable from "db.php" global $connection; // Query to be passed to mysqli_query() $query = "SELECT * FROM product"; $result = query_check($query); // Creating of table headers. echo "<table border=1 width=30%> <tr> <th>Product ID</th> <th>Product Name</th> <th>Price($)</th> <th>Qty</th> </tr>"; // List down all the products that exists on the database. while ($row = mysqli_fetch_assoc($result)) { $id = $row["id"]; $product_name = $row["product_name"]; $product_price = $row["product_price"]; $product_qty = $row["product_qty"]; // Inserting each row found in the database to the table. echo "<tr> <td>$id</td> <td>$product_name</td> <td>$product_price</td> <td>$product_qty</td> </tr>"; } // Table closing tags. echo "</table><hr>"; } function create_item($product_name, $product_price, $product_qty) { // $connection is a global scope variable from "db.php" global $connection; /* Sample Query: $query = "INSERT INTO users(username, password) "; $query .= "VALUES ('$username', '$password')"; */ $query = "INSERT into product(product_name, product_price, product_qty) "; $query .= "VALUES ('$product_name', '$product_price', '$product_qty')"; query_check($query); // Display a message to the user that the product has been created. echo "<p>$product_qty pieces of $product_name with a price tag of $product_price has been created!</p>"; } function query_check($query) { // $connection is a global scope variable from "db.php" global $connection; $result = mysqli_query($connection, $query); if (!$result) { die("<br>QUERY failed!" . mysqli_error()); } return $result; } ?>
true
bc0b8c429cc84beb728520b3c1e2232a5fb6da44
PHP
famer/screen-scraper-php
/models/Lang.class.php
UTF-8
4,040
2.546875
3
[]
no_license
<?php class Lang { // Translates description from english to georgian public function engToGeDescription ( $eng = NULL ) { if ( !$eng ) return false; $dict = array(); $dict['Chance of rain'] = 'მოსალოდნელია წვიმა'; $dict['Chance of rain or sleet'] = 'მოსალოდნელია წვიმა ან სველი თოვლი'; $dict['Chance of sleet or snow'] = 'მოსალოდნელია თოვლჭყაპი ან თოვლი'; $dict['Chance of snow'] = 'უღრუბლო ამინდი'; $dict['Clear weather'] = 'უღრუბლო ამინდი'; $dict['Cloudy skies'] = 'ღრუბლიანი ცა'; $dict['Few clouds'] = 'მცირედი ღრუბელი'; $dict['Heavy rain'] = 'ძლიერი წვიმა'; $dict['Heavy rain or sleet'] = 'ძლიერი წვიმა ან თოვლჭყაპი'; $dict['Heavy sleet or snow'] = 'ძლიერი თოვლჭყაპი ან თოვლი'; $dict['Light rain'] = 'მცირედი წვიმა'; $dict['Light rain or sleet'] = 'მცირედი წვიმა ან თოვლჭყაპი'; $dict['Light sleet or snow'] = 'მცირედი თოვლჭყაპი ან თოვლი'; $dict['Light snow'] = 'მცირედი თოვლი'; $dict['Partly cloudy skies'] = 'ნაწილობრივ ღრუბლიანი ცა'; $dict['Rain'] = 'წვიმა'; $dict['Rain and possible heavy thunderstorm'] = 'წვიმა, მოსალოდნელია ძლიერი ჭექა-ქუხილი'; $dict['Rain and possible thunder'] = 'წვიდა და ჭექა-ქუხილი'; $dict['Rain or sleet'] = 'წვიმა ან თოვლჭყაპი'; $dict['Rain or sleet and possible heavy thunder'] = 'წვიმა ან თოვლჭყაპი და შესაძლებელია ჭექა-ქუხილი'; $dict['Sleet or snow'] = 'თოვლჭყაპი ან თოვლი'; $dict['Snow'] = 'თოვლი'; return $dict[trim($eng)]; } // Wind direction english to georian translate public function engToGeWindDirectionLang ( $eng ) { if ( !$eng ) return false; $dict = array(); $dict['N'] = 'ჩ'; $dict['NNE'] = 'ჩჩა'; $dict['NE'] = 'ჩა'; $dict['ENE'] = 'აჩა'; $dict['E'] = 'ა'; $dict['ESE'] = 'ასა'; $dict['SE'] = 'სა'; $dict['SSE'] = 'სსა'; $dict['S'] = 'ს'; $dict['SSW'] = 'სსდ'; $dict['SW'] = 'სდ'; $dict['WSW'] = 'დსდ'; $dict['W'] = 'დ'; $dict['WNW'] = 'დჩდ'; $dict['NW'] = 'ჩდ'; $dict['NNW'] = 'ჩჩდ'; return $dict[trim($eng)]; } // Days of week public function engToGeDayOfWeek ( $eng ) { if ( !$eng ) return false; $dict = array(); $dict['Mon'] = 'ორშ'; $dict['Tue'] = 'სამ'; $dict['Wed'] = 'ოთხ'; $dict['Thu'] = 'ხუთ'; $dict['Fri'] = 'პარ'; $dict['Sat'] = 'შაბ'; $dict['Sun'] = 'კვ'; return $dict[trim($eng)]; } // Mounthes public function engToGeMounth ( $eng ) { if ( !$eng ) return false; $dict = array(); $dict['January'] = 'იანვარი'; $dict['February'] = 'თებერვალი'; $dict['March'] = 'მარტი'; $dict['April'] = 'აპრილი'; $dict['May'] = 'მაისი'; $dict['June'] = 'ივნისი'; $dict['July'] = 'ივლისი'; $dict['August'] = 'აგვისტო'; $dict['September'] = 'სექტემბერი'; $dict['October'] = 'ოქტომბერი'; $dict['November'] = 'ნოემბერი'; $dict['December'] = 'დეკემბერი'; return $dict[trim($eng)]; } }
true
cb9d2f15ae5d43579aa1f519787e5b82dfc4fd3a
PHP
2B-Smart/transfaring_co
/app/Http/Controllers/CitiesController.php
UTF-8
4,541
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\cities; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; class CitiesController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ protected $redirectTo = '/cities'; public function index() { $cities = cities::take(100)->get(); return view('cities/index', ['cities' => $cities]); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('cities/create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validateInput($request); cities::create([ 'city_name' => $request['city_name'], 'user_create' => Auth::user()->name, 'user_last_update' => Auth::user()->name ]); return redirect()->intended('/cities'); } /** * Display the specified resource. * * @param \App\cities $cities * @return \Illuminate\Http\Response */ public function show(cities $cities) { // } /** * Show the form for editing the specified resource. * * @param \App\cities $cities * @return \Illuminate\Http\Response */ public function edit($id) { $cities = cities::where('city_name', $id)->first(); // Redirect to user list if updating user wasn't existed if ($cities == null || $cities->count() == 0) { return redirect()->intended('/cities'); } return view('cities/edit', ['cities' => $cities]); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $cities * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $cities = cities::where('city_name', $id)->first(); $constraints=[]; if($cities->city_name!=$request['city_name']){ $constraints = [ 'city_name' => 'required|unique:cities', //'national_id_number' => 'required|max:20|unique:drivers', ]; }else{ $constraints = [ 'city_name' => 'required', //'national_id_number' => 'required|max:20|unique:drivers', ]; } $input = [ //'username' => $request['username'], 'city_name' => $request['city_name'], //'national_id_number' => $request['national_id_number'], 'user_last_update' => Auth::user()->name ]; $this->validate($request, $constraints); try{ cities::where('city_name', $id) ->update($input); }catch (\Exception $e){ return redirect()->intended('errorshandler/connot_do_this'); } return redirect()->intended('/cities'); } /** * Remove the specified resource from storage. * * @param \App\cities $cities * @return \Illuminate\Http\Response */ public function destroy($id) { try{ cities::where('city_name', $id)->delete(); }catch (\Exception $e){ return redirect()->intended('errorshandler/connot_do_this'); } return redirect()->intended('/cities'); } public function search(Request $request) { $constraints = [ 'city_name' => $request['اسمالمدينة'] ]; $cities = $this->doSearchingQuery($constraints); return view('cities/index', ['cities' => $cities, 'searchingVals' => $constraints]); } private function doSearchingQuery($constraints) { $query = cities::query(); $fields = array_keys($constraints); $index = 0; foreach ($constraints as $constraint) { if ($constraint != null) { $query = $query->where( $fields[$index], 'like', '%'.$constraint.'%'); } $index++; } return $query->get(); } private function validateInput($request) { $this->validate($request, [ 'city_name' => 'required|unique:cities', ]); } }
true
400465a65e3181a5e7d1d4a8c6a062da769af921
PHP
diazoxide/complex-cross-architecture
/src/common/Container.php
UTF-8
3,933
3.03125
3
[]
no_license
<?php namespace NovemBit\CCA\common; abstract class Container { /** * @var array * */ private array $instances = []; /** * @var self|null */ private $parent = null; /** * Child component * @var array */ public array $components = []; /** * Get call child components * @return array */ public function getComponents(): array { return $this->components; } /** * @param mixed $name * @return bool */ public function hasComponent(string $name): bool { return isset($this->instances[self::toSnakeCase($name)]); } /** * Get component instance * @param string $name Component key * @return mixed|null */ public function getComponent(string $name): ?self { return $this->instances[self::toSnakeCase($name)] ?? null; } /** * Init sub components */ final public function initComponents(): void { foreach ($this->getComponents() as $name => $component) { if (is_numeric($name)) { throw new \RuntimeException('SubComponent name must be declared in components array as key.'); } $name = self::toSnakeCase($name); $config = []; if (is_array($component)) { $config = $component[1]; $component = $component[0]; } if (class_exists($component) && is_subclass_of($component, self::class)) { $this->instances[$name] = $component::init($this, $config); } } } /** * @param $name * @param $arguments * @return mixed */ public function __call($name, $arguments) { $prefix = substr($name, 0, 3); $key = ltrim(substr($name, 3), '_'); if ($prefix === 'get' && ($method_name = self::toSnakeCase($key)) && isset($this->instances[$method_name])) { return $this->instances[$method_name]; } elseif (!isset($this->{$name}) || !is_callable([$this, $name])) { trigger_error('Call to undefined method ' . static::class . '::' . $name . '()', E_USER_ERROR); } return $this->{$name}; } /** * @param $key * @return mixed|self */ public function __get($key) { return $this->getComponent(self::toSnakeCase($key)) ?? $this->{$key}; } /** * @param string $input * @return string */ private static function toSnakeCase(string $input): string { preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches); $ret = $matches[0]; foreach ($ret as &$match) { $match = $match === strtoupper($match) ? strtolower($match) : lcfirst($match); } return implode('_', $ret); } /** * Early setup component * * @param array $params Component params */ protected function wakeup(array $params = []): void { } /** * @param array|null $params */ abstract protected function main(?array $params = []): void; /** * Component constructor. * @param Container|null $parent Optional: parent component * @param array $params optional: Component params */ protected function __construct(?Container $parent = null, array $params = []) { $this->parent = $parent; $this->wakeup($params); $this->initComponents(); $this->main($params); } /** * @param Container|null $parent * @param array $params * @return static */ public static function init(?Container $parent = null, array $params = []): self { return new static($parent, $params); } /** * @return $this|null */ public function getParent(): ?Container { return $this->parent; } }
true
ca2dad385eeea55e13a140211106f2fcf8c33f36
PHP
IP-CAM/Opencart-to-Symfony-Bridge-Extension
/src/Model/Api/ApiSession.php
UTF-8
1,274
3.046875
3
[]
no_license
<?php declare(strict_types=1); namespace Sypa\Model\Api; class ApiSession { private int $api_session_id; private int $api_id; private string $session_id; private string $ip; private \DateTimeImmutable $date_added; private \DateTimeImmutable $date_modified; public function __construct( int $api_session_id, int $api_id, string $session_id, string $ip, \DateTimeImmutable $date_added, \DateTimeImmutable $date_modified ) { $this->api_session_id = $api_session_id; $this->api_id = $api_id; $this->session_id = $session_id; $this->ip = $ip; $this->date_added = $date_added; $this->date_modified = $date_modified; } public function getApiSessionId(): int { return $this->api_session_id; } public function getApiId(): int { return $this->api_id; } public function getSessionId(): string { return $this->session_id; } public function getIp(): string { return $this->ip; } public function getDateAdded(): \DateTimeImmutable { return $this->date_added; } public function getDateModified(): \DateTimeImmutable { return $this->date_modified; } }
true
430434ad8f06490b297c9adecd48cca129488fb7
PHP
tanmotop/dmall
/database/migrations/2017_10_24_210324_create_couriers_table.php
UTF-8
776
2.65625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCouriersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('couriers', function (Blueprint $table) { $table->increments('id'); $table->string('name', 32)->comment('快递公司名称'); $table->unsignedInteger('sort')->default(50)->comment('排序,默认50,小在前,大在后'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('couriers'); } }
true
c2ac324fd8af1d646d4bd4322c88251acd6dc8d2
PHP
knowgod/Logika
/Logika.php
UTF-8
6,892
3.015625
3
[]
no_license
#!/usr/bin/php <?php define("LOGIKA_DEBUG_MODE", 0); /** * Logika game itself * * @author arkadij */ class Logika { const DigitsRange = 10; /** * Literal strings: */ const S_NoDoublesAllowed = "\n No doubles allowed!!!"; const S_YourGuess = "\n\nYour guess > "; const S_YouWin = "\n\n======= YOU WIN !!! ========\n"; protected $_number; protected $_guessTry; protected $_guessResult; protected $_guessLog = array(); /** * @var AnalysisMatrix */ protected $_analysisMatrix; public function run($digits = 2) { $this->init($digits); $this->input(); while (TRUE !== $this->compare()) { $this->input(); } echo self::S_YouWin; } public function init($digits) { $numbers = array(); for ($i = 0; $i < $digits; ++$i) { $unique = FALSE; while ($unique != TRUE) { $numbers[$i] = rand(0, self::DigitsRange - 1); if ($i > 0) { for ($j = 0; $j < $i; ++$j) { $this->_log("{$i}/{$digits}; j={$j}; >>> " . var_export($numbers, 1)); if ($numbers[$j] == $numbers[$i]) { $unique = FALSE; break; } else { $unique = TRUE; } } } else { $unique = TRUE; } } } $this->_number = implode('', $numbers); $this->_analysisMatrix = new AnalysisMatrix(strlen($this->_number), self::DigitsRange); return $this->_number; } public function test_getNumber() { if (defined('LOGIKA_PHPUNIT_TESTING')) { return $this->_number; } } public function input($inputString = NULL) { echo self::S_YourGuess; $this->_log($inputString); if (is_null($inputString)) { $inputString = trim(fgets(STDIN)); } $this->_guessTry = substr($inputString, 0, strlen($this->_number)); return $this->_guessTry; } public function compare() { $original = array_flip(str_split($this->_number)); $guess = array_flip(str_split($this->_guessTry)); // Debug::log(array('$original' => $original, '$guess' => $guess)); if (count($guess) != count($original)) { echo self::S_NoDoublesAllowed; } else { $correctNumber = 0; $correctPlace = 0; foreach ($original as $_original => $i) { if (isset($guess[$_original])) { $correctNumber++; if ($guess[$_original] == $i) { $correctPlace++; } } } if (0 == $correctNumber) { $this->_analysisMatrix->guessLike_0_0($this->_guessTry); } else { if (0 == $correctPlace) { $this->_analysisMatrix->guessLike_X_0($this->_guessTry); } if (strlen($this->_number) == $correctNumber) { $this->_analysisMatrix->guessLike_4_X($this->_guessTry); } } $this->_guessResult = "{$correctNumber}-{$correctPlace}"; $try = (count($this->_guessLog) + 1) . ". {$this->_guessTry} :: {$this->_guessResult}"; $this->_guessLog[] = $try; echo $this->_analysisMatrix->getTableOutput(); foreach ($this->_guessLog as $record) { echo "\n" . $record; } } return $original == $guess; } /** * Legacy method * * @param mixed $str */ protected function _log($str) { Debug::log($str, 1); } } class AnalysisMatrix { protected $_analizeMatrix = array(); protected $_matrixDimensions = array(); public function __construct($x, $y = 10) { $this->_matrixDimensions = array('x' => $x, 'y' => $y); $sample = array_keys(array_fill(0, $y, '')); $this->_analizeMatrix = array_fill(1, $x, $sample); } /** * None of these numbers are present * * @param string $guess */ public function guessLike_0_0($guess) { foreach ($this->_analizeMatrix as $pos => &$row) { for ($i = 0; $i < strlen($guess); ++$i) { unset($row[$guess[$i]]); } } } /** * Exclude numbers from its' places in matrix * * @param string $digits */ public function guessLike_X_0($guess) { // Debug::log(array('digits' => $digits)); for ($i = 0; $i < strlen($guess); ++$i) { unset($this->_analizeMatrix[$i + 1][$guess[$i]]); } } /** * All numbers guessed properly * * @param string $digits */ public function guessLike_4_X($digits) { foreach ($this->_analizeMatrix as $pos => $row) { $newRow = str_split($digits); asort($newRow); $this->_analizeMatrix[$pos] = array_combine($newRow, $newRow); } } public function getTableOutput() { $output = $ruler = "\n" . str_repeat('=', $this->_matrixDimensions['y'] + ($this->_matrixDimensions['y'] - 1) * 3 + 5); foreach ($this->_analizeMatrix as $position => $aAllowedNums) { $output .= "\n$position => " . implode(' | ', $aAllowedNums); } return $output . $ruler . "\n"; } public function test_getMatrix() { if (defined('LOGIKA_PHPUNIT_TESTING')) { $ret = array(); foreach ($this->_analizeMatrix as $i => $row) { $ret[$i] = implode('', $row); } return $ret; } return FALSE; } } /** * Debugging functions gathered here */ class Debug { protected static function _isEnabled() { return (defined('LOGIKA_PHPUNIT_TESTING') && LOGIKA_PHPUNIT_TESTING) || (defined('LOGIKA_DEBUG_MODE') && LOGIKA_DEBUG_MODE); } /** * * @param mixed $str * @param int $shift */ public static function log($str, $shift = 0) { if (self::_isEnabled()) { $stack = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $before = "\nDEBUG: {$stack[0 + $shift]['line']}. {$stack[1 + $shift]['class']}::{$stack[1 + $shift]['function']} :\n"; fwrite(STDOUT, $before . print_r($str, 1)); } } } ?> <?php if (defined('LOGIKA_PHPUNIT_TESTING') && LOGIKA_PHPUNIT_TESTING) { echo "\n---------- Starting tests here. Required class plugged in. -----------\n\n"; } else { var_export($argv); $l = new Logika(); $l->run(($argc > 1) ? $argv[1] : 2); }
true
efa691048f37ad9b0d91cb7b44c230f1124e3379
PHP
TiboProject/ave_noel
/assets/src/config/Database.php
UTF-8
916
3.09375
3
[]
no_license
<?php namespace App\config; require_once 'vendor/autoload.php'; class Database { const DB_HOST = 'mysql:host=localhost;dbname=avenoel;charset=utf8'; const DB_USER = 'root'; const DB_PASSWORD = ''; private $connection; public function getConnection() { $servername = 'localhost'; $username = 'root'; $password = ''; try{ $this->connection = new \PDO(self::DB_HOST, self::DB_USER, self::DB_PASSWORD); return $this->connection; }catch(PDOException $exception){ die("Erreur : " . $exception->getMessage()."<br>"); } } public function checkConnection() { if(!isset($this->connection)){ return $this->getConnection(); } return $this->connection; } } ?>
true
98a09e172a5e85c7439a2ec35542057b8aba4ecc
PHP
salantryrohan/info290T_iolab
/delicious_trails/tests/delicious_proxy.php
UTF-8
5,034
2.5625
3
[]
no_license
<?php /** * $Id$ */ /** * This PHP script serves as a proxy for Delicious API requests. It processes * the request made by the client, posts the request to Delicious, and * formats the response as JSON data for the client. It provides support for * a JSONP callback so that users can access the Delicious API entirely via * JavaScript and this proxy. */ /* * It is a security liability to accept the user's password parameter in a * GET request because it will show up in the server's logs. Unfortunately, * that's the only way this proxy can work across different servers because * the script must be loaded via a <script src="...this script..."></script> * tag. Note that the password is transmitted insecurely only to the proxy * script; it is sent to the Delicious server over https. * * To improve this situation, install this proxy script on the same server * that serves the Javascript and use a POST request instead. This will * hide the password when used in conjunction with https */ // For error management $errors = new Errors(); // Start with base URL for Delcious API // http://delicious.com/help/api $url ='https://api.del.icio.us/v1/'; // These are the methods described in the Delicious API $allowed_methods = array( 'posts/update', 'posts/add', 'posts/delete', 'posts/get', 'posts/dates', 'posts/recent', 'posts/all', 'posts/all?hashes', 'posts/suggest', 'tags/get', 'tags/delete', 'tags/rename', 'tags/bundles/all', 'tags/bundles/set', 'tags/bundles/delete' ); // These are the parameters allowed by the various Delicious API methods $allowed_params = array( 'bundle', 'count', 'description', 'dt', 'extended', 'fromdt', 'hashes', 'meta', 'meta', 'new', 'old', 'replace', 'results', 'shared', 'start', 'tag', 'tags', 'todt', 'url' ); // Check that a username and password were provided // Prefer $_POST to $_GET because of the security issues mentioned above $username = ''; $password = ''; if (isset($_POST['username'])) { $username = $_POST['username']; } else if (isset($_GET['username'])) { $username = $_GET['username']; } else { $errors->add('A Delicious username was not provided.'); } if (isset($_POST['password'])) { $password = $_POST['password']; } else if (isset($_GET['password'])) { $password = $_GET['password']; } else { $errors->add('A password was not provided.'); } // Check that a valid method was specified if (in_array($_POST['method'], $allowed_methods)) { $url .= $_POST['method']; } else if (in_array($_GET['method'], $allowed_methods)) { $url .= $_GET['method']; } else { // Use posts/add as default method $url .= 'posts/add'; } // Some methods (like all?hashes) already include the ? query indicator // Add it to the URL only if it is needed if (strpos($url, '?') === false) { $url .= '?'; } // Format the query parameters as part of the URL $params = array(); foreach (array_merge($_GET, $_POST) as $key => $value) { if (in_array($key, $allowed_params)) { $params[] = urlencode($key) . '=' . urlencode($value); } } $url .= implode('&', $params); // Final response $json = array(); if (!$errors->exist()) { // Fetch the URL using cURL // Uses cURL becuase allow_url_fopen may be disabled // This will fail if the current PHP installation does not include cURL $ch = curl_init(); $timeout = 5; // set to zero for no timeout curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt ($ch, CURLOPT_USERPWD, $username . ':' . $password); $rsp = curl_exec($ch); $curl_error = curl_errno($ch); curl_close($ch); if ($curl_error == 28) { // Connection timeout // CURLE_OPERATION_TIMEDOUT 28 $errors->add('Request to Delicious API timed out'); } else { // Convert XML response to JSON $xml = simplexml_load_string($rsp); $json['request_url'] = $url; $json['xml'] = $rsp; $json['result_code'] = (string) $xml['code']; } } if ($errors->exist()) { $json['errors'] = $errors->getErrors(); } header('Content-type: application/json'); $json = str_replace("\n", '', json_encode($json)); /* If a callback is specified that means the request is being processed * across domains using JSONP. Send the response wrapped in the callback. * Otherwise, just send the response. It doesn't make sense to set a callback * via POST, so we just check GET. */ if (isset($_GET['callback'])) { echo $_GET['callback'] . '(' . $json . ')'; } else { echo $json; } /** * This simple class manages a collection of errors */ class Errors { var $errors = array(); /** * Add an error to the list */ function add($error) { $this->errors[] = $error; } /** * Detect if any errors have been entered into the list */ function exist() { return count($this->errors) > 0; } /** * Return an array of errors */ function getErrors() { return $this->errors; } }
true
43d524af9a6d01b38e4c541c0e7b9278959e3589
PHP
ethancodes/drupal8
/magazine-issue-pages/src/Routing/MagazineIssuePagesRoutes.php
UTF-8
2,664
2.59375
3
[]
no_license
<?php namespace Drupal\magazine_issue_pages\Routing; use Symfony\Component\Routing\Route; class MagazineIssuePagesRoutes { public function routes() { $routes = []; // set up some shortcuts because i'm lazy $route_module = 'magazine_issue_pages'; $controller_path = '\Drupal\magazine_issue_pages\Controller\MagazineIssuePagesController'; $issues = $this->get_issues(); foreach ($issues as $nid => $issue) { // FROM OUR READERS $path = $issue['url'] . '/from-our-readers'; $def = [ '_controller' => $controller_path . '::from_our_readers', '_title' => 'From Our Readers for ' . $issue['name'], 'issue_nid' => $nid ]; $perms = [ '_permission' => 'access content' ]; $route_slug = 'issue' . $nid . 'from-our-readers'; $routes[$route_module . '.' . $route_slug] = new Route( $path, $def, $perms ); // AT RENSSELAER $path = $issue['url'] . '/at-rensselaer'; $def = [ '_controller' => $controller_path . '::at_rensselaer', '_title' => 'At Rensselaer for ' . $issue['name'], 'issue_nid' => $nid ]; $route_slug = 'issue' . $nid . 'at-rensselaer'; $routes[$route_module . '.' . $route_slug] = new Route( $path, $def, $perms ); // FEATURES $path = $issue['url'] . '/features'; $def = [ '_controller' => $controller_path . '::features', '_title' => 'Features for ' . $issue['name'], 'issue_nid' => $nid ]; $route_slug = 'issue' . $nid . 'features'; $routes[$route_module . '.' . $route_slug] = new Route( $path, $def, $perms ); } return $routes; } /** get all the slugs for Issues */ public function get_issues() { $issues = []; $q = 'SELECT nid, title FROM {node_field_data} '; $q .= 'WHERE type = :t '; $q .= 'AND status = :s '; $q .= 'ORDER BY created DESC '; $args = [ ':t' => 'issue', ':s' => 1 ]; $connection = \Drupal::database(); $result = $connection->query($q, $args); if ($result) { $am = \Drupal::service('path.alias_manager'); while ($row = $result->fetchAssoc()) { $d = [ 'id' => $row['nid'], 'name' => $row['title'], 'url' => $am->getAliasByPath('/node/'.$row['nid']) ]; $issues[$row['nid']] = $d; } } return $issues; } }
true
4be7291ba92fd85e37c2e44319bdf80f92d52786
PHP
bencollord/php_form_validation
/library/properties.trait.php
UTF-8
843
3.328125
3
[]
no_license
<?php /** * Allows classes that use it to use properties as * in C# and Java. * * When an inaccessable object property * is accessed, it searches the class for a getter or * setter method that matches the property name */ trait Properties { public function __get($name) { if(substr($name, 0, 2) == 'is' && method_exists($this, $name)) { return $this->{$name}(); } if(method_exists($this, 'get'.ucfirst($name))) { return $this->{'get'.ucfirst($name)}(); } throw new Exception('Could not get property "'.$name.'"'); } public function __set($name, $value) { if (method_exists($this, 'set'.ucfirst($name))) { return $this->{'set'.ucfirst($name)}($value); } throw new Exception('Could not set property "'.$name.'"'); } }
true
efb9b2ed9c2b5f31f3208fa7231501f6799c104c
PHP
bhuvneshkaushik/scat
/lib/Scat/CatalogService.php
UTF-8
2,628
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php namespace Scat; class CatalogService { public function __construct() { } public function createBrand() { return \Model::factory('Brand')->create(); } public function getBrands($only_active= true) { return \Model::factory('Brand')->where_gte('brand.active', (int)$only_active) ->order_by_asc('name') ->find_many(); } public function getBrandById($id) { return \Model::factory('Brand')->where('id', $id)->find_one(); } public function getBrandBySlug($slug) { return \Model::factory('Brand')->where('slug', $slug)->find_one(); } public function createDepartment() { return \Model::factory('Department')->create(); } public function getDepartments($parent_id= 0, $only_active= true) { return \Model::factory('Department')->where('parent_id', $parent_id) ->where_gte('department.active', (int)$only_active) ->order_by_asc('name') ->find_many(); } public function getDepartmentById($id) { return \Model::factory('Department')->where('id', $id)->find_one(); } public function getDepartmentBySlug($slug) { return \Model::factory('Department')->where('slug', $slug)->find_one(); } public function createProduct() { return \Model::factory('Product')->create(); } public function getProductById($id) { return \Model::factory('Product')->where('id', $id)->find_one(); } public function getProducts($active= 1) { return \Model::factory('Product')->where_gte('product.active', $active) ->find_many(); } public function getNewProducts($limit= 12) { return \Model::factory('Product')->where_gte('product.active', 1) ->order_by_desc('product.added') ->limit($limit) ->find_many(); } public function GetRedirectFrom($source) { // Whole product moved? $dst=\Model::factory('Redirect')->where_like('source', $source)->find_one(); // Category moved? if (!$dst) { $dst=\Model::factory('Redirect') ->where_raw('? LIKE CONCAT(source, "/%")', array($source)) ->find_one(); if ($dst) { $dst->dest= preg_replace("!^({$dst->source})/!", $dst->dest . '/', $source); } } return $dst; } }
true
b4dae89842699762dbdfbfc1b827296a0d213e88
PHP
dilab/omnipay-xendit
/src/Message/AbstractRequest.php
UTF-8
581
2.53125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: xuding * Date: 6/8/18 * Time: 12:03 PM */ namespace Omnipay\Xendit\Message; abstract class AbstractRequest extends \Omnipay\Common\Message\AbstractRequest { private $endPoint = 'https://api.xendit.co/v2/invoices'; public function getEndPoint() { return $this->endPoint; } public function getSecretApiKey() { return $this->getParameter('secretApiKey'); } public function setSecretApiKey($serverApiKey) { return $this->setParameter('secretApiKey', $serverApiKey); } }
true
e08b2b4305d481c98a27e7af8e8505cdcda2b6b8
PHP
Lpu8er/voidfield
/src/Command/UserTakeoverCommand.php
UTF-8
2,938
2.796875
3
[]
no_license
<?php namespace App\Command; use App\Entity\User; use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; class UserTakeoverCommand extends Command { /** * * @var UserPasswordHasherInterface */ protected $encoder = null; /** * * @var EntityManagerInterface */ protected $entityManager = null; public function __construct(UserPasswordHasherInterface $encoder = null, EntityManagerInterface $entityManager = null) { $this->encoder = $encoder; $this->entityManager = $entityManager; parent::__construct(); } protected function configure() { $help = <<<'EOT' "Steals" an user, changing his password. <error>This method should never be used in production.</error> <error>Remember the password WILL be visible in bash history !</error> It allows to change a password in order to "reset" an account by providing a new manual password. It cannot take over an active, bot or shadow account. Only inactive accounts can be taken over. <info>This method will reactivate the user account !</info> EOT; $this->setName('voidfield:user:takeover') ->setDescription('Take over an inactive account') ->setHelp($help); $this->addArgument('id', InputArgument::REQUIRED, 'Account ID'); $this->addArgument('pwd', InputArgument::REQUIRED, 'New Password'); } protected function execute(InputInterface $input, OutputInterface $output) { $uid = intval($input->getArgument('id')); $pwd = $input->getArgument('pwd'); $returns = 0; $userRepo = $this->entityManager->getRepository(User::class); try { $output->write('Fetching user ID '.$uid.'... '); $user = $userRepo->find($uid); if(!empty($user) && (User::STATUS_INACTIVE == $user->getStatus())) { $encoded = $this->encoder->hashPassword($user, $pwd); $user->setPwd($encoded); $user->setStatus(User::STATUS_ACTIVE); $this->entityManager->persist($user); $this->entityManager->flush(); $output->writeln('<info>User taken over !</info>'); } else { $output->writeln('<error>No inactive user found with this ID, check user status !</error>'); } } catch(\Exception $e) { $output->writeln([ '<error>A fatal error occured', $e->getMessage(), '</error>', ]); $returns = 1; } return $returns; } }
true
0ca22c44e922dbba5a58a62fe6f70462e12f4964
PHP
getmonitor/ZeeJong
/core/unit-tests/theme/content.php
UTF-8
2,540
2.84375
3
[]
no_license
<?php /* Template file for page content Author: Mathias Beke Url: http://denbeke.be Date: March 2014 */ ?> <h2>Running Unit Tests</h2> <div id="total-tests" <?php if($scenario->numberOfFailures != 0) echo 'class="failed"'; ?>> <p><?php echo $scenario->numberOfTest . ' tests in ' . sizeof($scenario->tests) . ' test cases'; ?></p> <?php if($scenario->numberOfFailures == 0) { ?> <p>All tests passed</p> <?php } else { ?> <p><?php echo $scenario->numberOfFailures; ?> failures</p> <?php } ?> </div> <?php foreach ($scenario->tests as $case) { ?> <h3><?php echo $case->name; ?></h3> <div class="table-wrapper"> <table> <tbody> <?php foreach ($case->sections as $section) { ?> <tr <?php if(!$section->success) echo 'class="failed"'; ?>> <td> <?php echo $section->name; ?> <ul class="failed-tests"> <?php foreach ($section->tests as $test) { if($test['result'] == false) { ?> <li> <?php if(isset($test['type']) and $test['type'] == 'unexpected') { ?> <p>Unexpected Exception</p> <?php } else { ?> <p>Failure on line <?php echo $test['line']; ?></p> <?php } ?> <code><?php echo $test['failed_line']; ?></code> </li> <?php } } ?> </ul> </td> <td> <?php if($section->success) { echo 'OK'; } else { echo 'ERROR'; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> <?php } ?>
true
b1cfad4f44910a7c7ce39f99a8c63c7c9cace5a4
PHP
Zotova2008/php
/project_15.6/knowledge.inc.php
UTF-8
398
3.53125
4
[]
no_license
<?php $a = 'Мои знания на'; $b = 100; $c = '%'; ?> <?php $price = 18; if ($price >= 15 && $price <= 20) { $priceEcho = "Число $price находится между 15 и 20"; } else { $priceEcho = "Число $price не находится между 15 и 20"; } $myArray = [1, 2, 'число']; $check; if (is_array($myArray)) { $check = ' - это массив'; } ?>
true
92ee0080019e90499b0b32c8c1e14caa667497fc
PHP
Toddish/Verify-L4
/src/Commands/AddRole.php
UTF-8
1,315
2.734375
3
[ "MIT" ]
permissive
<?php namespace Toddish\Verify\Commands; use Illuminate\Console\Command, Symfony\Component\Console\Input\InputOption, Symfony\Component\Console\Input\InputArgument; class AddRole extends Command { protected $name = 'verify:add-role'; protected $description = 'Add a new user role'; public function fire() { $name = $this->argument('name'); $level = $this->argument('level'); $description = $this->option('description'); $this->info('-- Adding new role - ' . $name . '.'); $role = app(config('verify.models.role')) ->fill([ 'name' => $name, 'level' => $level, 'description' => $description ]); $role->save(); $permissions = app(config('verify.models.permission')) ->get(); foreach ($permissions as $permission) { if ($this->confirm('Can ' . str_plural($name) . ' ' . $permission->name . '? [y|n]')) { $role->permissions()->attach($permission->id); } } $this->info('-- Role ' . $name . ' has been added!'); } protected function getArguments() { return [ ['name', InputArgument::REQUIRED, 'The name of the role.'], ['level', InputArgument::REQUIRED, 'The level of the role.'] ]; } protected function getOptions() { return [ ['description', 'd', InputOption::VALUE_OPTIONAL, 'The description of the role.', null] ]; } }
true
42be4fdef13b3406a69e4852b1780cc07bbc6d29
PHP
boxedsoftware/vicspace
/admin/user_search.php
UTF-8
1,739
2.5625
3
[]
no_license
<?php $title = "People Finder"; include($_SERVER['DOCUMENT_ROOT'].'/header.php'); $username = $_SESSION['username']; $accesslevel = mysql_query("SELECT user_level FROM users WHERE user_name='$username'"); $accesslevel = mysql_fetch_row($accesslevel); $accesslevel = $accesslevel[0]; if($accesslevel != 100) { echo "You are not an administrator! You should not be here"; include($_SERVER['DOCUMENT_ROOT'].'/footer.php'); die; } else ?> <h1>Search for Person</h1> <form action='user_search_connect.php' method='POST'> <table cellspacing="2"> <tr><td>Please select search by</td><td><select name='searchby'> <option>First name</option> <option>Middle name</option> <option>Last name</option> <option>Telephone</option> <option>Profession</option> </select></td> <td><input type='text' name='search'></td></tr> <tr><td><input type='submit' value="Search"></td></tr> </table> </form> <?php $result = mysql_query("SELECT user_name, user_pass, user_gender, first_name, middle_name, last_name, user_email, user_address, user_locality, user_phone, user_ip FROM users"); $numrows = mysql_num_rows($result); if (!$result) { $message = 'ERROR:' . mysql_error(); return $message; } else { $i = 0; echo '<table cellspacing="5" border="5"><tr>'; while ($i < mysql_num_fields($result)) { $meta = mysql_fetch_field($result, $i); echo '<td>' . $meta->name . '</td>'; $i = $i + 1; } echo '</tr>'; $i = 0; while ($row = mysql_fetch_row($result)) { echo '<tr>'; $count = count($row); $y = 0; while ($y < $count) { $c_row = current($row); echo '<td>' . $c_row . '</td>'; next($row); $y = $y + 1; } echo '</tr>'; $i = $i + 1; } echo '</table>'; mysql_free_result($result); } include($_SERVER['DOCUMENT_ROOT'].'/footer.php');?>
true
08c405a14496e973c9301290c8418548a09b06ee
PHP
alauderdale/Jewelry-Theme
/functions/le-stats.php
UTF-8
3,410
2.578125
3
[]
no_license
<?php // Hook for adding admin menus add_action('admin_menu', 'launch_stats_page'); // Action function for above hook to add a new top-level menu function launch_stats_page() { add_menu_page(__('Launch Stats','le_stats-page'), __('Launch Stats','le_stats-page'), 'manage_options', 'launch_stats_page', 'le_toplevel_page' ); } // Get a stylesheet up in here add_action('admin_head', 'admin_registers_head'); function admin_registers_head() { $url = get_bloginfo('template_directory') . '/functions/splash.css'; echo "<link rel='stylesheet' href='$url' />\n"; } // Displays the page content for the Launch Stats top-level menu function le_toplevel_page() { // Check that the user has the required capability if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient permissions to access this page.') ); } $wordpressapi_db_version = "1.0"; global $wpdb; global $wordpressapi_db_version; ?> <div class="wrap"> <div id="stats-wrapper"> <?php $stats_table = $wpdb->prefix . 'launcheffect'; if (isset($_GET['view'])) { // SHOW THE VISITOR DETAIL PAGE $view = $_GET['view']; $results = getDetail($stats_table, 'referred_by', $view); if (!$results) : ?> <h2>Stats: <a href="?page=launch_stats_page">Sign-ups</a>: Detail</h2> <p>Nothing to see here yet. <a href="?page=launch_stats_page">Go to Sign-Ups Stats.</a></p> <?php else: ?> <h2>Stats: <a href="?page=launch_stats_page">Sign-ups</a>: Detail</h2> <table id="individual"> <thead> <th>ID</th> <th>Time</th> <th>Converted To</th> <th>IP</th> </thead> <?php foreach ($results as $result) : ?> <tr> <td><?php echo $result->id; ?></td> <td style="white-space:nowrap;"><?php echo $result->time; ?></td> <td><a href="?page=launch_stats_page&view=<?php echo $result->code; ?>"><?php echo $result->email; ?></a></td> <td><?php echo $result->ip; ?></td> </tr> <?php endforeach; ?> </table> <?php endif; } else { // SHOW THE MAIN STATS PAGE ?> <h2>Stats: Sign-Ups</h2> <table id="signups"> <thead> <th>ID</a></th> <th>Time</a></th> <th>Email</a></th> <th>Visits</a></th> <th>Conversions</a></th> <th>Conversion Rate</th> <th>IP</th> </thead> <?php $results = getData($stats_table); foreach ($results as $result) : ?> <tr> <td><?php echo $result->id; ?></td> <td style="white-space:nowrap;"><?php echo $result->time; ?></td> <td><a href="?page=launch_stats_page&view=<?php echo $result->code; ?>"><?php echo $result->email; ?></a></td> <td><?php if($result->visits != 0) { echo $result->visits; }?></td> <td><?php if($result->conversions != 0) { echo $result->conversions; } ?></td> <td><?php // calculate the conversion rate: divide conversions by results and multiply it by 100. show up to 2 decimal places. if($result->visits + $result->conversions != 0 ) { $conversionRate = ($result->conversions/$result->visits) * 100; echo round($conversionRate, 2) . '%'; } ?> </td> <td><?php echo $result->ip; ?></td> </tr> <?php endforeach;?> </table> <?php } ?> </div> </div> <?php add_option("wordpressapi_db_version", $wordpressapi_db_version); } ?>
true
e62c5f6421c5ae0540fced412f238ac9da570ac7
PHP
jeandev84/janklod
/src/janklod/Component/Form/Type/Support/Type.php
UTF-8
2,296
2.875
3
[]
no_license
<?php namespace Jan\Component\Form\Type\Support; use Jan\Component\Form\Type\Traits\FormTrait; /** * Class AbstracType * @package Jan\Component\Form\Type\Support */ abstract class Type { use FormTrait; /** * @var string */ protected $child; /** * @var array */ protected $options; /** * AbstractType constructor. * @param string $child * @param array $options */ public function __construct(string $child, array $options) { $this->child = $child; $this->options = $options; } /** * @param $key * @param null $default * @return mixed|null */ public function getOption($key, $default = null) { return $this->options[$key] ?? $default; } /** * @param $key * @param $value * @return Type */ public function setOption($key, $value): Type { $this->options[$key] = $value; return $this; } /** * @param array $options * @return $this */ public function setOptions(array $options): Type { $this->options = array_merge($this->options, $options); return $this; } /** * @param $key * @return bool */ public function hasOption($key): bool { return isset($this->options[$key]); } /** * @return string */ public function getAttributes(): string { $attrs = $this->getOption('attr', []); return $this->buildAttributes($attrs); } /** * @return string */ public function buildLabel(): string { $html = ''; if($label = $this->getOption('label')) { $html .= '<label for="id">'. $this->getLabel() .'</label>'; } return $html; } /** * @return mixed|string */ public function getLabel(): string { return $this->getOption('label', ucfirst($this->child)); } /** * @return string */ public function getType(): string { // TODO implements in child class if you need } abstract public function buildHtml(); }
true
8c23a9f457949e7230371a2b86fc9b990ddff356
PHP
KubaKajderowicz/veiligprog2
/index.php
UTF-8
550
2.875
3
[]
no_license
<?php if (isset($_POST['zoekopdracht'])){ $zoekopdracht = $_POST['zoekopdracht']; echo htmlspecialchars("De zoekopdracht is: $zoekopdracht"); echo "Geen resultaat gevonden!"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>XSS</title> </head> <body> <form method="POST" action="index.php"> <input name="zoekopdracht" placeholder="Zoekopdracht"> <input type="submit" value="Zoek"> </form> </body> </html>
true
19d773eebc626b8930f4ef2f1048d7e4a895b333
PHP
Hetal2425/auto-loads-web-yii2
/common/components/Payment/PaymentI.php
UTF-8
582
2.90625
3
[]
no_license
<?php namespace common\components\Payment; /** * Interface PaymentI * * @package common\components\Payment */ interface PaymentI { /** * Sets user service ID and service price with response * * @param null|integer $id User service ID * @param null|double $price Service price */ public function setDefaultAttributes($id, $price); /** * Renders payment pay page */ public function pay(); /** * Validates, whether response from payment is valid * * @return boolean */ public function validate(); }
true
810c6161dd7695deadcc6765f291ae6dd85c933c
PHP
nursafitri/pw2020_193040181
/kuliah/pertemuan13/functions.php
UTF-8
6,059
2.671875
3
[]
no_license
<?php function koneksi() { return mysqli_connect('localhost', 'root', '', 'pw_193040181'); } function query($query) { $conn = koneksi(); $result = mysqli_query($conn, $query); if (mysqli_num_rows($result) == 1) { return mysqli_fetch_assoc($result); } $rows = []; while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } return $rows; } function upload() { $nama_file = $_FILES['gambar']['name']; $tipe_file = $_FILES['gambar']['type']; $ukuran_file = $_FILES['gambar']['size']; $error = $_FILES['gambar']['error']; $tmp_file = $_FILES['gambar']['tmp_name']; //jika user tidak menampilkan gambar if ($error == 4) { /*echo "<script> alert('pilih gambar terlebih dahulu!'); </script>";*/ return 'nonephoto.jpg'; } // cek ekstensi file $daftar_gambar = ['jpg', 'jpeg', 'png']; $ekstensi_file = explode('.', $nama_file); $ekstensi_file = strtolower(end($ekstensi_file)); if (!in_array($ekstensi_file, $daftar_gambar)) { echo "<script> alert('yang anda pilih bukan gambar!'); </script>"; return false; } // cek tipe file if ($tipe_file != 'image/jpeg' && $tipe_file != 'image/png') { echo "<script> alert('yang anda pilih bukan gambar!'); </script>"; return false; } // cek ukuran file if ($ukuran_file > 5000000) { echo "<script> alert('Ukuran gambar terlalu besar!'); </script>"; return false; } // lolos upload $nama_file_baru = uniqid(); $nama_file_baru .= '.'; $nama_file_baru .= $ekstensi_file; move_uploaded_file($tmp_file, 'gambar/' . $nama_file_baru); return $nama_file_baru; } function tambah($data) { $conn = koneksi(); $nama = htmlspecialchars($data['nama']); $nrp = htmlspecialchars($data['nrp']); $email = htmlspecialchars($data['email']); $jurusan = htmlspecialchars($data['jurusan']); $gambar = htmlspecialchars($data['gambar']); $query = "INSERT INTO mahasiswa VALUES (null, '$nama', '$nrp', '$email', '$jurusan', '$gambar'); "; mysqli_query($conn, $query); echo mysqli_error($conn); return mysqli_affected_rows($conn); } function hapus($id) { $conn = koneksi(); mysqli_query($conn, "DELETE FROM mahasiswa WHERE id = $id") or die(mysqli_error($conn)); return mysqli_affected_rows($conn); } function ubah($data) { $id = $data['id']; $conn = koneksi(); $nama = htmlspecialchars($data['nama']); $nrp = htmlspecialchars($data['nrp']); $email = htmlspecialchars($data['email']); $jurusan = htmlspecialchars($data['jurusan']); $gambar = htmlspecialchars($data['gambar']); $query = "UPDATE mahasiswa SET nama = '$nama', nrp = '$nrp', email = '$email', jurusan = '$jurusan', gambar = '$gambar' WHERE id = $id"; mysqli_query($conn, $query); echo mysqli_error($conn); return mysqli_affected_rows($conn); } function cari($keyword) { $conn = koneksi(); $query = "SELECT * FROM mahasiswa WHERE nama LIKE '%$keyword%' OR nrp LIKE '%$keyword%' OR email LIKE '%$keyword%' OR jurusan LIKE '%$keyword%'"; $result = mysqli_query($conn, $query); $rows = []; while ($row = mysqli_fetch_assoc($result)) { $rows[] = $row; } return $rows; } function login($data) { $conn = koneksi(); $username = htmlspecialchars($data['username']); $password = htmlspecialchars($data['password']); if ($user = query("SELECT * FROM user WHERE username = '$username'")) { if (password_verify($password, $user['password'])) { $_SESSION['login'] = true; header("Location: index.php"); exit; } } return [ 'eror' => true, 'pesan' => 'username / password salah !' ]; } function registrasi($data) { $conn = koneksi(); $username = htmlspecialchars(strtolower($data['username'])); $pass1 = mysqli_real_escape_string($conn, $data['pass1']); $pass2 = mysqli_real_escape_string($conn, $data['pass2']); // jika username / password kosong if (empty($username) || empty($pass1) || empty($pass2)) { echo "<script> alert('username / password tidak boleh kosong!'); document.location.href = 'registrasi.php'; </script>"; return false; } // jika username sudah ada if (query("SELECT * FROM user WHERE username = '$username'")) { echo "<script> alert('username sudah ada!'); document.location.href = 'registrasi.php'; </script>"; return false; } // Jika konfirmasi password tidak sesuai if ($pass1 !== $pass2) { echo "<script> alert('konfirmasi password tidak sesuai!'); document.location.href = 'registrasi.php'; </script>"; return false; } // jika password < 5 digit if (strlen($pass1) < 5) { echo "<script> alert('password terlalu pendek!'); document.location.href = 'registrasi.php'; </script>"; return false; } // Jika username dan password sudah sesuai // enkripsi password $password_baru = password_hash($pass1, PASSWORD_DEFAULT); // insert ke tabel user $query = "INSERT INTO user VALUES (null, '$username', '$password_baru') "; mysqli_query($conn, $query) or die(mysqli_error($conn)); return mysqli_affected_rows($conn); }
true
5ade640d0179732280273a88ea094b9795144a81
PHP
jasnzhuang/myThinkphp5
/application/blog/model/Blog.php
UTF-8
496
2.546875
3
[ "Apache-2.0" ]
permissive
<?php namespace app\blog\model; use think\Model; class Blog extends Model { //获取博客所属的用户 public function user() { return $this->belongsTo('User'); } //获取博客的内容 public function content() { return $this->hasOne('Content'); } //获取所有博客所属的分类 public function cate() { return $this->belongsTo('Cate'); } //获取所有针对文章的评论 public function comments() { return $this->morphMany('Comment', 'commentable'); } }
true