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
29ac6fc39c6d1a9fa76f520dc20e6e8c37a65687
PHP
jegawaran/test-server
/six/getoddnumber.php
UTF-8
605
3.515625
4
[]
no_license
<?php /** * Created by PhpStorm. * User: jegatheeswaran * Date: 6/21/2018 * Time: 3:44 PM */ function getOddnumber(array $srcValues){ $sizeof = sizeof($srcValues); //echo '<pre>'; print_r($sizeof); for($i=0;$i<$sizeof;$i++){ //print_r([$srcValues][$i]); $count= 0; for($j=0;$j<$sizeof;$j++){ if($srcValues[$i]== $srcValues[$j]){ $count++; } if($count %2 !=0){ return $srcValues[$i]; } } } return -1; } $value = [1,2,5,5,5,3,4,5,6,7]; echo getOddnumber($value); ?>
true
dae5922030910276eae672b070804848246cb32f
PHP
Martsynenko/openforum
/controllers/messages.controller.php
UTF-8
14,470
2.671875
3
[]
no_license
<?php class MessagesController extends Controller { public function __construct(array $data = []) { parent::__construct($data); $this->model = new modelMessages(); } /* * Сообщения (вопросы) - это разосланные вопросы определнным специалистам(зарегистрированным пользователям) * Возможно три варианта отправления: * 1. Всем пользователям по выбранной категории * 2. Пользователям которые добавлены в список 'Мой список' * 3. Определенному пользователю при нажатии кнопки Задать вопрос */ // Страница сообщений которые отправлял данный пользовател public function user_outbox(){ $id = Session::get('id'); /* Получаю количество сообщений outbox*/ $this->data['count_outbox'] = $this->model->getCountOutbox($id); /* Получаю количество сообщений inbox*/ $this->data['messages_inbox'] = $this->model->getMessagesInbox($id); if(empty($this->data['messages_inbox'])){ $this->data['count_inbox'] = 0; } else { $this->data['count_inbox'] = count($this->data['messages_inbox']); } // Получаю общее количество сообщений $count_messages = $this->data['count_outbox'] + $this->data['count_inbox']; $this->data['count_messages'] = $count_messages; Session::set('count_messages', $count_messages); // Получаю вопросы которые рассылал данный пользователь $this->data['messages'] = $this->model->getMessages($id); if(empty($this->data['messages'])){ Session::setFlash('nodata', '<span class="bold">На данный момент Вы не рассылали вопрос</span>. Для того чтоб разослать вопрос специалистам перейдите в раздел <a href="/user/messages/new/">Разослать вопрос</a>.'); } } // Страница сообщений которые получил данный пользователь public function user_inbox(){ $id = Session::get('id'); /* Получаю вопросы которые получил пользователь */ $this->data['messages'] = $this->model->getMessagesInbox($id); $this->data['isset_answer'] = $this->model->checkIssetAnswer($id); if(!$this->data['messages']){ Session::setFlash('nodata', '<span class="bold">На данный момент Вы не получали сообщений от пользователей</span>.'); } /* Получаю количество сообщений outbox*/ $this->data['count_outbox'] = $this->model->getCountOutbox($id); /* Получаю количество сообщений inbox*/ if(empty($this->data['messages'])){ $this->data['count_inbox'] = 0; } else { $this->data['count_inbox'] = count($this->data['messages']); } $count_messages = $this->data['count_outbox'] + $this->data['count_inbox']; Session::set('count_messages', $count_messages); } public function user_new(){ $id = Session::get('id'); /* Проверяю рассылка конкретному пользователю или из списка */ $params = App::getRouter()->getParams(); if(isset($params[0])){ $user_id = $params[0]; $data = $this->model->getUserName($user_id); $this->data['user_id'] = $data[0]['id']; $this->data['firstname'] = $data[0]['firstname']; $this->data['lastname'] = $data[0]['lastname']; } if($_POST){ $cat_id = $_POST['category']; $rank_id = $_POST['rank']; if($rank_id == 0){ $user_rank = $_POST['user_rank']; $data = $this->model->checkIssetRank($user_rank); if(!empty($data)){ $rank_id = $data[0]['id']; } } $for = $_POST['for']; $date = date('Y:m:d H:i:s'); $text = trim($_POST['text']); $text = htmlspecialchars($text, ENT_QUOTES); $text = stripcslashes($text); if($for === 'all'){ $users = $this->model->getUsersForMessage($cat_id, $rank_id, $id); if(!$users){ Session::setFlash('nousers', '<span class="bold">К сожалению нет специалистов по данной теме.</span> Попробуйте выбрать другую категорию или специальность и отправьте ещё раз.'); } else { $this->model->insert($id, $cat_id, $rank_id, $text, $date, $users); Session::setFlash('send', "<span class='bold'>Ваш вопрос будет отправлен всем указаным специалистам после проверки нашими модераторами</span>. Вам прийдет email уведомление с подтверждением. Для просмотра Ваших сообщений перейдите в раздел <a href='/user/messages/'>Мои сообщения</a>."); } } elseif($for === 'my'){ if(!$this->model->checkIssetUser($id)){ Session::setFlash('nousers', '<span class="bold">В вашем списке нет специалистов.</span> Можете выбрать категорию Всем специалистам или отправить вопрос конкретному специалисту.'); } else { $users = $this->model->getUsersForMessageMy($cat_id, $rank_id, $id); if(!$users){ Session::setFlash('nousers', '<span class="bold">К сожалению нет специалистов по данной теме.</span> Попробуйте выбрать другую категорию или специальность и отправьте ещё раз.'); } else { $this->model->insert($id, $cat_id, $rank_id, $text, $date, $users); Session::setFlash('send', "<span class='bold'>Ваш вопрос будет отправлен Вашим специалистам после проверки нашими модераторами</span>. Вам прийдет email уведомление с подтверждением. Для просмотра Ваших сообщений перейдите в раздел <a href='/user/messages/'>Мои сообщения</a>."); } } } else { $users = $_POST['for']; $data = $this->model->getUserName($users); $firstname = $data[0]['firstname']; $lastname = $data[0]['lastname']; $this->model->insert($id, $cat_id, $rank_id, $text, $date, $users); Session::setFlash('send', "<span class='bold'>Ваш вопрос будет отправлен пользователю $firstname $lastname после проверки нашими модераторами</span>. Вам прийдет email уведомление с подтверждением. Для просмотра Ваших сообщений перейдите в раздел <a href='/user/messages/'>Мои сообщения</a>."); } // Отправляю письмо с уведомлением модератору, о том что нужно подтвердить публикаю вопроса $mail = new PHPMailer(false); $mail->isSMTP(); $mail->Host = Config::get('smtp_host'); $mail->SMTPAuth = Config::get('smtp_auth'); $mail->Port = Config::get('smtp_port'); $mail->SMTPSecure = Config::get('smtp_secure'); $mail->CharSet = Config::get('smtp_charset'); $mail->Username = Config::get('smtp_username'); $mail->Password = Config::get('smtp_password'); $mail->setFrom(Config::get('smtp_addreply'), 'openForum.ua'); $mail->addAddress(Config::get('smtp_username'), "Admin"); $mail->Subject = htmlspecialchars('Модерация сообщения'); $text = file_get_contents(MAIL_PATH."/mail_moderation_message.html"); $text = str_replace(['%name%'], ['Александр'], $text); $mail->Body = "$text"; $mail->isHTML(true); $mail->send(); $mail->ClearAddresses(); $mail->ClearAttachments(); } /*Формирую данные для select */ $this->data['categories'] = $this->model->getCategories(); $this->data['ranks'] = $this->model->getRanks(1); } // Страница просмотра сообщения которые отправлял пользователь public function user_outview(){ $params = App::getRouter()->getParams(); $message_id = $params[0]; /* Формирую данные для темы*/ $this->data['message'] = $this->model->getUserMessageOut($message_id); $user_id = $this->data['message'][0]['user_id']; $this->data['position'] = $this->model->getUserPosition($user_id); $this->data['message_id'] = $message_id; $this->data['user_id'] = $this->data['message'][0]['user_id']; $this->data['firstname'] = $this->data['message'][0]['firstname']; $this->data['lastname'] = $this->data['message'][0]['lastname']; $this->data['avatar'] = $this->data['message'][0]['avatar']; $this->data['answers'] = $this->data['message'][0]['answers']; $this->data['rank'] = $this->data['message'][0]['rank']; $this->data['text'] = $this->data['message'][0]['text']; $users = $this->data['message'][0]['users']; $array = explode(', ', $users); $count = count($array); $this->data['gets'] = $count; $this->data['data_answers'] = $this->model->getAnswers($message_id); if(empty($this->data['answers'])){ Session::setFlash('nodata', '<span class="bold">К сожалению нет ответов на данный вопрос.</span> Возможно прошло слишком мало времени. Попробуйте задать другой вопрос или воспользуйтесь поиском на сайте.'); } } // Страница просмотра сообщения которые получил пользователь public function user_inview(){ $id = Session::get('id'); $params = App::getRouter()->getParams(); $message_id = $params[0]; /* Формирую данные для темы*/ $this->data['message'] = $this->model->getUserMessageIn($message_id); $user_id = $this->data['message'][0]['user_id']; $this->data['position'] = $this->model->getUserPosition($user_id); $this->data['message_id'] = $message_id; $this->data['user_id'] = $this->data['message'][0]['user_id']; $this->data['firstname'] = $this->data['message'][0]['firstname']; $this->data['lastname'] = $this->data['message'][0]['lastname']; $this->data['avatar'] = $this->data['message'][0]['avatar']; $this->data['city'] = $this->data['message'][0]['city']; $this->data['rank'] = $this->data['message'][0]['rank']; $this->data['text'] = $this->data['message'][0]['text']; $date_data = $this->data['message'][0]['date']; $date_array = explode(' ', $date_data); $this->data['date'] = $date_array[0]; $this->data['time'] = substr($date_array[1], 0, -3); if($_POST){ $answer = trim($_POST['answer']); $answer = htmlspecialchars($answer, ENT_QUOTES); $answer = stripcslashes($answer); $date = date('Y:m:d H:i:s'); $this->model->setAnswer($id, $message_id, $date, $answer); } $this->data['answer'] = $this->model->getUserAnswer($id, $message_id); } public function user_outdelete(){ $params = App::getRouter()->getParams(); $message_id = $params[0]; $this->model->deleteMessageOut($message_id); Session::set('count_messages', Session::get('count_messages')-1); Router::redirect('/user/messages/outbox/'); } public function user_indelete(){ $id = Session::get('id'); $params = App::getRouter()->getParams(); $message_id = $params[0]; $this->model->deleteMessageIn($message_id, $id); Session::set('count_messages', Session::get('count_messages')-1); Router::redirect('/user/messages/inbox/'); } public function admin_index(){ /* Получаю все сообщения */ $this->data['messages'] = $this->model->getAllMessages(); } public function admin_edit() { $params = App::getRouter()->getParams(); $message_id = $params[0]; $this->data['message_id'] = $message_id; if ($_POST) { $text = trim($_POST['text']); $text = htmlspecialchars($text, ENT_QUOTES); $text = stripcslashes($text); $this->model->updateMessage($message_id, $text); Session::setFlash('update', '<span class="bold">Вопрос успешно редактирован</span>.'); } $this->data['message'] = $this->model->getMessageInfo($message_id); } public function admin_delete(){ $params = App::getRouter()->getParams(); $message_id = $params[0]; $this->model->deleteMessageOut($message_id); Router::redirect('/admin/messages/index'); } }
true
902bebff8d4d43198820124a4b42a2dbe408953c
PHP
IWS-Spring-2021/Worldnews
/webservices/models/Category.php
UTF-8
3,379
3.21875
3
[]
no_license
<?php class Category { // DB stuff private $conn; private $table = 'category'; // Post Properties public $id; public $category; // Constructor with DB public function __construct($db) { $this->conn = $db; } // Get Posts public function read_all() { // Create query $query = "SELECT * FROM " . $this->table; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function insert_a_cat() { // Create query $query = "INSERT INTO " . $this->table . " SET category=:cat_name"; // prepare query $stmt = $this->conn->prepare($query); // sanitize $this->category = htmlspecialchars(strip_tags($this->category)); // bind values $stmt->bindParam(":cat_name", $this->category); // $stmt->bindParam(":posted_at", $this->posted_at); // execute query if ($stmt->execute()) { return true; } return false; } public function delete_a_cat() { $query = "DELETE FROM " . $this->table . " WHERE id = ?"; $stmt = $this->conn->prepare($query); $stmt->bindParam(1, $this->id); $stmt->execute(); // $row = $stmt->fetch(PDO::FETCH_ASSOC); return true; } public function read_cats() { // Create query $query = 'SELECT category.id, category.category AS cat_name FROM category ORDER BY category.id'; // Prepare statement $stmt = $this->conn->prepare($query); // Execute query $stmt->execute(); return $stmt; } public function read_single() { // Create query $query = 'SELECT category.id, category.category AS cat_name FROM ' . $this->table . ' WHERE id = ?'; // Prepare statement $stmt = $this->conn->prepare($query); // Bind ID $stmt->bindParam(1, $this->id); // Execute query $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); // Set properties $this->id = $row['id']; $this->category = $row['cat_name']; } public function update_a_cat() { // Create query $query = "UPDATE " . $this->table . " SET category=:cat_name WHERE id=:id"; // // prepare query $stmt = $this->conn->prepare($query); // sanitize $this->category = htmlspecialchars(strip_tags($this->category)); $this->id = htmlspecialchars(strip_tags($this->id)); // bind values $stmt->bindParam(":cat_name", $this->category); $stmt->bindParam(":id", $this->id); // $stmt->bindParam(":posted_at", $this->posted_at); // $query = "UPDATE " . $this->table . " SET title= " . $this->title . ", short_intro= " . $this->short_intro . ", content= " . $this->content . ", author= " . $this->author. ", created_date= " . $this->created_date . ", pic= " . $this->pic . ", cat_id= " . $this->cat_id . " WHERE id=" . $this->id; // $stmt = $this->conn->prepare($query); // execute query if ($stmt->execute()) { return true; } return false; } public function read_category_by_news() { // Create query $query = "SELECT * FROM " . $this->table . " WHERE id = ?"; // Prepare statement $stmt = $this->conn->prepare($query); $stmt->bindParam(1, $this->id); // Execute query $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); $this->id = $row['id']; $this->category = $row['category']; } }
true
45a1d7238a84168f4e9d2b2365d9b6bd5c66ea43
PHP
jtad009/udo_boiler
/src/Form/SmsForm.php
UTF-8
3,599
2.59375
3
[]
no_license
<?php namespace App\Form; use Cake\Form\Form; use Cake\Form\Schema; use Cake\Validation\Validator; use Cake\Network\Http\Client; /** * Sms Form. */ class SmsForm extends Form { /** * Builds the schema for the modelless form * * @param \Cake\Form\Schema $schema From schema * @return \Cake\Form\Schema */ protected function _buildSchema(Schema $schema) { return $schema->addField('to', 'string') ->addField('from', ['type' => 'string']) ->addField('message', ['type' => 'text'])->addField('count',['type'=>'hidden']); } /** * Form validation builder * * @param \Cake\Validation\Validator $validator to use against the form * @return \Cake\Validation\Validator */ protected function _buildValidator(Validator $validator) { return $validator->add('to', 'length', [ 'rule' => ['minLength', 11], 'message' => 'A valid phone number is required']) ->add('from','length',['rule' => ['maxLength', 10], 'message' => 'Sender ID cannot exceed 10 Characters']) ->add('message', [ 'minLength' => [ 'rule' => ['minLength', 10], 'last' => true, 'message' => 'Message is too short.' ], 'maxLength' => [ 'rule' => ['maxLength', 290], 'message' => 'Message cannot be too long.' ] ]); } /** * Defines what to execute once the From is being processed * * @param array $data Form data. * @return bool */ protected function _execute(array $data) { $result = false; $msg = $data['message']; $from = $data['from']; $sendTo = $data['to']; $count = $data['count']; if($this->getSMSUnits() !== null): $http = new Client(); $response = $http->get(SEND_SMS . "sender=$from&recipient=$sendTo&message=$msg&"); $sms_error = array(2904, 2905, 2906, 2907, 2908, 2909, 2910, 2911, 2912, 2913, 2914, 2915); if($response->isOk()){ if(in_array($response->body, $sms_error)){ $result = false; }else{ $this->updateSMSUnits($count); $result = true; } } endif; return $result; } private function getSMSUnits(){ //$used = $used * SMS_UNIT_COST; return \Cake\DataSource\ConnectionManager::get('default')->execute("SELECT units FROM companies_sms where location_id = :id",['id'=>$_SESSION['Auth']['User']['location_id']])->fetch('assoc')['units']; } private function updateSMSUnits($used){ $used = $used * SMS_UNIT_COST; \Cake\DataSource\ConnectionManager::get('default')->execute("UPDATE companies_sms SET units = (units - $used) where location_id = :id",['id'=>$_SESSION['Auth']['User']['location_id']]); } }
true
22da958a1979920baccd6c1ec66d77e87a9fbda5
PHP
kingkernel/socialdevelopers
/app/Models/User.php
UTF-8
1,328
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Helpers\thisSystem; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $table = 'usuarios'; protected $fillable = [ 'nome', 'email', "keypass", "nasc", 'sobrenome', "type_user" ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public static function login($email, $keypass) { $exists = json_decode(json_encode(\DB::table("usuarios")->select( \DB::RAW("count(*) as existe"))->where( ["email"=> $email, "keypass"=>thisSystem::makePassword($keypass), "active"=>true])->get()->toArray()), JSON_UNESCAPED_SLASHES); return $exists[0]; } }
true
291aa30411b7fb0eb9d999726d82bad6af323198
PHP
arizalsultan25/JWP_borang
/database/factories/RoomFactory.php
UTF-8
1,425
2.671875
3
[ "MIT" ]
permissive
<?php namespace Database\Factories; use App\Models\Room; use Illuminate\Database\Eloquent\Factories\Factory; class RoomFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Room::class; /** * Define the model's default state. * * @return array */ public function definition() { $jenis = $this->faker->randomElement(['kelas', 'lab']); if($jenis == 'lab'){ $fasilitas = 'papan tulis, meja, kursi, infocus, peralatan lab'; $gambar = $this->faker->randomElement(['lab-01.jpg', 'lab-02.jpg','lab-03.jpg','lab-04.jpg','lab-05.jpg','lab-06.jpg']); }else{ $fasilitas = $this->faker->randomElement(['papan tulis, meja, kursi', 'papan tulis, meja, kursi, infocus', 'papan tulis, meja, kursi, komputer']); $gambar = $this->faker->randomElement(['kelas-01.jpg', 'kelas-02.jpg','kelas-03.jpg','kelas-04.jpg','kelas-05.jpg','kelas-06.jpg']); } return [ // kolom 'kode' => 'R' . rand(0,999), 'nama_ruangan' => implode(' ', $this->faker->words(3)), 'jenis' => $jenis, 'daya_tampung' => rand(0,300), 'fasilitas' => $fasilitas, 'gambar' => $gambar, 'keterangan' => implode('</br>', $this->faker->sentences(3)), ]; } }
true
31ed6368b131655845caea9d800e7081a4bd488a
PHP
craidler/hb9hcr-library
/Entity/Duration.php
UTF-8
895
3.265625
3
[]
no_license
<?php namespace HB9HCR\Entity; use HB9HCR\Base\Item; /** * Class Duration * * @property int $h * @property int $m * @property int $s * @property string $hm * @property int $value */ class Duration extends Item { /** * @return string */ public function hm(): string { return sprintf('%02d:%02d', floor($this->value / 3600), floor($this->value % 3600 / 60)); } /** * @param string $round * @return int */ public function h(string $round = 'floor') { return call_user_func_array($round, [$this->value / 3600]); } /** * @param string $round * @return int */ public function m(string $round = 'floor'): int { return call_user_func_array($round, [$this->value / 60]); } /** * @return int */ public function s(): int { return $this->value; } }
true
509ac8813bdb3476747eae83c30bc26cbdf5f671
PHP
concretecms/concretecms
/concrete/src/Permission/Response/Response.php
UTF-8
3,841
2.6875
3
[ "MIT" ]
permissive
<?php namespace Concrete\Core\Permission\Response; use Exception; use Concrete\Core\User\User; use Concrete\Core\Support\Facade\Application; use Concrete\Core\Permission\Category as PermissionKeyCategory; use Core; class Response { /** @var \Concrete\Core\Permission\ObjectInterface */ protected $object; /** @var PermissionKeyCategory */ protected $category; public static $cache = array(); /** * Sets the current permission object to the object provided, this object should implement the Permission ObjectInterface. * * @param \Concrete\Core\Permission\ObjectInterface $object */ public function setPermissionObject($object) { $this->object = $object; } /** * Retrieves the current permission object. */ public function getPermissionObject() { return $this->object; } /** * Sets the current Permission Category object to an appropriate PermissionKeyCategory. * * @param PermissionKeyCategory $category */ public function setPermissionCategoryObject($category) { $this->category = $category; } /** * Returns an error constant if an error is present, false if there are no errors. * * @return bool|int */ public function testForErrors() { return false; } /** * Passing in any object that implements the ObjectInterface, retrieve the Permission Response object. * * @param \Concrete\Core\Permission\ObjectInterface $object * * @return \Concrete\Core\Permission\Response\Response */ public static function getResponse($object) { $cache = Core::make('cache/request'); $identifier = sprintf('permission/response/%s/%s', get_class($object), $object->getPermissionObjectIdentifier()); $item = $cache->getItem($identifier); if (!$item->isMiss()) { return $item->get(); } $className = $object->getPermissionResponseClassName(); /** @var \Concrete\Core\Permission\Response\Response $pr */ $pr = Core::make($className); if ($object->getPermissionObjectKeyCategoryHandle()) { $category = PermissionKeyCategory::getByHandle($object->getPermissionObjectKeyCategoryHandle()); $pr->setPermissionCategoryObject($category); } $pr->setPermissionObject($object); $cache->save($item->set($pr)); return $pr; } /** * This function returns true if the user has permission to the object, or false if they do not have access. * * @param string $permissionHandle A Permission Key Handle * @param array $args Arguments to pass to the PermissionKey object's validate function * * @return bool * * @throws Exception */ public function validate($permissionHandle, $args = array()) { $app = Application::getFacadeApplication(); $u = $app->make(User::class); if ($u->isSuperUser()) { return true; } if (!is_object($this->category)) { throw new Exception(t('Unable to get category for permission %s', $permissionHandle)); } $pk = $this->category->getPermissionKeyByHandle($permissionHandle); if (!$pk) { throw new Exception(t('Unable to get permission key for %s', $permissionHandle)); } $pk->setPermissionObject($this->object); return call_user_func_array(array($pk, 'validate'), $args); } public function __call($f, $a) { $permission = substr($f, 3); /** @var \Concrete\Core\Utility\Service\Text $textHelper */ $textHelper = Core::make('helper/text'); $permission = $textHelper->uncamelcase($permission); return $this->validate($permission, $a); } }
true
e09da08fa1c1f3861bdbcc50106fffc4f41459fb
PHP
librenms-plugins/Weathermap
/lib/editor.inc.php
UTF-8
23,159
2.796875
3
[ "GPL-2.0-only", "MIT", "CC-BY-2.5" ]
permissive
<?php /** editor.inc.php * * All the functions used by the editor. */ /** @function fix_gpc_string * * Take a string (that we got from $_REQUEST) and make it back to how the * user TYPED it, regardless of whether magic_quotes_gpc is turned on or off. * * @param string $input String to fix * * @returns string Fixed string * */ function fix_gpc_string($input) { if (true == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc()) { $input = stripslashes($input); } return ($input); } /** * Clean up URI (function taken from Cacti) to protect against XSS */ function wm_editor_sanitize_uri($str) { static $drop_char_match = array(' ','^', '$', '<', '>', '`', '\'', '"', '|', '+', '[', ']', '{', '}', ';', '!', '%'); static $drop_char_replace = array('', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); return str_replace($drop_char_match, $drop_char_replace, urldecode($str)); } // much looser sanitise for general strings that shouldn't have HTML in them function wm_editor_sanitize_string($str) { static $drop_char_match = array('<', '>' ); static $drop_char_replace = array('', ''); return str_replace($drop_char_match, $drop_char_replace, urldecode($str)); } function wm_editor_validate_bandwidth($bw) { if(preg_match( '/^(\d+\.?\d*[KMGT]?)$/', $bw) ) { return true; } return false; } function wm_editor_validate_one_of($input,$valid=array(),$case_sensitive=false) { if(! $case_sensitive ) $input = strtolower($input); foreach ($valid as $v) { if(! $case_sensitive ) $v = strtolower($v); if($v == $input) return true; } return false; } // Labels for Nodes, Links and Scales shouldn't have spaces in function wm_editor_sanitize_name($str) { return str_replace( array(" "), "", $str); } function wm_editor_sanitize_selected($str) { $res = urldecode($str); if( ! preg_match("/^(LINK|NODE):/",$res)) { return ""; } return wm_editor_sanitize_name($res); } function wm_editor_sanitize_file($filename,$allowed_exts=array()) { $filename = wm_editor_sanitize_uri($filename); if ($filename == "") return ""; $ok = false; foreach ($allowed_exts as $ext) { $match = ".".$ext; if( substr($filename, -strlen($match),strlen($match)) == $match) { $ok = true; } } if(! $ok ) return ""; return $filename; } function wm_editor_sanitize_conffile($filename) { $filename = wm_editor_sanitize_uri($filename); # If we've been fed something other than a .conf filename, just pretend it didn't happen if ( substr($filename,-5,5) != ".conf" ) { $filename = ""; } // TODO: check how these work # on top of the url stuff, we don't ever need to see a / in a config filename (CVE-2013-3739) if (strstr($filename,"/") !== false ) { $filename = ""; } return $filename; } function list_weathermaps($mapdir) { //return array of Weathermaps // global $WEATHERMAP_VERSION, $config_loaded, $cacti_found, $ignore_cacti,$configerror, $action; $files = array(); $titles = array(); $pages = array(); $notes = array(); $errorstring=""; if (is_dir($mapdir)) { $n=0; $dh=opendir($mapdir); if ($dh) { while (false !== ($file = readdir($dh))) { $realfile=$mapdir . '/' . $file; $note = ""; // skip directories, unreadable files, .files and anything that doesn't come through the sanitiser unchanged if ( (is_file($realfile)) && (is_readable($realfile)) && (!preg_match("/^\./",$file) ) && ( wm_editor_sanitize_conffile($file) == $file ) ) { if (!is_writable($realfile)) { $note .= "(read-only)"; } $title=$file; $fd=fopen($realfile, "r"); if ($fd) { while (!feof($fd)) { $buffer=fgets($fd, 4096); if (preg_match("/^\s*TITLE\s+(.*)/i", $buffer, $matches)) { $title= wm_editor_sanitize_string($matches[1]); } if (preg_match("/^\s*HTMLOUTPUTFILE\s+(.*)/i", $buffer, $matches)) { $page= wm_editor_sanitize_string($matches[1]); } } fclose ($fd); $titles[$file] = $title; $pages[$file] = $page; $notes[$file] = $note; $files[$file]['title'] = $title; $files[$file]['page'] = $page; $files[$file]['note'] = $note; $n++; } } } closedir ($dh); } else { $errorstring = "Can't open mapdir to read."; } ksort($files); ksort($titles); ksort($pages); ksort($notes); if ($n == 0) { $errorstring = "No files in mapdir"; } } else { $errorstring = "NO DIRECTORY named $mapdir"; } // return value return $files; } function show_editor_startpage() { global $mapdir, $WEATHERMAP_VERSION, $config_loaded, $cacti_found, $ignore_cacti,$configerror; $fromplug = false; if (isset($_REQUEST['plug']) && (intval($_REQUEST['plug'])==1) ) { $fromplug = true; } $matches=0; print '<html xmlns="http://www.w3.org/1999/xhtml"><head><link rel="stylesheet" type="text/css" media="screen" href="editor-resources/oldeditor.css" /><script type="text/javascript" src="vendor/jquery/dist/jquery.min.js"></script><script src="editor-resources/editor.js" type="text/javascript"></script><title>PHP Weathermap Editor ' . $WEATHERMAP_VERSION . '</title></head><body>'; print '<div id="nojs" class="alert"><b>WARNING</b> - '; print 'Sorry, it\'s partly laziness on my part, but you really need JavaScript enabled and DOM support in your browser to use this editor. It\'s a visual tool, so accessibility is already an issue, if it is, and from a security viewpoint, you\'re already running my '; print 'code on your <i>server</i> so either you trust it all having read it, or you\'re already screwed.<P>'; print 'If it\'s a major issue for you, please feel free to complain. It\'s mainly laziness as I said, and there could be a fallback (not so smooth) mode for non-javascript browsers if it was seen to be worthwhile (I would take a bit of convincing, because I don\'t see a benefit, personally).</div>'; $errormessage = ""; if ($configerror!='') { $errormessage .= $configerror.'<p>'; } // NOTE: Change to set for libreNMS // NOTE: Is the following code necessary? if ( !$librenms_found && !$ignore_librenms) { //$errormessage .= '$cacti_base is not set correctly. Cacti integration will be disabled in the editor.'; //$errormessage .= "$librenms_found and $ignore_librenms"; //if ($config_loaded != 1) { //$errormessage .= " You might need to copy editor-config.php-dist to editor-config.php and edit it."; //} } if ($errormessage != '') { print '<div class="alert" id="nocacti">'.htmlspecialchars($errormessage).'</div>'; } print '<div id="withjs">'; print '<div id="dlgStart" class="dlgProperties" ><div class="dlgTitlebar">Welcome</div><div class="dlgBody">'; print 'Welcome to the PHP Weathermap '.$WEATHERMAP_VERSION.' editor.<p>'; print '<div style="border: 3px dashed red; background: #055; padding: 5px; font-size: 90%;"><b>NOTE:</b> This editor is not finished! There are many features of '; print 'Weathermap that you will be missing out on if you choose to use the editor only.'; print 'These include: curves, node offsets, font definitions, colour changing, per-node/per-link settings and image uploading. You CAN use the editor without damaging these features if you added them by hand, however.</div><p>'; print 'Do you want to:<p>'; print 'Create A New Map:<br>'; if($action == 'newmap') { print "<b>Error creating map, the filename needs to end in .conf</b>"; } print '<form method="GET">'; print 'Named: <input type="text" name="mapname" size="20">'; print '<input name="action" type="hidden" value="newmap">'; print '<input name="plug" type="hidden" value="'.$fromplug.'">'; print '<input type="submit" value="Create">'; print '<p><small>Note: filenames must contain no spaces and end in .conf</small></p>'; print '</form>'; $titles = array(); $errorstring=""; if (is_dir($mapdir)) { $n=0; $dh=opendir($mapdir); if ($dh) { while (false !== ($file = readdir($dh))) { $realfile=$mapdir . DIRECTORY_SEPARATOR . $file; $note = ""; // skip directories, unreadable files, .files and anything that doesn't come through the sanitiser unchanged if ( (is_file($realfile)) && (is_readable($realfile)) && (!preg_match("/^\./",$file) ) && ( wm_editor_sanitize_conffile($file) == $file ) ) { if (!is_writable($realfile)) { $note .= "(read-only)"; } $title='(no title)'; $fd=fopen($realfile, "r"); if ($fd) { while (!feof($fd)) { $buffer=fgets($fd, 4096); if (preg_match('/^\s*TITLE\s+(.*)/i', $buffer, $matches)) { $title= wm_editor_sanitize_string($matches[1]); } } fclose ($fd); $titles[$file] = $title; $notes[$file] = $note; $n++; } } } closedir ($dh); } else { $errorstring = "Can't open mapdir to read."; } ksort($titles); if ($n == 0) { $errorstring = "No files in mapdir"; } } else { $errorstring = "NO DIRECTORY named $mapdir"; } print 'OR<br />Create A New Map as a copy of an existing map:<br>'; print '<form method="GET">'; print 'Named: <input type="text" name="mapname" size="20"> based on '; print '<input name="action" type="hidden" value="newmapcopy">'; print '<input name="plug" type="hidden" value="'.$fromplug.'">'; print '<select name="sourcemap">'; if ($errorstring == '') { foreach ($titles as $file=>$title) { $nicefile = htmlspecialchars($file); print "<option value=\"$nicefile\">$nicefile</option>\n"; } } else { print '<option value="">'.htmlspecialchars($errorstring).'</option>'; } print '</select>'; print '<input type="submit" value="Create Copy">'; print '</form>'; print 'OR<br />'; print 'Open An Existing Map (looking in ' . htmlspecialchars($mapdir) . '):<ul class="filelist">'; if ($errorstring == '') { foreach ($titles as $file=>$title) { # $title = $titles[$file]; $note = $notes[$file]; $nicefile = htmlspecialchars($file); $nicetitle = htmlspecialchars($title); print "<li>$note<a href=\"?mapname=$nicefile&plug=$fromplug\">$nicefile</a> - <span class=\"comment\">$nicetitle</span></li>\n"; } } else { print '<li>'.htmlspecialchars($errorstring).'</li>'; } print "</ul>"; print "</div>"; // dlgbody print '<div class="dlgHelp" id="start_help">PHP Weathermap ' . $WEATHERMAP_VERSION . ' Copyright &copy; 2005-2020 Howard Jones - howie@thingy.com<br />The current version should always be <a href="http://www.network-weathermap.com/">available here</a>, along with other related software. PHP Weathermap is licensed under the GNU Public License, version 2. See COPYING for details. This distribution also includes the Overlib library by Erik Bosrup.</div>'; print "</div>"; // dlgStart print "</div>"; // withjs print "</body></html>"; } function snap($coord, $gridsnap = 0) { if ($gridsnap == 0) { return ($coord); } else { $rest = $coord % $gridsnap; return ($coord - $rest + round($rest/$gridsnap) * $gridsnap ); } } function extract_with_validation($array, $paramarray, $prefix = "") { $all_present=true; $candidates=array( ); foreach ($paramarray as $var) { $varname=$var[0]; $vartype=$var[1]; $varreqd=$var[2]; if ($varreqd == 'req' && !array_key_exists($varname, $array)) { $all_present=false; } if (array_key_exists($varname, $array)) { $varvalue=$array[$varname]; $waspresent=$all_present; switch ($vartype) { case 'int': if (!preg_match('/^\-*\d+$/', $varvalue)) { $all_present=false; } break; case 'float': if (!preg_match('/^\d+\.\d+$/', $varvalue)) { $all_present=false; } break; case 'yesno': if (!preg_match('/^(y|n|yes|no)$/i', $varvalue)) { $all_present=false; } break; case 'sqldate': if (!preg_match('/^\d\d\d\d\-\d\d\-\d\d$/i', $varvalue)) { $all_present=false; } break; case 'any': // we don't care at all break; case 'ip': if (!preg_match( '/^((\d|[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)(?:\.(\d|[1-9]\d|2[0-4]\d|25[0-5]|1\d\d)){3})$/', $varvalue)) { $all_present=false; } break; case 'alpha': if (!preg_match('/^[A-Za-z]+$/', $varvalue)) { $all_present=false; } break; case 'alphanum': if (!preg_match('/^[A-Za-z0-9]+$/', $varvalue)) { $all_present=false; } break; case 'bandwidth': if (!preg_match('/^\d+\.?\d*[KMGT]*$/i', $varvalue)) { $all_present=false; } break; default: // an unknown type counts as an error, really $all_present=false; break; } if ($all_present) { $candidates["{$prefix}{$varname}"]=$varvalue; } } } if ($all_present) { foreach ($candidates as $key => $value) { $GLOBALS[$key]=$value; } } return array($all_present,$candidates); } function get_imagelist($imagedir) { $imagelist = array(); if (is_dir($imagedir)) { $n=0; $dh=opendir($imagedir); if ($dh) { while ($file=readdir($dh)) { $realfile=$imagedir . DIRECTORY_SEPARATOR . $file; $uri = $imagedir . "/" . $file; if (is_readable($realfile) && ( preg_match('/\.(gif|jpg|png)$/i',$file) )) { $imagelist[] = $uri; $n++; } } closedir ($dh); } } return ($imagelist); } function handle_inheritance(&$map, &$inheritables) { foreach ($inheritables as $inheritable) { $fieldname = $inheritable[1]; $formname = $inheritable[2]; $validation = $inheritable[3]; $new = $_REQUEST[$formname]; if($validation != "") { switch($validation) { case "int": $new = intval($new); break; case "float": $new = floatval($new); break; } } $old = ($inheritable[0]=='node' ? $map->nodes['DEFAULT']->$fieldname : $map->links['DEFAULT']->$fieldname); if ($old != $new) { if ($inheritable[0]=='node') { $map->nodes['DEFAULT']->$fieldname = $new; foreach ($map->nodes as $node) { if ($node->name != ":: DEFAULT ::" && $node->$fieldname == $old) { $map->nodes[$node->name]->$fieldname = $new; } } } if ($inheritable[0]=='link') { $map->links['DEFAULT']->$fieldname = $new; foreach ($map->links as $link) { if ($link->name != ":: DEFAULT ::" && $link->$fieldname == $old) { $map->links[$link->name]->$fieldname = $new; } } } } } } function get_fontlist(&$map,$name,$current) { $output = '<select class="fontcombo" name="'.$name.'">'; ksort($map->fonts); foreach ($map->fonts as $fontnumber => $font) { $output .= '<option '; if ($current == $fontnumber) { $output .= 'SELECTED'; } $output .= ' value="'.$fontnumber.'">'.$fontnumber.' ('.$font->type.')</option>'; } $output .= "</select>"; return($output); } function range_overlaps($a_min, $a_max, $b_min, $b_max) { if ($a_min > $b_max) { return false; } if ($b_min > $a_max) { return false; } return true; } function common_range ($a_min,$a_max, $b_min, $b_max) { $min_overlap = max($a_min, $b_min); $max_overlap = min($a_max, $b_max); return array($min_overlap,$max_overlap); } /* distance - find the distance between two points * */ function distance ($ax,$ay, $bx,$by) { $dx = $bx - $ax; $dy = $by - $ay; return sqrt( $dx*$dx + $dy*$dy ); } function tidy_links(&$map,$targets, $ignore_tidied=FALSE) { // not very efficient, but it saves looking for special cases (a->b & b->a together) $ntargets = count($targets); $i = 1; foreach ($targets as $target) { tidy_link($map, $target, $i, $ntargets, $ignore_tidied); $i++; } } /** * tidy_link - change link offsets so that link is horizonal or vertical, if possible. * if not possible, change offsets to the closest facing compass points */ function tidy_link(&$map,$target, $linknumber=1, $linktotal=1, $ignore_tidied=FALSE) { // print "\n-----------------------------------\nTidying $target...\n"; if(isset($map->links[$target]) and isset($map->links[$target]->a) ) { $node_a = $map->links[$target]->a; $node_b = $map->links[$target]->b; $new_a_offset = "0:0"; $new_b_offset = "0:0"; // Update TODO: if the nodes are already directly left/right or up/down, then use compass-points, not pixel offsets // (e.g. N90) so if the label changes, they won't need to be re-tidied // First bounding box in the node's boundingbox array is the icon, if there is one, or the label if not. $bb_a = $node_a->boundingboxes[0]; $bb_b = $node_b->boundingboxes[0]; // figure out if they share any x or y coordinates $x_overlap = range_overlaps($bb_a[0], $bb_a[2], $bb_b[0], $bb_b[2]); $y_overlap = range_overlaps($bb_a[1], $bb_a[3], $bb_b[1], $bb_b[3]); $a_x_offset = 0; $a_y_offset = 0; $b_x_offset = 0; $b_y_offset = 0; // if they are side by side, and there's some common y coords, make link horizontal if ( !$x_overlap && $y_overlap ) { // print "SIDE BY SIDE\n"; // snap the X coord to the appropriate edge of the node if ($bb_a[2] < $bb_b[0]) { $a_x_offset = $bb_a[2] - $node_a->x; $b_x_offset = $bb_b[0] - $node_b->x; } if ($bb_b[2] < $bb_a[0]) { $a_x_offset = $bb_a[0] - $node_a->x; $b_x_offset = $bb_b[2] - $node_b->x; } // this should be true whichever way around they are list($min_overlap,$max_overlap) = common_range($bb_a[1],$bb_a[3],$bb_b[1],$bb_b[3]); $overlap = $max_overlap - $min_overlap; $n = $overlap/($linktotal+1); $a_y_offset = $min_overlap + ($linknumber*$n) - $node_a->y; $b_y_offset = $min_overlap + ($linknumber*$n) - $node_b->y; $new_a_offset = sprintf("%d:%d", $a_x_offset,$a_y_offset); $new_b_offset = sprintf("%d:%d", $b_x_offset,$b_y_offset); } // if they are above and below, and there's some common x coords, make link vertical if ( !$y_overlap && $x_overlap ) { // print "ABOVE/BELOW\n"; // snap the Y coord to the appropriate edge of the node if ($bb_a[3] < $bb_b[1]) { $a_y_offset = $bb_a[3] - $node_a->y; $b_y_offset = $bb_b[1] - $node_b->y; } if ($bb_b[3] < $bb_a[1]) { $a_y_offset = $bb_a[1] - $node_a->y; $b_y_offset = $bb_b[3] - $node_b->y; } list($min_overlap,$max_overlap) = common_range($bb_a[0],$bb_a[2],$bb_b[0],$bb_b[2]); $overlap = $max_overlap - $min_overlap; $n = $overlap/($linktotal+1); // move the X coord to the centre of the overlapping area $a_x_offset = $min_overlap + ($linknumber*$n) - $node_a->x; $b_x_offset = $min_overlap + ($linknumber*$n) - $node_b->x; $new_a_offset = sprintf("%d:%d", $a_x_offset,$a_y_offset); $new_b_offset = sprintf("%d:%d", $b_x_offset,$b_y_offset); } // if no common coordinates, figure out the best diagonal... if ( !$y_overlap && !$x_overlap ) { $pt_a = new WMPoint($node_a->x, $node_a->y); $pt_b = new WMPoint($node_b->x, $node_b->y); $line = new WMLineSegment($pt_a, $pt_b); $tangent = $line->vector; $tangent->normalise(); $normal = $tangent->getNormal(); $pt_a->AddVector( $normal, 15 * ($linknumber-1) ); $pt_b->AddVector( $normal, 15 * ($linknumber-1) ); $a_x_offset = $pt_a->x - $node_a->x; $a_y_offset = $pt_a->y - $node_a->y; $b_x_offset = $pt_b->x - $node_b->x; $b_y_offset = $pt_b->y - $node_b->y; $new_a_offset = sprintf("%d:%d", $a_x_offset,$a_y_offset); $new_b_offset = sprintf("%d:%d", $b_x_offset,$b_y_offset); } // if no common coordinates, figure out the best diagonal... // currently - brute force search the compass points for the shortest distance // potentially - intersect link line with rectangles to get exact crossing point if ( 1==0 && !$y_overlap && !$x_overlap ) { // print "DIAGONAL\n"; $corners = array("NE","E","SE","S","SW","W","NW","N"); // start with what we have now $best_distance = distance( $node_a->x, $node_a->y, $node_b->x, $node_b->y ); $best_offset_a = "C"; $best_offset_b = "C"; foreach ($corners as $corner1) { list ($ax,$ay) = calc_offset($corner1, $bb_a[2] - $bb_a[0], $bb_a[3] - $bb_a[1]); $axx = $node_a->x + $ax; $ayy = $node_a->y + $ay; foreach ($corners as $corner2) { list($bx,$by) = calc_offset($corner2, $bb_b[2] - $bb_b[0], $bb_b[3] - $bb_b[1]); $bxx = $node_b->x + $bx; $byy = $node_b->y + $by; $d = distance($axx,$ayy, $bxx, $byy); if($d < $best_distance) { // print "from $corner1 ($axx, $ayy) to $corner2 ($bxx, $byy): "; // print "NEW BEST $d\n"; $best_distance = $d; $best_offset_a = $corner1; $best_offset_b = $corner2; } } } // Step back a bit from the edge, to hide the corners of the link $new_a_offset = $best_offset_a."85"; $new_b_offset = $best_offset_b."85"; } // unwritten/implied - if both overlap, you're doing something weird and you're on your own // finally, update the offsets $map->links[$target]->a_offset = $new_a_offset; $map->links[$target]->b_offset = $new_b_offset; // and also add a note that this link was tidied, and is eligible for automatic tidying $map->links[$target]->add_hint("_tidied",1); } } function untidy_links(&$map) { foreach ($map->links as $link) { $link->a_offset = "C"; $link->b_offset = "C"; } } function retidy_links(&$map, $ignore_tidied=FALSE) { $routes = array(); $done = array(); foreach ($map->links as $link) { if(isset($link->a)) { $route = $link->a->name . " " . $link->b->name; if(strcmp( $link->a->name, $link->b->name) > 0) { $route = $link->b->name . " " . $link->a->name; } $routes[$route][] = $link->name; } } foreach ($map->links as $link) { if(isset($link->a)) { $route = $link->a->name . " " . $link->b->name; if(strcmp( $link->a->name, $link->b->name) > 0) { $route = $link->b->name . " " . $link->a->name; } if( ($ignore_tidied || $link->get_hint("_tidied")==1) && !isset($done[$route]) && isset( $routes[$route] ) ) { if( sizeof($routes[$route]) == 1) { tidy_link($map,$link->name); $done[$route] = 1; } else { # handle multi-links specially... tidy_links($map,$routes[$route]); // mark it so we don't do it again when the other links come by $done[$route] = 1; } } } } } function editor_log($str) { // $f = fopen("editor.log","a"); // fputs($f, $str); // fclose($f); } // vim:ts=4:sw=4:
true
361752242a915d571bd084d8b02cd2134eeed76f
PHP
Emjy1990/Portfolio
/Mealoclock/app/Controllers/CommunityController.php
UTF-8
887
2.59375
3
[]
no_license
<?php // MealOclock => app/ // Controllers => Controllers/ // au final => app/Controllers/ namespace MealOclock\Controllers; // Import des classes externes use MealOclock\Models\CommunityModel; class CommunityController extends CoreController { public function community($urlParams) { // Je récupère l'id se trouvant dans l'URL $id = $urlParams['id']; // echo "Vous souhaitez consulter la communauté n°{$id}<br>"; // Je veux récuperer l'objet CommunityModel correspondant à l'id de la communauté fourni dans l'URL $communityModel = CommunityModel::find($id); // dump($communityModel);exit; // debug // Exécute la view '/community/community' avec passage de données jusqu'à la view $this->show('/community/community', [ 'communityModel' => $communityModel ]); } }
true
5bd736f96d4ac3bb6ddc6bb8acbd951a411a2def
PHP
gitter-badger/dephpend
/src/Formatters/PlantUmlFormatter.php
UTF-8
772
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php declare(strict_types=1); namespace Mihaeu\PhpDependencies\Formatters; use Mihaeu\PhpDependencies\Dependencies\DependencyPair; use Mihaeu\PhpDependencies\Dependencies\DependencyPairSet; class PlantUmlFormatter implements Formatter { /** * {@inheritdoc} */ public function format(DependencyPairSet $dependencyCollection) : string { return '@startuml'.PHP_EOL.$this->dependenciesInPlantUmlFormat($dependencyCollection).PHP_EOL.'@enduml'; } /** * @param DependencyPairSet $dependencyCollection * * @return mixed */ private function dependenciesInPlantUmlFormat(DependencyPairSet $dependencyCollection) : string { return str_replace('-->', '--|>', $dependencyCollection->toString()); } }
true
32d1dd6e4c45c0e82d012f5a2c727d1011d8efb1
PHP
joebubna/Cora
/vendor/cora/cora-framework/system/classes/Session.php
UTF-8
744
2.828125
3
[ "MIT" ]
permissive
<?php namespace Cora; class Session { public function __construct($data = false) { $this->start(); } public function __get($name) { if (isset($_SESSION[$name])) { return $_SESSION[$name]; } return false; } public function __set($name, $value) { $_SESSION[$name] = $value; } public function start() { if (session_status() == PHP_SESSION_NONE) { session_start(); } } public function delete($name) { unset($_SESSION[$name]); } public function close() { session_write_close(); } public function destroy() { session_destroy(); } }
true
aca0bd239674ae683bf042d705d835f7140768ce
PHP
jonathanpglick/jquery-mobile-seed
/application/lib/app/BaseAPI.php
UTF-8
1,535
2.90625
3
[]
no_license
<?php /** * @file * Class to manage requesting data from the API. */ require_once ROOT_PATH . '/application/lib/app/render.php'; class BaseAPI { // 12 hours. const MEMCACHED_EXPIRATION = 43200; protected static $memcachedPrefix = 'mobile_site_'; protected static $memcached = FALSE; /** * Set the memcache object. */ public static function setMemcachedObject($memcached, $prefix = NULL) { self::$memcached = $memcached; if (isset($prefix) && !empty($prefix)) { self::$memcachedPrefix = $prefix; } } /** * Put an item in the cache. */ public static function cacheSet($key, $value, $expiration = NULL) { if ($expiration === NULL) { $expiration = self::MEMCACHED_EXPIRATION; } $cache_key = self::$memcachedPrefix . $key; if (self::$memcached !== FALSE) { self::$memcached->set($cache_key, $value, NULL, $expiration); } } /** * Get an item from the cache. */ public static function cacheGet($key) { $cache_key = self::$memcachedPrefix . $key; if (self::$memcached === FALSE) { return FALSE; } return self::$memcached->get($cache_key); } /** * Get and decode json from a url. */ public static function getJson($url, $cache = TRUE) { if ($cache) { $data = self::cacheGet($url); if ($data) { return $data; } } $data = file_get_contents($url); $data = json_decode($data, TRUE); if ($cache) { self::cacheSet($url, $data); } return $data; } }
true
937036e32a152d113693de07cc1a44f5f4daf2cb
PHP
benboute/hector
/Hector/Core/Db/QueryBuilder/QueryPart/Where.php
UTF-8
548
2.84375
3
[]
no_license
<?php namespace Hector\Core\Db\QueryBuilder\QueryPart; class Where extends QueryPart { private $conditions; public function init( $conditions ) { $this->conditions = $conditions; $this->query->bindValues( $this->conditions ); } public function limit( $limit ) { return $this->query->add( 'Limit', [ $limit ] ); } public function toString() { $fields = array_keys( $this->conditions ); array_walk( $fields, function( &$v ) { $v = $this->quote( $v ) . ' = ?'; } ); return 'WHERE ' . implode( ' AND ', $fields ); } }
true
058b720edceee30584646a1ceb06daf7505d91ee
PHP
bg1bgst333/Sample
/php/class/const/src/class/const.php
UTF-8
212
3.15625
3
[ "MIT" ]
permissive
<html> <head> <title>class#const</title> </head> <body> <?php class TestClass{ const NUM = 10; } //TestClass::NUM = 20; echo TestClass::NUM; ?> </body> </html>
true
4ab7201ec6c8dc3eb0b9fe1b738c8d7753d48e87
PHP
HelaGone/deriva_v2_1.0
/output.php
UTF-8
6,721
2.515625
3
[]
no_license
<?php include('header.php'); include('connect_to_db.php'); include('parts/part-outputform.php'); $the_function = ''; $the_search = ''; $the_search_key = ''; $file_type_query = ''; if( $_SERVER['REQUEST_METHOD'] == 'POST' ): $file_ID = ($_POST['the_file_id']) ? $_POST['the_file_id'] : ''; $file_name = ($_POST['the_file_name']) ? $_POST['the_file_name'] : ''; $file_type_query = ($_POST['file_type']) ? $_POST['file_type']: ''; $state_query = ($_POST['state']) ? $_POST['state']: ''; $unity_query = ($_POST['unity']) ? $_POST['unity']: ''; $type_query = ($_POST['type']) ? $_POST['type']: ''; $space_query = ($_POST['space']) ? $_POST['space']: ''; $population_query = ($_POST['population']) ? $_POST['population']: ''; $ecosystem_query = ($_POST['ecosystem']) ? $_POST['ecosystem']: ''; $light_query = ($_POST['light']) ? $_POST['light']: ''; $camera_query = ($_POST['camera']) ? $_POST['camera']: ''; $movement_query = ($_POST['movement']) ? $_POST['movement']: ''; $sound_query = ($_POST['sound']) ? $_POST['sound']: ''; $subject_query = ($_POST['subject']) ? $_POST['subject']: ''; $geometry_query = ($_POST['geometry']) ? $_POST['geometry']: ''; $color_query = ($_POST['color']) ? $_POST['color']: ''; $rythm_query = ($_POST['rythm']) ? $_POST['rythm']: ''; $intensity_query = ($_POST['intensity']) ? $_POST['intensity']: ''; $impact_query = ($_POST['impact']) ? $_POST['impact']: ''; $theme_query = ($_POST['theme']) ? $_POST['theme']: ''; //save values to a general array $arr_queries = array( 'id'=>$file_ID, 'nombreArchivo'=>$file_name, 'tipoDeArchivo'=>$file_type_query,'estado'=>$state_query,'unidad'=>$unity_query,'tipo'=>$type_query,'espacio'=>$space_query,'poblacion'=>$population_query,'ecosistema'=>$ecosystem_query,'luz'=>$light_query,'camara'=>$camera_query,'movimiento'=>$movement_query,'sonido'=>$sound_query,'sujeto'=>$subject_query,'geometriaDominante'=>$geometry_query,'color'=>$color_query,'ritmo'=>$rythm_query,'nuevaIntensidad'=>$intensity_query,'impacto'=>$impact_query,'temas'=>$theme_query); $arr_keys = array(); $arr_values = array(); $arr = array(); foreach ($arr_queries as $key => $value): if($value == ''): //do nothing else: //términos de búsqueda $the_search = $value; $the_search_key = $key; //save to array array_push($arr_values, $value); array_push($arr_keys, $key); endif; endforeach; //save key-val pairs array $arr = array_combine($arr_keys, $arr_values); $counting_index = 0; $el_query_part = ''; $byid = false; foreach ($arr as $k => $v){ $v = str_replace('-', ' ', $v); if($k == 'id'): $byid = true; $el_query_part .= $k.'='.$v; else: $el_query_part .= $k." LIKE ". "'%".$v."%'" ." AND "; endif; $counting_index++; } $elquery = "SELECT * FROM materiales WHERE ".$el_query_part; if($byid == true): //do nothing else: $elquery = substr($elquery, 0, -5); endif; if( !($result = mysqli_query($dbconn, $elquery) ) ){ die('Error en la consulta!'); }else{ if( mysqli_num_rows( $result ) == 0 ): echo 'No hay resultados para esta consulta'; else: $result = mysqli_fetch_all($result, MYSQLI_ASSOC); ?> <section class="nme_resultados main_section"> <span class="txt lbl_res">Resultados para <em><?php echo $the_search.': '; ?></em></span><span class="lbl_num_res"><?php echo count($result); ?></span><br> <?php //echo $the_search; ?> <section class="file_names_pool"> <div> <div class="nmes"> <?php $str = ''; $s_arr = array(); $filenames = array(); foreach ($result as $key => $searched): array_push($s_arr, $searched); array_push($filenames, $searched['nombreArchivo']); echo "<p>"; echo $searched['nombreArchivo']; echo "</p>"; endforeach; ?> </div> </div> </section> <section class="file_created"> <?php foreach ($filenames as $key => $name): $str .= $name.', '; endforeach; $search = $the_search; $search_key = $the_search_key; $filename_prefix = 'termino'; $extension = '.txt'; $date = date('Ymd'); $the_filename = './files/'.$filename_prefix.'-'.$search_key.'-'.$search.'-'.$date.$extension; $str = substr($str, 0, -2); if($str != ''): if(file_exists($the_filename)): print('El archivo ya existe'); else: if (file_put_contents($the_filename, $str)): print 'Archivo creado: <a href="files/'.basename($the_filename).'" target="_blank" class="the_txt_file">' . basename($the_filename).'</a><br>'; // else: // print 'Error al crear archivo: ' . basename($the_filename); endif; endif; endif; ?> </section> </section> <!-- end name results --> <section id="sec_res_table"> <table class="result_table"> <thead> <tr> <th>Update</th> <th>ID</th> <th>Nombre</th> <th>Tipo</th> <th>nNombre</th> <th>Autor</th> <th>Subs</th> <th>Créditos</th> <th>Fecha</th> <th>Estado</th> <th>Mun/Ciu</th> <th>Lugar</th> <th>Serie Nombre</th> <th>Preg</th> <th>Unidad</th> <th>Tipo</th> <th>Espacio</th> <th>Población</th> <th>Ecosistema</th> <th>Luz</th> <th>Cámara</th> <th>Movimiento</th> <th>Sonido</th> <th>Sujeto</th> <th>Geometría</th> <th>Color</th> <th>Ritmo</th> <th>nIntensidad</th> <th>Impacto</th> <th>Temas</th> <th>Imagen</th> </tr> </thead> <tbody> <?php $row_count = 1; $checkbox = '<input type="checkbox" name="selected-'.$key.'" >'; foreach ($s_arr as $key => $value) { echo "<tr id='row_".$row_count."'>"; echo "<td><button type='button' class='btn_update' data-row='row_".$row_count."'>update</button></td>"; foreach ($value as $k => $v): if($k == 'imagen'): echo "<td class='".$k."'><a href='".$v."' target='_blank'><img src='".$v."' width='90px' height='auto' ></td>"; else: echo "<td class='".$k."'>".$v."</td>"; endif; endforeach; echo "</tr>"; // echo "<tr><td>".$mks[0]."</td><td>".$mks[1]."</td></tr>"; $row_count++; } ?> </tbody> </table> </section> <?php endif; } else: echo ":"; endif; ?> <?php include('footer.php'); ?>
true
d08c8d10e3011095e9c3238d80e3c9169c89294d
PHP
wudnf/my
/mogujie/action/stu.php
UTF-8
651
2.78125
3
[]
no_license
<?php //对学生信息的增删改查 //1 引入配置文件 引入model类 include("dbconfig.php"); include("Model.php"); //2 实例化model产生一个mod对象 $mod = new Model("stu"); //根据前端传递的值 实现对stu表的增删改查 switch($_GET['a']){ case "insert": $res['info'] = $mod->insert(); break; case "delete": $res['info'] = $mod->del($_GET['id']); break; case "update": $res['info'] = $mod->update(); break; case "show": default: $res['info'] = $mod->findAll(); break; } // echo "<pre>"; // print_r($res['info']); //6 准备数据 输出到前端 echo json_encode($res['info']);
true
ea805fe9bddf110a86524fb04b0ed64328f82f98
PHP
omaben/paxful-back
/vendor/flying-panda/php-framework/libs/MySql/Search.php
UTF-8
2,286
2.6875
3
[]
no_license
<?php namespace Libs\MySql; use Libs\DataSource\Interfaces\Field; use Libs\DataSource\Interfaces\SearchInfo; use Manage\CoreManage; class Search implements \Libs\DataSource\Interfaces\Search { private array $fieldList = []; private array $table; private SearchInfo $searchInfo; function addFieldList(string $val): \Libs\DataSource\Interfaces\Search { $this->fieldList[] = $val; return $this; } function getFieldList(): array { return $this->fieldList; } function setFieldList(array $fieldList): \Libs\DataSource\Interfaces\Search { $this->fieldList = $fieldList; return $this; } function succeed($event): \Libs\DataSource\Interfaces\Search { return $this; } function succeedItem($event): \Libs\DataSource\Interfaces\Search { return $this; } function fail($event): \Libs\DataSource\Interfaces\Search { return $this; } function from(string $name): \Libs\DataSource\Interfaces\Search { $this->table[] = $name; return $this; } function getSearchInfo(): SearchInfo { return $this->searchInfo; } function setSearchInfo(SearchInfo $v): \Libs\DataSource\Interfaces\Search { $this->searchInfo = $v; return $this; } function execute(int $page, int $count) { $sqlInfo = $this->getSqlInfo(); return CoreManage::$coreDataBase->Search($sqlInfo[0], $sqlInfo[1]); } function getSqlInfo(): array { $fieldList = []; $parameterList = []; foreach ($this->fieldList as $item) { $fieldList[] = $item ; } $sql = "select " . (count($this->fieldList) == 0 ? "*" : implode(",", $this->fieldList)) . " from " . implode(",", $this->table); if ($this->getSearchInfo() != null) { $searchInfo = $this->getSearchInfo()->execute(); $sql .= $searchInfo[0]; $parameterList = $searchInfo[1]; } return [$sql, $parameterList]; } function getOne() { $sqlInfo = $this->getSqlInfo(); $ret = CoreManage::$coreDataBase->Search($sqlInfo[0], $sqlInfo[1]); return count($ret) == 0 ? null : $ret[0]; } }
true
db78a4ca51aa857b2230e7392bf4b0122ba6511d
PHP
matteodedonno02/covid19
/phpClass/Utente.php
UTF-8
1,255
3.578125
4
[]
no_license
<?php class Utente { private $CF; private $nome; private $cognome; private $username; private $password; private $amministratore; public function __construct($CF, $nome, $cognome, $username, $password, $amministratore) { $this->CF = $CF; $this->nome = $nome; $this->cognome = $cognome; $this->username = $username; $this->password = $password; $this->amministratore = $amministratore; } public function getCF() { return $this->CF; } public function getNome() { return $this->nome; } public function getCognome() { return $this->cognome; } public function getUsername() { return $this->username; } public function getPassword() { return $this->password; } public function getAmministratore() { return $this->amministratore; } public function __toString() { return "Utente[CF=" . $this->CF . ", nome=" . $this->nome . ", cognome=" . $this->cognome . ", username=" . $this->username . ", password=" . $this->amministratore . ", amministratore=" . $this->amministratore . "]"; } } ?>
true
b8142210f5618b43ac04a8ddedefb583b4a708c9
PHP
barshamalbul/attendance-mgnt-system
/controller/teacher/view_attendance_controller.php
UTF-8
2,085
2.546875
3
[]
no_license
<?php if(isset($_POST['send'])) { $errcount=0; $err = array(); if((isset($_POST['class'])) && (!empty($_POST['class']))) { $class=$_POST['class']; } else { $errclass="enter the class"; $err['class']="class is empty"; $errcount++; } if((isset($_POST['section'])) && (!empty($_POST['section']))) { $section=$_POST['section']; } else{ $errsection="enter the section"; $err['Section']="Section is empty"; $errcount++; } if((isset($_POST['startdate'])) && (!empty($_POST['startdate']))) { $startdate=$_POST['startdate']; } else{ $errstartdate="enter the start date"; $err['startdate']="startdate is empty"; $errcount++; } if((isset($_POST['enddate'])) && (!empty($_POST['enddate']))) { $enddate=$_POST['enddate']; } else{ $errenddate="enter the end date"; $err['enddate']="enddate is empty"; $errcount++; } session_start(); $_SESSION['class']=$_POST['class']; $_SESSION['section']=$_POST['section']; $_SESSION['startdate']=$_POST['startdate']; $_SESSION['enddate']=$_POST['enddate']; var_dump($_SESSION); if(empty($err)) { include '../../common/connect.php'; $sql="SELECT * from tbl_students_class inner join tbl_students on tbl_students.Sid=tbl_students_class.Sid WHERE tbl_students_class.class='$class' and tbl_students_class.section='$section' and date= YEAR(CURRENT_TIMESTAMP)"; $result=mysqli_query($con,$sql); if($result) { $_SESSION['sql']=$sql; header('location:../../pages/teacher/teacher_view_attendance.php'); } else{ header('location:../../pages/teacher/teacher_view_attendance.php?err=fail'); } mysqli_close($con); } else { header('location:../../pages/teacher/teacher_view_attendance.php?err=empty'); } } ?>
true
38f1427aec7dcf3ba20166baf3323b5b87f3e325
PHP
nfonseca1/Slotify
/includes/classes/Account.php
UTF-8
1,023
3.453125
3
[]
no_license
<?php class Account { private $errorLogs; public function __construct() { $errorLogs = array(); } public function validate($un, $fn, $ln, $email, $pass, $pass2) { validateUsername($un); validateName($fn); validateName($ln); validateEmail($email); validatePassword($pass, $pass2); } private function validateUsername($user) { if (strlen($user) > 25 || strlen($user) < 5) { array_push($errorLogs, "Username must be between 5 and 25 characters"); return; } } private function validateName($name) { if (preg_match('#^[a-zA-Z0-9_]{4,10}$D#', $name)) { array_push($errorLogs, "Not a valid name"); return; } } private function validateEmail($email) { if(!filter_var($email, FILTER_VALIDATE_EMAIL)) { array_push($errorLogs, "Not a valid email"); return; } } private function validatePassword($pass, $pass2) { if(!$pass == $pass2) { array_push($errorLogs, "Passwords do not match"); } } } ?>
true
7d63be3d49d578e7c06f76a3722eb01624cb87a0
PHP
Stranger7/e-test
/core/db_drivers/sql_builders/SqlBuilder.php
UTF-8
16,616
2.921875
3
[ "MIT" ]
permissive
<?php /** * This file is part of the Crystal framework. * * (c) Sergey Novikov (novikov.stranger@gmail.com) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Date: 20.12.2014 * Time: 23:31 */ namespace core\db_drivers\sql_builders; use core\generic\DbDriver; use core\Utils; /** * Class SqlBuilder * @package core\db_drivers\sql_builders * * Example of usage for select: * $sql = (new MySQLiSqlBuilder) * ->select(['id', 'name']) * ->from('users') * ->where('name = ?', 'John') * ->compile(); * * Example of usage for insert: * $sql = (new MySQLiSqlBuilder)->insert('users', $data)->compile(); * * Example of usage for update: * $sql = (new MySQLiSqlBuilder)->update('users', $data)->where('name = ?', 'John')->compile(); * * Example of usage for delete: * $sql = (new MySQLiSqlBuilder)->delete('users')->where('name = ?', 'John')->compile(); */ abstract class SqlBuilder { const INSERT_QUERY = 1; const UPDATE_QUERY = 2; const DELETE_QUERY = 3; const SELECT_QUERY = 4; const CUSTOM_QUERY = 5; /** * @var string */ protected $bind_marker = '?'; /** * ESCAPE character * * @var string */ protected $like_escape_chr = '!'; /** * @var string * * Name of table for insert|update|delete */ protected $table_name = ''; /** * @var array * * Data for insert|update */ protected $ins_upd_data = []; /** * @var string */ protected $custom_sql = ''; /** * @var array */ protected $select = []; /** * @var array */ protected $from = []; /** * @var array */ protected $join = []; /** * @var array */ protected $where = []; /** * @var array */ protected $order_by = []; /** * @var bool */ protected $limit = false; /** * @var bool */ protected $offset = false; /** * @var array */ protected $binds = []; /** * @var int */ protected $query_type = 0; /** * @var \core\generic\DbDriver */ protected $db; /** * @var mixed * * Name of id field */ protected $id_field_name; /*===============================================================*/ /* I M P L E M E N T A T I O N */ /*===============================================================*/ /** * @return SqlBuilder */ public function __construct() { return $this; } /** * @param \core\generic\DbDriver $db * @return \core\db_drivers\sql_builders\SqlBuilder */ public function setDb(DbDriver $db) { $this->db = $db; return $this; } /** * @return string * * Make SQL string using escaping */ public function compile() { $qs = ''; switch ($this->query_type) { case self::INSERT_QUERY: $this->binds = array_values($this->ins_upd_data); $qs = $this->insertPattern(); break; case self::UPDATE_QUERY: $this->binds = array_merge(array_values($this->ins_upd_data), $this->binds); $qs = $this->updatePattern() . $this->compileWhereExpr(); break; case self::DELETE_QUERY: $qs = $this->deletePattern() . $this->compileWhereExpr(); break; case self::SELECT_QUERY: $qs = $this->compileSelectExpr() . $this->compileFromExpr() . $this->compileJoinExpr() . $this->compileWhereExpr() . $this->compileOrderByExpr() . $this->compileLimitExpr(); break; case self::CUSTOM_QUERY: $qs = $this->custom_sql; break; } $this->query_type = 0; if ($qs === '') { throw new \LogicException('Query string is empty.' . ' Possible causes: incorrect or passing a query type' . ' or custom query text is empty', 500); } return $this->compileBind($qs); } /** * @return \core\db_drivers\query_results\QueryResult|null */ public function run() { if (empty($this->db)) { throw new \RuntimeException('Db driver not defined', 500); } return $this->db->query($this->compile()); } /*===============================================================*/ /* C U S T O M */ /*===============================================================*/ public function custom($sql, $binds) { $this->query_type = self::CUSTOM_QUERY; $this->binds = is_array($binds) ? $binds : [$binds]; $this->custom_sql = $sql; return $this; } /*===============================================================*/ /* I N S E R T */ /*===============================================================*/ /** * @param string $table_name * @param array $data * @param string $id - field name of identifier * @return SqlBuilder */ public function insert($table_name, $data, $id = '') { $this->query_type = self::INSERT_QUERY; $this->table_name = $table_name; $this->ins_upd_data = $data; $this->id_field_name = $id; return $this; } /** * @return string * * May be overridden */ protected function insertPattern() { $fields = implode(',', array_keys($this->ins_upd_data)); $placeholders = implode( ',', array_fill( 0, count($this->ins_upd_data), $this->bind_marker ) ); return ('INSERT' . ' INTO ' . $this->table_name . ' (' . $fields . ') ' . ' VALUES (' . $placeholders . ')'); } /*===============================================================*/ /* U P D A T E */ /*===============================================================*/ /** * @param string $table_name * @param array $data * @return \core\db_drivers\sql_builders\SqlBuilder */ public function update($table_name, $data) { $this->query_type = self::UPDATE_QUERY; $this->table_name = $table_name; $this->ins_upd_data = $data; return $this; } /** * @return string */ protected function updatePattern() { $fields = implode( ',', array_map( function($field) { return ($field . ' = ' . $this->bind_marker); }, array_keys($this->ins_upd_data) ) ); return 'UPDATE ' . $this->table_name . ' SET ' . $fields; } /*===============================================================*/ /* D E L E T E */ /*===============================================================*/ /** * @param string $table_name * @return \core\db_drivers\sql_builders\SqlBuilder */ public function delete($table_name) { $this->query_type = self::DELETE_QUERY; $this->table_name = $table_name; return $this; } /** * @return string */ protected function deletePattern() { return 'DELETE' . ' FROM ' . $this->table_name; } /*===============================================================*/ /* S E L E C T */ /*===============================================================*/ /** * @param array|string $fields * @return \core\db_drivers\sql_builders\SqlBuilder */ public function select($fields = []) { $this->query_type = self::SELECT_QUERY; $this->select = array_merge($this->select, (!is_array($fields) ? [$fields] : $fields)); return $this; } /** * @param string|array $table * @return $this */ public function from($table) { $this->from = array_merge($this->from, (!is_array($table) ? [$table] : $table)); return $this; } /** * @param string $table * @param string $on * @param string $type should be INNER|LEFT|RIGHT|LEFT OUTER|RIGHT OUTER * @return \core\db_drivers\sql_builders\SqlBuilder */ public function join($table, $on, $type = 'INNER') { $this->join[] = [ 'table' => trim($table), 'on' => trim($on), 'type' => trim($type) ]; return $this; } /** * @param string $expr * @param array $binds * @param string $operator * @return \core\db_drivers\sql_builders\SqlBuilder */ public function where($expr, $binds = [], $operator = 'AND') { $expr = '(' . $expr . ')'; $operator = (!empty($operator) ? trim($operator) : 'AND'); if (!empty($this->where)) $expr = ($operator . ' ') . $expr; $this->where[] = $expr; if (!is_array($binds)) { $binds = [$binds]; } // Make sure we're using numeric keys $binds = array_values($binds); $this->binds = array_merge($this->binds, $binds); return $this; } /** * @param string $expr * @param array $binds * @param string $operator * @return \core\db_drivers\sql_builders\SqlBuilder */ public function whereIn($expr, $binds = [], $operator = 'AND') { $expr = $expr . ' IN (' . implode(',', array_fill(0, count($binds), '?')) . ')'; return $this->where($expr, $binds, $operator); } /** * @param array $fields * @return \core\db_drivers\sql_builders\SqlBuilder */ public function orderBy($fields = []) { $this->order_by = array_merge($this->order_by, is_array($fields) ? $fields : [$fields]); return $this; } /** * @param int $limit * @param bool|int $offset * @return \core\db_drivers\sql_builders\SqlBuilder */ function limit($limit, $offset = false) { $this->limit = (int) $limit; if ($offset !== false) $this->offset = (int) $offset; return $this; } /** * @param int $offset * @return \core\db_drivers\sql_builders\SqlBuilder */ function offset($offset) { $this->offset = (int) $offset; return $this; } /*===============================================================*/ /* C O M P I L E R S */ /*===============================================================*/ /** * @return string */ protected function compileSelectExpr() { return 'SELECT ' . (empty($this->select) ? '*': implode(',', $this->select)); } /** * @return string */ protected function compileFromExpr() { if (empty($this->from)) { throw new \LogicException('Table name not specified', 500); } return ' FROM ' . implode(',', $this->from); } /** * @return string */ protected function compileJoinExpr() { $result = ''; foreach($this->join as $item) { $result .= (!empty($item['type']) ? (' ' . $item['type']) : '') . ' JOIN ' . $item['table'] . ' ON ' . $item['on']; } return $result; } /** * @return string */ protected function compileWhereExpr() { $result = ''; if (!empty($this->where)) { $result = ' WHERE ' . implode(' ', $this->where); } return $result; } /** * @return string */ protected function compileOrderByExpr() { $result = ''; if (!empty($this->order_by)) { $result = ' ORDER BY ' . implode(', ', $this->order_by); } return $result; } /** * @return string */ protected function compileLimitExpr() { if ($this->limit !== false) { return ' LIMIT ' . ($this->offset ? $this->offset . ', ' : '') . $this->limit; } return ''; } /** * This function has been copied from the framework "CodeIgniter v.3" * * "Smart" Escape String * * Escapes data based on type * Sets boolean and null types * * @param string $param * @return mixed */ public function escape($param) { if (is_array($param)) { $param = array_map([&$this, 'escape'], $param); return $param; } elseif (is_string($param) OR (is_object($param) && method_exists($param, '__toString'))) { return "'" . $this->escapeString($param) . "'"; } elseif (is_bool($param)) { return ($param === FALSE) ? 0 : 1; } elseif ($param === NULL) { return 'NULL'; } return $param; } /** * This function has been copied from the framework "CodeIgniter v.3" * * Escape String * * @param string $value * @param bool $like Whether or not the string will be used in a LIKE condition * @return string */ public function escapeString($value, $like = false) { if (is_array($value)) { foreach ($value as $key => $val) { $value[$key] = $this->escapeString($val, $like); } return $value; } $value = $this->escapeApostrophe($value); // escape LIKE condition wildcards if ($like === true) { return str_replace( [ $this->like_escape_chr, '%', '_' ], [ $this->like_escape_chr . $this->like_escape_chr, $this->like_escape_chr . '%', $this->like_escape_chr . '_' ], $value ); } return $value; } /** * This function has been copied from the framework "CodeIgniter v.3" * * Platform-dependant string escape * * @param string $str * @return string */ protected function escapeApostrophe($str) { return str_replace("'", "''", Utils::removeInvisibleCharacters($str)); } /** * Replaces placeholder with values * This function has been copied from the framework "CodeIgniter v.3" * @param string $sql * @return string */ protected function compileBind($sql) { if (empty($this->binds) OR empty($this->bind_marker) OR strpos($sql, $this->bind_marker) === false) { return $sql; } $bind_count = count($this->binds); // We'll need the marker length later $ml = strlen($this->bind_marker); // Make sure not to replace a chunk inside a string that happens to match the bind marker if ($c = preg_match_all("/'[^']*'/i", $sql, $matches)) { $c = preg_match_all('/'.preg_quote($this->bind_marker, '/').'/i', str_replace($matches[0], str_replace($this->bind_marker, str_repeat(' ', $ml), $matches[0]), $sql, $c), $matches, PREG_OFFSET_CAPTURE); // Bind values' count must match the count of markers in the query if ($bind_count !== $c) { return $sql; } } elseif (($c = preg_match_all( '/' . preg_quote($this->bind_marker, '/') . '/i', $sql, $matches, PREG_OFFSET_CAPTURE)) !== $bind_count) { return $sql; } do { $c--; $escaped_value = $this->escape($this->binds[$c]); if (is_array($escaped_value)) { $escaped_value = '('.implode(',', $escaped_value).')'; } $sql = substr_replace($sql, $escaped_value, $matches[0][$c][1], $ml); } while ($c !== 0); return $sql; } }
true
b7f8e4e32912eb08bb6ee90abe044e8b88a8a14a
PHP
DarioMora/DAI_codeIgniter
/application/models/vehiculo.php
UTF-8
1,060
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Vehiculo { private $vin; private $patente; private $marca; private $moldeo; private $color; private $anio; function __construct() { } function getVin() { return $this->vin; } function getPatente() { return $this->patente; } function getMarca() { return $this->marca; } function getMoldeo() { return $this->moldeo; } function getColor() { return $this->color; } function getAnio() { return $this->anio; } function setVin($vin) { $this->vin = $vin; } function setPatente($patente) { $this->patente = $patente; } function setMarca($marca) { $this->marca = $marca; } function setMoldeo($moldeo) { $this->moldeo = $moldeo; } function setColor($color) { $this->color = $color; } function setAnio($anio) { $this->anio = $anio; } }
true
3be8697835283fdf0fc7ac09dccc410835e52c77
PHP
BrowserGameScriptz/xnova-game
/app/modules/Core/Models/Session.php
UTF-8
1,580
2.609375
3
[]
no_license
<?php namespace Friday\Core\Models; use Phalcon\Di; use Phalcon\Mvc\Model; use Phalcon\Security\Random; /** @noinspection PhpHierarchyChecksInspection */ /** * @method static Session[]|Model\ResultsetInterface find(mixed $parameters = null) * @method static Session findFirst(mixed $parameters = null) */ class Session extends Model { public $id; public $token; public $object_type; public $object_id; public $timestamp; public $lifetime; public $useragent; public $request; const OBJECT_TYPE_USER = 'user'; public function getSource() { return DB_PREFIX."sessions"; } public function initialize() {} public function onConstruct() { $this->useDynamicUpdate(true); } public function afterUpdate () { $this->setSnapshotData($this->toArray()); } public function isExist ($token) { return self::count(['conditions' => 'token = ?0', 'bind' => [$token]]) > 0; } public static function start ($type, $id, $lifetime = 3600) { $event = Di::getDefault()->getShared('eventsManager')->fire('core:beforeStartSession', null, $id); if ($event !== null && is_bool($event) && $event === false) return false; $session = new self; $token = new Random(); do { $key = $token->uuid(); } while ($session->isExist($key)); $success = $session->create([ 'token' => $key, 'object_type' => $type, 'object_id' => $id, 'timestamp' => time(), 'lifetime' => $lifetime, 'useragent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => print_r($_REQUEST, true) ]); return $success ? $session : false; } }
true
ec4f87effe4f24e18f3b0eb038c30be99740c95e
PHP
generalsoftby/code-examples
/Oleg/PHP-Services/Services/Calculator/FrontConverter/ErrorsConverter.php
UTF-8
1,454
3.015625
3
[]
no_license
<?php namespace App\Services\Calculators\FrontConverter; use App\Services\Calculators\Errors; use App\Services\Calculators\FrontConverter\Contracts\ErrorsConverter as ErrorsConverterInterface; use App\Services\Calculators\FrontConverter\Traits\ThrowsNoneErrorsException; /** * Converts the given errors to some formats. */ class ErrorsConverter implements ErrorsConverterInterface { use ThrowsNoneErrorsException; /** * An instance of Errors. * * @var Errors */ protected $errors; /** * Sets the given Errors. * * @param Errors $errors * @return self */ public function setInstanceOfErrors(Errors $errors): ErrorsConverterInterface { $this->errors = $errors; return $this; } /** * Returns an instance of Errors. * * @return Errors|null */ public function getInstanceOfErrors(): ?Errors { return $this->errors; } /** * Checks whether the instance has an instance of Errors. * * @return bool */ public function hasInstanceOfErrors(): bool { return isset($this->errors); } /** * Converts errors to an array of the format of React's front-end * of the calculator interface. * * @return array */ public function toArrayOfReactFE(): array { $this->throwNoneErrorsException(); return $this->errors->toArray(); } }
true
16f948a85c2aff4303db0da02f412830c8042c96
PHP
freshy969/Saito
/app/Controller/StatusController.php
UTF-8
1,230
2.53125
3
[]
no_license
<?php App::uses('AppController', 'Controller'); class StatusController extends AppController { public $uses = [ 'Shout' ]; public $autoRender = false; /** * Current app status ping * * @return string * @throws BadRequestException */ public function status() { $data = [ 'lastShoutId' => $this->Shout->findLastId() ]; $data = json_encode($data); if ($this->request->accepts('text/event-streams')) { return $this->_statusAsEventStream($data); } else { return $this->_statusAsJson($data); } } protected function _statusAsEventStream($data) { // time in ms to next request $_retry = '10000'; $this->response->type(['eventstream' => 'text/event-stream']); $this->response->type('eventstream'); $this->response->disableCache(); $_out = ''; $_out .= "retry: $_retry\n"; $_out .= 'data: ' . $data . "\n\n"; return $_out; } protected function _statusAsJson($data) { if ($this->request->is('ajax') === false) { throw new BadRequestException(); } return $data; } public function beforeFilter() { parent::beforeFilter(); if ($this->Components->enabled('Auth')) { $this->Components->disable('Auth'); } } }
true
9e0a87171322957b7d796b089d9d641da2539838
PHP
Xeragus/Winery
/app/Core/ResultLists/Pagination/PaginatableResultsInterface.php
UTF-8
465
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Core\ResultLists\Pagination; interface PaginatableResultsInterface { public function setOffset(int $offset); /** * @return int|null */ public function getOffset(); public function setItemsPerPage(int $items); public function resetItemsPerPage(); /** * @return int|null */ public function getItemsPerPage(); public function countTotal(): int; public function getResults(): array; }
true
17a2050d1999d88cf597336385fdcda7f5e98afa
PHP
shivank1404/getmehome1
/signup.php
UTF-8
1,989
2.8125
3
[]
no_license
<html> <head><title> Sign up</title></head> <?php // define variables and set to empty values $user= ""; $password= ""; $email= ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $user = test_input($_POST["user"]); $password = test_input($_POST["password"]); $email = test_input($_POST["email"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <head> <link rel="stylesheet" type="text/css" href="cascadesignup.css"> </head> <p class="texto">Sign Up</p> <div class="Registro"> <form method="post" action="signup.php"> <span class="fontawesome-user"></span> <input type="text" required placeholder="username" autocomplete="off" name="user"> <br> <span class="fontawesome-envelope-alt"></span> <input type="email" id="email" required placeholder="Email" autocomplete="off" name="email"> <br> <span class="fontawesome-lock"></span><input type="password" name="password" id="password" required placeholder="Password" autocomplete="off" name="password"> <input type="submit" value="Sign Up" title="register"> </body> <?php $servername = "localhost"; $username = "root"; $pass = ""; $dbname = "getmehome"; // Create connection $conn = new mysqli($servername, $username, $pass, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $check=mysqli_query($conn,"select * from user where username='$user';"); $checkrows=mysqli_num_rows($check); $flag=0; if($checkrows==0&&$user!="") { $sql = "INSERT INTO `user`(`username`, `password`, `email`) VALUES ('$user','$password','$email');"; $flag=1; header('location:first.php'); } else if($checkrows>0) { echo'<br>'; echo'<br>'; echo'<br>'; echo "<font size=5>Username exists"; } if($flag==1) { if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } } $conn->close(); ?> </html>
true
ef61e36ee55fd8af05cbaff8d091a8224fd43eea
PHP
phly/PhlyPaste
/src/PhlyPaste/View/Highlight.php
UTF-8
2,887
2.859375
3
[]
no_license
<?php namespace PhlyPaste\View; use DOMDocument; use DOMXPath; use GeSHi; use HTMLPurifier; use HTMLPurifier_Config; use Zend\View\Helper\AbstractHelper; class Highlight extends AbstractHelper { public function __invoke($content, $language) { if ($language == 'markdown') { return $this->renderMarkdown($content); } $segments = preg_split( '/^\#\#(.*)$/m', $content, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE ); $count = count($segments); if (1 == $count) { return $this->highlightCode($content, $language); } if (1 == $count % 2) { $segments[$count - 2] .= $segments[$count - 1]; unset($segments[$count - 1]); } $aggregate = ''; $title = false; $content = false; $escaper = $this->view->plugin('escapeHtml'); for ($i = 0 ; $i < $count; $i += 2) { $lang = $language; $title = trim($segments[$i]); $matches = array(); if (preg_match('/\[\s*(?P<lang>[a-zA-Z0-9_]+)\s*\]/', $title, $matches)) { $lang = $matches['lang']; $title = preg_replace('/\[[^\]]+\]/', '', $title); } $segment = trim($segments[$i + 1]); $aggregate .= sprintf( "<h4 class=\"code title\">%s</h4>\n%s", $escaper($title), $this->highlightCode($segment, $lang) ); } return $aggregate; } /** * Renders markdown * * @param string $content * @return string */ protected function renderMarkdown($content) { $renderer = $this->getView(); $markdown = $renderer->plugin('markdown'); $dirtyHtml = $markdown($content); $cleanHtml = $this->sanitiseHtml($dirtyHtml); return $cleanHtml; } /** * Sanitises HTML by running it through HTMLPurifier using default * configuration. * * @param string $dirtyHtml * @return string */ protected function sanitiseHtml($dirtyHtml) { $config = HTMLPurifier_Config::createDefault(); $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); $purifier = new HTMLPurifier($config); return $purifier->purify($dirtyHtml); } /** * Highlight code using GeSHi * * @param string $content * @param string $language * @return string */ protected function highlightCode($content, $language) { $geshi = new GeSHi($content, $language); $geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS, 5); $geshi->set_header_type(GESHI_HEADER_DIV); $code = $geshi->parse_code(); return $this->sanitiseHtml($code); } }
true
ac77e9ebc88eb7fbb1cda85efbf1f50705dfcd31
PHP
MichaelJouve/rezalps
/app/Http/Controllers/Api/PostController.php
UTF-8
1,636
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Post; use Illuminate\Support\Facades\Auth; class PostController extends Controller { public function index() { return Post::all(); } public function show(Post $post) { return $post; } public function store(Request $request) { $validateData = $request->validate([ 'publication' => 'required', // 'user_id' => 'required' ]); $authUser = Auth::user(); $post = new Post($validateData); $post->user_id = $authUser->id; $post->save(); // thoses tow lines was the automatics. // return back(); // $post = Post::create($request->all()); return response()->json($post, 201); } /** * @param Request $request * @param Post $post * @return \Illuminate\Http\JsonResponse */ public function update(Request $request, Post $post) { // $authUser = Auth::user(); $validateData = $this->validate($request, [ 'publication' => 'required', 'user_id' => 'required' ]); $post->publication = $validateData['publication']; $post->save(); // $post->update($request->all()); lines added automaticly return response()->json($post, 200); } /** * @param $id * @return \Illuminate\Http\JsonResponse * @throws \Exception */ public function delete(Post $post) { $post->delete(); return response()->json(null, 204); } }
true
b96bf678941cbbae658550c80a92a94a971a8f31
PHP
joaopfzousa/UFP-library
/app/Http/Controllers/UsersController.php
UTF-8
2,712
2.65625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Helpers\APIHelpers; class UsersController extends Controller { private $user; private $request; private $apiHelpers; /** * Create a new controller instance. * * @return void */ public function __construct(User $user, Request $request, APIHelpers $apiHelpers) { $this->user = $user; $this->request = $request; $this->apiHelpers = $apiHelpers; } public function index() { return $this->apiHelpers->jsonResponse($this->user::all()); } public function create() { $this->apiHelpers->validateRequest($this, $this->request, [ 'number' => 'required|unique:users', 'password' => 'required', 'degree' => 'required' ]); $number = $this->request->input('number'); $password = Hash::make($this->request->input('password')); $admin = empty($this->request->input('admin')) ? '0' : $this->request->input('admin'); $degree = $this->request->input('degree'); $user = new User; $user->number = $number; $user->password = $password; $user->admin = $admin; $user->degree = $degree; $user->save(); return $this->apiHelpers->jsonResponse($user); } public function show($number) { $user = $this->user->where('number', $number)->firstOrFail(); if (!$user) { abort(404); } return $this->apiHelpers->jsonResponse($user); } public function showAllReservations($number) { $user = $this->user->where('number', $number)->firstOrFail(); if (!$user) { abort(404); } return $this->apiHelpers->jsonResponse($user->getAllReservations()); } public function showActiveReservations($number) { $user = $this->user->where('number', $number)->firstOrFail(); if (!$user) { abort(404); } return $this->apiHelpers->jsonResponse($user->getActiveReservations()); } public function update($number) { $user = $this->user->where('number', $number)->firstOrFail(); if (!$user) { abort(404); } $admin = empty($this->request->input('admin')) ? '0' : $this->request->input('admin'); $user->save(); return $this->apiHelpers->jsonResponse($user); } public function destroy($number) { $user = $this->user->where('number', $number)->firstOrFail(); $user->delete(); } }
true
fd70fe57c5f4675b9d8b833b8c15763bfc1b4d8c
PHP
hindolam/camaga.org
/artists/Artist.php
UTF-8
701
3.25
3
[]
no_license
<?php class Artist { var $artist; function __construct($concert, $index) { $artists = $concert->getArtists(); $this->artist = $artists[$index]; } function getName() { return $this->artist["name"]; } function getInstrument() { return $this->artist["instrument"]; } function getLink() { $search_array = array( 'first' => 1, 'second' => 4 ); if (empty($this->artist["link"])) { $link = "https://www.google.com/search?q=" . $this->getName(); } else { $link = $this->artist["link"]; } return $link; } } ?>
true
3a1ff681b6286b9f3bd54a987b0690b662f0d8bc
PHP
Lesnier/HC_Sistem
/Dominio/Turno.php
UTF-8
965
2.578125
3
[]
no_license
<?php class Turno { public function Consultar_Turno($sql) { $base=new Conexion; $con=$base->conectardb(); $res=$con->Execute($sql); $datos=array(); while(!$res->EOF) { $datos[]=array("id_tu"=>$res->fields[0],"id_usu"=>$res->fields[1],"id_pac"=>$res->fields[2],"id_hor"=>$res->fields[3],"fechaR_tu"=>$res->fields[4],"fechaC_tu"=>$res->fields[5],"usuarioR_tu"=>$res->fields[6],"numero_tur"=>$res->fields[7],"estado_tur"=>$res->fields[8],"estadoEmer_tur"=>$res->fields[9],"estadoPa_tur"=>$res->fields[8]); $res->MoveNext(); } $res->Close(); return $datos; } public function Consultar($sql) { $base=new Conexion; $con=$base->conectardb(); $res=$con->Execute($sql); return $res->fields[0]; } public function Ejecutar($sql) { $base=new Conexion; $con=$base->conectardb(); $res=$con->Execute($sql); if(!$res) { return $con->ErrorMsg(); } else { return "La informacion se ejecuto correctamente"; } } } ?>
true
cb4671eaf7742753476ff098be552edaf2111d14
PHP
langr-org/langr
/hphp/plugin/cphp/include/function/xml.fun.php
GB18030
1,771
3.328125
3
[ "MIT" ]
permissive
<?php /** * xml DQɞ array * * @param string xmlı * @return array DQĔM */ function xml2array ($xml) { $xmlary = array (); $ReElements = '/<(\w+)\s*([^\/>]*)\s*(?:\/>|>(.*?)<(\/\s*\1\s*)>)/s'; $ReAttributes = '/(\w+)=(?:"|\')([^"\']*)(:?"|\')/'; preg_match_all ($ReElements, $xml, $elements); foreach ($elements[1] as $ie => $xx) { $xmlary[$ie]["name"] = $elements[1][$ie]; if ( $attributes = trim($elements[2][$ie])) { preg_match_all ($ReAttributes, $attributes, $att); foreach ($att[1] as $ia => $xx) $xmlary[$ie]["attributes"][$att[1][$ia]] = $att[2][$ia]; } $cdend = strpos($elements[3][$ie],"<"); if ($cdend > 0) { $xmlary[$ie]["text"] = substr($elements[3][$ie],0,$cdend -1); } if (preg_match ($ReElements, $elements[3][$ie])){ $xmlary[$ie]["elements"] = xml2array ($elements[3][$ie]); } else if (isset($elements[3][$ie])){ $xmlary[$ie]["text"] = $elements[3][$ie]; } $xmlary[$ie]["closetag"] = $elements[4][$ie]; } return $xmlary; } /** * array DQɞ xml * * @param array xmlݵĔM * @return string xmlı */ function array2xml ($arr) { $xml = ""; if (is_array($arr)) { while(list($key, $val) = each($arr)) { if (is_array($val)) { $xml .= array2xml($val); } else { if ('name' == $key) $xml .= '<'.$val.'>'; if ('text' == $key) $xml .= $val; if ('closetag' == $key) $xml .= '<'.$val.'>'; } } } return $xml; } ?>
true
c8eb3eefd0d917add2533898301f8c1b26970a57
PHP
alizafar29/yii2
/advanced/frontend/models/RegisteredSearch.php
UTF-8
1,943
2.546875
3
[]
no_license
<?php namespace frontend\models; use Yii; use common\models\User; use yii\web\UploadedFile; use frontend\models\Registered; use yii\data\ActiveDataProvider; class RegisteredSearch extends Registered { public $name; public $Mobile_Number; public $Email; public $DOB; public function rules() { return [ // [['name','Mobile_Number','Email','DOB','password'],'required'], [['name'], 'string'], // [['Mobile_Number'], 'integer'], // [['Email'], 'email'], // [['DOB'], 'date'], [['name','Mobile_Number', 'Email', 'DOB'], 'safe'], ]; } public function search($params) { // create ActiveQuery $query = Registered::find(); $dataProvider = new ActiveDataProvider([ 'pagination' => [ 'pageSize' => 3, ], 'query' => $query, // 'sort' => ['attributes' => ['name', 'Mobile_Number', 'Email', 'DOB']] ]); // No search? Then return data Provider $this->load($params); if (!$this->validate()) { return $dataProvider; } // $query->andFilterWhere([ // 'id' => $this->id, // 'name' => $this->name, // // 'Mobile_Number' => $this->Mobile_Number, // // 'Email' => $this->Email, // // 'DOB' => $this->DOB, // ]); $query->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'Mobile_Number', $this->Mobile_Number]) ->andFilterWhere(['like', 'Email', $this->Email]) ->andFilterWhere(['like', 'DOB', $this->DOB]); return $dataProvider; } } ?>
true
16ce2d4f3a56ab60c54c4bfd73c621bd8445aff0
PHP
chorry/libphonenumber
/src/tools/CarrierWriter.php
UTF-8
893
3.046875
3
[]
no_license
<?php declare(strict_types=1); namespace chr\phoneNumber\tools; class CarrierWriter { private $headerWritten = false; public function __construct($resource) { $this->resource = $resource; } public function write(array $data) { if (!$this->headerWritten) { $this->headerWritten = true; $this->writeHeader($this->resource); } foreach ($data as $prefix => $carrier) { fwrite($this->resource, sprintf ("\t%s => '%s',\n", $prefix, str_replace("'", "\'", $carrier))); } } public function __destruct() { $this->writeFooter($this->resource); } private function writeHeader($resource) { fwrite($resource, <<<'TEXT' <?php return [ TEXT ); } private function writeFooter($resource) { fwrite($resource, '];' . PHP_EOL); } }
true
9ce22a9c404ead65b990736127615ad44c7a1fd5
PHP
bjblayney/inventory-tracker
/includes/checkInventory.php
UTF-8
2,158
2.515625
3
[ "MIT" ]
permissive
<?php include 'db.php'; $jsonResponse = ['status' => false]; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die($jsonResponse['msg'] = 'Connection Error'); } $sql = []; $a_bind_params = []; $a_param_type = []; // set parameters if ($_GET['type']) { $sql[] = " i.type = ? "; $a_bind_params[] = $_GET['type']; $a_param_type[] = 'i'; } if ($_GET['brand']) { $sql[] = " i.brand = ? "; $a_bind_params[] = $_GET['brand']; $a_param_type[] = 'i'; } if ($_GET['colour']) { $sql[] = " i.type = ? "; $a_bind_params[] = $_GET['type']; $a_param_type[] = 'i'; } if ($_GET['gender']) { $sql[] = " i.type = ? "; $a_bind_params[] = $_GET['type']; $a_param_type[] = 'i'; } if ($_GET['size']) { $sql[] = " i.type = ? "; $a_bind_params[] = $_GET['type']; $a_param_type[] = 'i'; } $query = "SELECT t.name AS shirt_type, b.name AS brand_name, i.gender, i.quantity, i.size, c.name AS colour FROM inventory i JOIN brand b ON i.brand=b.id JOIN type t ON i.type=t.id JOIN colour c ON i.colour=c.id"; if (!empty($sql)) { $query .= ' WHERE ' . implode(' AND ', $sql); } $stmt = $conn->prepare($query); $param_type = implode('', $a_param_type); $a_params = []; $a_params[] = &$param_type; foreach ($sql as $i => $sqlPart) { $a_params[] = &$a_bind_params[$i]; } call_user_func_array(array($stmt, 'bind_param'), $a_params); $filterResult = $stmt->execute();//returns true/false if ($filterResult) { $json = []; $result = $stmt->get_result(); while ($row = $result->fetch_array(MYSQLI_ASSOC)) { $json[] = $row; } if (!empty($json)) { $jsonResponse['status'] = true; $jsonResponse['payload'] = $json; } else { $jsonResponse['msg'] = 'No results found'; } } else { $jsonResponse['msg'] = 'SQL parse failed'; } $conn->close(); header('Content-Type: application/json'); echo json_encode($jsonResponse); ?>
true
1a54d17337bc1d04bc0518c1cfa668dba1610860
PHP
magnus-eriksson/guestbook-test
/app/Libraries/Database.php
UTF-8
1,864
3.328125
3
[]
no_license
<?php namespace App\Libraries; use PDO; class Database { /** * @var PDO */ protected $pdo; /** * @param PDO $pdo */ public function __construct(PDO $pdo) { // Configure PDO to throw exceptions on error // and to use ASSOC as default fetch mode $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); $this->pdo = $pdo; } /** * Insert a record * * @param string $query * @param array $params * @return int The id of the last inserted record */ public function insert($query, array $params = []) { $stmt = $this->query($query, $params); return $this->pdo->lastInsertId(); } /** * Update a record * * @param string $query * @param array $params * @return int Number of affected rows */ public function update($query, array $params = []) { $stmt = $this->query($query, $params); return $stmt->rowCount(); } /** * Get records * * @param string $query * @param array $params * @param boolean $single If true, only the first record will be returned * @return array */ public function select($query, array $params = [], $single = false) { $stmt = $this->query($query, $params); return $single ? $stmt->fetch() : $stmt->fetchAll(); } /** * Make a generic query and return the statement * * @param string $query * @param array $params * @return PDOStatement */ public function query($query, array $params = []) { $stmt = $this->pdo->prepare($query); $stmt->execute($params); return $stmt; } }
true
cf0e4fc47882cc68a520c30a036456bb43ed4cb9
PHP
RudyBodo/hotel_reservation-phalcon
/app/forms/testForm.php
UTF-8
1,036
2.53125
3
[]
no_license
<?php use Phalcon\Forms\Form; use Phalcon\Forms\Element\Text; use Phalcon\Forms\Element\Select; use Phalcon\Forms\Element\Date; use Phalcon\Validation\Validator\PresenceOf; use Phalcon\Validation\Validator\StringLength; class TestForm extends Form { public function initialize() { //field checkin $checkin = new text('checkin'); $checkin->addValidators(array( new PresenceOf(array( 'message' => 'Checkin date is required' )) )); $this->add($checkin); //field checkout $checkout = new text('checkout'); $checkout->addValidators(array( new PresenceOf(array( 'message' => 'Checkout date is required' )) )); $this->add($checkout); } public function messages($name) { if ($this->hasMessagesFor($name)) { foreach ($this->getMessagesFor($name) as $message) { $this->flash->error($message); } } } }
true
2f6476dc8e3ed067bb3c3d925ae0979f35c796db
PHP
travhow99/docutheraphp-laravel
/app/Session.php
UTF-8
1,686
2.5625
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Session extends Model { /** * Mass assignable attributes. * * @var array */ protected $fillable = ['client_id', 'session_date', 'session_time', 'complete', 'cancelled', 'submitted', 'billed', 'notes']; /** * The accessors to append to the model's array form. * * @var array */ protected $appends = ['client_name', 'session_attributes']; /** * Return the client who owns the session. */ public function client() { return $this->belongsTo('App\Session'); } /** * Get the SessionGoals the Goal has. */ public function sessionGoals() { return $this->hasMany('App\SessionGoal'); } /** * Get the session's client name. */ public function clientName() { return $this->client_id ? Client::clientNameFromId($this->client_id) : null;// Client::clientNameFromId($this->first()->client_id); } /** * Set the client name attribute. */ public function getClientNameAttribute() { return $this->clientName(); } /** * Get all of the session's attributes. */ public function attributes() { return $this->morphMany('App\SessionAttribute', 'attributable'); } /** * Set the session session_attributes attributes. */ public function getSessionAttributesAttribute() { return $this->attributes()->get(); } /** * Get all of the session's attributes. */ public function invoiceLineItem() { return $this->hasOne('App\InvoiceLineItem'); } }
true
92865e0e61036d859737bdf0f021c17d80168f44
PHP
Bardo1/daemon-bundle
/src/Uecode/Bundle/DaemonBundle/Command/ExampleCommand.php
UTF-8
1,175
2.828125
3
[]
no_license
<?php /** * @author Aaron Scherer <aequasi@gmail.com> * @date Oct 12, 2012 */ namespace Uecode\Bundle\DaemonBundle\Command; use \Symfony\Component\Console\Input\InputInterface; use \Symfony\Component\Console\Output\OutputInterface; use \Symfony\Component\Console\Input\InputArgument; /** * Example Command class */ class ExampleCommand extends ExtendCommand { protected $name = 'example'; protected $description = 'Starts an example Daemon'; protected $help = 'Usage: <info>php app/console example start|stop|restart 1 [--sleep|-s 2]</info>'; /** * Configures the Command */ protected function setArguments() { $this->addArgument('debug', InputArgument::OPTIONAL, 'Debug mode?'); } protected function setOptions() { $this->addOption('sleep', 's', 5, 'How long should we sleep for?'); } /** * Sample Daemon Logic. Logs `Daemon is running!` every 5 seconds */ protected function daemonLogic() { // Do a little logging $this->container->get('logger') ->info('Daemon is running!'); // And then sleep for 5 seconds $this->daemon->iterate(5); } }
true
9dc88ba8b55d8fa2c3633a4171c77290cefe481a
PHP
ComandPromt/JS
/listas_json/cargaProvinciasJSON.php
UTF-8
194
2.59375
3
[]
no_license
<?php include('provincias.php'); foreach($provincias as $codigo => $nombre) { $elementos_json[] = "\"$codigo\": \"$nombre\""; } echo "{".implode(",", $elementos_json)."}" ?>
true
48148065ba36fc3b9cf237231749674554078801
PHP
urpi07/ml2
/application/models/genericQuery.php
UTF-8
1,732
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php //Here we encapsulate the repetitive operations //that are the generic add, edit and delete. class genericQuery extends CI_Model{ protected $operation = '{operation}'; private $delete = 'delete'; private $edit = 'edit'; //TODO: figure out why it fails when i use $this->operation //in place of {operation} private $MESSAGES = array( 'FAILED' => array( 'title' => "Failed to {operation}", 'result' => 'FAILED', 'message' => ' ' ), 'SUCCESS' => array( 'title' => "Successful to {operation}", 'result' => 'SUCCESS', 'message' => ' ' ) ); public function __construct(){ parent::__construct(); $this->load->database(); } public function add($table, $arg){ if(isset($table) && isset($arg)){ } } public function edit($table, $arg){ if(isset($table) && isset($arg)){ } } public function deleteRecord($table, $id){ $res; $message; if(isset($table) && isset($id)){ $res = $this->db->delete($table, array("id"=>$id)); } if(!isset($res) || $res == FALSE){ $message = $this->MESSAGES['FAILED']; str_replace($this->operation, $this->delete, $message); $dbError = $this->db->_error_message(); if($dbError != ''){ $message['message'] = 'Database Error: '.$dbError; } else { $message['message'] = 'The selected record may have been already deleted.'; } } else{ $message = $this->MESSAGES['SUCCESS']; $message['message'] = "Record $id has been deleted."; } return $message; } public function get($table, $id){ $res = null; if(isset($table) && isset($id)){ $query = $this->db->get_where($table, array("id"=>$id)); $res = $query->result(); } return $res[0]; } }
true
637310c627c6081379a87014ab263189713782b4
PHP
ibidem/mjolnir-base
/Lang.php
UTF-8
2,225
3.15625
3
[ "BSD-2-Clause" ]
permissive
<?php namespace ibidem\base; /** * @package ibidem * @category Base * @author Ibidem Team * @copyright (c) 2008-2012 Ibidem Team * @license https://github.com/ibidem/ibidem/blob/master/LICENSE.md */ class Lang implements \ibidem\types\Lang { /** * @var string */ protected static $lang = 'en-us'; /** * Translate a given term. The translation may not necesarily be from one * language to another. For example, grammer use: * * Lang::tr(':num people visited London.', ... ); * // 1 => 1 person visited London. * // 2 => 2 people visited London. * // 0 => Nobody visited London. * * If a term is not defined, it will be returned as-is. * * [!!] Keys and terms are seperate entities. * * @param string term * @param array addins * @param string source language * @return string */ public static function tr($term, array $addins = null, $lang = 'en-us') { $config = \app\CFS::config('lang/'.static::$lang.'/'.$lang); if ( ! isset($config['terms'][$term])) { return $addins ? \strtr($term, $addins) : $term; } else if ($addins !== null) { // if we have addins, the term matches to a lambda return $config['terms'][$term]($addins); } else # no addins { // if there are no addins, the key maps to a string return $config['terms'][$term]; } } /** * Access a specific message identified by the key. * * The key MUST be defined. * * [!!] Keys and terms are seperate entities. * * @param string key * @param string source language * @return string */ public static function msg($key, array $addins = null, $lang = 'en-us') { $config = \app\CFS::config('lang/'.static::$lang.'/'.$lang); if ($addins !== null) { // if we have addins, the term matches to a lambda return $config['messages'][$key]($addins); } else # no addins { // if there are no addins, the key maps to a string return $config['messages'][$key]; } } /** * @param string target lang */ public static function lang($lang) { static::$lang = $lang; } /** * @return string current target language */ public static function get_lang() { return static::$lang; } } # class
true
4a78798c1aba7c60d795fea37ef4d76743d72775
PHP
JobGrouper/jobgrouperdevteam
/app/Http/Controllers/EmailsTemplatesController.php
UTF-8
2,043
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use File; class EmailsTemplatesController extends Controller { public function renderEmail($emailTemplateName, $scenario=NULL){ $originTemplatePath = '../resources/views/emails/'.$emailTemplateName.'.blade.php'; $tmpTemplatePath = '../resources/views/emails/tmp_template.blade.php'; // load json email file $raw_spec = file_get_contents('../resources/views/emails/email-spec.json'); $email_spec = json_decode($raw_spec, true); $email_scenario = NULL; //var_dump($email_spec); //var_dump($scenario); if ($scenario) { // 1st array: $common_data // 2nd array: situational_data (scenario) // $email_scenario = array_replace_recursive($email_spec[ $emailTemplateName ]['render_data'][ 'common' ], $email_spec[ $emailTemplateName ]['render_data'][ $scenario ]); //var_dump($email_scenario); return view('emails.' . $emailTemplateName, $email_scenario); } else { // If there is no scenario, but email has render data attached // if (isset($email_spec[ $emailTemplateName ])) { return view('emails.' . $emailTemplateName, $email_spec[ $emailTemplateName ]['render_data']); } // No render data has been added yet // else { //creating temporary template file with some changes to prevent Blade`s work File::copy($originTemplatePath, $tmpTemplatePath); $templateString = file_get_contents($tmpTemplatePath); $templateString = str_replace("@if", "<b>if</b>", $templateString); $templateString = str_replace("@endif", "<b>endif</b><br><br>", $templateString); $templateString = str_replace("@elseif", "<b>elseif</b><br><br>", $templateString); $templateString = str_replace("@else", "<b>else</b><br><br>", $templateString); $templateString = str_replace("{{", "<b>@{{", $templateString); $templateString = str_replace("}}", "}}</b>", $templateString); file_put_contents($tmpTemplatePath, $templateString); return view('emails.tmp_template'); } } } }
true
9cd0b6ac2fb8a00b309eafddb4d40c3c8b8a90f4
PHP
alex-kalanis/kw_storage
/php-src/Storage/Key/DefaultKey.php
UTF-8
328
2.625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace kalanis\kw_storage\Storage\Key; use kalanis\kw_storage\Interfaces\IKey; /** * Class DefaultKey * @package kalanis\kw_storage\Key * Change nothing - keys are valid as they are */ class DefaultKey implements IKey { public function fromSharedKey(string $key): string { return $key; } }
true
4c323fe55b7ae5587f4960abc2e28606bb21fd51
PHP
gregor-tokarev/micro
/app/controllers/Url.php
UTF-8
538
2.640625
3
[]
no_license
<?php class Url extends Controller { public function addUrl() { $url = trim(filter_var($_POST['url'], FILTER_SANITIZE_STRING)); $shortUrl = trim(filter_var($_POST['shortUrl'], FILTER_SANITIZE_STRING)); $urls = $this->model('urls'); echo $urls->addUrl(['url' => $url, 'shortUrl' => $shortUrl]); } public function deleteUrl() { $id = trim(filter_var($_POST['id'], FILTER_SANITIZE_STRING)); $url = $this->model('urls'); $url->deleteUrl($id); echo 'OK'; } }
true
8587ef641e50fc3a388b140c29b7708c2f1f1d0c
PHP
RaviHas/kidscorner
/app/Http/Requests/CreateChildRequest.php
UTF-8
1,164
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class CreateChildRequest extends Request { /** * 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() { return [ 'username'=>'required|min:4|unique:children,username|unique:users,email', 'grade'=>'required|numeric', 'password'=>'required|confirmed', 'password_confirmation'=>'required', 'childname'=>'required|alpha', 'childlastname'=>'required|alpha' ]; } public function messages() { return[ 'username.unique'=>'Sorry, the username is already taken. ', 'username.required'=>'Username is required. ', 'grade.numeric'=>'Please select a grade', 'password_confirmation.required'=>'Password Confirmation is required', 'childname.alpha'=>'First Name may only contain letters.', 'childlastname.alpha'=>'Last Name may only contain letters.', 'childlastname.required'=>'Last name is required.', 'childname.required'=>'First Name is required.', ]; } }
true
67cee71c4cb1051363c35616778a4b549ce14923
PHP
ARCANEDEV/LogViewer
/src/Utilities/LogStyler.php
UTF-8
2,534
2.96875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Arcanedev\LogViewer\Utilities; use Arcanedev\LogViewer\Contracts\Utilities\LogStyler as LogStylerContract; use Illuminate\Contracts\Config\Repository as ConfigContract; use Illuminate\Support\HtmlString; /** * Class LogStyler * * @author ARCANEDEV <arcanedev.maroc@gmail.com> */ class LogStyler implements LogStylerContract { /* ----------------------------------------------------------------- | Properties | ----------------------------------------------------------------- */ /** * The config repository instance. * * @var \Illuminate\Contracts\Config\Repository */ protected $config; /* ----------------------------------------------------------------- | Constructor | ----------------------------------------------------------------- */ /** * Create a new instance. * * @param \Illuminate\Contracts\Config\Repository $config */ public function __construct(ConfigContract $config) { $this->config = $config; } /* ----------------------------------------------------------------- | Getters & Setters | ----------------------------------------------------------------- */ /** * Get config. * * @param string $key * @param mixed $default * * @return mixed */ private function get($key, $default = null) { return $this->config->get("log-viewer.$key", $default); } /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * Make level icon. * * @param string $level * @param string|null $default * * @return \Illuminate\Support\HtmlString */ public function icon($level, $default = null) { return new HtmlString( '<i class="'.$this->get("icons.$level", $default).'"></i>' ); } /** * Get level color. * * @param string $level * @param string|null $default * * @return string */ public function color($level, $default = null) { return $this->get("colors.levels.$level", $default); } /** * Get strings to highlight. * * @param array $default * * @return array */ public function toHighlight(array $default = []) { return $this->get('highlight', $default); } }
true
a41ce5579c7735bbc6015a8a7bcec175339e075d
PHP
Delermando/systemAgendaV3
/apiAgenda/test/response/ResponseTest.php
UTF-8
1,269
2.546875
3
[]
no_license
<?php class ResponseTest extends PHPUnit_Framework_TestCase { protected $instancia; protected function setUp() { $this->instancia = New \Cartao\services\response\Response(); } /** * @group testMakeResponse */ public function testMakeResponse() { $this->assertInstanceOf('\Cartao\services\response\Response', $this->instancia); } /** * @group testJson * @dataProvider dataForJson */ public function testJson($expected, $data) { $this->instancia->data = $data['data']; $this->instancia->message = $data['message']; $this->assertJsonStringEqualsJsonString( json_encode($expected), $this->instancia->json()); } public function dataForJson() { return array( array(array("response" => "success", "message"=>"no error", "data"=> array('teste')), array("data" => array('teste'), 'message' => '')), array(array("response" => "failed", "message"=>"error", "data"=> ''), array("data" => '', 'message' => 'error')), ); } }
true
dc87a72ebe17be78e3d9d3af525ff9bd66ac0120
PHP
luqmankahloon/MoDeCaSo
/server/model/projects/cards.class.php
UTF-8
7,050
2.8125
3
[]
no_license
<?php /* * MoDeCaSo - A Web Application for Modified Delphi Card Sorting Experiments * Copyright (C) 2014-2015 Peter Folta. All rights reserved. * * Project: MoDeCaSo * Version: 1.0.0 * * File: /server/model/projects/cards.class.php * Created: 2014-12-10 * Author: Peter Folta <mail@peterfolta.net> */ namespace model; use Exception; use main\database; class cards { private $database; public function __construct() { $this->database = database::get_instance(); } public function add_card($project_key, $text, $tooltip) { /* * Get project ID */ $project_id = projects::get_project_id($project_key); /* * Insert new card into database */ $this->database->insert("project_cards", array( 'project' => $project_id, 'text' => $text, 'tooltip' => $tooltip, 'created' => $GLOBALS['timestamp'], 'last_modified' => 0 )); /* * Update project last modified timestamp */ projects::update_last_modified($project_key); /* * Compute project status */ projects::compute_project_status($project_key); $result = array( 'error' => false, 'msg' => "card_created" ); return $result; } public function delete_card($project_key, $card_id) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); /* * Check if card exists */ $this->database->select("project_cards", null, "`id` = '".$card_id."' AND `project` = '".$project_id."'"); if ($this->database->row_count() == 1) { /* * Delete card */ $this->database->delete("project_cards", "`id` = '".$card_id."'"); /* * Update project last modified timestamp */ projects::update_last_modified($project_key); /* * Compute project status */ projects::compute_project_status($project_key); $result = array( 'error' => false, 'msg' => "card_deleted" ); } else { throw new Exception("Invalid Card"); } return $result; } public function delete_all_cards($project_key) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); /* * Delete all cards linked to this project from database */ $this->database->delete("project_cards", "`project` = '".$project_id."'"); /* * Update project last modified timestamp */ projects::update_last_modified($project_key); /* * Compute project status */ projects::compute_project_status($project_key); $result = array( 'error' => false, 'msg' => "all_cards_deleted" ); return $result; } public function edit_card($project_key, $card_id, $text, $tooltip) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); /* * Check if card exists */ $this->database->select("project_cards", null, "`id` = '".$card_id."' AND `project` = '".$project_id."'"); if ($this->database->row_count() == 1) { $data = array( 'text' => $text, 'tooltip' => $tooltip, 'last_modified' => $GLOBALS['timestamp'] ); /* * Update card in database */ $this->database->update("project_cards", "`id` = '".$card_id."'", $data); /* * Update project last modified timestamp */ projects::update_last_modified($project_key); $result = array( 'error' => false, 'msg' => "card_edited" ); } else { throw new Exception("Invalid Card"); } return $result; } public function get_card($project_key, $card_id) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); $this->database->select("project_cards", null, "`id` = '".$card_id."' AND `project` = '".$project_id."'"); if ($this->database->row_count() == 1) { $card = $this->database->result()[0]; $result = array( 'error' => false, 'card' => $card ); } else { throw new Exception("Invalid Card"); } return $result; } public function export_cards($project_key) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); $this->database->select("project_cards", null, "`project` = '".$project_id."'"); $cards = $this->database->result(); $export_data = ""; foreach ($cards as $card) { $export_data .= $card['text']; if (!empty($card['tooltip'])) { $export_data .= "|".$card['tooltip']; } $export_data .= "\n"; } $export_data = trim($export_data); return $export_data; } public function import_cards($project_key, $import_file) { /* * Get Project ID */ $project_id = projects::get_project_id($project_key); if ($import_file['type'] != "text/plain") { throw new Exception("'".$import_file['name']."' is not a plain text file"); } $file_handle = fopen($import_file['tmp_name'], "rb"); while (($line = fgets($file_handle)) !== false) { $card = explode("|", $line); $text = trim($card[0]); $tooltip = ""; if (isset($card[1])) { $tooltip = trim($card[1]); } if (!empty($text)) { $this->database->insert("project_cards", array( 'project' => $project_id, 'text' => $text, 'tooltip' => $tooltip, 'created' => $GLOBALS['timestamp'], 'last_modified' => 0 )); } } /* * Update project last modified timestamp */ projects::update_last_modified($project_key); /* * Compute project status */ projects::compute_project_status($project_key); return array( 'error' => false, 'msg' => "cards_imported" ); } }
true
e49627693eacccc338e6b89fd812b9eca4d6fa39
PHP
PCouaillier/loterie
/src/Service/TransactionService.php
UTF-8
899
2.609375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: paulcouaillier * Date: 30/11/2017 * Time: 12:20 */ namespace App\Service; use App\Entity\RoomEntity; use App\Entity\UserEntity; use JJWare\Util\Optional; use Monolog\Logger; use PDO; class TransactionService { private $db; private $log; public function __construct(PDO $db, Logger $log) { $this->db = $db; $this->log = $log; } public function getBalance(RoomEntity $room, UserEntity $user): Optional { $st = $this->db->prepare('SELECT SUM(points) as "balance" FROM `UserRollInRoom` WHERE `room`=:room AND `user`=:user;'); $st->bindParam(':room', $room->id, PDO::PARAM_INT); $st->bindParam(':user', $user->id, PDO::PARAM_INT); $st->execute(); $balance = $st->fetch(); return $balance ? Optional::of(intval($balance['balance'])) : Optional::empty(); } }
true
9b77f15055521d8698cf3bc0c0874cf97bc43e47
PHP
Marwelln/basset
/src/Basset/SortingIterator.php
UTF-8
436
2.953125
3
[ "MIT" ]
permissive
<?php // https://github.com/salathe/spl-examples/wiki/Sorting-Iterators namespace Basset; use ArrayIterator; class SortingIterator extends ArrayIterator { public function __construct($iterator, $callback) { if ( ! is_callable($callback)) { throw new InvalidArgumentException(sprintf('Callback must be callable (%s given).', $callback)); } parent::__construct(iterator_to_array($iterator)); $this->uasort($callback); } }
true
a1e71a6475bb20dfe1f1ab5becc6b7ea7fca6c37
PHP
Fincallorca/HitchHikerApi
/src/Wsdl/v3_1_388_1/StructType/SSRRequestData.php
UTF-8
5,248
2.8125
3
[ "MIT" ]
permissive
<?php namespace Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\StructType; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for SSRRequestData StructType * Meta informations extracted from the WSDL * - nillable: true * - type: tns:SSRRequestData * @subpackage Structs */ class SSRRequestData extends AbstractStructBase { /** * The Code * Meta informations extracted from the WSDL * - nillable: true * @var string */ public $Code; /** * The FreeText * Meta informations extracted from the WSDL * - minOccurs: 0 * - nillable: true * @var string */ public $FreeText; /** * The Segments * Meta informations extracted from the WSDL * - minOccurs: 0 * - nillable: true * @var \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint */ public $Segments; /** * Constructor method for SSRRequestData * @uses SSRRequestData::setCode() * @uses SSRRequestData::setFreeText() * @uses SSRRequestData::setSegments() * @param string $code * @param string $freeText * @param \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint $segments */ public function __construct($code = null, $freeText = null, \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint $segments = null) { $this ->setCode($code) ->setFreeText($freeText) ->setSegments($segments); } /** * Get Code value * @return string|null */ public function getCode() { return $this->Code; } /** * Set Code value * @param string $code * @return \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\StructType\SSRRequestData */ public function setCode($code = null) { // validation for constraint: string if (!is_null($code) && !is_string($code)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($code)), __LINE__); } $this->Code = $code; return $this; } /** * Get FreeText value * An additional test has been added (isset) before returning the property value as * this property may have been unset before, due to the fact that this property is * removable from the request (nillable=true+minOccurs=0) * @return string|null */ public function getFreeText() { return isset($this->FreeText) ? $this->FreeText : null; } /** * Set FreeText value * This property is removable from request (nillable=true+minOccurs=0), therefore * if the value assigned to this property is null, it is removed from this object * @param string $freeText * @return \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\StructType\SSRRequestData */ public function setFreeText($freeText = null) { // validation for constraint: string if (!is_null($freeText) && !is_string($freeText)) { throw new \InvalidArgumentException(sprintf('Invalid value, please provide a string, "%s" given', gettype($freeText)), __LINE__); } if (is_null($freeText) || (is_array($freeText) && empty($freeText))) { unset($this->FreeText); } else { $this->FreeText = $freeText; } return $this; } /** * Get Segments value * An additional test has been added (isset) before returning the property value as * this property may have been unset before, due to the fact that this property is * removable from the request (nillable=true+minOccurs=0) * @return \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint|null */ public function getSegments() { return isset($this->Segments) ? $this->Segments : null; } /** * Set Segments value * This property is removable from request (nillable=true+minOccurs=0), therefore * if the value assigned to this property is null, it is removed from this object * @param \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint $segments * @return \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\StructType\SSRRequestData */ public function setSegments(\Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\ArrayType\ArrayOfint $segments = null) { if (is_null($segments) || (is_array($segments) && empty($segments))) { unset($this->Segments); } else { $this->Segments = $segments; } return $this; } /** * Method called when an object has been exported with var_export() functions * It allows to return an object instantiated with the values * @see AbstractStructBase::__set_state() * @uses AbstractStructBase::__set_state() * @param array $array the exported values * @return \Fincallorca\HitchHikerApi\Wsdl\v3_1_388_1\StructType\SSRRequestData */ public static function __set_state(array $array) { return parent::__set_state($array); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
true
f880f842796227aa80a3946dc9aac760f769fc03
PHP
Sionist/ALC-MAT
/app/models/Estados.php
UTF-8
1,949
2.859375
3
[]
no_license
<?php class Estados extends \Phalcon\Mvc\Model { /** * * @var integer */ protected $id_estado; /** * * @var string */ protected $estado; /** * Method to set the value of field id_estado * * @param integer $id_estado * @return $this */ public function setIdEstado($id_estado) { $this->id_estado = $id_estado; return $this; } /** * Method to set the value of field estado * * @param string $estado * @return $this */ public function setEstado($estado) { $this->estado = $estado; return $this; } /** * Returns the value of field id_estado * * @return integer */ public function getIdEstado() { return $this->id_estado; } /** * Returns the value of field estado * * @return string */ public function getEstado() { return $this->estado; } /** * Initialize method for model. */ public function initialize() { $this->hasMany('id_estado', 'Ciudades', 'id_estado', array('alias' => 'Ciudades')); $this->hasMany('id_estado', 'Ciudades', 'id_estado', NULL); } /** * Returns table name mapped in the model. * * @return string */ public function getSource() { return 'estados'; } /** * Allows to query a set of records that match the specified conditions * * @param mixed $parameters * @return Estados[] */ public static function find($parameters = null) { return parent::find($parameters); } /** * Allows to query the first record that match the specified conditions * * @param mixed $parameters * @return Estados */ public static function findFirst($parameters = null) { return parent::findFirst($parameters); } }
true
57eec363bd05d1d0c2ef4b31b3195773f9c5d2ba
PHP
RafsDuarte/SistemaDeVendas
/app/Http/Controllers/Admin/NumberController.php
UTF-8
2,777
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Admin; use App\Models\Number; use App\Http\Controllers\Controller; use Illuminate\Http\Request; class NumberController extends Controller { public function __construct(Number $number) { $this->number = $number; } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function registros() { $numbers = $this->number->paginate(10); return view('admin.numbers.registros', compact('numbers')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('admin.numbers.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function numero(Request $request) { $data = $request->all(); $number = $this->number::create($data); flash('Número Criado com Sucesso!')->success(); return redirect()->route('admin.vendas.registros_numeros'); } /** * Display the specified resource. * * @param \App\Models\Number $number * @return \Illuminate\Http\Response */ public function show(Number $number) { // } /** * Show the form for editing the specified resource. * * @param \App\Models\Number $number * @return \Illuminate\Http\Response */ public function edit($number) { $number = $this->number->find($number); return view('admin.numbers.edit', compact('number')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \App\Models\Number $number * @return \Illuminate\Http\Response */ public function update(Request $request, $number) { $data = $request->all(); $number = $this->number->find($number); $number->update($data); if($number->getChanges()) { flash('Número Atualizado com Sucesso!')->success(); return redirect()->route('admin.vendas.registros_numeros'); } else { return back(); } } /** * Remove the specified resource from storage. * * @param \App\Models\Number $number * @return \Illuminate\Http\Response */ public function destroy($number) { $number = $this->number->find($number); $number->delete(); flash('Número Removido com Sucesso!')->success(); return redirect()->route('admin.vendas.registros_numeros'); } }
true
6218338facfb0ed6b7d09684a499f13beb7cc547
PHP
mdeville/Piscine_PHP_rush00
/backend/user.php
UTF-8
1,728
2.6875
3
[]
no_license
<?php include(__DIR__ . "/general.php"); function add_user($login, $passwd, $group) { if (!$login || !$passwd || !$group) return FALSE; if (($data = file_to_data(__DIR__ . PASSWD)) === FALSE || isset($data[$login])) return FALSE; $data[$login] = array(); $data[$login]['passwd'] = hash("whirlpool", $passwd); $data[$login]['group'] = $group; if (data_to_file($data, __DIR__ . PASSWD) === FALSE) return FALSE; return TRUE; } function auth($login, $passwd) { if ($login == "" || $passwd == "") return FALSE; if (($data = file_to_data(__DIR__ . PASSWD)) === FALSE) return FALSE; $passwd = hash("whirlpool", $passwd); if ($data[$login]['passwd'] === $passwd) return TRUE; else return FALSE; } function remove_user($login) { if ($login == "") return FALSE; if (($data = file_to_data(__DIR__ . PASSWD)) === FALSE) return FALSE; unset($data[$login]); if (data_to_file($data, __DIR__ . PASSWD) === FALSE) return FALSE; return TRUE; } function modif_pwd($login, $oldpwd, $newpwd) { if ($login == "" || $oldpwd == "" || $newpwd == "") return FALSE; if (($data = file_to_data(__DIR__ . PASSWD)) === FALSE || !isset($data[$login]) || !isset($data[$login]['passwd'])) return FALSE; $oldpwd = hash("whirlpool", $oldpwd); if ($data[$login]['passwd'] !== $oldpwd) return FALSE; $data[$login]['passwd'] = hash("whirlpool", $newpwd); if (data_to_file($data, __DIR__ . PASSWD) === FALSE) return FALSE; return TRUE; } function get_user_group($login) { if (!$login || $login == "") { return (null); } if (($data = file_to_data(__DIR__ . PASSWD)) === FALSE) return FALSE; if (isset($data[$login])) return $data[$login]['group']; return FALSE; } ?>
true
7904eec9d21de91afc16caacc4a5260941087b9f
PHP
MartimTSilva/Techpower-web
/frontend/tests/functional/SignupCest.php
UTF-8
3,489
2.578125
3
[]
no_license
<?php namespace frontend\tests\functional; use frontend\tests\FunctionalTester; class SignupCest { protected $formId = '#form-signup'; public function _before(FunctionalTester $I) { $I->amOnRoute('site/signup'); } public function signupWithEmptyFields(FunctionalTester $I) { $I->see('Registar nova conta', 'h1'); $I->see('Por favor preencha os seguintes campos:'); $I->submitForm($this->formId, []); $I->seeValidationError('Introduza um nome de utilizador.'); $I->seeValidationError('Introduza um e-mail.'); $I->seeValidationError('Introduza uma password.'); $I->seeValidationError('Introduza um nome.'); $I->seeValidationError('Introduza um apelido.'); $I->seeValidationError('Introduza um número de telefone.'); $I->seeValidationError('Introduza uma morada.'); $I->seeValidationError('Introduza um NIF.'); $I->seeValidationError('Introduza um código de postal.'); $I->seeValidationError('Introduza uma cidade.'); $I->seeValidationError('Introduza um país.'); } public function signupWithWrongEmail(FunctionalTester $I) { $I->submitForm( $this->formId, [ 'SignupForm[username]' => 'tester', 'SignupForm[email]' => 'ttttt', 'SignupForm[password]' => 'tester_password', 'SignupForm[firstName]' => 'tester', 'SignupForm[lastName]' => 'ttttt', 'SignupForm[phone]' => '999999999', 'SignupForm[address]' => 'tester', 'SignupForm[postal_code]' => '1234-123', 'SignupForm[city]' => 'test', 'SignupForm[country]' => 'tester', 'SignupForm[nif]' => '555555555', ] ); $I->dontSee('Introduza um nome de utilizador.'); $I->dontSee('Introduza uma password.'); $I->dontSee('Introduza um nome.'); $I->dontSee('Introduza um apelido.'); $I->dontSee('Introduza um número de telefone.'); $I->dontSee('Introduza uma morada.'); $I->dontSee('Introduza um código de postal.'); $I->dontSee('Introduza uma cidade.'); $I->dontSee('Introduza um país.'); $I->dontSee('Introduza um NIF.'); $I->see('Introduza um e-mail válido.', '.help-block'); } public function signupSuccessfully(FunctionalTester $I) { $I->submitForm($this->formId, [ 'SignupForm[username]' => 'tester', 'SignupForm[email]' => 'tester.email@example.com', 'SignupForm[password]' => 'tester_password', 'SignupForm[firstName]' => 'Unit', 'SignupForm[lastName]' => 'Test', 'SignupForm[phone]' => '000000000', 'SignupForm[address]' => 'Unit test address', 'SignupForm[postal_code]' => '1234-123', 'SignupForm[city]' => 'Unit City', 'SignupForm[country]' => 'Unit Country', 'SignupForm[nif]' => '123456789', ]); $I->seeRecord('common\models\User', [ 'username' => 'tester', 'email' => 'tester.email@example.com', 'status' => \common\models\User::STATUS_ACTIVE ]); $profile = $I->grabRecord('common\models\Profile', [ 'firstName' => 'Unit', 'city' => 'Unit City', 'nif' => '123456789' ]); $I->see('Registo efetuado com sucesso.'); $profile->delete(); } }
true
065afa14be93bf796acc33780ed40d1c37da7778
PHP
OlivierValette/booklib
/src/Controller/CategoryController.php
UTF-8
1,401
2.625
3
[]
no_license
<?php namespace App\Controller; use App\Entity\Category; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * Class CategoryController * @package App\Controller * @Route("/category") */ class CategoryController extends BaseController { /** * @Route("/", name="category_list", methods="GET") */ public function index(Request $request): Response { // request with array output for json API // (to avoid serialization problems) $categories = $this->getDoctrine() ->getRepository(Category::class) ->createQueryBuilder('c') ->getQuery() ->getArrayResult(); if ($request->isXmlHttpRequest()) { return $this->json($categories); } return new Response('html'); } /** * @Route("/show/{id}", name="category_show") */ public function show(Category $category) { return $this->render('category/show.html.twig', [ 'category' => $category, ]); } public function dropDown() { $categories = $this->getDoctrine()->getRepository(Category::class) ->findBy([], ['name' => 'ASC']); return $this->render('category/dropdown.html.twig', ['categories' => $categories]); } }
true
6f830cbfd555ed7cbca8c7f8163261bd4e767a86
PHP
xiebruce/PicUploader
/vendor/cloudinary/cloudinary_php/src/AuthToken.php
UTF-8
3,140
2.828125
3
[ "MIT" ]
permissive
<?php namespace Cloudinary; /** * Class AuthToken * @package Cloudinary */ class AuthToken { const UNSAFE = '/([ "#%&\'\/:;<=>?@\[\]^`{\|}~\\\\])/'; /** * Generate an authorization token. * Options: * string key - the secret key required to sign the token * string ip - the IP address of the client * number start_time - the start time of the token in seconds from epoch * string expiration - the expiration time of the token in seconds from epoch * string duration - the duration of the token (from start_time) * string acl - the ACL for the token * string url - the URL to authentication in case of a URL token * * @param array $options token configuration * * @return string the authorization token * @throws Error if both expiration and duration were not provided */ public static function generate($options = array()) { $key = \Cloudinary::option_get($options, "key"); if (!isset($key)) { throw new \Cloudinary\Error("Missing authentication token key configuration"); } $name = \Cloudinary::option_get($options, "token_name", "__cld_token__"); $start = \Cloudinary::option_get($options, "start_time"); $expiration = \Cloudinary::option_get($options, "expiration"); $ip = \Cloudinary::option_get($options, "ip"); $acl = \Cloudinary::option_get($options, "acl"); $url = \Cloudinary::option_get($options, "url"); $duration = \Cloudinary::option_get($options, "duration"); if (!strcasecmp($start, "now")) { $start = time(); } elseif (is_numeric($start)) { $start = 0 + $start; } if (!isset($expiration)) { if (isset($duration)) { $expiration = (isset($start) ? $start : time()) + $duration; } else { throw new \Cloudinary\Error("Must provide 'expiration' or 'duration'."); } } $token = array(); if (isset($ip)) { array_push($token, "ip=$ip"); } if (isset($start)) { array_push($token, "st=$start"); } array_push($token, "exp=$expiration"); if (isset($acl)) { array_push($token, "acl=" . self::escape_to_lower($acl)); } $to_sign = $token; if (isset($url) && !isset($acl)) { array_push($to_sign, "url=" . self::escape_to_lower($url)); } $auth = self::digest(join("~", $to_sign), $key); array_push($token, "hmac=$auth"); return "$name=" . join("~", $token); } private static function digest($message, $key = null) { if (!isset($key)) { $key = \Cloudinary::config_get("akamai_key"); } $bin_key = pack("H*", $key); return hash_hmac("sha256", $message, $bin_key); } private static function escape_to_lower($url) { return preg_replace_callback(self::UNSAFE, function ($match) { return '%'.bin2hex($match[0]); }, $url); } }
true
20b015ed30d826fc1d8b750894e6579cadc587ae
PHP
luisrita/matteo
/includes/images.php
UTF-8
3,653
2.640625
3
[]
no_license
<?php /********************************************************** **Remove images size /**********************************************************/ //stop generating images with the medium and large sizes //more info: https://developer.wordpress.org/reference/hooks/intermediate_image_sizes_advanced/ function filter_image_sizes( $sizes) { unset( $sizes['medium']); unset( $sizes['large']); return $sizes; } add_filter('intermediate_image_sizes_advanced', 'filter_image_sizes'); /********************************************************** ** Add images size /**********************************************************/ function my_image_sizes_setup() { add_image_size( 'gallery-thumb', 193, 193, true ); add_image_size( 'square-block', 372, 372, true ); add_image_size( 'stores', 241, 502, true ); add_image_size( 'product', 636, 851, true ); add_image_size( 'product-cover', 505, 505, true ); } add_action( 'after_setup_theme', 'my_image_sizes_setup' ); function my_image_sizes($sizes) { $addsizes = array( "gallery-thumb" => __( "Gallery Thumb") ); $newsizes = array_merge($sizes, $addsizes); return $newsizes; } add_filter('image_size_names_choose', 'my_image_sizes'); /********************************************************** ** Add SVG support /**********************************************************/ class svg_support { public function __construct() { $this->_add_filters(); } private function _add_filters() { add_filter( 'upload_mimes', array( &$this, 'allow_svg_uploads' ) ); } public function allow_svg_uploads( $existing_mime_types = array() ) { return $this->_add_svg_mime_type( $existing_mime_types ); } private function _add_svg_mime_type( $mime_types ) { $mime_types[ 'svg' ] = 'image/svg+xml'; return $mime_types; } } function svg_support_run() { if (class_exists('svg_support')) { new svg_support(); } } add_action('after_setup_theme', 'svg_support_run'); /********************************************************** ** Change WP Standart Gallery /**********************************************************/ function customFormatGallery($string,$attr){ $posts = get_posts(array('include' => $attr['ids'],'post_type' => 'attachment')); $limit = 5; $count = count($posts); $k = 0; $output = '<div class="gallery" data-control="GALLERY">'; foreach($posts as $imagePost){ $k++; if ( $k == $limit ){ if ( $count > $limit): $output .= '<a href="#" class="gallery-item" data-id="'.$imagePost->ID.'">'; $output .= '<img class="gbox" src="'.wp_get_attachment_image_src($imagePost->ID, 'full')[0].'">'; $output .= '<span class="gradient"></span>'; $output .= '<span class="count">+'.( $count - $limit ).'</span>'; $output .= '</a>'; else: $output .= '<a href="#" class="gallery-item" data-id="'.$imagePost->ID.'">'; $output .= '<img class="gbox" src="'.wp_get_attachment_image_src($imagePost->ID, 'full')[0].'"></a>'; $output .= '</a>'; endif; } else if ( $k < $limit ){ $output .= '<a href="#" class="gallery-item" data-id="'.$imagePost->ID.'">'; $output .= '<img class="gbox" src="'.wp_get_attachment_image_src($imagePost->ID, 'full')[0].'"></a>'; $output .= '</a>'; } else { $output .= '<a href="#" class="gallery-item hidden" data-id="'.$imagePost->ID.'">'; $output .= '<img class="gbox" src="'.wp_get_attachment_image_src($imagePost->ID, 'full')[0].'"></a>'; $output .= '</a>'; } } $output .= "</div>"; return $output; } add_filter('post_gallery','customFormatGallery',10,2); ?>
true
f3858442bc1cb0e5e745038b3120ee4ebaf0774f
PHP
elzup/kitasenju_station_view
/helper/functions.php
UTF-8
3,467
2.875
3
[]
no_license
<?php function generate_location_lib($railways) { $lib = array(); foreach($railways as $rail) { foreach ($rail->stations as $st) { $lib[$st->url] = $st->location; } } return $lib; } function install_train(&$trains, $lib_location, $lib_timetables, $lib_color) { foreach ($trains as $key => &$train) { $train->install($lib_location, $lib_timetables, $lib_color); } } // 何割終わっているか function time_progress_raito($time_start, $time_end, $time) { list($hs, $is) = explode(':', $time_start); list($he, $ie) = explode(':', $time_end); list($ht, $it) = explode(':', $time); $start = $hs * 60 + $is; $end = $he * 60 + $ie; $p = $ht * 60 + $it; $diff = $end - $start; $pdiff = $p - $start; return $diff == 0 ? '0' : $pdiff / $diff; } function calc_location($location_start, $location_end, $raito) { $loc = new stdclass(); $loc->lat = $location_end->lat * $raito + (1 - $raito) * $location_start->lat; $loc->lon = $location_end->lon * $raito + (1 - $raito) * $location_start->lon; return $loc; } function float_time4($time) { if ($time < '03:00') { list($h, $i) = explode(':', $time); $h += 24; $time = implode(':', array($h, $i)); } return $time; } function check_weekday($timestamp = NULL) { if (!isset($timestamp)) { $timestamp = time(); } $ymd = split_ymd($timestamp); if (is_holiday($ymd[0], $ymd[1], $ymd[2])) { return TIMETABLE_HOLIDAYS; } elseif (is_saturday()) { return TIMETABLE_SATURDAYS; } return TIMETABLE_WEEKDAYS; } function split_ymd($timestamp = NULL) { if (!isset($timestamp)) { $timestamp = time(); } return explode(':', date('Y:m:d', $timestamp)); } function is_holiday($year, $month, $day) { if ( date("w", mktime(0,0,0, $month ,$day ,$year )) == 0 ) { return TRUE; } $known_hol = array("1/1", "4/29", "5/3", "5/4", "5/5", "11/3", "11/23", "12/23"); if ( $year > 1999 ) { $y = $year - 2000; $spring_equinox = (int)(20.69115 + 0.2421904 * $y - (int)($y/4 + $y/100 + $y/400) ); $autumnal_equinox = (int)(23.09000 + 0.2421904 * $y - (int)($y/4 + $y/100 + $y/400) ); array_push( $known_hol, "3/".$spring_equinox ); array_push( $known_hol, "9/".$autumnal_equinox ); } if( array_search( $month."/".$day , $known_hol ) !== FALSE ) return TRUE; $pre_day = $day - 1; if( $pre_day < 1 ) return FALSE; if( date("w", mktime(0,0,0, $month ,$pre_day ,$year ) ) == 0 ) { if( array_search( $month."/".$pre_day , $known_hol ) !== FALSE ) return TRUE; } for( $tom = 1; $tom < 8; $tom++ ) { if( date("w", mktime(0,0,0, $month ,$tom ,$year )) == 1 ) break; } if( ($month == 10) || ($month == 1) ) { if( $day == ($tom+7) ) return TRUE; } if( ($month == 7) || ($month == 9) ) { if( $day == ($tom+14) ) return TRUE; } return FALSE; } function is_sunday($timestamp = NULL) { $ymd = split_ymd($timestamp); return date("w", mktime(0,0,0, $ymd[1] ,$ymd[2], $ymd[0])) == 0; } function is_saturday($timestamp = NULL) { $ymd = split_ymd($timestamp); return date("w", mktime(0,0,0, $ymd[1] ,$ymd[2], $ymd[0])) == 6; } function get_colon_value($text) { $arr = explode(':', $text); return $arr[1]; }
true
52c5ec5949d7af6ff4ed4071898d632c03db1f9d
PHP
czim/laravel-repository
/tests/BaseRepositoryTest.php
UTF-8
14,900
2.609375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Czim\Repository\Test; use Czim\Repository\Contracts\BaseRepositoryInterface; use Czim\Repository\Test\Helpers\TestSimpleModel; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Support\Collection; class BaseRepositoryTest extends TestCase { protected const TABLE_NAME = 'test_simple_models'; protected const UNIQUE_FIELD = 'unique_field'; protected const SECOND_FIELD = 'second_field'; protected ?BaseRepositoryInterface $repository = null; public function setUp(): void { parent::setUp(); $this->repository = $this->app->make(Helpers\TestBaseRepository::class); } protected function seedDatabase(): void { TestSimpleModel::create([ 'unique_field' => '999', 'second_field' => null, 'name' => 'unchanged', 'active' => true, ]); TestSimpleModel::create([ 'unique_field' => '1234567', 'second_field' => '434', 'name' => 'random name', 'active' => false, ]); TestSimpleModel::create([ 'unique_field' => '1337', 'second_field' => '12345', 'name' => 'special name', 'active' => true, ]); } // -------------------------------------------- // Retrieval // -------------------------------------------- /** * @test */ public function it_handles_basic_retrieval_operations(): void { // all $result = $this->repository->all(); static::assertInstanceOf(Collection::class, $result, 'Did not get Collection for all()'); static::assertCount(3, $result, 'Did not get correct count for all()'); // get an id that we can use find on $someId = $result->first()->id; static::assertNotEmpty($someId, "Did not get a valid Model's id from the all() result"); // find static::assertInstanceOf(Model::class, $this->repository->find($someId), 'Did not get Model for find()'); // count static::assertEquals(3, $this->repository->count(), 'Did not get correct result for count()'); // first static::assertInstanceOf(Model::class, $this->repository->first(), 'Did not get Model for first() on all'); // findBy static::assertInstanceOf( Model::class, $this->repository->findBy(self::UNIQUE_FIELD, '1337'), 'Did not get Model for findBy() for unique field value' ); // findAllBy static::assertCount( 2, $this->repository->findAllBy('active', true), 'Did not get correct count for result for findAllBy(active = true)' ); // paginate static::assertCount(2, $this->repository->paginate(2), 'Did not get correct count for paginate()'); // pluck $list = $this->repository->pluck(self::UNIQUE_FIELD); static::assertCount(3, $list, 'Did not get correct array count for lists()'); static::assertContains('1337', $list, 'Did not get correct array content for lists()'); } /** * @test */ public function it_creates_a_new_instance_and_fills_attributes_with_data(): void { $attributes = [ self::UNIQUE_FIELD => 'unique_field_value', self::SECOND_FIELD => 'second_field_value', ]; $model = $this->repository->make($attributes); // Asserting that only the desired attributes got filled and are the same. static::assertEquals($attributes, $model->getDirty()); // Asserting the the model had its attributes filled without being persisted. static::assertEquals(0, $this->repository->findWhere($attributes)->count()); } /** * @test */ public function it_throws_an_exception_when_findorfail_does_not_find_anything(): void { $this->expectException(ModelNotFoundException::class); $this->repository->findOrFail(895476); } /** * @test */ public function it_throws_an_exception_when_firstorfail_does_not_find_anything(): void { $this->expectException(ModelNotFoundException::class); // Make sure we won't find anything. $mockCriteria = $this->makeMockCriteria( 'once', fn ($query) => $query->where('name', 'some name that certainly does not exist') ); $this->repository->pushCriteria($mockCriteria); $this->repository->firstOrFail(); } /** * Bosnadev's findWhere() method. * * @test */ public function it_can_perform_a_findwhere_with_custom_parameters(): void { // Simple field/value combo's by key static::assertCount( 1, $this->repository->findWhere([ self::UNIQUE_FIELD => '1234567', self::SECOND_FIELD => '434', ]), 'findWhere() with field/value combo failed (incorrect match count)' ); // Arrays with field/value sets static::assertCount( 1, $this->repository->findWhere([ [self::UNIQUE_FIELD, '1234567'], [self::SECOND_FIELD, '434'], ]), 'findWhere() with field/value sets failed (incorrect match count)' ); // Arrays with field/operator/value sets static::assertCount( 1, $this->repository->findWhere([ [self::UNIQUE_FIELD, 'LIKE', '%234567'], [self::SECOND_FIELD, 'LIKE', '43%'], ]), 'findWhere() with field/operator/value sets failed (incorrect match count)' ); // Closure send directly to the model's where() method static::assertCount( 1, $this->repository->findWhere([ function ($query) { return $query->where(self::UNIQUE_FIELD, 'LIKE', '%234567'); }, ]), 'findWhere() with Closure callback failed (incorrect match count)' ); } /** * @test */ public function it_can_perform_find_and_all_lookups_with_a_callback_for_custom_queries(): void { // allCallback $result = $this->repository->allCallback(function ($query) { return $query->where(self::UNIQUE_FIELD, '1337'); }); static::assertCount(1, $result, 'Wrong count for allCallback()'); // findCallback $result = $this->repository->findCallback(function ($query) { return $query->where(self::UNIQUE_FIELD, '1337'); }); static::assertEquals('1337', $result->{self::UNIQUE_FIELD}, 'Wrong result for findCallback()'); } /** * @test */ public function it_throw_an_exception_if_the_callback_for_custom_queries_is_incorrect(): void { $this->expectException(\InvalidArgumentException::class); $this->repository->allCallback(function () { return 'incorrect return value'; }); } // -------------------------------------------- // Manipulation // -------------------------------------------- /** * @test * @depends it_handles_basic_retrieval_operations */ public function it_handles_basic_manipulation_operations(): void { // Update existing $someId = $this->repository->findBy(self::UNIQUE_FIELD, '999')->id; static::assertNotEmpty($someId, "Did not get a valid Model's id from the findBy(unique_field) result"); $this->repository->update(['name' => 'changed it!'], $someId); static::assertEquals( 'changed it!', $this->repository->findBy(self::UNIQUE_FIELD, '999')->name, 'Change did not apply after update()' ); // Create new $model = $this->repository->create([ self::UNIQUE_FIELD => '313', 'name' => 'New Model', ]); static::assertInstanceOf(Model::class, $model, 'Create() response is not a Model'); static::assertNotEmpty($model->id, 'Model does not have an id (likely story)'); static::assertDatabaseHas(static::TABLE_NAME, ['id' => $model->id, self::UNIQUE_FIELD => '313', 'name' => 'New Model', ]); static::assertEquals(4, $this->repository->count(), 'Total count after creating new does not match'); // Delete static::assertEquals(1, $this->repository->delete($model->id), 'Delete() call did not return succesful count'); static::assertEquals(3, $this->repository->count(), 'Total count after deleting does not match'); static::assertDatabaseMissing(static::TABLE_NAME, ['id' => $model->id]); unset($model); } /** * @test */ public function it_fills_a_retrieved_model_attributes_without_persisting_it(): void { $persistedModel = $this->repository->all()->first(); $attributes = [ self::UNIQUE_FIELD => 'unique_field_value', self::SECOND_FIELD => 'second_field_value', ]; $filledModel = $this->repository->fill($attributes, $persistedModel->id); static::assertEquals($filledModel->getDirty(), $attributes); static::assertDatabaseMissing(static::TABLE_NAME, $attributes); } // -------------------------------------------- // Criteria // -------------------------------------------- /** * @test */ public function it_returns_and_can_restore_default_criteria(): void { static::assertTrue($this->repository->defaultCriteria()->isEmpty(), 'Defaultcriteria is not empty'); $this->repository->pushCriteria($this->makeMockCriteria('never')); static::assertCount( 1, $this->repository->getCriteria(), 'getCriteria() count incorrect after pushing new Criteria' ); $this->repository->restoreDefaultCriteria(); static::assertTrue( $this->repository->getCriteria()->isEmpty(), 'getCriteria() not empty after restoring default Criteria()' ); } /** * @test * @depends it_handles_basic_retrieval_operations */ public function it_takes_criteria_and_handles_basic_criteria_manipulation(): void { // Clear all criteria, see if none are applied. $this->repository->clearCriteria(); static::assertTrue( $this->repository->getCriteria()->isEmpty(), 'getCriteria() not empty after clearCriteria()' ); static::assertMatchesRegularExpression( "#^select \* from [`\"]" . static::TABLE_NAME . '[`\"]$#i', $this->repository->query()->toSql(), 'Query SQL should be totally basic after clearCriteria()' ); // Add new criteria, see if it is applied. $criteria = $this->makeMockCriteria('twice', fn ($query) => $query->where(self::UNIQUE_FIELD, '1337')); $this->repository->pushCriteria($criteria, 'TemporaryCriteria'); static::assertCount( 1, $this->repository->getCriteria(), 'getCriteria() count incorrect after pushing new Criteria' ); static::assertMatchesRegularExpression( '#where [`"]' . self::UNIQUE_FIELD . '[`"] =#i', $this->repository->query()->toSql(), 'Query SQL should be altered by pushing Criteria' ); // Set repository to ignore criteria, see if they do not get applied. $this->repository->ignoreCriteria(); static::assertDoesNotMatchRegularExpression( '#where [`\"]' . self::UNIQUE_FIELD . '[`\"] =#i', $this->repository->query()->toSql(), 'Query SQL should be altered by pushing Criteria' ); $this->repository->ignoreCriteria(false); // Remove criteria once, see if it is not applied. $this->repository->removeCriteriaOnce('TemporaryCriteria'); static::assertCount( 1, $this->repository->getCriteria(), 'getCriteria() should still have a count of one if only removing temporarily' ); static::assertMatchesRegularExpression( "#^select \* from [`\"]" . static::TABLE_NAME . '[`\"]$#i', $this->repository->query()->toSql(), 'Query SQL should be totally basic while removing Criteria once' ); static::assertMatchesRegularExpression( '#where [`\"]' . self::UNIQUE_FIELD . '[`\"] =#i', $this->repository->query()->toSql(), 'Query SQL should be altered again on next call after removing Criteria once' ); // override criteria once, see if it is overridden succesfully and not called $secondCriteria = $this->makeMockCriteria('once', fn ($query) => $query->where(self::SECOND_FIELD, '12345')); $this->repository->pushCriteriaOnce($secondCriteria, 'TemporaryCriteria'); $sql = $this->repository->query()->toSql(); static::assertDoesNotMatchRegularExpression( '#where [`\"]' . self::UNIQUE_FIELD . '[`\"] =#i', $sql, 'Query SQL should not be built using first TemporaryCriteria' ); static::assertMatchesRegularExpression( '#where [`\"]' . self::SECOND_FIELD . '[`\"] =#i', $sql, 'Query SQL should be built using the overriding Criteria' ); // remove specific criteria, see if it is not applied $this->repository->removeCriteria('TemporaryCriteria'); static::assertTrue( $this->repository->getCriteria()->isEmpty(), 'getCriteria() not empty after removing Criteria' ); static::assertMatchesRegularExpression( "#^select \* from [`\"]" . static::TABLE_NAME . '[`\"]$#i', $this->repository->query()->toSql(), 'Query SQL should be totally basic after removing Criteria' ); // override criteria once, see if it is changed $criteria = $this->makeMockCriteria('once', fn ($query) => $query->where(self::UNIQUE_FIELD, '1337')); $this->repository->pushCriteriaOnce($criteria); static::assertTrue( $this->repository->getCriteria()->isEmpty(), 'getCriteria() not empty with only once Criteria pushed' ); static::assertMatchesRegularExpression( '#where [`\"]' . self::UNIQUE_FIELD . '[`\"] =#i', $this->repository->query()->toSql(), 'Query SQL should be altered by pushing Criteria once' ); } }
true
a25b962c4ccd66af84d047609b29f74efcaff94e
PHP
michalkleiner/silverstripe-base
/src/Forms/GridField/GridFieldInfoRow.php
UTF-8
901
2.75
3
[ "MIT" ]
permissive
<?php namespace LeKoala\Base\Forms\GridField; use SilverStripe\Forms\GridField\GridField_HTMLProvider; /** * A message to display next to a gridfield * * @author Koala */ class GridFieldInfoRow implements GridField_HTMLProvider { /** * Fragment to write the button to */ protected $targetFragment; protected $content; /** * @param string $targetFragment The HTML fragment to write the button into */ public function __construct($content, $targetFragment = "before") { $this->content = $content; $this->targetFragment = $targetFragment; } /** * Place the export button in a <p> tag below the field */ public function getHTMLFragments($gridField) { return array( $this->targetFragment => '<div class="message" style="margin-bottom:10px;">' . $this->content . '</div>', ); } }
true
a8e82c583c1299bcf75faaf2884ebabe42da23f1
PHP
zhangjiquan1/phpsourcecode
/a07061625/swooleyaf/libs_frame/AliOpen/Nas/TieringPolicyDeleteRequest.php
UTF-8
593
2.578125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace AliOpen\Nas; use AliOpen\Core\RpcAcsRequest; /** * Request of DeleteTieringPolicy * @method string getName() */ class TieringPolicyDeleteRequest extends RpcAcsRequest { /** * Class constructor. */ public function __construct() { parent::__construct('NAS', '2017-06-26', 'DeleteTieringPolicy', 'nas'); } /** * @param string $name * @return $this */ public function setName($name) { $this->requestParameters['Name'] = $name; $this->queryParameters['Name'] = $name; return $this; } }
true
65b1100897d81bebf10337bb0bf676f929c334b9
PHP
payoub/creditorwatch-interview
/app/CreditorWatch/Transport/Request/HttpRequest.php
UTF-8
1,378
2.953125
3
[]
no_license
<?php namespace CreditorWatch\Transport\Request; class HttpRequest implements RequestInterface { protected $endpoint; protected $method = 'GET'; protected $queryParams = array(); protected $postFields = array(); public function setRequestData($requestData = null) { foreach($requestData as $key => $value){ $this->$key = $value; } return $this; } public function setUrlEndpoint($url){ $this->endpoint = $url; return $this; } public function setMethodGet(){ return $this->setMethod('GET'); } public function setMethodPost(){ return $this->setMethod('POST'); } public function setQueryParams(array $params){ $this->queryParams = $params; return $this; } public function setPostBody(array $postFields){ $this->setMethodPost(); $this->postFields = $postFields; return $this; } protected function setMethod(string $method){ $this->method = $method; return $this; } public function getRequestData(){ $queryString = http_build_query($this->queryParams); $endpoint = (strlen($queryString) > 0) ? $this->endpoint."?".$queryString : $this->endpoint; $options = [ CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, ]; if($this->method === "POST"){ $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $this->postFields; } return $options; } }
true
36fbd657986f608a7dd540781a8a361f476a11d1
PHP
jamestylerwarren/codeup.dev
/codingChallenge.php
UTF-8
532
3.6875
4
[]
no_license
<?php //1.) $string = "welcome to the coding challenge"; function capitalize($string) { $array = explode(" ", $string); foreach ($array as $key => $value) { $array[$key] = ucfirst($value); } $newString = implode(" ", $array); return $newString . PHP_EOL; } print_r(capitalize($string)); //2.) $string = 'abcdefgh'; function changeLetter($change){ } //3.) function pyramid($string) { $newString = strrev($string); $array = str_split($newString); $length = count($array); var_dump($array); } print_r(pyramid($string));
true
56c99afbb54af1c1b21eefb11b6c23ba65ba97ed
PHP
Gorwast/gaming-webpage
/chat/login.php
UTF-8
1,637
2.671875
3
[ "MIT" ]
permissive
<?php session_start(); include('header.php'); $loginError = ''; if (!empty($_POST['username']) && !empty($_POST['pwd'])) { include ('Chat.php'); $chat = new Chat(); $user = $chat->loginUsers($_POST['username'], $_POST['pwd']); if(!empty($user)) { $_SESSION['username'] = $user[0]['username']; $_SESSION['id'] = $user[0]['id']; $chat->updateUserOnline($user[0]['id'], 1); $lastInsertId = $chat->insertUserLoginDetails($user[0]['id']); $_SESSION['login_details_id'] = $lastInsertId; header("Location:index.php"); } else { $loginError = "Usuario y Contraseña invalida"; } } ?> <title>Sistema de chat en vivo con Ajax, PHP y MySQL</title> <?php include('container.php');?> <div class="container"> <h2>Sistema de chat en vivo con Ajax, PHP y MySQL</h1> <div class="row"> <div class="col-sm-4"> <h4>Chat Login:</h4> <form method="post"> <div class="form-group"> <?php if ($loginError ) { ?> <div class="alert alert-warning"><?php echo $loginError; ?></div> <?php } ?> </div> <div class="form-group"> <label for="username">Usuario:</label> <input type="username" class="form-control" name="username" required> </div> <div class="form-group"> <label for="pwd">Contraseña:</label> <input type="password" class="form-control" name="pwd" required> </div> <button type="submit" name="login" class="btn btn-info">Iniciar Sesion</button> </form> <br> <p><b>Usuario</b> : jorge<br><b>Password</b> : root</p> <p><b>Usuario</b> : maria<br><b>Password</b> : 12345</p> </div> </div> </div> <?php include('footer.php');?>
true
c54797f799a8b1f8a771de05867a8b50e3cfc26c
PHP
bacardi55/i55WebManager
/src/B55/I55WebManager/I55ConfigParser.php
UTF-8
957
2.71875
3
[]
no_license
<?php namespace B55\I55WebManager; //use B55\Entity; use B55\I55WebManager\Entity\I55Config; use B55\I55WebManager\Entity\I55Workspace; class I55ConfigParser { protected $filename; protected $workpaces; public function __construct($filename) { if (is_file($filename) && is_readable($filename)) { $this->filename = $filename; $this->workspaces = array(); } } public function getFilename() { return $this->filename; } public function setFilename($filename) { $this->filename = $filename; } public function parse() { $file_handle = fopen($this->filename, "r"); while (!feof($file_handle)) { $line = fgets($file_handle); $matches = array(); if (preg_match('#move workspace (.+)#i', $line, $matches)) { $workspace_name = $matches[1]; $this->workspaces[] = new i55Workspace($workspace_name); } } fclose($file_handle); return $this->workspaces; } }
true
18348cea9c3777997a21382fdf8dce05777bb75f
PHP
anhducbkhn/php-design-pattern-example
/Behavioral/Strategy/StrategyUploader.php
UTF-8
1,302
3.03125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: AnhDuc * Date: 6/19/16 * Time: 2:14 PM */ interface IUploader { public function doUploadImage($originalPath, $newPath); } class S3AmazonUpload implements IUploader { public function doUploadImage($originalPath, $newPath) { // TODO: Implement doUploadImage() method. echo 'Upload file from ' . $originalPath . ' to S3 ' . $newPath; } } class LocalUpload implements IUploader { public function doUploadImage($originalPath, $newPath) { // TODO: Implement doUploadImage() method. echo 'Upload file from ' . $originalPath . ' to local ' . $newPath; } } class Uploader { /** * @var IUploader $uploader */ private $uploader; /** * Uploader constructor. * @param IUploader $uploader */ public function __construct(IUploader $uploader) { $this->uploader = $uploader; } public function doUploadImage($originalPath, $newPath) { $this->uploader->doUploadImage($originalPath, $newPath); } } //Client $localUpload = new Uploader(new LocalUpload()); $localUpload->doUploadImage('var/www/html/test', '/var/www/a'); $s3Upload = new Uploader(new S3AmazonUpload()); $localUpload->doUploadImage('var/www/html/test', 'bucketS3');
true
ffad8949805cac19224e91e1e7eca8207488db9e
PHP
adejaremola/barterbuy
/app/Blog.php
UTF-8
532
2.6875
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Blog extends Model { protected $table = 'blogs'; protected $fillable = ['pic_url', 'title', 'content', 'user_id']; public static $rules = [ 'title' => 'required', 'content' => 'required', 'pic_url' => 'image' ]; //reverse relationship with User model (hasWritten) public function getUser() { return $this->belongsTo('User'); } //relationship with Comment model public function getComments() { return $this->hasMany('Comment'); } }
true
e781af3f5712039f6b71944294838cd64b63a0b8
PHP
AntonMariadas/umtasa
/controller/membre/modification_cuisiniere_controller.php
UTF-8
2,952
2.6875
3
[]
no_license
<?php require_once('model/Database.php'); include('model/Display.php'); include('model/Update.php'); include('controller/Check.php'); $id = $_SESSION['id']; $db = Database::pdo(); $affichage = new Display($db); $cuisiniere = $affichage->cuisiniere($id); if (isset($_POST['modification-cuisiniere'])) { if (!empty($_POST['nom']) && !empty($_POST['prenom']) && !empty($_POST['adresse']) && !empty($_POST['cp']) && !empty($_POST['ville']) && !empty($_POST['tel']) && !empty($_POST['email']) && !empty($_POST['mdp']) && !empty($_POST['confirmation'])) { $nom = $_POST['nom']; $prenom = $_POST['prenom']; $adresse = $_POST['adresse']; $cp = $_POST['cp']; $ville = $_POST['ville']; $tel = $_POST['tel']; $email = $_POST['email']; $mdpTemp = $_POST['mdp']; $confirmation = $_POST['confirmation']; $emailOriginal = $cuisiniere->email; //Verification des données receptionnées $verification = new Check(); $validation = $verification->validate($nom, $prenom, $adresse, $cp, $ville, $tel, $email, $mdpTemp, $confirmation); if ($validation) { $mdp = password_hash($mdpTemp, PASSWORD_BCRYPT); $db = Database::pdo(); //Verification si l'adresse mail est déjà utilisée par une autre cuisinière $sql = $db->prepare("SELECT email FROM users WHERE email=?"); $sql->execute(array($email)); $result = $sql->rowCount(); if (($email != $emailOriginal)&&($result > 0)) { ?> <script>alert('Cette adresse email est déja utilisée par un autre membre.')</script> <?php $db = null; } //Vérification que la cuisinière garde son adresse mail ou en choisis une qui n'est pas utilisée par une autre cuisinière else if ((($email == $emailOriginal)&&($result == 1)) || (($email != $emailOriginal)&&($result == 0))) { //Si oui, modification $modification = new Update($db); $retour = $modification->cuisiniere($nom, $prenom, $adresse, $cp, $ville, $tel, $email, $mdp, $id); if ($retour) { ?> <script>alert('Profil mis à jour!')</script> <?php } else { ?> <script>alert('Erreur lors de la modification du profil.')</script> <?php } } } else { ?> <script>alert('Veuillez remplir correctement le formulaire.')</script> <?php } } else { ?> <script>alert('Veuillez remplir tous les champs du formulaire.')</script> <?php } } include('view/membre/modification_cuisiniere.php'); require_once('view/membre/template_membre.php');
true
194e84af256bb740ea2c7e6f5ac52a3bc790bd08
PHP
meandmymonkey/phpbnl13-workshop
/src/Acme/Bundle/DicWorkshopBundle/Adapter/GuzzleAdapter.php
UTF-8
660
2.53125
3
[ "MIT" ]
permissive
<?php namespace Acme\Bundle\DicWorkshopBundle\Adapter; use Guzzle\Http\ClientInterface; class GuzzleAdapter implements AdapterInterface { private $httpAdapter; private $endpointUrl; public function __construct(ClientInterface $httpAdapter, $endpointUrl) { $this->httpAdapter = $httpAdapter; $this->endpointUrl = $endpointUrl; } /** * @{inheritdoc} */ public function getRawData() { $request = $this->httpAdapter->get($this->endpointUrl); $request->addCacheControlDirective('must-revalidate'); $response = $request->send(); return $response->getBody(true); } }
true
bab3685360c01e90c58c824b86e5e3f8cf26ebb1
PHP
ArlemGabriel/LaboratorioPHP
/Controlador/DAOusuarios.php
UTF-8
4,007
2.609375
3
[]
no_license
<?php include_once 'C:\xampp\htdocs\Modelo\usuario.php'; include_once 'C:\xampp\htdocs\Controlador\conexiondb.php'; require_once 'C:\xampp\htdocs\Controlador\ConexionDB.php'; function validarRegistro($registusuario){ $base=ConexionDB::getInstance(); $sql = 'CALL validatenewuser(:correo,:nombreusuario)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":nombreusuario",$registusuario->getNombreUsuario()); $resultado->bindValue(":correo",$registusuario->getCorreo()); $resultado->execute(); $numeroregistro = $resultado->rowCount(); if($numeroregistro == 0){ return false; }else{ return true; } } function registrarUsuario($registusuario){ $base=ConexionDB::getInstance(); $sql = 'CALL insertnewuser(:nombreusuario,:correo,:nombre,:apellidos,:fechanacimiento,:telefono,:contrasenna)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":nombreusuario",$registusuario->getNombreUsuario()); $resultado->bindValue(":correo",$registusuario->getCorreo()); $resultado->bindValue(":nombre",$registusuario->getNombre()); $resultado->bindValue(":apellidos",$registusuario->getApellidos()); $resultado->bindValue(":fechanacimiento",$registusuario->getFechaNacimiento()); $resultado->bindValue(":telefono",$registusuario->getTelefono()); $resultado->bindValue(":contrasenna",$registusuario->getContrasenna()); $resultado->execute(); header("location:../Vista/registroexitoso.php"); } function validarAutenticacion($authusuario){ $base=ConexionDB::getInstance($authusuario); $sql = 'CALL validatecredentials(:nombreusuario,:contrasenna)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":nombreusuario",$authusuario->getNombreUsuario()); $resultado->bindValue(":contrasenna",$authusuario->getContrasenna()); $resultado->execute(); $numeroregistro = $resultado->rowCount(); if($numeroregistro == 0){ return false; }else{ return true; } } function validarExistenciUsuario($authusuario){ $base=ConexionDB::getInstance($authusuario); $sql = 'CALL validateuserexistent(:correousuario)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":correousuario",$authusuario->getCorreo()); $resultado->execute(); $numeroregistro = $resultado->rowCount(); if($numeroregistro == 0){ return false; }else{ return true; } } function cambiarContrasenna($authusuario){ $base=ConexionDB::getInstance($authusuario); $sql = 'CALL changepassword(:correousuario,:nuevacontrasenna)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":correousuario",$authusuario->getCorreo()); $resultado->bindValue(":nuevacontrasenna",$authusuario->getContrasenna()); $resultado->execute(); header("location:../Vista/cambiocontrasennaexitoso.php"); } function loginUsuario($authusuario){ //TODO: Mostrar el nombre y los apellidos del usuario que se autentico $base=ConexionDB::getInstance(); $sql = 'CALL getuserdata(:nombreusuario)'; $resultado = $base->prepararQuery($sql); $resultado->bindValue(":nombreusuario",$authusuario->getNombreUsuario()); $resultado->execute(); $numeroregistro = $resultado->rowCount(); if($numeroregistro == 1){ echo "Login exitoso"; $row = $resultado->fetch(PDO::FETCH_ASSOC); $authusuario->setApellidos($row['apellidos']); $authusuario->setNombre($row['nombre']); return $authusuario; }else{ echo "Error: Hay más de un usuario con el mismo nombre de usuario"; } } ?>
true
0b752b740db15c9338f0afd46a6e9148a6003e7c
PHP
bearablyk/laravel_api
/app/Models/StoryCatogory.php
UTF-8
794
2.703125
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Reliese\Database\Eloquent\Model; /** * Class StoryCatogory * * @property int $id * @property string $name * @property \Illuminate\Database\Eloquent\Collection $stories * @package App\Models * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StoryCatogory whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\StoryCatogory whereName($value) * @mixin \Eloquent */ class StoryCatogory extends Model { const FEATURED = 1; const TRENDING = 2; const NEW = 3; public $incrementing = false; public $timestamps = false; protected $casts = [ 'id' => 'int' ]; protected $fillable = [ 'id', 'name' ]; public function stories() { return $this->hasMany(\App\Models\Story::class); } }
true
e298a6c7edd1c46f0869d36bd8d49cffc625e3c9
PHP
fabiangothman/PHP
/Laravel8_sample1/app/Models/Permission.php
UTF-8
571
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Permission extends Model { use HasFactory; /** * El metodo asume que la foranea se llama "role_id" y que la id del permission_role es "id" * Relación m:m * Obtener la propiedad via: * $permission = Permission::find(1); * $permission->roles; */ public function roles(){ //return $this->belongsToMany('App\Models\Role'); return $this->belongsToMany(Role::class); } }
true
b6189be360f88085bc95e26698253c72442d390f
PHP
dongitwork/LarevelShop
/database/migrations/2016_04_01_155228_create_wards_table.php
UTF-8
792
2.609375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWardsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('ward', function (Blueprint $table) { $table->integer('WardId')->unsigned()->primary(); $table->string('WardName',50); $table->string('Type',30); $table->string('Location',30); $table->integer('DistrictId')->unsigned(); $table->foreign('DistrictId')->references('DistrictId')->on('district'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('ward'); } }
true
ff590e3b4d3a7f119df6236484bb3c68db6eac6a
PHP
PriymakVl/data.lar
/app/Quote.php
UTF-8
1,550
2.578125
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Quote extends Model { use SoftDeletes; protected $table = 'quotes'; protected $fillable = ['author_id', 'book_id', 'text', 'rating']; public function book() { return $this->belongsTo('App\Book'); } public function author() { return $this->belongsTo('App\Author'); } public static function addQuotesFromFile($request) { $items = file($_FILES['quotes']['tmp_name']); if (!$items) return; $quotes = self::setCharset($items); return self::addQuotes($quotes, $request); } private static function setCharset($items) { foreach ($items as $item) { $quotes[] = mb_convert_encoding($item, "UTF-8", "CP1251"); } return $quotes; } private static function addQuotes($quotes, $request) { $counter = 0; foreach ($quotes as $quote) { $quote = str_replace(["\r\n", "\r", "\n"], '', $quote); if(self::where('text', $quote)->first()) continue; $counter++; $params = ['author_id' => $request->author_id, 'book_id' => $request->book_id, 'text' => $quote, 'rating' => 0]; $quote = self::create($params); if ($request->tag_id) QuoteTag::add($request->tag_id, $quote->id); } return $counter; } public function tags() { return $this->hasMany('App\QuoteTag', 'quote_id'); } }
true
10a02b2714f44b37f56f06a85a098c154bb3c880
PHP
drWaka/doctor-attendance-mgmt
/core/php/connection.php
UTF-8
1,092
2.75
3
[ "Apache-2.0" ]
permissive
<?php // Application Database Connection $host = [ "dam" => $_ENV['DB_HOST'], "bio" => $_ENV['BIO_DB_HOST'] ]; $username = [ "dam" => $_ENV['DB_USER'], "bio" => $_ENV['BIO_DB_USER'] ]; $password = [ "dam" => $_ENV['DB_PASS'], "bio" => $_ENV['BIO_DB_PASS'] ]; $database = [ "dam" => $_ENV['DB_NAME'], "bio" => $_ENV['BIO_DB_NAME'] ]; $port = [ "dam" => $_ENV['DB_PORT'], "bio" => '' ]; // System Configuration Connection $connection = new mysqli($host['dam'], $username['dam'], $password['dam'], $database['dam'], $port['dam']); if ($connection->connect_error) { die("Error connecting to MySQL Server: " . $connection->connect_error); } // Biometrics Database Connection $bioConnection = ''; try { $bioConnection = new PDO( "sqlsrv:server={$host['bio']};Database={$database['bio']}", $username['bio'], $password['bio'], array( //PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ) ); } catch (PDOException $error) { die("Error connecting to SQL Server: " . $error -> getMessage()); }
true
fe8bc35648b1bd8b52b69d0d45083397b31866de
PHP
MonteverdeLtda/php-crud-api
/crm-admin/model/tIdentificationsModel.php
UTF-8
600
2.546875
3
[]
permissive
<?php /* ******************************* * * Developer by FelipheGomez * * Git: https://github.com/Feliphegomez/crm-crud-api-php * ******************************* */ class tIdentifiactionsModel extends ModeloBase { private $table; public function __construct(){ $this->table = TBL_T_IDENTIFICATIONS; parent::__construct($this->table); } //Metodos de consulta public function getUnPermiso(){ $query = "SELECT * FROM " . TBL_T_IDENTIFICATIONS . " LIMIT 1"; $usuario = $this->ejecutarSql($query); return ($usuario); } }
true
e3aa9697ea367c83e9097c3033be6a2f309608c7
PHP
ninomey/Review
/test2.php
UTF-8
2,050
2.8125
3
[]
no_license
<?php function bmi($weight,$height) { if(!$weight && !$height) return; $debu= $weight / $height /$height; if ($debu < 15) { $result = "がりがり"; } elseif (15 <= $debu && $debu < 19.5) { $result = "痩せ"; } elseif (19.5 <= $debu && $debu < 25) { $result = "普通"; } else { $result = "デブ"; } return $result; } ?> <!DOCTYPE html> <html lang="ja"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>タイトル</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body class="col-lg-offset-2 col-lg-8"> <h1>あなたの肥満度をチェックしましょう!</h1> <form action="test2.php" method="POST" class="form-inline"> <div class="form-group"> <label >体重</label> <input type="text" class="form-control" name="weight" placeholder="0.0kg"> </div> <div class="form-group"> <label >身長</label> <input type="text" class="form-control" name="height" placeholder="0.0m"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="送信"> </div> </form> <div> <span class="label label-default">NEW!</span> <h3>あなたは<?php print bmi($_POST['weight'],$_POST['height']); ?>です。</h3> </div> </body> </html>
true
fab457244f126ec2f77f2504c9a435dc538c6030
PHP
jonaselan/univ-control
/app/Http/Controllers/UniversityController.php
UTF-8
2,569
2.609375
3
[ "MIT" ]
permissive
<?php namespace UnivControl\Http\Controllers; use UnivControl\University; use Illuminate\Http\Request; use UnivControl\Http\Requests\UniversityRequest; class UniversityController extends Controller { // public function __construct() // { // $this->middleware('auth'); // } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $universities = University::latest()->simplePaginate(5); return view('university.index')->withUniversities($universities); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('university.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(UniversityRequest $request) { if (University::create($request->all())) flash('University created!')->success(); else flash('An error has occurred!')->error(); return redirect() ->action('UniversityController@index'); } /** * Show the form for editing the specified resource. * * @param \UnivControl\University $university * @return \Illuminate\Http\Response */ public function edit(String $id) { $university = University::find($id); return view('university.edit', compact('university')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param \UnivControl\University $university * @return \Illuminate\Http\Response */ public function update(Request $request, String $id) { if (University::find($id)->update($request->all())) flash('University updated!')->success(); else flash('An error has occurred!')->error(); return redirect() ->action('UniversityController@index'); } /** * Remove the specified resource from storage. * * @param \UnivControl\University $university * @return \Illuminate\Http\Response */ public function destroy(String $id) { if (University::find($id)->delete()) flash('University deleted!')->success(); else flash('An error has occurred!')->error(); return redirect() ->action('UniversityController@index'); } }
true
2f0c8127f77de7764a27729a1ed39096dbeae9d2
PHP
Yanlaz/Vitrans
/Adapter/AbstractAdapter.php
UTF-8
1,003
2.828125
3
[]
no_license
<?php namespace Yanlaz\Vitrans\Adapter; use Yanlaz\Vitrans\Exception\VitransException; /** * AbstractAdapter */ abstract class AbstractAdapter implements AdapterInterface{ protected $data = array(); protected $defaultLang = 'en_US'; protected $lang = null; protected $ext = null; public function setLanguage($lang){ $this->lang = $lang; } public function getLanguageFile($path){ $pathLang = $path.$this->lang.$this->ext; if(!file_exists($pathLang)){ $pathLang = $path.$this->defaultLang.$this->ext; } return $pathLang; } public function setOption($key, $value){} public function del($key){ throw new VitransException('not ready yet'); } public function set($key,$value){ throw new VitransException('not ready yet'); } public function get($key){ return (isset($this->data[$key])) ? $this->data[$key] : $key; } public function has($key){ return (isset($this->data[$key])) ? true : false; } }
true
1f64813c22fdb889bf7ff328f6e6074805a09f2f
PHP
zshall/kimica
/contrib/wiki/theme.php
UTF-8
5,277
2.90625
3
[]
no_license
<?php class WikiTheme extends Themelet { /* * Show a page * * $page = the shimmie page object * $wiki_page = the wiki page, has ->title and ->body * $nav_page = a wiki page object with navigation, has ->body */ public function display_page(Page $page, WikiPage $wiki_page, $nav_page) { // $nav_page = WikiPage or null if(is_null($nav_page)) { $nav_page = new WikiPage(); $nav_page->body = ""; } $tfe = new TextFormattingEvent($nav_page->body); send_event($tfe); // only the admin can edit the sidebar global $user; if($user->is_admin()) { $tfe->formatted .= "<p>(<a href='".make_link("wiki/wiki:sidebar", "edit=on")."'>Edit</a>)"; } $page->set_title(html_escape($wiki_page->title)); $page->set_heading(html_escape($wiki_page->title)); if($tfe->formatted){ $page->add_block(new Block("Wiki Index", $tfe->formatted, "left", 10)); } $this->display_nav(); $page->add_block(new Block(html_escape($wiki_page->title), $this->create_display_html($wiki_page), "main", 10)); } public function display_nav(){ global $page; $html = '<form method="GET" action="'.make_link("wiki/list").'"> <input type="text" autocomplete="off" value="" name="search" id="search_input" class="ac_input"> <input type="submit" style="display: none;" value="Find"> </form>'; $page->add_block(new Block("Navigation", $html, "left", 0)); } public function display_changes($changes){ global $page; $tfe = new TextFormattingEvent($changes); send_event($tfe); $page->add_block(new Block("Recent Changes", $tfe->formatted, "left", 20)); } public function display_page_editor(Page $page, WikiPage $wiki_page) { $page->set_title(html_escape($wiki_page->title)); $page->set_heading(html_escape($wiki_page->title)); $page->add_block(new Block("Editor", $this->create_edit_html($wiki_page))); } public function display_wiki_pages($wikis, $search, $pageNumber, $totalPages){ global $page; if(empty($search)){ $pagination = $this->build_paginator("wiki/list", null, $pageNumber, $totalPages); } else{ $pagination = $this->build_paginator("wiki/list/$search", null, $pageNumber, $totalPages); } $html = "<table><thead><tr><th>Title</th><th>Date</th><th>Updater</th></tr></thead><tbody>"; $n = 0; foreach($wikis as $wiki){ $oe = ($n++ % 2 == 0) ? "even" : "odd"; $page_link = "<a href='".make_link("wiki/".html_escape($wiki["title"]))."'>".html_escape($wiki["title"])."</a> "; $user_link = "<a href='".make_link("account/profile/".$wiki['updater'])."'>".$wiki['updater']."</a> "; $html .= "<tr class='$oe'><td>".$page_link."</td><td>".autodate($wiki['date'])."</td><td>".$user_link."</td></tr>"; } $html .= "</tbody></table>"; $this->display_nav(); $page->set_title("Wiki"); $page->set_heading("Wiki"); $page->add_block(new Block("Wiki", $html.$pagination, "main", 10)); } protected function create_edit_html(WikiPage $page) { $h_title = html_escape($page->title); $u_title = url_escape($page->title); $i_revision = int_escape($page->revision) + 1; global $user; if($user->is_admin()) { $val = $page->is_locked() ? " checked" : ""; $lock = "<br>Lock page: <input type='checkbox' name='lock'$val>"; } else { $lock = ""; } return " <form action='".make_link("wiki_admin/save")."' method='POST'> <input type='hidden' name='title' value='$h_title'> <input type='hidden' name='revision' value='$i_revision'> <textarea name='body' style='width: 100%' rows='20'>".html_escape($page->body)."</textarea> $lock <br><input type='submit' value='Save'> </form> "; } protected function create_display_html(WikiPage $page) { $owner = $page->get_owner(); $tfe = new TextFormattingEvent($page->body); send_event($tfe); global $user; $edit = "<table><tr>"; $edit .= Wiki::can_edit($user, $page) ? " <td><form action='".make_link("wiki_admin/edit")."' method='POST'> <input type='hidden' name='title' value='".html_escape($page->title)."'> <input type='hidden' name='revision' value='".int_escape($page->revision)."'> <input type='submit' value='Edit'> </form></td> " : ""; if($user->is_admin()) { $edit .= " <td><form action='".make_link("wiki_admin/delete_revision")."' method='POST'> <input type='hidden' name='title' value='".html_escape($page->title)."'> <input type='hidden' name='revision' value='".int_escape($page->revision)."'> <input type='submit' value='Delete This Version'> </form></td> <td><form action='".make_link("wiki_admin/delete_all")."' method='POST'> <input type='hidden' name='title' value='".html_escape($page->title)."'> <input type='submit' value='Delete All'> </form></td> "; } $edit .= "</tr></table>"; return " <div class='wiki-page'> $tfe->formatted <hr> <p class='wiki-footer'> Revision {$page->revision} by <a href='".make_link("account/profile/{$owner->name}")."'>{$owner->name}</a> at {$page->date} $edit </p> </div> "; } public function display_tag_related($posts){ global $page; if(!empty($posts)){ $page->add_block(new Block("Related Posts", $this->build_table($posts, null), "main", 20)); } } } ?>
true
8debd2d6e78da8d804b55fc3ca1218fc92a8a5cf
PHP
chapellu/Watch_Bot
/PublicSite/core/Url/Request.php
UTF-8
524
2.796875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: alan * Date: 21/01/2017 * Time: 22:02 */ namespace Core\Url; class Request { public $url; //URL appellée par l'utilisateur public $page = 1; //Par défaut public $prefix = false; public $data = false; function __construct(){ $this->url = $_SERVER['REQUEST_URI']; if(!empty($_POST)){ $this->data= array(); foreach ($_POST as $k => $v) { $this->data[$k]=$v; } } } }
true
7279511a380bd2e12e890869a4c32fc12022fbfc
PHP
zhongweidai/freephp
/src/apps/base/admin/servers/AdminMenuServerBase.php
UTF-8
4,626
2.625
3
[]
no_license
<?php defined('IN_FREE') or exit('No permission resources.'); class AdminMenuServerBase extends FreeProServer { protected $tree = array(); function __construct() { parent::__construct(); } public function model() { $this->model = M('admin_menu','admin'); } /** * 获取所有的菜单 **/ public function getAll() { static $admin_menu = ''; if($admin_menu === '') { $menus = $this->model->select( array(), '*', '', 'ORDERNO desc'); $admin_menu = array(); foreach($menus as $key => $m) { $admin_menu[$m['ID']] = $m; } } return $admin_menu; } /** * 获取所有后台菜单树(供菜单添加) **/ public function getMenuTree($p_id=0,$delid = 0) { $admin_menu = $this->getAll(); if(isset($admin_menu[$delid])) { unset($admin_menu[$delid]); } return $this->treeMenu($p_id,$admin_menu); } /** * 获取指定权限可访问菜单(供adminfile) **/ public function getMenuRole($p_id=0,$roleid = 0) { $admin_menu = $this->getAll(); if($roleid != 0) { $roles = S('Role','admin')->getAll(); if(strpos($roleid,',')) { $rs = implode(',',$roleid); }else{ $rs = array($roleid); } $priv = array(); foreach($rs as $key => $r) { $priv = array_merge($priv, empty($roles[$r]['PRIV']) ? array() : explode(',',$roles[$r]['PRIV'])); } } foreach($admin_menu as $key => $r) { if($r['STATUS'] == 0) { unset($admin_menu[$key]); continue; } if($roleid != 0) { if($r['FATHERID'] != 0 && !in_array($r['ID'],$priv)) { unset($admin_menu[$key]); } } } return $admin_menu; } /** * 获取指定权限后台菜单树 **/ public function getMenuRoleTree($p_id=0,$roleid = 0) { $admin_menu = $this->getMenuRole($p_id,$roleid); return $this->treeMenu($p_id,$admin_menu); } /** * 导航选择 * @param string $p_id 父id * @param intval/array $id 别选中的ID,多选是可以是数组 */ public function selectMenu($p_id=0,$id = 0) { $admin_menu = $this->getAll(); $array = array(); foreach($admin_menu as $key => $val) { if($val['FATHERID'] != 0) { continue; } $array[$key] = $val; if($val['ID'] == $id) { $array[$key]['selected'] = 'selected'; } } $tree = E('tree'); $str = "<option value='\$ID' \$selected>\$spacer \$NAME</option>;"; $str2 = "<optgroup label='\$spacer \$NAME'></optgroup>"; $tree->init($array); $string = $tree->get_tree_category(0, $str, $str2); return $string; } /** * 生成tree **/ private function treeMenu($p_id=0,$trees = array()) { foreach($trees as $key => $val) { if($val['FATHERID'] == $p_id) { $tree[$val['ID']] = $val; $tree[$val['ID']]['id'] = $val['ID']; $tree[$val['ID']]['name'] = $val['NAME']; $tree[$val['ID']]['icon'] = ''; $tree[$val['ID']]['tip'] = ''; $tree[$val['ID']]['parent'] = $p_id ==0 ? 'root' : $p_id; $tree[$val['ID']]['url'] = $this->resolveMenuUrl($val['QUERY']); $tree[$val['ID']]['items'] = $this->treeMenu($val['ID'],$trees); } } return $tree; } /** * 获取所有的父菜单 **/ public function getFatherMenu($c_id=0) { $admin_menu = $this->getAll(); if($c_id == 0) { return array(); } foreach($admin_menu as $key => $val) { if($val['ID'] == $c_id) { $this->tree[] = $val; if($val['FATHERID'] != 0) { $this->getFatherMenu($val['FATHERID']); } } } return $this->tree; } public function get($id) { return $this->model->getOne(array('ID'=>$id)); } public function edit($data,$where) { return $this->model->update($data,$where); } public function add($data) { return $this->model->insert($data,true); } /** * 删除指定菜单 **/ public function delete($ids) { if($this->model->getOne(array('FATHERID'=>$ids))) { return false; } $this->model->delete(array('ID'=>$ids)); return true; } /** * 拼凑后台菜单url **/ public function resolveMenuUrl($str) { if(stripos($str,',') !== false) { $urls = explode(',', $str); $str = $urls[0]; } //var_dump(U(str_replace('*','',$str))); if(stripos($str,'?') !== false) { $us = explode('?', $str); $str = $us[0]; return U(str_replace('*','',$str),array('showmodule'=>$us[1])); }else{ return U(str_replace('*','',$str)); } } }
true
620e1205fd27635178187eac43ab0db923b17ebf
PHP
justem007/rossina
/app/Repositories/Transformers/BlocoCamisetaTransformer.php
UTF-8
771
2.59375
3
[ "MIT" ]
permissive
<?php namespace Rossina\Repositories\Transformers; use League\Fractal\TransformerAbstract; use Rossina\BlocoCamiseta; /** * Class BlocoCamisetaTransformer * @package namespace Rossina\Repositories/Transformers; */ class BlocoCamisetaTransformer extends TransformerAbstract { /** * Transform the \BlocoCamiseta entity * @param \BlocoCamiseta $model * * @return array */ public function transform(BlocoCamiseta $model) { return [ 'id' => (int) $model->id, 'title' => $model->title, 'sub_title' => $model->sub_title, 'alt' => $model->alt, 'created_at' => $model->created_at, 'updated_at' => $model->updated_at ]; } }
true
71c3092d86e14d9eaccce5454fbd2faf46faf710
PHP
zapbr/Hackerrank
/utopian/index.php
UTF-8
277
2.984375
3
[]
no_license
<?php $_fp = fopen("php://stdin", "r"); /* Enter your code here. Read input from STDIN. Print output to STDOUT */ fscanf($_fp,"%d",$n); while (($line = fgets($_fp)) !== false) { echo (preg_match('/^[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}/', $line))? 'VALID' : 'INVALID', PHP_EOL; }
true
2ebfa4ac0ba8c64377c8eaab536643103b2cf0d2
PHP
janith-rathanyaka/CRUD-PHP-MySQL
/dao/PessoaDao.php
UTF-8
2,075
3
3
[ "Apache-2.0" ]
permissive
<?php require_once("../model/Banco.php"); class PessoaDao { private $mysqli; public function __construct() { $this->mysqli = Banco::getInstance()->getConnection(); } public function salvar($p) { $stmt = $this->mysqli->prepare("INSERT INTO Pessoa (nome, data_nascimento, cpf, ocupacao) VALUES (?,?,?,?)"); if($stmt == FALSE) printf("Error: %s.\n", $this->mysqli->error); else { $nome = $p->getNome(); $data_nascimento = $p->getDataNascimento(); $cpf = $p->getCpf(); $ocupacao = $p->getOcupacao(); $stmt->bind_param('ssss', $nome, $data_nascimento, $cpf, $ocupacao); return $stmt->execute(); } } public function update($p) { $stmt = $this->mysqli->prepare("UPDATE Pessoa SET nome = ?, data_nascimento = ? , cpf = ?, ocupacao = ? WHERE id = ?"); if($stmt == FALSE) printf("Error: %s.\n", $this->mysqli->error); else { $nome = $p->getNome(); $data_nascimento = $p->getDataNascimento(); $cpf = $p->getCpf(); $ocupacao = $p->getOcupacao(); $id = $p->getId(); echo $id . ''; $stmt->bind_param('ssssi', $nome, $data_nascimento, $cpf, $ocupacao, $id); return $stmt->execute(); } } public function getPessoas() { $query = $this->mysqli->query("SELECT * FROM Pessoa"); while ($row = $query->fetch_assoc()) { $result[] = $row; } return $result; } public function deletar($id) { if($this->mysqli->query("DELETE FROM Pessoa WHERE id = ".$id.";") == TRUE) { return true; } else return false; } public function getById($id) { $query = $this->mysqli->query("SELECT * FROM Pessoa WHERE id = ".$id.";"); if($query->num_rows == 0) return false; else return $query->fetch_assoc(); } } ?>
true
c0c8ddb6376f88525bf0b74a85235423ff08cd83
PHP
osundiranay/Advance-PHP-Complete-Course-With-Codes-By-NBL
/102.RealWorld Use of Session In PHP/login.php
UTF-8
899
3
3
[]
no_license
<?php //Start Session session_start(); if(!isset($_SESSION['uname'])){ if(isset($_REQUEST['username']) || isset($_REQUEST['password'])){ //Set Session Data $uname=$_REQUEST['username']; $pass=$_REQUEST['password']; $_SESSION['uname']=$uname; $_SESSION['pass']=$pass; echo "<script>location.href='welcome.php'</script>"; } } else{ echo "<script>location.href='welcome.php'</script>"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>PHP Programming</title> </head> <body> <form action="" method="POST"> Username: <input type="text" name="username" id="username"><br> <br> Password: <input type="text" name="password" id="password"> <br> <br> <input type="submit" value="Login" name="login"> </form> </body> </html>
true
97bc53f5d7188243dda45e302c218f24aeae1df6
PHP
ezra-obiwale/RESTServer
/core/classes/Upload.php
UTF-8
809
2.828125
3
[ "MIT" ]
permissive
<?php use Exception; /** * Description of Upload * * @author Ezra Obiwale <contact@ezraobiwale.com> */ class Upload extends JsonData { public static function create($data, $id = null) { return uploadFiles($_FILES, [ 'extensions' => ['jpg', 'png', 'gif'], 'maxSize' => (1 * 1024 * 1000) / 2, // Half a mb 'filename' => preg_replace('/[^a-zA-Z0-9]/', '-', $data['title']), 'path' => DATA . $data['path'] ]); } public static function get($id = null) { throw new Exception('Not implemented'); } public static function update($id, $data) { throw new Exception('Not implemented'); } public static function delete($path = null) { throw new Exception('Not implemented'); } }
true
59b09c8e9361a341f5770a924d093216ec70c902
PHP
imutafchiev94/Programing-Basics-PHP
/Conditional Statements/14. Pets.php
UTF-8
628
3.296875
3
[]
no_license
<?php $days = intval(readline()); $foodInKg = intval(readline()); //in kilograms $foodForDogPerDay = floatval(readline()); //in kilograms $foodForCatPerDay = floatval(readline()); //in grams $foodForTurtlePerDay = floatval(readline()); //in kilograms $allNeededFoodPerDay = $foodForCatPerDay + $foodForDogPerDay + ($foodForTurtlePerDay / 1000); $allNeededFoodForAllDays = $allNeededFoodPerDay * $days; if($allNeededFoodForAllDays <= $foodInKg) { echo floor($foodInKg - $allNeededFoodForAllDays) . " kilos of food left."; } else { echo ceil($allNeededFoodForAllDays - $foodInKg) . " more kilos of food are needed."; }
true
f6393eeb7e136e972a0ef963aa45dcf70d17d5e6
PHP
ThibaudDauce/EloquentVariableModelConstructor
/tests/ThibaudDauce/EloquentVariableModelConstructor/VariableModelConstructorTraitTest.php
UTF-8
2,922
2.921875
3
[ "MIT" ]
permissive
<?php use ThibaudDauce\EloquentVariableModelConstructor\VariableModelConstructorTrait; use Illuminate\Database\Eloquent\Model as Eloquent; class VariableModelConstructorTraitTest extends PHPUnit_Framework_TestCase { public $character; public $characterCustomClassnameField; public $warrior; public function setUp() { parent::setUp(); // Build some objects for our tests $this->character = new Character; $this->warrior = new Warrior; $this->characterCustomClassnameField = new CharacterCustomClassnameField; } public function tearDown() { // } public function testNewFromBuilderDefaultClassnameField() { // Test without a class_name $character = new Character; $characterAttributes = ['name' => 'Antoine']; $character = $character->newFromBuilder($characterAttributes); $this->assertTrue($character instanceof Character); $this->assertFalse($character instanceof Warrior); $this->assertFalse($character instanceof Wizard); $this->assertEquals($characterAttributes['name'], $character->getAttribute('name')); // Test with a class_name $character = new Character; $characterAttributes = ['class_name' => 'Warrior', 'name' => 'Antoine', 'rage' => 42]; $warrior = $character->newFromBuilder($characterAttributes); $this->assertTrue($warrior instanceof Warrior); $this->assertEquals($characterAttributes['name'], $warrior->getAttribute('name')); $this->assertEquals($characterAttributes['rage'], $warrior->getAttribute('rage')); } public function testNewFromBuilderSpecificClassnameField() { // Test with a class_name (wrong class_name_field) $character = new CharacterCustomClassnameField; $characterAttributes = ['class_name' => 'Warrior', 'name' => 'Antoine']; $character = $character->newFromBuilder($characterAttributes); $this->assertTrue($character instanceof CharacterCustomClassnameField); $this->assertFalse($character instanceof Warrior); $this->assertEquals($characterAttributes['name'], $character->getAttribute('name')); // Test with a custom_class_name_field (right class_name_field) $character = new CharacterCustomClassnameField; $characterAttributes = ['custom_class_name_field' => 'Warrior', 'name' => 'Antoine']; $character = $character->newFromBuilder($characterAttributes); $this->assertTrue($character instanceof Warrior); $this->assertTrue($character instanceof Character); $this->assertEquals($characterAttributes['name'], $character->getAttribute('name')); } } // The parent classes class Character extends Eloquent { use VariableModelConstructorTrait; } class CharacterCustomClassnameField extends Eloquent { use VariableModelConstructorTrait; protected function getClassnameField() { return 'custom_class_name_field'; } } // Child classe class Warrior extends Character { }
true
d80d9ba0bb6b0e313cce160247b5001e2b776380
PHP
StefftheEmperor/3rei
/Structure/Classes/Form.php
UTF-8
2,078
2.984375
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: stefan * Date: 28.05.15 * Time: 17:22 */ namespace Structure\Classes; use Structure\Classes\AbstractStructure; use Request\Classes\Request\Post; use Structure\Interfaces\Value; use Structure\Classes\Form\Input\Hidden; /** * Class Form * @package Structure\Classes */ class Form extends AbstractStructure { const METHOD_POST = 'post'; const METHOD_GET = 'get'; /** * @var array */ protected $fields = array(); /** * @var null */ protected $identifier = NULL; /** * @param AbstractStructure $structure * @return $this */ public function add(AbstractStructure $structure) { $this->fields[] = $structure; return $this; } /** * @return array */ public function get_fields() { return $this->fields; } /** * @return string */ public function get_fields_html() { $fields_html = ''; foreach ($this->get_fields() as $field) { $field->set_renderer($this->get_renderer()); $fields_html .= $field->get_renderer()->render($field); } return $fields_html; } /** * @param $identifier */ public function init($identifier) { $this->identifier = $identifier; $this->add(Hidden::factory($this->identifier.'_ds','1')); } /** * @param $post_data * @return bool */ public function is_submitted($post_data) { return isset($post_data[$this->identifier.'_ds']); } /** * @param Post $post * @return $this */ public function validate(Post $post) { if ($this->is_submitted($post)) { foreach ($this->get_fields() as $field) { if ($field instanceof Value) { $field->validate($post); } } } return $this; } public function get_value_of($field_name) { $value = NULL; foreach ($this->get_fields() as $field) { if ($field instanceof Value) { $value = $field->get_value_of($field_name); if (isset($value)) { break; } } } return $value; } /** * @return string */ public function get_html() { return '<form'.$this->get_attributes_html().'>'.$this->get_fields_html().'</form>'; } }
true
9b91c7bad11a7f6dda95a1b0743d445426d7616a
PHP
petewurster/cis-244
/wurster_lab03/index.php
UTF-8
2,131
2.96875
3
[]
no_license
<?php $navs = [ 'page1' => 'p_cubensis', 'page2' => 'p_tampanensis', 'page3' => 'a_muscaria' ]; $pageData = [ 'p_cubensis' => [ 'image' => 'p_cubensis.jpg', 'text' => [ 'p_cubensis fact 1 of 2', 'p_cubensis fact 2 of 2' ] ], 'p_tampanensis' => [ 'image' => 'p_tampanensis.jpg', 'text' => [ 'p_tampanensis fact 1 of 3', 'p_tampanensis fact 2 of 3', 'p_tampanensis fact 3 of 3' ] ], 'a_muscaria' => [ 'image' => 'a_muscaria.jpg', 'text' => [ 'a_muscaria fact 1 of 4', 'a_muscaria fact 2 of 4', 'a_muscaria fact 3 of 4', 'a_muscaria fact 4 of 4' ] ] ]; $page = $_GET['show'] ?? 'mushrooms'; Class Page { public $head = '<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" type="text/css" href="./css/style.css"><link rel="icon" type="image/ico" href="./images/hat2.png"><title>'; public $page; public $h1; public $li = "\n"; public $main = '<main><h2>Select a strain to explore!</h2>' . "\n"; public $foot = '<footer><p>2019 mushroom guide</p></footer>'; //called to set init values public function __construct($navs, $pageData, $page) { $this->page = $page; $this->h1 = strtoupper($page); $this->head .= $this->h1 . '</title></head><body>'; foreach($navs as $k => $v) { $this->li .= '<li><a href="index.php?show=' . $v .'">' . $v . '</a></li>' . "\n"; } //re-build main as needed if($page !== 'mushrooms') { $this->main = '<main class="full"><aside><img src="./images/'. $pageData[$page]['image'] .'" alt="picture of ' . $page . '"></aside>'; foreach($pageData[$page]['text'] as $p) { $this->main .= '<p>' . $p . '</p>' . "\n"; } } } //call to create page public function displayPage() { echo $this->head; echo '<div id="outside">'; echo '<header><h1>' . $this->h1 . '</h1></header>'; echo '<nav><ul>' . $this->li . '</ul></nav>'; echo $this->main . '</main>'; echo $this->foot; echo '</div></body></html>'; } } //create new page object & display $test = new Page($navs, $pageData, $page); $test->displayPage(); ?>
true
d74f4e5afd40e7328b9c404ff827fa771f43a683
PHP
bpolaszek/hostname-extractor
/src/Visitor/SuffixVisitor.php
UTF-8
1,605
2.828125
3
[ "MIT" ]
permissive
<?php namespace BenTools\HostnameExtractor\Visitor; use BenTools\HostnameExtractor\ParsedHostname; use BenTools\HostnameExtractor\SuffixProvider\NaiveSuffixProvider; use BenTools\HostnameExtractor\SuffixProvider\SuffixProviderInterface; use BenTools\Violin\Violin; use function BenTools\Violin\string; /** * Class SuffixVisitor * @internal */ final class SuffixVisitor implements HostnameVisitorInterface { /** * @var SuffixProviderInterface */ private $suffixProvider; /** * @inheritDoc */ public function __construct(SuffixProviderInterface $suffixProvider = null) { $this->suffixProvider = $suffixProvider ?? new NaiveSuffixProvider(); } /** * @inheritDoc */ public function visit($hostname, ParsedHostname $parsedHostname): void { $hostname = string($hostname); if (!$parsedHostname->isIp() && $hostname->contains('.')) { $suffix = $this->findSuffix($hostname); if (null !== $suffix) { $parsedHostname->setSuffix($suffix); } else { $hostnameParts = \explode('.', $hostname); $parsedHostname->setSuffix(\array_pop($hostnameParts)); } } } /** * @param Violin $hostname * @return null|string */ private function findSuffix(Violin $hostname): ?string { foreach ($this->suffixProvider->getSuffixes() as $suffix) { if ($hostname->endsWith(\sprintf('.%s', $suffix))) { return $suffix; } } return null; } }
true
46aa65506ff6afa6f076c4c24bb4f658ef2df376
PHP
MariangelaEscobarMarcondes/TicketHappy
/controller/ContatoController.php
UTF-8
3,618
2.671875
3
[]
no_license
<?php class ContatoController extends Controller{ public function __call($m,$a){ $this->view->renderizar("erro"); } public function cadastroContato(){ $this->view->renderizar("header"); $this->view->renderizar("contato"); $this->view->renderizar("footer"); } // https://ticket-happy-mariangela.c9users.io/contato/cadastroContato //esta fazendo um redirect public function sucesso(){ $this->view->renderizar("header"); $this->view->renderizar("sucesso"); $this->view->renderizar("footer"); } public function inserir(){ //Obtem da view $nomeCompleto = $_POST["nomeCompleto"]; $email = $_POST["email"]; $assunto = $_POST["assunto"]; $mensagem = $_POST["mensagem"]; //ignorar id = autoincremento //passa para o ContatoModel $contatoModel = new ContatoModel(0, $nomeCompleto, $email, $assunto, $mensagem); $contatoDao = new ContatoDAO(); //PASSA AO MODEL $ret = $contatoDao->insert($contatoModel); if($ret === ""){ header("Location: /contato/sucesso"); }else{ $this->view->interpolar("errosql",$ret); } } public function listar(){ $contatoDao = new ContatoDAO(); $todosContatos = $contatoDao->getContatos(); $this->view->renderizar("header"); $this->view->interpolar("listar_contato",$todosContatos); $this->view->renderizar("footer"); } // https://ticket-happy-mariangela.c9users.io/contato/listar // carrega os campos na pagina contatoAlterar.php public function alterar(){ $id = $_GET["arg0"]; $contatoDao = new ContatoDAO(); $contato = $contatoDao->getContato($id); $dado["id"] = $contato->getId(); // estou trazendo o id pq na function update nao esta pegando o id pelo GET // MANDANDO PARA VIEW $dado["nomeCompleto"] = $contato->getNomeCompleto(); $dado["email"] = $contato->getEmail(); $dado["assunto"] = $contato->getAssunto(); $dado["mensagem"] = $contato->getMensagem(); //nao esta carregando $this->view->renderizar("header"); $this->view->interpolar("contatoAlterar",$dado); $this->view->renderizar("footer"); } public function update(){ //$id = $_GET["arg0"]; //Obtem da view $id = $_POST["id"]; $nomeCompleto = $_POST["nomeCompleto"]; $email = $_POST["email"]; $assunto = $_POST["assunto"]; $mensagem = $_POST["mensagem"]; //passa para o ContatoModel $contatoModel = new ContatoModel($id,$nomeCompleto, $email, $assunto, $mensagem); $contatoDao = new ContatoDAO(); //PASSA AO MODEL $contatoDao->updateContato($contatoModel); header("Location: /contato/listar"); /* if($ret === ""){ header("Location: /contato/listar"); }else{ $this->view->interpolar("errosql",$ret); } */ } public function deletar(){ $id = $_GET["arg0"]; //pega id via url $contatoDao = new ContatoDAO(); $contatoDao->deleteContato($id); header("Location: /contato/listar"); } } ?>
true
1941241b64d7ab5805a6189ab79ea24905546c86
PHP
hassanhitleap1/desgin_pattern
/Creational/AbstractFacrory2/FactoryFile.php
UTF-8
566
2.796875
3
[]
no_license
<?php namespace Creational\AbstractFacrory2; class FactoryFile { public function uploadFileXls(){ $file= new XLSFile(1); $file->set_name("name xls"); $file->upload_file(); return $file; } public function uploadFileCSV(){ $file= new CSVFile(1); $file->set_name("name csv"); $file->upload_file(); return $file; } public function uploadFileHtml(){ $file= new HtmlFile(1); $file->set_name("name html"); $file->upload_file(); return $file; } }
true
12b03e31a1562e0230f7fdcdba537ddb8c20080e
PHP
HydraWiki/hydrawiki-codesniffer
/HydraWiki/Sniffs/WhiteSpace/SpaceBeforeSingleLineCommentSniff.php
UTF-8
4,752
3.078125
3
[ "MIT" ]
permissive
<?php /** * Curse Inc. * SpaceBeforeSingleLineCommentSniff * * Verify comments are preceded by a single space. * * This file was copied from MediaWiki Codesniffer before being modified * File: MediaWiki/Sniffs/WhiteSpace/SpaceBeforeSingleLineCommentSniff.php * From repository: https://github.com/wikimedia/mediawiki-tools-codesniffer * * @author Dieser Benutzer * @author Samuel Hilson <shhilson@curse.com> * @copyright https://github.com/wikimedia/mediawiki-tools-codesniffer/blob/master/COPYRIGHT * @license https://github.com/wikimedia/mediawiki-tools-codesniffer/blob/master/LICENSE GPL-2.0-or-later * @package HydraWiki */ namespace HydraWiki\Sniffs\WhiteSpace; use PHP_CodeSniffer\Files\File; use PHP_CodeSniffer\Sniffs\Sniff; class SpaceBeforeSingleLineCommentSniff implements Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return [T_COMMENT]; } /** * Process the file * * @param File $phpcsFile * @param integer $stackPtr The current token index. * * @return void */ public function process(File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); $currToken = $tokens[$stackPtr]; $preToken = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true); // Test if comment starts on a new line if ($preToken !== false && $tokens[$preToken]['line'] === $tokens[$stackPtr]['line'] ) { $phpcsFile->addWarning( 'Comments should start on new line.', $stackPtr, 'NewLineComment' ); } // Validate Current Token if (!$this->isComment($currToken) || $this->isDocBlockComment($currToken) || $this->isEmptyComment($currToken) ) { return; } // Checking whether there is a space between the comment delimiter // and the comment if (substr($currToken['content'], 0, 2) === '//') { $this->handleDoubleSlashComment($phpcsFile, $stackPtr, $currToken); return; } // Finding what the comment delimiter is and checking whether there is a space // between the comment delimiter and the comment. if ($currToken['content'][0] === '#') { $this->handleHashComment($phpcsFile, $stackPtr, $currToken); } } /** * Check contents of current token for empty state * * @param array $currToken * * @return boolean */ private function isEmptyComment($currToken) { return ( (substr($currToken['content'], 0, 2) === '//' && rtrim($currToken['content']) === '//') || ($currToken['content'][0] === '#' && rtrim($currToken['content']) === '#') ); } /** * Check contents of current token for doc block * * @param array $currToken * * @return boolean */ private function isDocBlockComment($currToken) { // Accounting for multiple line comments, as single line comments // use only '//' and '#' // Also ignoring PHPDoc comments starting with '///', // as there are no coding standards documented for these return (substr($currToken['content'], 0, 2) === '/*' || substr($currToken['content'], 0, 3) === '///'); } /** * Check if current token is a comment token * * @param [type] $currToken * * @return boolean */ private function isComment($currToken) { return $currToken['code'] === T_COMMENT; } /** * Handle any double slash style'//' comments * * @param File $phpcsFile * @param integer $stackPtr * @param array $currToken * * @return void */ private function handleDoubleSlashComment($phpcsFile, $stackPtr, $currToken) { $commentContent = substr($currToken['content'], 2); $commentTrim = ltrim($commentContent); if (strlen($commentContent) == strlen($commentTrim)) { $fix = $phpcsFile->addFixableWarning( 'At least a single space expected after "//"', $stackPtr, 'SingleSpaceBeforeSingleLineComment' ); if ($fix) { $newContent = '// '; $newContent .= $commentTrim; $phpcsFile->fixer->replaceToken($stackPtr, $newContent); } } } /** * Handle any hash style '#' comments * * @param File $phpcsFile * @param integer $stackPtr * @param array $currToken * * @return void */ private function handleHashComment($phpcsFile, $stackPtr, $currToken) { // Find number of `#` used. $startComment = 0; while ($currToken['content'][$startComment] === '#') { $startComment += 1; } if ($currToken['content'][$startComment] !== ' ') { $fix = $phpcsFile->addFixableWarning( 'At least a single space expected after "#"', $stackPtr, 'SingleSpaceBeforeSingleLineComment' ); if ($fix) { $content = $currToken['content']; $newContent = '# '; $tmpContent = substr($content, 1); $newContent .= ltrim($tmpContent); $phpcsFile->fixer->replaceToken($stackPtr, $newContent); } } } }
true
92c9d77fe648f0e0d3d3d012b5bd07618603d504
PHP
secondred-fleckner/php-imageprocessing
/Media/Filtering/MeanRemoval.php
UTF-8
662
2.671875
3
[ "MIT" ]
permissive
<?php namespace lib\Media\Filtering; class MeanRemoval extends \lib\Media\Filtering\AbstractImageFilter implements \lib\Interfaces\InterfaceImageFilter { /** * MeanRemoval::__construct() * * @param mixed $args (no Params) * @return void */ public function __construct( $args = array() ) { $this->filterName = 'MeanRemoval'; $this->args = $args; } public function applyFilter() { imagefilter($this->canvas, IMG_FILTER_MEAN_REMOVAL); } }
true