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
6d0441bb5fa62e00975ace4abef996defd36be17
PHP
Krienas/rocketeer
/src/Rocketeer/Services/TasksHandler.php
UTF-8
8,768
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /* * This file is part of Rocketeer * * (c) Maxime Fabre <ehtnam6@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace Rocketeer\Services; use Closure; use Illuminate\Container\Container; use Rocketeer\Abstracts\AbstractTask; use Rocketeer\Console\Commands\BaseTaskCommand; use Rocketeer\Tasks; use Rocketeer\Traits\HasLocator; /** * Handles the registering and firing of tasks and their events. * * @author Maxime Fabre <ehtnam6@gmail.com> */ class TasksHandler { use HasLocator; /** * The registered events. * * @var array */ protected $registeredEvents = []; /** * The registered plugins. * * @var array */ protected $registeredPlugins = []; /** * Build a new TasksQueue Instance. * * @param Container $app */ public function __construct(Container $app) { $this->app = $app; } /** * Delegate methods to TasksQueue for now to * keep public API intact. * * @param string $method * @param array $parameters * * @return mixed */ public function __call($method, $parameters) { return call_user_func_array([$this->queue, $method], $parameters); } //////////////////////////////////////////////////////////////////// ///////////////////////////// REGISTRATION ///////////////////////// //////////////////////////////////////////////////////////////////// /** * Register a custom task with Rocketeer. * * @param string|Closure|AbstractTask $task * @param string|null $name * @param string|null $description * * @return BaseTaskCommand */ public function add($task, $name = null, $description = null) { // Build task if necessary $task = $this->builder->buildTask($task, $name, $description); $slug = 'rocketeer.tasks.'.$task->getSlug(); // Add the task to Rocketeer $this->app->instance($slug, $task); $bound = $this->console->add(new BaseTaskCommand($this->app[$slug])); // Bind to Artisan too if ($this->app->bound('artisan') && $this->app->resolved('artisan')) { $command = $this->builder->buildCommand($task); $this->app['artisan']->add($command); } return $bound; } /** * Register a task with Rocketeer. * * @param string $name * @param string|Closure|AbstractTask|null $task * @param string|null $description * * @return BaseTaskCommand */ public function task($name, $task = null, $description = null) { return $this->add($task, $name, $description)->getTask(); } //////////////////////////////////////////////////////////////////// /////////////////////////////// EVENTS ///////////////////////////// //////////////////////////////////////////////////////////////////// /** * Execute a task before another one. * * @param string $task * @param Closure $listeners * @param int $priority */ public function before($task, $listeners, $priority = 0) { $this->addTaskListeners($task, 'before', $listeners, $priority); } /** * Execute a task after another one. * * @param string $task * @param Closure $listeners * @param int $priority */ public function after($task, $listeners, $priority = 0) { $this->addTaskListeners($task, 'after', $listeners, $priority); } /** * Register with the Dispatcher the events in the configuration. */ public function registerConfiguredEvents() { // Clean previously registered events foreach ($this->registeredEvents as $event) { $this->events->forget('rocketeer.'.$event); } // Clean previously registered plugins $plugins = $this->registeredPlugins; $this->registeredPlugins = []; // Register plugins again foreach ($plugins as $plugin) { $this->plugin($plugin['plugin'], $plugin['configuration']); } // Get the registered events $hooks = (array) $this->rocketeer->getOption('hooks'); unset($hooks['custom']); // Bind events foreach ($hooks as $event => $tasks) { foreach ($tasks as $task => $listeners) { $this->addTaskListeners($task, $event, $listeners, 0, true); } } } /** * Register listeners for a particular event. * * @param string $event * @param array|callable $listeners * @param int $priority * * @return string */ public function listenTo($event, $listeners, $priority = 0) { /** @var AbstractTask[] $listeners */ $listeners = $this->builder->buildTasks((array) $listeners); // Register events foreach ($listeners as $listener) { $listener->setEvent($event); $this->events->listen('rocketeer.'.$event, [$listener, 'fire'], $priority); } return $event; } /** * Bind a listener to a task. * * @param string|array $task * @param string $event * @param array|callable $listeners * @param int $priority * @param bool $register * * @throws \Rocketeer\Exceptions\TaskCompositionException * * @return string|null */ public function addTaskListeners($task, $event, $listeners, $priority = 0, $register = false) { // Recursive call if (is_array($task)) { foreach ($task as $t) { $this->addTaskListeners($t, $event, $listeners, $priority, $register); } return; } // Prevent events on anonymous tasks $slug = $this->builder->buildTask($task)->getSlug(); if ($slug === 'closure') { return; } // Get event name and register listeners $event = $slug.'.'.$event; $event = $this->listenTo($event, $listeners, $priority); // Store registered event if ($register) { $this->registeredEvents[] = $event; } return $event; } /** * Get all of a task's listeners. * * @param string|AbstractTask $task * @param string $event * @param bool $flatten * * @return array */ public function getTasksListeners($task, $event, $flatten = false) { // Get events $task = $this->builder->buildTaskFromClass($task)->getSlug(); $events = $this->events->getListeners('rocketeer.'.$task.'.'.$event); // Flatten the queue if requested foreach ($events as $key => $event) { $task = $event[0]; if ($flatten && $task instanceof Tasks\Closure && $stringTask = $task->getStringTask()) { $events[$key] = $stringTask; } elseif ($flatten && $task instanceof AbstractTask) { $events[$key] = $task->getSlug(); } } return $events; } //////////////////////////////////////////////////////////////////// /////////////////////////////// PLUGINS //////////////////////////// //////////////////////////////////////////////////////////////////// /** * @return array */ public function getRegisteredPlugins() { return $this->registeredPlugins; } /** * Register a Rocketeer plugin with Rocketeer. * * @param string $plugin * @param array $configuration */ public function plugin($plugin, array $configuration = []) { // Build plugin if (is_string($plugin)) { $plugin = $this->app->make($plugin, [$this->app]); } // Store registration of plugin $identifier = get_class($plugin); if (isset($this->registeredPlugins[$identifier])) { return; } $this->registeredPlugins[$identifier] = [ 'plugin' => $plugin, 'configuration' => $configuration, ]; // Register configuration $vendor = $plugin->getNamespace(); $this->config->package('rocketeers/'.$vendor, $plugin->configurationFolder); if ($configuration) { $this->config->set($vendor.'::config', $configuration); } // Bind instances $this->app = $plugin->register($this->app); // Add hooks to TasksHandler $plugin->onQueue($this); } }
true
277be563056694d905da160a8193a6efa1a109c0
PHP
ymihaylov/Football_Manager_OOP
/Modules/Database.php
UTF-8
761
2.890625
3
[]
no_license
<?php class Database { protected $database_name = 'FootballManager'; protected $host = 'localhost'; protected $username_db = 'yavcho_despark'; protected $password_db = 'quadro0'; public $connection; protected static $instance = null; protected function __construct() { $this->connection = new mysqli($this->host, $this->username_db, $this->password_db, $this->database_name); if($this->connection->connect_error){ die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } // FIX Cyrillic $this->connection->query("SET NAMES UTF8"); } public static function getInstance() { if(self::$instance === null) { self::$instance = new self(); } return self::$instance; } }
true
c77aef67e581bb7080d9f98cb06cb309b5bca5d4
PHP
dianamontes1516/PHP-OO
/Curso11-12/Persona.php
ISO-8859-1
3,120
3.875
4
[]
no_license
<?php class Persona { /** * Clase que abstrae a una persona * Esta clase contiene el nombre y el contacto (email) **/ /** * Variable esttica de numero de personas creadas * @var nombre */ private static $poblacion = 0; /** * Primer nombre de la persona * @var nombre */ private $nombre; /** * Apellido paterno de la persona * @var apellidoPaterno */ private $apellido_paterno; /** * Apellido materno de la persona * @var apellidoMaterno */ private $apellido_materno; /** * Correo electrónico de la persona * @var correoElectronico */ private $correo; /** * Método constructor de la persona * @param nombre - de la persona * @param apellidoPaterno - de la persona * @param apellidoMaterno - de la persona * @param correoElectronico - de la persona **/ public function __construct($nombre, $apellidoPaterno, $apellidoMaterno, $correoElectronico){ $this->nombre=$nombre; $this->apellido_paterno=$apellidoPaterno; $this->apellido_materno=$apellidoMaterno; $this->correo=$correoElectronico; self::$poblacion++; } /** * Método que de acceso a la variable esttica poblacion * @return nombre de la persona **/ public static function getPoblacion(){ return self::$poblacion; } /** * Método que regresa el primer nombre de la persona * @return nombre de la persona **/ public function getNombre() { return $this->nombre; } /** * Método que regresa el apellido paterno de la persona * @return apellido paterno **/ public function getApellidoPaterno() { return $this->apellido_paterno; } /** * Método que regresa el apellido materno de la persona * @return apellido materno **/ public function getApellidoMaterno() { return $this->apellido_materno; } /** * Método que regresa el correo de la persona * @return correo electrónico de la persona **/ public function getCorreo() { return $this->$correo; } /** * Método que asigna nombre a la persona **/ public function setNombre($nuevoNombre) { $this->nombre = $nuevoNombre; } /** * Método que asigna apellido paterno de la persona **/ public function setApellidoPaterno($nuevoAP) { $this->apellido_paterno = $nuevoAP; } /** * Método que asigna apellido materno de la persona **/ public function setApellidoMaterno($nuevoAM) { $this->apellido_materno = $nuevoAM; } /** * Método que asina correo de la persona **/ public function setCorreo($nuevoCorreo) { $this->$correo = $nuevoCorreo; } /** * Método destructor **/ public function __destruct(){ echo "R.I.P.: ".$this->nombre; } /** * Método para saludar * @param nombre - recibe una cadena **/ public function saludaA($nombre){ return "Hola " . $nombre . "</br>"; } }
true
c6f44497f2c57136e2482b020ea84bb2fe512e62
PHP
codelego/phpfox-pf5
/app/library/phpfox-view/src/HeadMeta.php
UTF-8
652
2.984375
3
[]
no_license
<?php namespace Phpfox\View; class HeadMeta implements HtmlElementInterface { /** * @var array */ protected $data = []; /** * @param string $name * @param array $props */ public function add($name, $props = []) { $this->data[$name] = $props; } public function clear() { $this->data = []; } /** * @return string */ public function getHtml() { if (!$this->data) { return ''; } return implode(PHP_EOL, array_map(function ($v) { return '<meta ' . _attrize($v) . '/>'; }, $this->data)); } }
true
5cc38606980bb0ebd69f0eaaaabb33f7ce0b6301
PHP
PHPfrank/origin
/app/Repositories/Traits/BaseRepositoryTrait.php
UTF-8
8,448
2.703125
3
[]
no_license
<?php namespace App\Repositories\Traits; use Illuminate\Support\Facades\DB; /** * Created by PhpStorm. * User: frank * Date: 2018/12/3 * Time: 10:43 */ trait BaseRepositoryTrait { /** * 根据条件获取一条数据 * @param array $where * @param array $columns * @return mixed * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function firstWhere(array $where, $columns = ['*']){ $this->applyCriteria(); $this->applyScope(); $this->applyConditions($where); $model = $this->model->first($columns); $this->resetModel(); return $this->parserResult($model); } /** * 根据条件获取最新一条数据 * @param array $where * @param array $columns * @param string $orderBy * @param string $desc * @return mixed * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function firstWhereNew(array $where,$columns = ['*'],$orderBy="id",$desc="desc"){ $this->applyCriteria(); $this->applyScope(); $this->applyConditions($where); $model = $this->model->orderBy($orderBy,$desc)->first($columns); $this->resetModel(); return $this->parserResult($model); } /** * 根据条件更新 * @param array $where * @param array $data * @return mixed * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function updateWhere(array $where,array $data){ $this->applyCriteria(); $this->applyScope(); $this->applyConditions($where); $model = $this->model->update($data); $this->resetModel(); return $this->parserResult($model); } /** * 根据多条件更新 * @param $field * @param array $values * @param array $data * @return mixed * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function updateWhereIn($field,array $values,array $data){ $this->applyCriteria(); $this->applyScope(); $model = $this->model->whereIn($field,$values)->update($data); $this->resetModel(); return $this->parserResult($model); } /** * 根据where数组获取列表 * @param $where * @param null $orderRaw * @param array $columns * @param int $page * @param int $limit * @return mixed */ public function getWhereList(array $where,$orderRaw=null,$columns=['*'],$page=1,$limit=10) { if ($orderRaw == null){ $orderRaw = "id desc"; } $result['list'] = $this->model ->where($where) ->orderByRaw($orderRaw) ->select($columns) ->forPage($page, $limit) ->get(); $result['count'] = $this->model ->where($where) ->count(); return $result; } /** * 根据whereRaw条件获取列表 * @param $where * @param null $orderRaw * @param array $columns * @param int $page * @param int $limit * @return mixed */ public function getWhereListByLaw($where,$orderRaw=null,$columns=['*'],$page=1,$limit=10){ if ($orderRaw == null){ $orderRaw = "id desc"; } $result['list'] = $this->model ->whereRaw($where) ->orderByRaw($orderRaw) ->select($columns) ->forPage($page, $limit) ->get(); $result['count'] = $this->model ->whereRaw($where) ->count(); return $result; } /** * 多选删除 * @param array $data * @param string $id * @return mixed */ public function delWhereIn(array $data,$id=""){ if (empty($id)){ $id = "id"; } $result = $this->model->whereIn($id, $data)->delete(); return $result; } /** * whereIn查询 * @param $field * @param array $value * @param array $columns * @return mixed */ public function getByWhereIn($field, array $value, $columns = ['*']) { return $this->model->whereIn($field, $value)->get($columns); } /** * 根据key或者最大 * @param string $data * @return mixed */ public function getMax($data='id'){ $result = $this->model->max($data); return $result; } /** * 根据条件获取count总数 * @param array $where * @return mixed */ public function getCount(array $where){ $result = $this->model->where($where)->count(); return $result; } /** * 根据条件获取不在count总数 * @param array $where * @param $field * @param array $values * @param array $columns * @return mixed * @throws \Prettus\Repository\Exceptions\RepositoryException */ public function getCountNotIn(array $where,$field,array $values,$columns=['*']){ $this->applyCriteria(); $this->applyScope(); $model = $this->model->where($where)->whereNotIn($field, $values)->count($columns); $this->resetModel(); return $this->parserResult($model); } /** * 计算总和 * @param array $where * @param string $parameter * @return mixed */ public function getSum(array $where,$parameter=""){ return $this->model->where($where)->sum($parameter); } /** * 设置递增 * @param array $where * @param array $data * @return bool */ public function setIncrement(array $where,array $data){ if (is_array($data)){ foreach ($data as $key => $value){ return $this->model->where($where)->increment($key,$value); } } return false; } /** * 设置递减 * @param array $where * @param array $data * @return bool */ public function setDecrement(array $where,array $data){ if (is_array($data)){ foreach ($data as $key => $value){ return $this->model->where($where)->decrement($key,$value); } } return false; } public function wherePaginate(array $where,$columns = ['*'],$limit=null,$method = "paginate"){ $this->applyCriteria(); $this->applyScope(); $limit = is_null($limit) ? config('repository.pagination.limit', 15) : $limit; $results = $this->model->where($where)->{$method}($limit, $columns); $results->appends(app('request')->query()); $this->resetModel(); return $this->parserResult($results); } public function whereRawPaginate($where,$columns = ['*'],$limit=null,$method = "paginate"){ $this->applyCriteria(); $this->applyScope(); $limit = is_null($limit) ? config('repository.pagination.limit', 15) : $limit; $results = $this->model->whereRaw($where)->{$method}($limit, $columns); $results->appends(app('request')->query()); $this->resetModel(); return $this->parserResult($results); } /** * 批量更新 * 批量之前需要确保in里面的key不重复,否则后面一个不更新 * @param string $tableName * @param array $multipleData * @return bool|int */ public function updateBatch($tableName = "",$multipleData = array()){ if ($tableName && !empty($multipleData)){ $updateColumn = array_keys($multipleData[0]); $referenceColumn = $updateColumn[0]; unset($updateColumn[0]); $whereIn = ""; $query = "UPDATE ".$tableName." SET "; foreach ($updateColumn as $item){ $query .= $item." = CASE "; foreach ($multipleData as $data){ $query .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$item]."' "; } $query .= "ELSE ".$item." END, "; } foreach ($multipleData as $data){ $whereIn .= "'".$data[$referenceColumn]."', "; } $query = rtrim($query,", ")." WHERE ".$referenceColumn." IN (".rtrim($whereIn,', ').")"; return DB::update(DB::raw($query)); }else{ return false; } } }
true
200841f39b5c8df46ea336f5fcda05d8456c2ac8
PHP
EmptyWave/test-order-api
/src/Dto/Api/ResponseData.php
UTF-8
466
2.765625
3
[]
no_license
<?php namespace App\Dto\Api; use App\Dto\DataTransferObject; class ResponseData extends DataTransferObject { /** @var array $body */ public $body; /** @var int $statusCode */ public $statusCode; /** * @return array|null */ public function getBody(): ?array { return $this->body; } /** * @return int|null */ public function getStatusCode(): ?int { return $this->statusCode; } }
true
c6c8ef854f7cdda0ac15d5042ea7a8427996ce6a
PHP
korhankonaray/FileTypeDetector
/dataset/php/repeater-class.php
UTF-8
14,247
2.703125
3
[ "DOC" ]
permissive
<?php /** * swing lite customizer repeater class * * * @package swing */ if( class_exists('WP_Customize_Control')): /** * Repeater Custom Control */ class swing_lite_Repeater_Controler extends WP_Customize_Control { /** * The control type. * * @access public * @var string */ public $type = 'repeater'; public $swing_lite_box_label = ''; //public $swing_lite_box_add_control = ''; public $no_of_options = 1; private $cats = ''; private $pages = ''; /** * The fields that each container row will contain. * * @access public * @var array */ public $fields = array(); /** * Repeater drag and drop controler * * @since 1.0.0 */ public function __construct( $manager, $id, $args = array(), $fields = array() ) { $this->fields = $fields; $this->swing_lite_box_label = $args['swing_lite_box_label'] ; //$this->swing_lite_box_add_control = $args['swing_lite_box_add_control']; $this->cats = get_categories(array( 'hide_empty' => false )); $this->pages = get_pages(array('post_type' => 'page')); parent::__construct( $manager, $id, $args ); } public function render_content() { $values = json_decode($this->value()); ?> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <?php if($this->description){ ?> <span class="description customize-control-description"> <?php echo wp_kses_post($this->description); ?> </span> <?php } ?> <ul class="swing-repeater-field-control-wrap"> <?php $this->swing_lite_get_fields(); ?> </ul> <input type="hidden" <?php esc_attr( $this->link() ); ?> class="swing-repeater-collector" value="<?php echo esc_attr( $this->value() ); ?>" /> <?php /*<button type="button" class="button swing-add-control-field"><?php echo esc_html( $this->swing_lite_box_add_control ); ?></button> */ ?> <?php } private function swing_lite_get_fields(){ $fields = $this->fields; $no_of_options = $this->no_of_options; $values = json_decode($this->value()); if(is_array($values)){ for( $i = 0; $i < $no_of_options; $i++ ){ ?> <li class="swing-repeater-field-control"> <h3 class="swing-repeater-field-title"><?php echo esc_html( $this->swing_lite_box_label ); ?></h3> <div class="swing-repeater-fields"> <?php foreach ($fields as $key => $field) { $class = isset($field['class']) ? $field['class'] : ''; ?> <div class="swing-fields swing-type-<?php echo esc_attr($field['type']) . ' ' . esc_attr($class); ?>"> <?php $label = isset($field['label']) ? $field['label'] : ''; $description = isset($field['description']) ? $field['description'] : ''; if($field['type'] != 'checkbox'){ ?> <span class="customize-control-fields"><?php echo esc_html( $label ); ?></span> <span class="description customize-control-description"><?php echo esc_html( $description ); ?></span> <?php } $new_value = isset($values[$i]->$key) ? $values[$i]->$key : ''; $default = isset($field['default']) ? $field['default'] : ''; switch ($field['type']) { case 'text': echo '<input data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'" type="text" value="'.esc_attr($new_value).'"/>'; break; case 'url': echo '<input data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'" type="url" value="'.esc_url_raw($new_value).'"/>'; break; case 'number': echo '<input data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'" type="number" value="'.esc_attr($new_value).'"/>'; break; case 'textarea': echo '<textarea data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'">'.esc_textarea($new_value).'</textarea>'; break; case 'upload': $image = $image_class= ""; if($new_value){ $image = '<img src="'.esc_url_raw($new_value).'" style="max-width:100%;"/>'; $image_class = ' hidden'; } echo '<div class="swing-fields-wrap">'; echo '<div class="attachment-media-view">'; echo '<div class="placeholder'.esc_attr($image_class).'">'; esc_html_e('No image selected', 'swing-lite'); echo '</div>'; echo '<div class="thumbnail thumbnail-image">'; echo wp_kses_post($image); echo '</div>'; echo '<div class="actions clearfix">'; echo '<button type="button" class="button swing-delete-button align-left">'.esc_html__('Remove', 'swing-lite').'</button>'; echo '<button type="button" class="button swing-upload-button alignright">'.esc_html__('Select Image', 'swing-lite').'</button>'; echo '<input data-default="'.esc_attr($default).'" class="upload-id" data-name="'.esc_attr($key).'" type="hidden" value="'.esc_attr($new_value).'"/>'; echo '</div>'; echo '</div>'; echo '</div>'; break; case 'category': echo '<select data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'">'; echo '<option value="0">'.esc_html__('Select Category', 'swing-lite').'</option>'; echo '<option value="-1">'.esc_html__('Latest Posts', 'swing-lite').'</option>'; foreach ( $this->cats as $cat ) { printf('<option value="%s" %s>%s</option>', esc_attr($cat->term_id), selected($new_value, $cat->term_id, false), esc_html($cat->name)); } echo '</select>'; break; case 'select': $options = $field['options']; echo '<select data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'">'; foreach ( $options as $option => $val ) { printf('<option value="%s" %s>%s</option>', esc_attr($option), selected($new_value, $option, false), esc_html($val)); } echo '</select>'; break; case 'checkbox': echo '<label>'; echo '<input data-default="'.esc_attr($default).'" value="' . esc_attr($new_value) . '" data-name="'.esc_attr($key).'" type="checkbox" '.checked($new_value, 'yes', false).'/>'; echo esc_html( $label ); echo '<span class="description customize-control-description">'.esc_html( $description ).'</span>'; echo '</label>'; break; case 'colorpicker': echo '<input data-default="'.esc_attr($default).'" class="swing-color-picker" data-alpha="true" data-name="'.esc_attr($key).'" type="text" value="'.esc_attr($new_value).'"/>'; break; case 'page': echo '<select data-default="'.esc_attr($default).'" data-name="'.esc_attr($key).'">'; echo '<option value="0">'.esc_html__('Select Page', 'swing-lite').'</option>'; foreach ( $this->pages as $page ) { printf('<option value="%s" %s>%s</option>', esc_attr($page->ID), selected($new_value, $page->ID, false), esc_html($page->post_title)); } echo '</select>'; break; case 'selector': $options = $field['options']; echo '<div class="selector-labels">'; foreach ( $options as $option => $val ){ $class = ( $new_value == $option ) ? 'selector-selected': ''; echo '<label class="'. esc_attr($class) . '" data-val="'.esc_attr($option).'">'; echo '<img src="'.esc_url($val).'"/>'; echo '</label>'; } echo '</div>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; break; case 'radio': $options = $field['options']; echo '<div class="radio-labels">'; foreach ( $options as $option => $val ){ echo '<label>'; echo '<input value="'.esc_attr($option).'" type="radio" '.checked($new_value, $option, false).'/>'; echo wp_kses_post($val); echo '</label>'; } echo '</div>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; break; case 'switch': $switch = $field['switch']; $switch_class = ($new_value == 'on') ? 'switch-on' : ''; echo '<div class="onoffswitch ' . esc_attr($switch_class) . '">'; echo '<div class="onoffswitch-inner">'; echo '<div class="onoffswitch-active">'; echo '<div class="onoffswitch-switch">'.esc_html($switch["on"]).'</div>'; echo '</div>'; echo '<div class="onoffswitch-inactive">'; echo '<div class="onoffswitch-switch">'.esc_html($switch["off"]).'</div>'; echo '</div>'; echo '</div>'; echo '</div>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; break; case 'range': $options = $field['options']; $new_value = $new_value ? $new_value : $options['val']; echo '<div class="swing-range-slider" >'; echo '<div class="range-input" data-defaultvalue="'. esc_attr($options['val']) .'" data-value="' . esc_attr($new_value) . '" data-min="' . esc_attr($options['min']) . '" data-max="' . esc_attr($options['max']) . '" data-step="' . esc_attr($options['step']) . '"></div>'; echo '<input class="range-input-selector" type="text" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; echo '<span class="unit">' . esc_html($options['unit']) . '</span>'; echo '</div>'; break; case 'icon': echo '<div class="swing-selected-icon clearfix">'; echo '<i class="'.esc_attr($new_value).'"></i>'; echo '<span><i class="fa fa-chevron-down"></i></span>'; echo '</div>'; echo '<ul class="swing-icon-list clearfix">'; $swing_lite_icons_array = swing_lite_icons_array(); foreach ($swing_lite_icons_array as $swing_lite_font_awesome_icon) { $icon_class = $new_value == $swing_lite_font_awesome_icon ? 'icon-active' : ''; echo '<li class=' . esc_attr($icon_class) . '><i class="fa ' . esc_attr($swing_lite_font_awesome_icon) . '"></i></li>'; } echo '</ul>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; break; case 'all_icon': echo '<div class="swing-selected-icon clearfix">'; echo '<i class="'.esc_attr($new_value).'"></i>'; echo '<span><i class="fa fa-chevron-down"></i></span>'; echo '</div>'; echo '<ul class="swing-icon-list clearfix">'; $swing_lite_icons_array = swing_lite_all_icons_array(); foreach ($swing_lite_icons_array as $swing_lite_font_awesome_icon) { $icon_class = $new_value == $swing_lite_font_awesome_icon ? 'icon-active' : ''; echo '<li class=' . esc_attr($icon_class) . '><i class="fa ' . esc_attr($swing_lite_font_awesome_icon) . '"></i></li>'; } echo '</ul>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr($new_value).'" data-name="'.esc_attr($key).'"/>'; break; case 'multicategory': $new_value_array = !is_array( $new_value ) ? explode( ',', $new_value ) : $new_value; echo '<ul class="swing-multi-category-list">'; echo '<li><label><input type="checkbox" value="-1" '. checked('-1', $new_value, false ) .'/>'.esc_html__( 'Latest Posts', 'swing-lite' ).'</label></li>'; foreach ( $this->cats as $cat ){ $checked = in_array( $cat->term_id, $new_value_array) ? 'checked="checked"' : ''; echo '<li>'; echo '<label>'; echo '<input type="checkbox" value="'.esc_attr($cat->term_id).'" '. esc_attr($checked) .'/>'; echo esc_html( $cat->name ); echo '</label>'; echo '</li>'; } echo '</ul>'; echo '<input data-default="'.esc_attr($default).'" type="hidden" value="'.esc_attr(implode( ',', $new_value_array )).'" data-name="'.esc_attr($key).'"/>'; break; default: break; } ?> </div> <?php } ?> <div class="clearfix swing-repeater-footer"> <div class="alignright"> <a class="swing-repeater-field-remove" href="#remove"><?php esc_html_e('Delete', 'swing-lite') ?></a> | <a class="swing-repeater-field-close" href="#close"><?php esc_html_e('Close', 'swing-lite') ?></a> </div> </div> </div> </li> <?php } } } } endif;
true
fe9f86d45946880cf441c2f6ce196ae38e99be82
PHP
lamu88/cgwx
/addons/netbuffer_domainsearch/ShowApi.class.php
UTF-8
3,371
2.59375
3
[]
no_license
<?php class ShowApiSdk { static $showapi_appid = '9958'; static $showapi_sign = '9fc7866fc5f14196859b38002f42b24f'; static function createSign($paramArr) { $sign = ""; ksort($paramArr); foreach ($paramArr as $key => $val) { if ($key != '' && $val != '') { $sign .= $key . $val; } } $sign .= ShowApiSdk::$showapi_sign; $sign = strtoupper(md5($sign)); return $sign; } static function createStrParam($paramArr) { $strParam = ''; foreach ($paramArr as $key => $val) { if ($key != '' && $val != '') { $strParam .= $key . '=' . urlencode($val) . '&'; } } return $strParam; } static function getContent() { $paramArr = array( 'showapi_appid' => ShowApiSdk::$showapi_appid, 'time' => date('Y-m-d'), 'page' => '', 'maxResult' => '50', 'showapi_timestamp' => date('YmdHis') ); $sign = ShowApiSdk::createSign($paramArr); $strParam = ShowApiSdk::createStrParam($paramArr); $strParam .= 'showapi_sign=' . $sign; $url = 'http://route.showapi.com/341-1?' . $strParam; $result = file_get_contents($url); $result = json_decode($result); if (intval($result->showapi_res_code) == 0) { var_dump(count($result->showapi_res_body->contentlist)); echo $result->showapi_res_body->contentlist[0]->text; } else { var_dump('失败了'); } } static function getIDInfo($id) { $paramArr = array( 'showapi_appid' => ShowApiSdk::$showapi_appid, 'id' => $id, 'showapi_timestamp' => date('YmdHis') ); $sign = ShowApiSdk::createSign($paramArr); $strParam = ShowApiSdk::createStrParam($paramArr); $strParam .= 'showapi_sign=' . $sign; $url = 'http://route.showapi.com/25-3?' . $strParam; $result = file_get_contents($url); $result = json_decode($result); if (intval($result->showapi_res_code) == 0) { if ($result->showapi_res_body->retMsg == "success") { return $result->showapi_res_body->retData; } } else { return ''; } } static function getDomainInfo($domain) { $paramArr = array( 'showapi_appid' => ShowApiSdk::$showapi_appid, 'domain' => $domain, 'showapi_timestamp' => date('YmdHis') ); $sign = ShowApiSdk::createSign($paramArr); $strParam = ShowApiSdk::createStrParam($paramArr); $strParam .= 'showapi_sign=' . $sign; $url = 'http://route.showapi.com/846-1?' . $strParam; $result = file_get_contents($url); $result = json_decode($result); if (intval($result->showapi_res_code) == 0) { if ($result->showapi_res_error == "") { return $result->showapi_res_body->obj; } } else { return ''; } } static function endWith($haystack, $needle) { $length = strlen($needle); if ($length == 0) { return true; } return (substr($haystack, -$length) === $needle); } }
true
8b7d769b73d37994f220bb9209f76961a3cb4c52
PHP
Lucerno/nextwab
/nextwab.class.php
UTF-8
4,317
2.78125
3
[]
no_license
<?php /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * fichier : nextwab.class.php * version : 0.1 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * author : LucernoPower * copyright : (C) 2017 LucernoPower * email : lucernopower@gmail.com * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ class Nextwab { private $email; private $pass; private $cleapi; private $cookie = "777/cookies.txt"; public function __construct() { return true; } public function connection($email, $pass, $cleapi) { global $cookie; $lien = 'https://www.nextwab.com/account/connect-trait.php'; $post = array( 'mail' => $email, 'password' => $pass ); $this->email = $email; $this->pass = $pass; $this->cleapi = $cleapi; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $lien); curl_setopt($curl, CURLOPT_COOKIESESSION, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); //curl_setopt($curl, CURLOPT_COOKIEJAR, realpath($cookie)); curl_setopt($curl, CURLOPT_COOKIE, $cookie); curl_setopt($curl, CURLOPT_HTTPHEADER, ['Accept-Language: fr']); curl_setopt($curl, CURLOPT_USERAGENT,'LucernoPower\'s Bot'); $retour = curl_exec($curl); curl_close($curl); if(strpos($retour, "Mon Panel Client")){ return true; }else{ return $retour; } } public function statusdomaine($domaine){ global $cookie; $url = 'https://www.nextwab.com/domaines/ajax-domain_check_index.php'; $array = explode('.', $domaine); $post = array( 'domain' => $domaine, 'extension' => $array[1] ); $retour = $this->request($url, "POST", $post); if(strpos($retour, "semble disponible")){ return true; }else{ return false; } } public function envoyersms($nom, $numero, $message){ global $cookie; //https://www.nextwab.com/forum/sources/432-api-php-envoyer-un-sms-a-partir-de-son-site-web.html $Configuration = array( 'user_mail' => $this->email, 'user_password' => $this->cleapi, 'Nom' => $nom, //11 Caracteres maxi 'Numero' => $numero, 'Message' => $message, 'Action' => "Send" ); $POST_Chaine = ""; foreach($Configuration as $Cle => $Valeur) {$POST_Chaine .= $Cle.'='.$Valeur.'&amp;';} rtrim($POST_Chaine, '&amp;'); $url="http://api.nextwab.com/sms/"; $retour = $this->request($url, "POST", $POST_Chaine); return $retour; } public function prixsms($nom, $numero, $message){ global $cookie; //https://www.nextwab.com/forum/sources/432-api-php-envoyer-un-sms-a-partir-de-son-site-web.html $Configuration = array( 'user_mail' => $this->email, 'user_password' => $this->cleapi, 'Nom' => $nom, //11 Caracteres maxi 'Numero' => $numero, 'Message' => $message, 'Pricing' => "Send" ); $POST_Chaine = ""; foreach($Configuration as $Cle => $Valeur) {$POST_Chaine .= $Cle.'='.$Valeur.'&amp;';} rtrim($POST_Chaine, '&amp;'); $url="http://api.nextwab.com/sms/"; $retour = $this->request($url, "POST", $POST_Chaine); return $retour; } public function commanderdomaine($domaine){ global $cookie; $url = 'https://www.nextwab.com/account/reserve_domain?domain='.$domaine.'&action=create'; $retour = $this->request($url, "GET", null); return $retour; } private function request($url, $method, $post) { global $cookie; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_COOKIESESSION, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_COOKIEFILE, realpath($cookie)); curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); if($method == "POST"){ curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $post); } curl_setopt($curl, CURLOPT_HTTPHEADER, ['Accept-Language: fr']); curl_setopt($curl, CURLOPT_USERAGENT,'LucernoPower\'s Bot'); $retour = curl_exec($curl); curl_close($curl); return $retour; } }
true
3ee39f987f1928d339a72f1cedff368bc39678ff
PHP
DenielWorld/TechMine-PM
/src/DenielWorld/TechMinePM/managers/Manager.php
UTF-8
630
3.0625
3
[ "Apache-2.0" ]
permissive
<?php namespace DenielWorld\TechMinePM\managers; use DenielWorld\TechMinePM\Main; use http\Exception\InvalidArgumentException; class Manager{ protected $type; private $plugin; public function __construct(Main $plugin, string $type) { $this->type = $type; $this->plugin = $plugin; if($type == "BlockManager"){ return new BlockManager($plugin, $type); } else { throw new InvalidArgumentException("Non-existing manager type was provided as the second argument"); } } public function getType(){ return $this->type; } }
true
1ec78a67d107d579146566aadd76cfd23f5ed2ce
PHP
VladimirMolkin/First-Project
/PHP/cli/pdo/pdo.connect.mysql.errormode.test.php
UTF-8
1,449
2.84375
3
[ "MIT" ]
permissive
<?php // pdo.connect.mysql.errormode.test.php // example of PDO MySQL connection $host = "localhost"; $user = "root"; $pass = "ghbdtn"; $dbname = "store"; // PDO::ERRMODE_EXCEPTION // В большинстве ситуаций этот тип контроля выполнения скрипта предпочтителен. Он выбрасывает исключение, что позволяет вам ловко обрабатывать ошибки и скрывать щепетильную информацию. Как, например, тут: // подключаемся к базе данных try { $pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Oops! Набрал DELECT вместо SELECT! $pdo->prepare('DELECT name FROM posts')->execute(); } catch(PDOException $e) { // В SQL-выражении есть синтаксическая ошибка, которая вызовет исключение. Мы можем записать детали ошибки в лог-файл и человеческим языком намекнуть пользователю, что что-то случилось. echo "SQL, у нас проблемы.\n"; error_log($e->getMessage()); file_put_contents('PDOErrors.log', $e->getMessage(), FILE_APPEND); } catch (Throwable $e) { error_log($e->getMessage()); }
true
532ec12ea763fa243ac7ad43df222444580ccde0
PHP
courtney-miles/schnoop
/src/SchemaFactory/MySQL/DataType/BlobTypeFactory.php
UTF-8
482
2.6875
3
[ "MIT" ]
permissive
<?php namespace MilesAsylum\Schnoop\SchemaFactory\MySQL\DataType; use MilesAsylum\SchnoopSchema\MySQL\DataType\BlobType; class BlobTypeFactory implements DataTypeFactoryInterface { public function createType($typeStr, $collation = null) { if (!$this->doRecognise($typeStr)) { return false; } return new BlobType(); } public function doRecognise($typeStr) { return 1 === preg_match('/^blob$/i', $typeStr); } }
true
b97cae026330e979b21aa75b8e7e08c115857e09
PHP
shadysherifsayed/laravel-vue-notes-app
/database/factories/NoteFactory.php
UTF-8
2,259
2.671875
3
[]
no_license
<?php use Faker\Generator as Faker; $factory->define(App\Note::class, function (Faker $faker) { $title = $faker->sentence; $description = htmlspecialchars( "<h1>A Guide to Solving Web Development Problems</h1> <p>This is mainly about how to solve technical problems that arise from using front or back end technologies to make web pages or web apps but some of these steps will be applicable to solving technical problems in general.</p> <p>Half the technical problems in web development are caused by something trivial like forgetting a semi-colon somewhere and are usually easily solvable if you've had your coffee but for all the problems past this level, you'll probably need to do some structured thinking.</p> <h2> The Web Development Troubleshooting Steps Summary</h2> <p>1. Define the problem that you're trying to solve. If you're not asking exactly the right question then you're not going to get exactly the right answer.</p> <p>2. Verify the problem exists. Make sure it's really a problem by replicating the error on more than one machine.</p> <p>3. Gather additional information about the problem. Use a javascript debugger, fiddler or any other common tool to get additional clues about the nature of the problem.</p> <p>4. Back-up your work before making even a single teeny tiny little change. Don't make things worse when trying to fix the problem. Keep a back-up so you can roll back if you have to.</p> <p>5. Review your past experiences versus the present situation. Have you encountered a similar problem in the past, if so then test to see if your past approach will fix the problem at hand.</p> <p>6. Search for people who've been in similar situations and how they solved the problem. You have all the information you need so start using a search engine to find possible solutions.</p> <p>7. Make one change at a time (and then test it). Proceed methodically and if you make multiple changes at the same time then you often can't tell what worked or didn't work. So proceed step by step.</p>" ); return [ 'title' => $title, 'description' => $description, 'slug' => str_slug($title) ]; });
true
121cacdaedae788cd93cfb5a6a663cc2e7e2e91b
PHP
odaydev/MFF
/PostIt/contact.php
UTF-8
710
2.640625
3
[]
no_license
<?php session_start(); include 'includes/functions.php'; $result = isIsset($_POST); if($result == "true"){ $name = $_POST['name']; $email = $_POST['email']; $adresse = $_POST['adresse']; $message = $_POST['message']; $date = date("d-m-Y H:i:s"); $msg = "\r\n\r\n"; $msg .= $date."\r\n".$name."\r\n".$email."\r\n".$adresse."\r\n".$message; $monfichier = fopen('contact\contacts.txt', 'a+'); //fseek($monfichier, 0); fputs($monfichier, $msg); fclose($monfichier); $return[0] = 1; $return[1] = "Votre message a bien été transmis ! "; }else{ $return[0] = 2; $return[1] = "Erreur lors de la transmission du message ! "; } displayInfo($return); header('Location:index.php#contact-form');
true
877a6e2152b483b90fce46551c2b2ef6fe4606e4
PHP
camgeek/projetsEtna
/PHPmyadmin_2/vues/v_del_ligne.php
UTF-8
597
2.515625
3
[]
no_license
<div class="container"> <h1> Supprimer une ligne : </h1> <?php $key = ""; foreach ($values as $value) { foreach ($value as $key1 => $val) { if (!is_numeric($key1)) { echo "Colone ".$key1." Valeur :".$val." ||"; if ($key == "") $key = $key1; } } ?> <input type="button" value="Supprimer la ligne" onclick="javascript:location.href='index.php?choix=c_gest_ligne&action=delligne&info=<?php echo $value[0]?>&name=<?php echo $key?>'"><br> <?php $key = ""; } ?>
true
0251ba21d2aee984c0ec98164bbb715c0ecd36b0
PHP
cawitaz/Proyecto2014
/m_usuario/sql_select_usuario_insertar.php
UTF-8
1,740
3.015625
3
[]
no_license
<?php //Agregamos conexion a la base de datos include '../template/conexion.php'; //Si detecta post hacer operación if(isset($_POST['idUsuario'])){ //Obteniendo campos pasados por post $idUsuario = trim($_POST['idUsuario']); $nomUsuario = trim($_POST['nomUsuario']).' '.trim($_POST['apellUsuario']); $passUsuario = sha1(trim($_POST['passUsuario']));//Codificado con Sha1 longitud 40 $emailUsuario = trim($_POST['emailUsuario']); $tipoUsuario = $_POST['tipoUsuario'];//Array de valores //contar cantidad de elementos en el vector count($tipoUsuario) //$tipoUsuario[$i]; } //Si el usuario tiene el valor de 2 significa que debe de cambiar el password lo más pronto posible //Primera sentencia $sql1 = "INSERT INTO FVAM_usuario_2014 (AM_idUsuario,AM_nombreUsuario,AM_email,AM_contraUsuario,AM_estadoUsuario) VALUES('$idUsuario','$nomUsuario','$emailUsuario','$passUsuario','2');"; //Completando sentencias insert correspondientes a los perfiles $sql2=''; for ($j=0; $j < count($tipoUsuario); $j++) { $sql2 = "$sql2 INSERT INTO FVAM_auxUsuarioPerfil_2014 (AM_idUsuario,AM_idPerfil) VALUES('$idUsuario','".$tipoUsuario[$j]."');"; } //Haciendo un solo lote de sentencias insert... $sql = $sql1 . $sql2; //Asumiendo validación de información //Se define la variable como global, ya que sino se hace esto entonces //no se tiene acceso a dicha variable que se definio en el archivo conexion //Iniciamos de inserción en base de datos $msg=trim(insertar($sql)); //Verificando resultado if ($msg == 1) { $msg="\nSe inserto el usuario correctamente"; } else if ($msg == 2) { $msg="Este usuario ya existe en la base de datos"; } else { $msg="No se pudo insertar el usuario"; } //Enviando mensaje echo $msg; ?>
true
4a9f16f7f149b810cfdd727e106647b745202368
PHP
dvsa/olcs-backend
/module/Api/src/Service/Qa/Structure/Element/Custom/Ecmt/AnnualTripsAbroad.php
UTF-8
1,147
2.828125
3
[ "MIT" ]
permissive
<?php namespace Dvsa\Olcs\Api\Service\Qa\Structure\Element\Custom\Ecmt; use Dvsa\Olcs\Api\Service\Qa\Structure\Element\ElementInterface; use Dvsa\Olcs\Api\Service\Qa\Structure\Element\Text\Text; class AnnualTripsAbroad implements ElementInterface { /** @var int */ private $intensityWarningThreshold; /** @var bool */ private $showNiWarning; /** @var Text */ private $text; /** * Create instance * * @param int $intensityWarningThreshold * @param bool $showNiWarning * @param Text $text * * @return AnnualTripsAbroad */ public function __construct($intensityWarningThreshold, $showNiWarning, Text $text) { $this->intensityWarningThreshold = $intensityWarningThreshold; $this->showNiWarning = $showNiWarning; $this->text = $text; } /** * {@inheritdoc} */ public function getRepresentation() { return [ 'intensityWarningThreshold' => $this->intensityWarningThreshold, 'showNiWarning' => $this->showNiWarning, 'text' => $this->text->getRepresentation(), ]; } }
true
ed0a1b8184bd6c8995895e4de006ef76fb79dcdf
PHP
luispuentesvega/autospot
/app/Http/Controllers/UserController.php
UTF-8
764
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\User; use http\Env\Response; use Illuminate\Http\Request; use App\Http\Resources\User as UserResource; class UserController extends Controller { public function index() { //Get all users $users = User::get(); // Return a collection of $users with pagination return UserResource::collection($users); } public function create(Request $request) { $userData = $request->only([ 'firstname', 'lastname', ]); if (empty($userData['firstname']) && empty($userData['lastname'])) { return new \Exception('Missing data', 404); } return $userData['firstname'] . ' ' . $userData['lastname']; } }
true
f6f52c4060554516d715b16a5e6e7aca80476064
PHP
Wakeel03/social-distancing-detector-website
/lib/User.php
UTF-8
6,483
3.1875
3
[]
no_license
<?php class User{ private $db; public function __construct(){ $this->db = new Database; } // register a user public function register($firstname, $lastname, $username, $password, $email, $company_name){ $encrypted_password = hash('sha256', $password); try{ $this->db->query("INSERT INTO tb_user (firstname, lastname, username, password, email, company_name) VALUES (:firstname, :lastname, :username, :encrypted_password, :email, :company_name)"); $this->db->bind(":firstname", $firstname); $this->db->bind(":lastname", $lastname); $this->db->bind(":username", $username); $this->db->bind(":encrypted_password", $encrypted_password); $this->db->bind(":email", $email); $this->db->bind(":company_name", $company_name); $this->db->execute(); return $username; }catch(PDOException $e){ return $e->getMessage(); } } public function getCameras($username){ try{ $this->db->query("SELECT camera_id, camera_name FROM tb_cameras WHERE username=:username "); $this->db->bind(":username", $username); return $this->db->resultSet(); }catch(PDOException $e){ return $e->getMessage(); } } //login user public function login($username, $password){ $encrypted_password = hash('sha256', $password); try{ $this->db->query("SELECT * FROM tb_user WHERE username = :username AND password = :encrypted_password"); $this->db->bind(":username", $username); $this->db->bind(":encrypted_password", $encrypted_password); $result = $this->db->single(); if ($result){ return $result->username;//check }else{ return -1; } }catch(PDOException $e){ return $e->getMessage(); } } //found similar username public function foundSimilarUsername($username){ $this->db->query("SELECT username FROM tb_user WHERE username = :username"); $this->db->bind(":username", $username); $result = $this->db->resultSet(); if (count($result) > 0){ return true; } return false; } //update user limits public function add_user_level_limit($username, $first_level_limit, $second_level_limit, $third_level_limit, $fourth_level_limit, $fifth_level_limit){ try{ $this->db->query("UPDATE tb_user SET first_level_limit = :first_level_limit, second_level_limit= :second_level_limit, third_level_limit =:third_level_limit, fourth_level_limit=:fourth_level_limit, fifth_level_limit= :fifth_level_limit WHERE username = :username"); $this->db->bind(":username", $username); $this->db->bind(":first_level_limit", $first_level_limit); $this->db->bind(":second_level_limit", $second_level_limit); $this->db->bind(":third_level_limit", $third_level_limit); $this->db->bind(":fourth_level_limit", $fourth_level_limit); $this->db->bind(":fifth_level_limit", $fifth_level_limit); $this->db->execute(); return 1; }catch(PDOException $e){ return $e->getMessage(); } } //update user info public function updateProfile($username, $firstname, $lastname, $email, $company_name){ try{ $this->db->query("UPDATE tb_user SET firstname = :firstname, lastname = :lastname, email = :email, company_name = :company_name WHERE user_name = :username"); $this->db->bind(":email", $email); $this->db->bind(":firstname", $firstname); $this->db->bind(":lastname", $lastname); $this->db->bind(":username", $username); $this->db->bind(":company_name", $company_name); $this->db->execute(); return 1; }catch(PDOException $e){ return $e->getMessage(); } } //update user change password public function updatePassword($username, $newpassword){ $encrypted_password = hash('sha256', $newpassword); try{ $this->db->query("UPDATE tb_user SET passwors =:password WHERE user_name = :username"); $this->db->bind(":password", $encrypted_password); $this->db->bind(":username", $username); $this->db->execute(); return 1; }catch(PDOException $e){ return $e->getMessage(); } } // Get all Users public function getAllUsers(){ $this->db->query("SELECT * FROM tb_user"); // Assign result set $results = $this->db->resultSet(); return $results; } //get row by username public function getByUsername($username){ $this->db->query("SELECT FROM tb_user WHERE username = :username"); $this->db->bind(":username", $username); $results = $this->db->single(); return $results->user_id; } // Get all User's names public function getAllNames(){ $this->db->query("SELECT firstname, lastname FROM tb_user"); // Assign result set $results = $this->db->resultSet(); return $results; } //Get user's name by user_id public function getNameById($user_id){ $this->db->query("SELECT first_name, last_name FROM registered_users WHERE user_id = :user_id"); $this->db->bind(":user_id", $user_id); // Assign result set $results = $this->db->single(); return $results; } } ?>
true
ab60e8ad260d334542ee1ebdfa1202773627d68d
PHP
JohnAdib/dash
/addons/content_enter/home/controller.php
UTF-8
1,451
2.546875
3
[ "MIT" ]
permissive
<?php namespace addons\content_enter\home; class controller extends \addons\content_enter\main\controller { /** * check route of account * @return [type] [description] */ function _route() { // if the user login redirect to base if(\lib\permission::access('enter:another:session')) { // the admin can login by another session // never redirect to main } else { parent::if_login_not_route(); } // check remeber me is set // if remeber me is set: login! parent::check_remember_me(); // save all param-* | param_* in $_GET | $_POST $this->save_param(); if(self::get_request_method() === 'get') { $this->get(false, 'enter')->ALL(); } elseif(self::get_request_method() === 'post') { $this->post('enter')->ALL(); } else { self::error_method('home'); } } /** * Saves a parameter. * save all param-* in url into the session * */ public function save_param() { $post = \lib\utility::post(); $get = \lib\utility::get(null, 'raw'); $param = []; if(is_array($post) && is_array($get)) { $param = array_merge($get, $post); } if(!is_array($param)) { $param = []; } $save_param = []; foreach ($param as $key => $value) { if(preg_match("/^param(\-|\_)(.*)$/", $key, $split)) { if(isset($split[2])) { $save_param[$split[2]] = $value; } } } if(!empty($save_param)) { $_SESSION['param'] = $save_param; } } } ?>
true
69227fe6306bb4ecf010733c2d437c1c6d2e9447
PHP
samwilson/foodcoopstuff
/inc/request_new_password.php
UTF-8
1,773
2.65625
3
[]
no_license
<?php $Page['body'] .= "<div style='width:50%; margin:auto; text-align:justify'>"; if ($_POST['username']) { $sql = "SELECT * FROM people WHERE username=".dbesc($_POST['username'])." LIMIT 1"; $res = mysql_query($sql); if (mysql_num_rows($res) == 1) { $p = mysql_fetch_assoc($res); $newpwd = genpwd(); mysql_query("UPDATE people SET password=SHA1('$newpwd') WHERE username=".dbesc($_POST['username'])); $to = $p['email_address']; $subject = 'New password for the Food Co-op Stuff'; $message = " You requested a new password for the Food Coop Stuff; it is: $newpwd (your username, by the way, is ".$p['username'].") Log in at http://anu.foodco-op.com/stuff "; $headers = 'From: webmaster@anu.foodco-op.com'."\r\n"; if (!mail($to, $subject, $message, $headers)) { $Page['error_message'] .= "<p>Your password was reset, but an email couldn't be sent. Please try again.</p>"; } else { $Page['body'] .= "<p style='text-align:center'>An email has been sent to you containing your new password.</p>"; } } else { $Page['body'] .= "<p>That username is not registered. <a href='12'>Try again</a>.</p>"; } } else { $Page['body'] .= "<form action='12' method='post'> <p>Enter your username in the box below to have a new password sent to you. Your username is usually your full name with no spaces (e.g. Fred Smith would be fredsmith) and for some of you it's just your first name.</p> <p><input type='text' name='username' style='width:100%' /></p> <p class='submit'><input type='submit' name='newpwd' value='Get new password' /></p> </form>"; } $Page['body'] .= "</div>"; ?>
true
aa1122491af987596458df26db210e680d23693d
PHP
sampdubs/bar-mitzvah-website
/process.php
UTF-8
1,431
2.640625
3
[ "MIT" ]
permissive
<?php $servername = "localhost"; $username = "sampw"; $password = ""; $dbname = "formInfo_db"; $conn = mysqli_connect($servername, $username, $password, $dbname) or die(); function alert($msg) { echo '<script type="text/javascript">alert("' . $msg . '")</script>'; } $firstName = mysqli_real_escape_string($conn, $_POST["first-name"]); $lastName = mysqli_real_escape_string($conn, $_POST["last-name"]); $email = mysqli_real_escape_string($conn, $_POST["email"]); $guestNum = mysqli_real_escape_string($conn, $_POST["guest-number"]); $partyNum = mysqli_real_escape_string($conn, $_POST["partiers-number"]); $comments = mysqli_real_escape_string($conn, $_POST["comments"]); $sqli = "INSERT INTO rsvpInfo (firstName, lastName, email, guestNum, partyNum, comment) VALUES ('$firstName', '$lastName', '$email', '$guestNum', '$partyNum', '$comments')"; if (mysqli_query($conn, $sqli)){ echo(' <html lang="en"> <head> <meta charset="utf-8" /> <title>Thank you</title> <link rel="stylesheet" href="style.css" type="text/css"/> <link rel="icon" href="thumbnail.jpg"> </head> <body> <p id = "thank-you">Thank you for RSVPing, ' . ucfirst($firstName) . ' ' . ucfirst($lastName) . '. Click <a href = "index.html">here</a> to continue.</p> </body> </html> '); } else { echo('There was an error!: '. mysqli_error($conn)); } ?>
true
ff9a948dc0be18de1f8590e45fb83f8c129967f8
PHP
softedge/yii2-countries
/src/models/Country.php
UTF-8
1,973
2.546875
3
[ "MIT" ]
permissive
<?php namespace slayvin\countries\models; use Yii; use yii\helpers\ArrayHelper; use yii\db\ActiveRecord; use yeesoft\multilingual\behaviors\MultilingualBehavior; use slayvin\countries\models\CountryQuery; /** * This is the model class for table "{{%countries}}". * * @property string $iso (3) * @property boolean $selectable * @property boolean $default * @property string $name (63) * @property string $demonym (63) * */ class Country extends ActiveRecord { public static function tableName() { return '{{%countries}}'; } public function behaviors() { return [ 'multilingual' => [ 'class' => MultilingualBehavior::class, 'languages' => Yii::$app->params['languages'] ?? ['en' => 'English'], 'requireTranslations' => false, 'attributes' => ['name', 'demonym'], 'languageForeignKey' => 'country_iso', ], ]; } public function rules() { return [ // Name ['name', 'string', 'max' => 63], // Nationality ['demonym', 'string', 'max' => 63], ]; } public function attributeLabels() { return [ 'iso' => 'ISO', 'name' => Yii::t('label', 'Country'), 'demonym' => Yii::t('label', 'Country'), ]; } public static function find() { return new CountryQuery(get_called_class()); } /** * * @param boolean $selectable * @return array */ public static function getList($selectable = false) { $countries = static::find() ->multilingual() ->andOnCondition(['selectable' => $selectable]) ->orderBy('default DESC, iso') ->all(); return ArrayHelper::map($countries, 'iso', 'name'); } }
true
b90d73a5f07af480fe25a82494c4c8761d482b5c
PHP
wexo-labs/siteimprove-magento2
/src/Model/Token.php
UTF-8
542
2.640625
3
[]
no_license
<?php declare(strict_types=1); namespace Siteimprove\Magento\Model; use Siteimprove\Magento\Api\TokenInterface; class Token implements TokenInterface { /** * @var Flag */ protected $_flag; public function __construct( Flag $flag ) { $this->_flag = $flag; } /** * {@inheritdoc} */ public function getToken(): string { if (!$this->_flag->getFlagData()) { $this->_flag->loadSelf(); } return $this->_flag->getFlagData() ?? ''; } }
true
c271c7bdf9e5b2923b71f093b71d3415b3a02f15
PHP
QistiIzatus/pw2021_203040083
/praktikum/tubes/latihan6c/PHP/tambah.php
UTF-8
1,769
2.515625
3
[ "MIT" ]
permissive
<?php session_start(); if (!isset($_SESSION["username"])) { header("Location: login.php"); exit; } require 'functions.php'; if(isset($_POST['tambah'])) { if (tambah($_POST) > 0) { echo "<script> alert('Data Berhasil ditambahkan!'); document.location.href = 'admin.php'; </script>"; } else { echo "<script> alert('Data Gagal ditambahkan!'); document.location.href = 'admin.php'; </script>"; } } ?> <h3>Tambah Data Novel</h3> <form action="" method="post"> <ul> <li> <label for="gambar">Gambar :</label><br> <input type="file" name="gambar" id="gambar required"><br><br> </li> <li> <label for="judul">Judul:</label><br> <input type="text" name="judul" id="judul"><br><br> </li> <li> <label for="pengarang">Pengarang:</label><br> <input type="pengarang" name="pengarang" id="pengarang"><br><br> </li> <li> <label for="sinopsis">Sinopsis :</label><br> <input type="sinopsis" name="sinopsis" id="sinopsis"><br><br> </li> <li> <label for="harga">Harga :</label><br> <input type="harga" name="harga" id="harga"><br><br> </li> <li> <label for="kategori">Kategori :</label><br> <input type="kategori" name="kategori" id="kategori"><br><br> </li> </div> <button type="submit" name="tambah" class="waves-effect waves-light brown lighten-2 btn-small">Tambah Data!</button> <a href="../index.php" class="waves-effect waves-light brown lighten-2 btn-small">Kembali</a> </div> </form>
true
c818f3d2f26ba515f59417f54fb0bb5b84f67aa1
PHP
valeu36/KanbanBoardLaravel
/app/Http/Controllers/Api/V1/TaskController.php
UTF-8
1,756
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api\V1; use App\Classes\Constants; use App\Http\Controllers\Controller; use App\Task; use Illuminate\Http\Request; use Illuminate\Validation\Rule; class TaskController extends Controller { public function index() { $tasks = Task::all(); return response()->json($tasks); } public function store(Request $request) { $rules = [ 'title' => 'required', 'description' => 'required', 'owner' => 'required', 'status' => ['required', Rule::in(Constants::ALLOWED_TASK_STATUSES)], ]; $this->validate($request, $rules); $task = Task::create([ 'title' => $request->title, 'description' => $request->description, 'owner' => $request->owner, 'status' => $request->status, ]); return response()->json($task); } public function show(Task $task) { return response()->json($task); } public function update(Task $task, Request $request) { $rules = [ 'title' => 'required', 'description' => 'required', 'owner' => 'required', 'status' => ['required', Rule::in(Constants::ALLOWED_TASK_STATUSES)], ]; $this->validate($request, $rules); $task['title'] = $request->title; $task['description'] = $request->description; $task['owner'] = $request->owner; $task['status'] = $request->status; $task->save(); return response()->json($task); } public function destroy($id) { $task = Task::findOrFail($id); $task->delete(); return response()->json($task); } }
true
8a6e70534c2131a216bb351cd647c40a7f1c4e51
PHP
golinskis/php
/index.php
UTF-8
715
2.9375
3
[]
no_license
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Prework PHP - zadanie 14</title> <style> table{ background-color: aqua; border: solid 1px black; } </style> </head> <body> <?php for($i=1;$i<11;$i++){ echo "<table><tr>"; for($j=1;$j<11;$j++){ echo "<td>$i*$j"."=".$i*$j."</td>"; } echo "</tr></table>"; } ?> </body> </html>
true
e4c86234f084c9d2451da239863e937187339d55
PHP
nao-pon/xoopscube-preloads
/Script/MakePackageInfo.php
UTF-8
2,927
2.53125
3
[]
no_license
<?php $sourceFile = __DIR__.'/../xupdate.yaml'; $iniFile = __DIR__.'/../xupdate.ini'; $localizedIniFile = __DIR__.'/../xupdate/language/%s/xupdate.ini'; $readmeTemplate = __DIR__.'/README.template.md'; $readmeFile = __DIR__.'/../README.md'; $languageMap = [ 'ja' => 'ja_utf8', ]; $preloads = yaml_parse_file($sourceFile); // get default foreach ( $preloads as $index => $preload ) { if ( $preload['dirname'] === 'default' ) { $default = $preload; unset($preloads[$index]); break; } } // set up data $data = []; foreach ( $preloads as $index => $preload ) { $preload = array_merge($default, $preload); $preload['description'] = array_merge($default['description'], $preload['description']); $preload['tag'] = array_merge($default['tag'], $preload['tag']); $preload['target_key'] = $preload['dirname']; $preload['addon_url'] = $default['addon_url'].'/'.$preload['dirname'].'/'.$preload['dirname'].'.class.php'; $preload['detail_url'] = $default['detail_url'].'/'.$preload['dirname'].'/'; $name = $preload['dirname']; $data[$name] = $preload; } // sort ksort($data); // create ini string $iniString = ''; foreach ( $data as $name => $preload ) { $iniString .= sprintf("[%s]\n", $name); foreach ( $preload as $key => $value ) { if ( in_array($key, ['description', 'tag']) ) { $value = $value['en']; } if ( is_bool($value) or is_null($value) ) { $value = var_export($value, true); } else { $value = sprintf('"%s"', addslashes($value)); } $iniString .= sprintf("%s = %s\n", $key, $value); } $iniString .= "\n"; } $iniString = trim($iniString); // lint ini string if ( parse_ini_string($iniString, true) === false ) { throw new RuntimeException('Failed to parse ini string'); } // create ini file file_put_contents($iniFile, $iniString); // create localized ini string foreach ( $languageMap as $langcode => $languageName ) { $localizedIniString = ''; foreach ( $data as $name => $preload ) { $localizedIniString .= sprintf("[%s]\n", $name); $localizedIniString .= sprintf("description = \"%s\"\n", addslashes($preload['description'][$langcode])); $localizedIniString .= sprintf("tag = \"%s\"\n", addslashes($preload['tag'][$langcode])); $localizedIniString .= "\n"; } // lint ini string if ( parse_ini_string($localizedIniString, true) === false ) { throw new RuntimeException('Failed to parse localized ini string: '.$langcode); } // create localized ini file file_put_contents(sprintf($localizedIniFile, $languageName), $localizedIniString); } // create index string $index = []; foreach ( $data as $name => $preload ) { $index[] = sprintf("### [%s](%s)\n%s", $preload['dirname'], $preload['detail_url'], $preload['description']['ja']); } $index = implode("\n", $index); // create README $readme = file_get_contents($readmeTemplate); $readme = str_replace('{index}', $index, $readme); file_put_contents($readmeFile, $readme);
true
533e75e1fa13a8d8e69cb40f9eace05c8aa2ef50
PHP
smalot/shell-commander
/src/Command.php
UTF-8
3,258
3.34375
3
[ "MIT" ]
permissive
<?php namespace Smalot\Commander; /** * Class Command * @package Smalot\Commander */ class Command { /** * @var string */ protected $command; /** * @var array */ protected $subCommands = []; /** * @var array */ protected $arguments = []; /** * @var array */ protected $params = []; /** * Command constructor. * @param string $command */ public function __construct($command) { $this->command = $command; } /** * @param string|SubCommand $subCommand * @return $this */ public function addSubCommand($subCommand) { if (!$subCommand instanceof SubCommand) { $subCommand = new SubCommand($subCommand); } $this->subCommands[] = $subCommand; return $this; } /** * @param string|Argument $argument * @param string|null $value * @return $this */ public function addArgument($argument, $value = null) { if (!$argument instanceof Argument) { $argument = new Argument($argument, $value); } $this->arguments[] = $argument; return $this; } /** * @param array $arguments * @return $this */ public function addArguments($arguments) { foreach ($arguments as $argument => $value) { if ($value instanceof Argument) { $this->addArgument($value); } else { $this->addArgument($argument, $value); } } return $this; } /** * @param string|Flag $flag * @param string|null $value * @return $this */ public function addFlag($flag, $value = null) { if (!$flag instanceof Flag) { $flag = new Flag($flag, $value); } $this->arguments[] = $flag; return $this; } /** * @param array $flags * @return $this */ public function addFlags($flags) { foreach ($flags as $flag => $value) { if ($value instanceof Flag) { $this->addFlag($value); } else { $this->addFlag($flag, $value); } } return $this; } /** * @param string|Param $param * @return $this */ public function addParam($param) { if (!$param instanceof Param) { $param = new Param($param); } $this->params[] = $param; return $this; } /** * @param array $params * @return $this */ public function addParams($params) { foreach ($params as $param) { $this->addParam($param); } return $this; } /** * @return string */ public function __toString() { $command = escapeshellarg($this->command) . ' '; if ($this->subCommands) { $command .= implode(' ', $this->subCommands) . ' '; } if ($this->arguments) { $command .= implode(' ', $this->arguments) . ' '; } if ($this->params) { $command .= implode(' ', $this->params) . ' '; } return trim($command); } }
true
cf8d95c72292767acdfc18a9ca22e6611ed28b7c
PHP
BH-M87/sy
/app/models/PsBillIncomeInvoice.php
UTF-8
1,736
2.546875
3
[]
no_license
<?php namespace app\models; use Yii; /** * This is the model class for table "ps_bill_income_invoice". * * @property integer $id * @property integer $income_id * @property integer $type * @property string $invoice_no * @property string $title * @property string $tax_no * @property integer $create_at */ class PsBillIncomeInvoice extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'ps_bill_income_invoice'; } /** * @inheritdoc */ public function rules() { return [ [['income_id', 'type', 'invoice_no'], 'required'], [['income_id', 'type'], 'integer', 'on' => ['add', 'edit']], [['invoice_no'], 'string', 'max' => 50, 'on' => ['add', 'edit']], [['title'], 'string', 'max' => 100, 'on' => ['add', 'edit']], [['tax_no'], 'string', 'max' => 18, 'on' => ['add', 'edit']], // 新增场景 ['create_at', 'default', 'value' => time(), 'on' => 'add'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'income_id' => 'ps_bill_income表 ID', 'type' => '发票类型', 'invoice_no' => '发票号', 'title' => '发票抬头', 'tax_no' => '税号', 'create_at' => '操作时间', ]; } // 新增 编辑 public function saveData($scenario, $param) { if ($scenario == 'edit') { $param['create_at'] = time(); return self::updateAll($param, ['income_id' => $param['income_id']]); } return $this->save(); } }
true
9f20d2f8106afe1002854e871971f553f70c87be
PHP
fileGetContents/bananams
/database/seeds/HotelRoom.php
UTF-8
750
2.578125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class HotelRoom extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { foreach (range(1, 20) as $value) { DB::table('hotel_room')->insert([ 'room_hotel_id' => rand(4, 22), 'room_name' => str_random(), 'room_info' => str_random(), 'room_image' => 'http://www.bananatrip.com/testImage/room.png', 'room_price' => rand(100, 300), 'room_time' => $_SERVER['REQUEST_TIME'], 'room_num' => rand(0, 300), 'room_order' => rand(30, 100) ]); } } }
true
8704dc92549c2339806715814fe233bf163212b1
PHP
yuanshaoyue/openapi-sdk-php
/src/BssOpenApi/V20171214/GetPayAsYouGoPrice.php
UTF-8
2,420
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
<?php namespace AlibabaCloud\BssOpenApi\V20171214; use AlibabaCloud\Rpc; /** * Api GetPayAsYouGoPrice * * @method string getProductCode() * @method string getSubscriptionType() * @method array getModuleList() * @method string getOwnerId() * @method string getRegion() * @method string getProductType() */ class GetPayAsYouGoPrice extends Rpc { public $product = 'BssOpenApi'; public $version = '2017-12-14'; public $method = 'POST'; /** * @param string $productCode * * @return $this */ public function withProductCode($productCode) { $this->data['ProductCode'] = $productCode; $this->options['query']['ProductCode'] = $productCode; return $this; } /** * @param string $subscriptionType * * @return $this */ public function withSubscriptionType($subscriptionType) { $this->data['SubscriptionType'] = $subscriptionType; $this->options['query']['SubscriptionType'] = $subscriptionType; return $this; } /** * @param array $moduleList * * @return $this */ public function withModuleList(array $moduleList) { $this->data['ModuleList'] = $moduleList; foreach ($moduleList as $i => $iValue) { $this->options['query']['ModuleList.' . ($i + 1) . '.ModuleCode'] = $moduleList[$i]['ModuleCode']; $this->options['query']['ModuleList.' . ($i + 1) . '.PriceType'] = $moduleList[$i]['PriceType']; $this->options['query']['ModuleList.' . ($i + 1) . '.Config'] = $moduleList[$i]['Config']; } return $this; } /** * @param string $ownerId * * @return $this */ public function withOwnerId($ownerId) { $this->data['OwnerId'] = $ownerId; $this->options['query']['OwnerId'] = $ownerId; return $this; } /** * @param string $region * * @return $this */ public function withRegion($region) { $this->data['Region'] = $region; $this->options['query']['Region'] = $region; return $this; } /** * @param string $productType * * @return $this */ public function withProductType($productType) { $this->data['ProductType'] = $productType; $this->options['query']['ProductType'] = $productType; return $this; } }
true
8236346e334f2f7d11d023c93e6744ded4428a5f
PHP
Abhimanyu9988/cloudbox
/login.php
UTF-8
1,190
2.953125
3
[]
no_license
<?php include 'conn.php'; $error = ''; // Variable To Store Error Message if (isset($_POST['submit'])) { if (empty($_POST['username']) || empty($_POST['pass'])) { $error = "Username or Password is blank"; } else{ // Define $username and $password $username = $_POST['username']; $password = md5($_POST['pass']); // mysqli_connect() function opens a new connection to the MySQL server. // SQL query to fetch information of registerd users and finds user match. $query = "SELECT * from users where username='$username' AND password='$password'"; // To protect MySQL injection for Security purpose $result = mysqli_query($conn,$query); if(!mysqli_num_rows($result)){ $error = "check username and password"; echo "<script type='text/javascript'>alert('$error');</script>"; }else{ while ($row = mysqli_fetch_array($result) ){ $id=$row['id']; $image=$row['pic']; $firstName = $row['firstName']; } $_SESSION['id']=$id; $_SESSION['pic']=$image; $firstName['firstName']=$firstName; echo '<script> window.location="index.php";</script>'; } } } ?>
true
af144af157355c7a79bc542870d4cb90739ff978
PHP
ReaGet/reamedia
/php/uploadData.php
UTF-8
3,752
2.5625
3
[]
no_license
<?php $input_name = 'file'; $path = "../uploads/"; $deny = array( 'phtml', 'php', 'php3', 'php4', 'php5', 'php6', 'php7', 'phps', 'cgi', 'pl', 'asp', 'aspx', 'shtml', 'shtm', 'htaccess', 'htpasswd', 'ini', 'log', 'sh', 'js', 'html', 'htm', 'css', 'sql', 'spl', 'scgi', 'fcgi' ); if (isset($_POST['number'])) { require_once('config.php'); $roomNumber = filter_var($_POST['number'], FILTER_SANITIZE_STRING); $user = filter_var($_POST['user'], FILTER_SANITIZE_STRING); $conn = new mysqli($host, $username, $password, $db); if ($conn->connect_error) { die("Ошибка подключения: " . $conn->connect_error); } $sql = "SELECT id FROM rooms WHERE number=$roomNumber"; if($result = $conn->query($sql)) { $rows = $result->num_rows; if ($rows > 0) { $path .= $roomNumber . "/"; if (!file_exists($path)) mkdir($path, 0700); $files = array(); $diff = count($_FILES[$input_name]) - count($_FILES[$input_name], COUNT_RECURSIVE); if ($diff == 0) { $files = array($_FILES[$input_name]); } else { foreach($_FILES[$input_name] as $k => $l) { foreach($l as $i => $v) { $files[$i][$k] = $v; } } } foreach ($files as $file) { $pattern = "[^a-zа-яё0-9,~!@#%^-_\$\?\(\)\{\}\[\]\.]"; $name = mb_eregi_replace($pattern, '-', $file['name']); $name = mb_ereg_replace('[-]+', '-', $name); $converter = array( 'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', 'э' => 'e', 'ю' => 'yu', 'я' => 'ya', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'E', 'Ж' => 'Zh', 'З' => 'Z', 'И' => 'I', 'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F', 'Х' => 'H', 'Ц' => 'C', 'Ч' => 'Ch', 'Ш' => 'Sh', 'Щ' => 'Sch', 'Ь' => '', 'Ы' => 'Y', 'Ъ' => '', 'Э' => 'E', 'Ю' => 'Yu', 'Я' => 'Ya', ); $name = strtr($name, $converter); $parts = pathinfo($name); $success = array(); $i = 0; $prefix = ''; while (is_file($path . $parts['filename'] . $prefix . '.' . $parts['extension'])) { $prefix = '(' . ++$i . ')'; } $name = $parts['filename'] . $prefix . '.' . $parts['extension']; if (move_uploaded_file($file['tmp_name'], $path . $name)) { $sql = "INSERT INTO images (room, name, user) VALUES ($roomNumber, '" . $path . $name . "', '$user')"; if ($conn->query($sql) === TRUE) { $success = 'Файл «' . $name . '» успешно загружен.'; // array_push($success, $path . $name); // $success[] = $path . $name; } } if (!empty($success)) { // echo '<p>' . $success . '</p>'; echo json_encode($success); } } // if (move_uploaded_file($tmp_file, $path . $filename)) { // } } else { } } $conn->close(); } // $tmp_file = $_FILES['image']['tmp_name']; // $filename = $_FILES['image']['name']; // move_uploaded_file($tmp_file, '../uploads/' . $filename); ?>
true
38e5c3e6755096fa78eadfd1b2ba83974f654d5a
PHP
natahon/QuickCode
/Test/Error.php
UTF-8
744
2.859375
3
[ "Apache-2.0" ]
permissive
<?php function getErrorMsg($error_level,$message,$file,$line){ $EXIT =FALSE; switch($error_level){ //提醒级别 case E_NOTICE: case E_USER_NOTICE: $error_type = 'Notice'; break; //警告级别 case E_WARNING: case E_USER_WARNING: $error_type='warning'; break; //错误级别 case E_ERROR: case E_USER_ERROR: $error_type='Fatal Error'; $EXIT = TRUE; break; //其他未知错误 default: $error_type='Unknown'; $EXIT = TRUE; break; } printf("<font color='#FF0000'><b>%s</b></font>:%s in<b>%s</b> on line <b>%d</b><br>\n",$error_type,$message,$file,$line); }
true
ddb4795487ebf936b91e71589c4cd31fc90ea7b4
PHP
ValentinNikolaev/elevator
/src/Classes/Queue.php
UTF-8
1,117
3.28125
3
[]
no_license
<?php declare(strict_types=1); namespace Elevator\Classes; use Elevator\Classes\Contracts\QueueInterface; use Elevator\Classes\Contracts\QueueStorageInterface; class Queue implements QueueInterface { /** * @var QueueStorageInterface */ private $storage; /** * Queue constructor. * @param QueueStorageInterface $storage */ public function __construct(QueueStorageInterface $storage) { $this->storage = $storage; } /** * @param $floor * @return bool */ public function addItem($floor) { return $this->storage->push($floor); } /** * @return array */ public function list(): array { return $this->storage->list() ?? []; } /** * @param $floor * @return bool */ public function removeItem($floor) { return $this->storage->remove($floor); } /** * @return string */ public function __toString() : string { return "Queue: " . implode(", ", $this->list()); } }
true
f83b52320a12905eb7de2f49b38eea3635abe5ee
PHP
baaane/image-optimizer
/tests/Unit/Action/UploadTest.php
UTF-8
1,916
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php use Tests\TestCase; use Baaane\ImageOptimizer\Core\Upload; class UploadTest extends TestCase { public function setUp(): void { parent::setUp(); $this->directory = __DIR__. '/_files/'; $_FILES = [ 'filename' => [ 'name' => 'uploaded-image.jpg', 'type' => 'image/jpeg', 'size' => 542, 'tmp_name' => __DIR__. '/_files/test.jpg', 'error' => 0, 'new_name' => 'new_name1' ] ]; $this->mocked_upload = new Upload($this->directory); } /** * @test */ public function it_should_list_file_info() { $data = $this->mocked_upload->handle($_FILES['filename']); $result = new \stdClass(); $result = json_decode(json_encode([$data])); $this->assertObjectHasAttribute('name', $result[0]); $this->assertObjectHasAttribute('type', $result[0]); $this->assertObjectHasAttribute('tmp_name', $result[0]); $this->assertObjectHasAttribute('error', $result[0]); $this->assertObjectHasAttribute('size', $result[0]); $this->assertObjectHasAttribute('path', $result[0]); } /** * @test */ public function it_should_upload_file() { $data = $this->mocked_upload->handle($_FILES['filename']); $result = $this->mocked_upload->upload($data['tmp_name'], $data['path'].'/'.$data['name']); $this->assertTrue($result); @unlink($data['path'].'/'.$data['name']); } /** * @test */ public function it_should_check_file_exist() { $data = $this->mocked_upload->handle($_FILES['filename']); $result = $this->mocked_upload->check_file($data['tmp_name']); $this->assertTrue($result); } /** * will remove the uploaded images */ public function tearDown(): void { unset($_FILES); } }
true
66b422cee369e96073e6891b124d11fc338cb38d
PHP
Uniceub-Web-Development-2016-2/Jader-Germano
/aula2/request.php
UTF-8
1,571
3.015625
3
[]
no_license
<?php class Request{ private $method; private $protocol; private $ip; private $resource; private $parameters; public function __construct($protocol, $ip, $resource, $parameters, $method){ $this->protocol = $protocol; $this->ip = $ip; $this->resource = $resource; $this->parameters = $parameters; $this->method = $method; } public function toString(){ $request = $this->$protocol."://".$this->ip."/".$this->resourse."/"; foreach($this->params_arr as $key => $param){ $request .= $key."=".$param; } return utf8_encode($request); } public function setMethod($method){ $this->method = $method; } public function getMethod(){ return $method; } public function setProtocol($protocol){ $this->protocol = $protocol; } public function getProtocol(){ return $protocol; } public function setIP($ip){ $this->ip = $ip; } public function getIP(){ return $ip; } public function setResource($resource){ $this->resource = $resource; } public function getResource(){ return $resource; } public function setParameters($parameters){ $this->parameters = $parameters; } public function getParameters(){ return $method; } } $request = new Request("http","127.0.0.1/8","resource",array("pesquisa1","pesquisa2","pesquisa3"),"GET"); echo $request->toString();
true
81b586fa9c97051d1a129771a1572cf3eecd7da3
PHP
hoku/HttpStatusCodeResolver
/src/HttpStatusCodeResolver/HttpHeader.php
UTF-8
1,026
2.9375
3
[ "MIT" ]
permissive
<?php /** * HttpStatusCode resolver. * * @license MIT License * @author hoku */ namespace HttpStatusCodeResolver; require_once(dirname(__FILE__) . '/HttpStatusCode.php'); class HttpHeader { public static function http_response_code($code, $unknownMessage = 'Unknown', $httpVersion = '1.1', $excludeTeapot = false, $return = false) { $headerString = 'HTTP/' . $httpVersion; $statusCodeInfo = HttpStatusCode::resolve($code, $excludeTeapot); if ($statusCodeInfo) { $headerString .= ' ' . $statusCodeInfo[0] . ' ' . $statusCodeInfo[1]; } else { $headerString .= ' ' . intval($code) . ' ' . $unknownMessage; } if ($return) { return $headerString; } else { header($headerString); return true; } } }
true
32c127d9c91a70d2202a03ec329836b689eb8e30
PHP
andrewgilmartin/mws_signup
/lib/Volunteer.php
UTF-8
980
3.078125
3
[]
no_license
<?php class Volunteer { private static $nextId = 1; private $id; private $shift; private $contact; private $event; private $nameToProperty = array(); function __construct() { $this->id = Volunteer::$nextId++; } function setId( $id ) { $this->id = $id; } function getId() { return $this->id; } function setShift( $shift ) { $this->shift = $shift; } function getShift() { return $this->shift; } function setContact( $contact ) { $this->contact = $contact; } function getContact() { return $this->contact; } function setEvent($event) { $this->event = $event; } function getEvent() { return $this->event; } function addProperty( $name, $value ) { $this->nameToProperty[ $name ] = $value; return $this; } function getProperty( $name ) { return array_key_exists( $name, $this->nameToProperty ) ? $this->nameToProperty[$name] : null; } function getProperties() { return $this->nameToProperty; } } # END
true
6a34b16359fdbb4f67542635ff561fce71dac043
PHP
maxy96/doer
/database/seeds/DatabaseSeeder.php
UTF-8
891
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->truncateTablas([ 'servicios', 'tipos_servicios', 'emps', 'users', 'perfiles', 'estados_usuarios' ]); $this->call(EstadosUsuariosSeeder::class); $this->call(PerfilesSeeder::class); $this->call(UsersSeeder::class); $this->call(EmpsSeeder::class); $this->call(TiposServiciosSeeder::class); $this->call(ServiciosSeeder::class); } public function truncateTablas(array $tablas){ DB::statement('SET FOREIGN_KEY_CHECKS = 0;'); foreach ($tablas as $tabla) { DB::table($tabla)->truncate(); } DB::statement('SET FOREIGN_KEY_CHECKS = 1;'); } }
true
b6f2a7894596bb50c9cbfc74b67cfb8f483604fa
PHP
christianfp/ProyectoSisWeb
/final/CursosDeFormacionContinua/modulos/controlador.php
UTF-8
1,623
3.03125
3
[]
no_license
<?php include_once("./clases/cursos.php"); class ControladorCursos { // Atributos private $cursos; // Metodos public function __construct() { $this->cursos = new Curso(); } public function index() { $resultado = $this->cursos->listar(); return $resultado; } public function crear($sigla, $titulo, $resumen, $fecha_inicio, $docente, $name, $image) { $this->cursos->set("curso_id", $curso_id); $this->cursos->set("sigla", $sigla); $this->cursos->set("titulo", $titulo); $this->cursos->set("resumen", $resumen); $this->cursos->set("fecha_inicio", $fecha_inicio); $this->cursos->set("docente", $docente); $this->cursos->set("name",$name); $this->cursos->set("image",$image); $this->cursos->crear(); } public function eliminar($curso_id) { $this->cursos->set("curso_id", $curso_id); $this->cursos->eliminar(); } public function ver($curso_id) { $this->cursos->set("curso_id", $curso_id); $datos = $this->cursos->ver(); return $datos; } public function editar($curso_id,$sigla, $titulo, $resumen, $fecha_inicio, $docente, $name, $image) { $this->cursos->set("curso_id", $curso_id); $this->cursos->set("sigla", $sigla); $this->cursos->set("titulo", $titulo); $this->cursos->set("resumen", $resumen); $this->cursos->set("fecha_inicio", $fecha_inicio); $this->cursos->set("docente", $docente); $this->cursos->set("name",$name); $this->cursos->set("image",$image); $this->cursos->editar(); } public function getdocentes() { $resultado = $this->cursos->getdocentes(); return $resultado; } } ?>
true
04d78f5f9f94fda50e41bd429fc4ff1b9275624c
PHP
aprbrown/ProjectManagement_GroupWork
/database/factories/ModelFactory.php
UTF-8
2,319
2.53125
3
[]
no_license
<?php use Faker\Generator as Faker; /* |-------------------------------------------------------------------------- | Model Factories |-------------------------------------------------------------------------- | | This directory should contain each of the model factory definitions for | your application. Factories provide a convenient way to generate new | model instances for testing / seeding your application's database. | */ $factory->define(App\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => str_random(10), ]; }); $factory->define(App\Task::class, function (Faker $faker) { $startingDate = $faker->dateTimeBetween('+1 day', '+6 day'); $dueDate = $faker->dateTimeBetween('+9 days', '+20 day'); return [ 'user_id' => function() { return factory('App\User')->create()->id; }, 'project_id'=> function() { return factory('App\Project')->create()->id; }, 'name' => $faker->sentence, 'description' => $faker->paragraph, 'status' => $faker->randomElement(['backlog', 'in_progress', 'completed']), 'priority' => $faker->randomElement(['low', 'normal', 'high']), 'start_date' => $startingDate, 'due_date' => $dueDate ]; }); $factory->define(App\Project::class, function (Faker $faker) { $startingDate = $faker->dateTimeBetween('this week', '+90 days'); $dueDate = $faker->dateTimeBetween('+120 days', '+300 days'); $name = $faker->word; return [ 'name' => $name, 'slug' => $name, 'user_id' => function() { return factory('App\User')->create()->id; }, 'start_date' => $startingDate, 'due_date' => $dueDate, 'description' => $faker->paragraph, 'status' => $faker->randomElement(['backlog', 'in_progress']) ]; }); $factory->define(App\Comment::class, function (Faker $faker) { return [ 'task_id' => function() { return factory('App\Task')->create()->id; }, 'user_id' => function() { return factory('App\User')->create()->id; }, 'comment' => $faker->paragraph ]; });
true
125845dbab39642c23fb6a6b6833ef0ec4ab99a1
PHP
tronghieu/flywheel-framework
/src/Flywheel/Event/Dispatcher.php
UTF-8
4,648
2.984375
3
[]
no_license
<?php namespace Flywheel\Event; class Dispatcher implements IDispatcher { private $_listeners = array(); private $_sorted = array(); /** * @see IDispatcher::dispatch * * @api */ public function dispatch($eventName, \Flywheel\Event\Event $event = null) { if (null === $event) { $event = new Event(); } $event->setDispatcher($this); $event->setName($eventName); if (!isset($this->_listeners[$eventName])) { return $event; } $this->doDispatch($this->getListeners($eventName), $eventName, $event); return $event; } /** * @see IDispatcher::getListeners */ public function getListeners($eventName = null) { if (null !== $eventName) { if (!isset($this->_sorted[$eventName])) { $this->sortListeners($eventName); } return $this->_sorted[$eventName]; } foreach (array_keys($this->_listeners) as $eventName) { if (!isset($this->_sorted[$eventName])) { $this->sortListeners($eventName); } } return $this->_sorted; } /** * @see IDispatcher::hasListeners */ public function hasListeners($eventName = null) { return (Boolean) count($this->getListeners($eventName)); } /** * @see Ming_Event_IDispatcher::addListener * * @api */ public function addListener($eventName, $listener, $priority = 0) { $this->_listeners[$eventName][$priority][] = $listener; unset($this->_sorted[$eventName]); } /** * @see IDispatcher::removeListener */ public function removeListener($eventName, $listener) { if (!isset($this->_listeners[$eventName])) { return; } foreach ($this->_listeners[$eventName] as $priority => $listeners) { if (false !== ($key = array_search($listener, $listeners))) { unset($this->_listeners[$eventName][$priority][$key], $this->_sorted[$eventName]); } } } /** * @see IDispatcher::addSubscriber * * @api */ public function addSubscriber(ISubscriber $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_string($params)) { $this->addListener($eventName, array($subscriber, $params)); } elseif (is_string($params[0])) { $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0); } else { foreach ($params as $listener) { $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0); } } } } /** * @see IDispatcher::removeSubscriber */ public function removeSubscriber(ISubscriber $subscriber) { foreach ($subscriber->getSubscribedEvents() as $eventName => $params) { if (is_array($params) && is_array($params[0])) { foreach ($params as $listener) { $this->removeListener($eventName, array($subscriber, $listener[0])); } } else { $this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0])); } } } /** * Triggers the listeners of an event. * * This method can be overridden to add functionality that is executed * for each listener. * * @param array[callback] $listeners The event listeners. * @param string $eventName The name of the event to dispatch. * @param \Flywheel\Event\Event $event The event object to pass to the event handlers/listeners. */ protected function doDispatch($listeners, $eventName, Event $event) { foreach ($listeners as $listener) { call_user_func($listener, $event); if ($event->isPropagationStopped()) { break; } } } /** * Sorts the internal list of listeners for the given event by priority. * * @param string $eventName The name of the event. */ private function sortListeners($eventName) { $this->_sorted[$eventName] = array(); if (isset($this->_listeners[$eventName])) { krsort($this->_listeners[$eventName]); $this->_sorted[$eventName] = call_user_func_array('array_merge', $this->_listeners[$eventName]); } } }
true
19bf25a91a21ea880ec4f3978be8ce3260165cca
PHP
PeeHaa/HexDump
/src/HexDump/Http/RequestData.php
UTF-8
1,965
2.984375
3
[ "MIT" ]
permissive
<?php /** * Interface for HTTP request classes * * PHP version 5.4 * * @category HexDump * @package Http * @author Pieter Hordijk <info@pieterhordijk.com> * @copyright Copyright (c) 2013 Pieter Hordijk * @license http://www.opensource.org/licenses/mit-license.html MIT License * @version 1.0.0 */ namespace HexDump\Http; /** * Interface for HTTP request classes * * @category HexDump * @package Http * @author Pieter Hordijk <info@pieterhordijk.com> */ interface RequestData { /** * Gets the path of the URI * * @return string The path */ public function getPath(); /** * Gets the get variables * * @return array The get variables */ public function getGetVariables(); /** * Gets a get variable * * @return mixed The get variable value (or null if it doesn't exists) */ public function getGetVariable($key, $defaultValue = null); /** * Gets the post variables * * @return array The post variables */ public function getPostVariables(); /** * Gets a post variable * * @return mixed The post variable value (or null if it doesn't exists) */ public function getPostVariable($key, $defaultValue = null); /** * Gets the cookie variables * * @return array The cookie variables */ public function getCookieVariables(); /** * Gets a cookie variable * * @return mixed The cookie variable value (or null if it doesn't exists) */ public function getCookieVariable($key, $defaultValue = null); /** * Gets the HTTP method * * @return string The HTTP method */ public function getMethod(); /** * Gets the host * * @return string The host */ public function getHost(); /** * Check whether the connection is over SSL * * @return boolean Whether the connection is over SSL */ public function isSsl(); }
true
431a7c8e795a00654aaa93056f3b96fa4203d5a7
PHP
1194331476/PolicePeople
/model/user.php
UTF-8
882
3.1875
3
[]
no_license
<?php class user{ private $username; private $truename; private $sex; /** * @return the $username */ public function getUsername() { return $this->username; } /** * @return the $truename */ public function getTruename() { return $this->truename; } /** * @return the $sex */ public function getSex() { return $this->sex; } /** * @param field_type $username */ public function setUsername($username) { $this->username = $username; } /** * @param field_type $truename */ public function setTruename($truename) { $this->truename = $truename; } /** * @param field_type $sex */ public function setSex($sex) { $this->sex = $sex; } }
true
3ae5ba0459bf01d67cb2b6bfbfa9ea422222ac75
PHP
felixmetallica/gestionDelivery
/controladores/recetas.controlador.php
UTF-8
7,424
2.578125
3
[]
no_license
<?php class ControladorRecetas{ /*============================================= MOSTRAR RECETA =============================================*/ static public function ctrMostrarRecetas($item, $valor){ $tabla1 = "Receta"; $tabla2 = "Producto"; $respuesta = ModeloRecetas::mdlMostrarRecetas($tabla1, $tabla2, $item, $valor); return $respuesta; } /*============================================= REGISTRAR RECETA =============================================*/ static public function ctrRegistrarReceta(){ if(isset($_POST["productoReceta"])){ if (preg_match('/^[0-9]+$/', $_POST["productoReceta"])){ $tabla = "Receta"; $idProducto = $_POST["productoReceta"]; $listaInsumos = json_decode($_POST["listadoInsumos"], true); $idReceta = ModeloRecetas::mdlRegistrarReceta($tabla, $idProducto); if ($idReceta != "error") { $tablaRecetaDetalle = "RecetaDetalle"; foreach ($listaInsumos as $key => $value) { $idInsumo = $value["idInsumo"]; $Cantidad = $value["cantidadInsumo"]; $respuesta = ModeloRecetas::mdlRegistrarDetalleReceta($tablaRecetaDetalle, $idReceta, $idInsumo, $Cantidad); } if($respuesta = "ok"){ echo'<script> swal({ title:"¡Registro Exitoso!", text:"¡La receta se registró correctamente!", type:"success", confirmButtonText: "Cerrar", closeOnConfirm: false }, function(isConfirm){ if(isConfirm){ window.location="recetas"; } }); </script>'; }else{ echo'<script> swal({ title:"¡Registro Fallido!", text:"¡Ocurrio un error, revise los datos!'.$respuesta.'", type:"error", confirmButtonText:"Cerrar", closeOnConfirm: false }); </script>'; } }// fin if receta error } else { echo '<script> swal({ title:"¡Error!", text:"¡No ingrese caracteres especiales!", type:"warning", confirmButtonText:"Cerrar", closeOnConfirm:false }, function(isConfirm){ if(isConfirm){ window.location="recetas"; } }); </script>'; } } //if isset } /*============================================= EDITAR RECETA =============================================*/ static public function ctrEditarReceta(){ if(isset($_POST["idProductoReceta"])){ if (preg_match('/^[0-9]+$/', $_POST["idProductoReceta"])){ $tabla = "Receta"; $idProducto = $_POST["idProductoReceta"]; $idReceta = $_POST["idReceta"]; $listaInsumos = json_decode($_POST["listadoInsumos"], true); $tablaRecetaDetalle = "RecetaDetalle"; $eliminoDetalle = ModeloRecetas::mdlEliminarDetalleReceta($tablaRecetaDetalle, $idReceta); foreach ($listaInsumos as $key => $value) { $idInsumo = $value["idInsumo"]; $Cantidad = $value["cantidadInsumo"]; $respuesta = ModeloRecetas::mdlRegistrarDetalleReceta($tablaRecetaDetalle, $idReceta, $idInsumo, $Cantidad); } if($respuesta = "ok"){ echo'<script> swal({ title:"¡Registro Exitoso!", text:"¡La receta se modificó correctamente!", type:"success", confirmButtonText: "Cerrar", closeOnConfirm: false }, function(isConfirm){ if(isConfirm){ window.location="recetas"; } }); </script>'; }else{ echo'<script> swal({ title:"¡Registro Fallido!", text:"¡Ocurrio un error, revise los datos!'.$respuesta.'", type:"error", confirmButtonText:"Cerrar", closeOnConfirm: false }); </script>'; } } else { echo '<script> swal({ title:"¡Error!", text:"¡No ingrese caracteres especiales!", type:"warning", confirmButtonText:"Cerrar", closeOnConfirm:false }, function(isConfirm){ if(isConfirm){ window.location="recetas"; } }); </script>'; } } //if isset } /*============================================= LISTADO DE INSUMOS DE RECETA =============================================*/ static public function ctrListadoInsumos($valor){ $tabla1 = "Receta"; $tabla2 = "RecetaDetalle"; $tabla3 = "Insumos"; $respuesta = ModeloRecetas::mdlListadoInsumos($tabla1, $tabla2, $tabla3, $valor); return $respuesta; } /*============================================= ELIMINAR RECETA =============================================*/ static public function ctrEliminarReceta($receta){ $idReceta = $receta; $tabla = "Receta"; $tablaRecetaDetalle = "RecetaDetalle"; //ELIMINAMOS PRIMERO EL DETALLE DE LA VENTA $eliminoDetalle = ModeloRecetas::mdlEliminarDetalleReceta($tablaRecetaDetalle, $idReceta); //ELIMINAMOS LA RECETA $respuesta = ModeloRecetas::mdlEliminarReceta($tabla, $idReceta); if($respuesta=="ok"){ echo 0; }else{ echo 1; } } }
true
0a4c96b8226751faf835c1ee7a4241bfc99c6cdb
PHP
Zhao-666/MDYaf
/application/controllers/Mail.php
UTF-8
1,332
2.609375
3
[ "Apache-2.0" ]
permissive
<?php /** * Created by PhpStorm. * User: Next * Date: 2018/2/18 * Time: 12:38 */ class MailController extends Yaf_Controller_Abstract { public function indexAction() { } public function sendAction() { $submit = $this->getRequest()->getQuery("submit", "0"); if ($submit != "1") { echo json_encode(array("errno" => -3001, "errmsg" => "请通过正确渠道提交")); return FALSE; } // 获取参数 $uid = $this->getRequest()->getPost("uid", false); $title = $this->getRequest()->getPost("title", false); $contents = $this->getRequest()->getPost("contents", false); if (!$uid || !$title || !$contents) { echo json_encode(array("errno" => -3002, "errmsg" => "用户ID、邮件标题、邮件内容均不能为空。")); return FALSE; } // 调用Model, 发邮件 $model = new MailModel(); if ($model->send(intval($uid), trim($title), trim($contents))) { echo json_encode(array( "errno" => 0, "errmsg" => "", )); } else { echo json_encode(array( "errno" => $model->errno, "errmsg" => $model->errmsg, )); } return FALSE; } }
true
6d906466ad4864b02faa1b43d2aa03a4d921a6e6
PHP
awwab1384/php-cli
/restApi.php
UTF-8
1,422
2.578125
3
[ "MIT" ]
permissive
<?php require_once('vendor/autoload.php'); use Spatie\ArrayToXml\ArrayToXml; $file_name = "products.json"; if(!file_exists($file_name))return; $string = file_get_contents($file_name); $fData = $data = json_decode($string, true); $filter_by_name = $filter_by_pvp = false; $values = array('f_name:','f_pvp:'); $values = getopt(null, $values); if(isset($values['f_name']))$filter_by_name = explode(",", strtolower($values['f_name'])); if(isset($values['f_pvp']))$filter_by_pvp = explode(",", $values['f_pvp']); if(isset($_GET['filter_by_name']))$filter_by_name = explode(",", strtolower($_GET['filter_by_name'])); if(isset($_GET['filter_by_pvp']))$filter_by_pvp = explode(",", $_GET['filter_by_pvp']); if($filter_by_name || $filter_by_pvp)$fData = array(); if($filter_by_name || $filter_by_pvp): $fData = array(); $count = 0; foreach ($data['product'] as $key => $value) { if($filter_by_name && !in_array(strtolower($value['name']),$filter_by_name))continue; if($filter_by_pvp && $value['pvp']<$filter_by_pvp[0])continue; if($filter_by_pvp && $value['pvp']>$filter_by_pvp[1])continue; $fData['product'][$count] = $value; $count++; } endif; // headers for not caching the results header('Cache-Control: no-cache, must-revalidate'); // headers to tell that result is JSON header('Content-type: application/xml'); // send the result now // exit(json_encode($fData)); exit(ArrayToXml::convert($fData)); ?>
true
6ffd59dc41b999566f53ca1e064337fb5bb1f49b
PHP
yiyuanjian/asf
/Asf/ViewAction.php
UTF-8
407
2.71875
3
[]
no_license
<?php abstract class Asf_ViewAction { protected static function output($templateFilename, $data = array(), $autoExit = 1) { $tpl = new Asf_Template($templateFilename); $tpl->display($data); return $autoExit && exit(); } protected static function display($templateFilename, $data = array()) { return self::output($templateFilename, $data, 0); } }
true
426fb67459c4f8cdb8ea119ff428720d7a443a09
PHP
yoonani/CBT
/include/frmValid.php
UTF-8
530
3.015625
3
[]
no_license
<? class frmValid { /* function __construct($historyBack = 1) { $this->historyBack = $historyBack; } */ function lengthlt($str, $length) { if(strlen(trim($str)) < $length) return true; else return false; } function lengthgt($str, $length) { if(strlen(trim($str)) > $length) return true; else return false; } function lengthTerm($str, $min, $max) { if( (strlen(trim($str)) >= $min) AND (strlen(trim($str)) <= $max) ) return true; else return false; } } $fv = new frmValid(); ?>
true
895638fe4017ccf7ad67f997e31dc7a7b112deb9
PHP
WendyGraphex/jobs-application
/modules/employees/frontend/locales/Pagers/EmployeeControllerPager.class.php
UTF-8
742
2.59375
3
[]
no_license
<?php class EmployeeControllerPager extends Pager { function __construct() { parent::__construct(array("Employee","EmployeeContent","EmployeeContentI18n")); } protected function fetchObjects($db) { while ($items = $db->fetchObjects()) { $item=$items->getEmployee(); $item->set('content',$items->hasEmployeeContent()?$items->getEmployeeContent():false); if ($item->hasContent() && $items->hasEmployeeContentI18n()) $item->getContent()->setI18n($items->getEmployeeContentI18n()); $this->items[$item->get('id')]=$item; } } }
true
a4a68d415d0a73c936feba33fa90563ec3b5928a
PHP
iamhefang/php-mvc
/src/link/hefang/mvc/views/ErrorView.class.php
UTF-8
828
2.5625
3
[ "MIT" ]
permissive
<?php namespace link\hefang\mvc\views; defined('PHP_MVC') or die("Access Refused"); use link\hefang\helpers\CollectionHelper; use link\hefang\helpers\ObjectHelper; class ErrorView extends BaseView { private $code = 200; /** * ErrorView constructor. * @param int $code * @param string|null $message */ public function __construct(int $code, string $message = null) { $this->code = $code; $this->result = ObjectHelper::nullOrDefault($message, CollectionHelper::getOrDefault(StatusView::HTTP_STATUS_CODE, $code, $code)); } public function compile(): BaseView { $this->isCompiled = true; return $this; } public function render() { $this->checkCompile(); header("HTTP/1.1 $this->code $this->result"); $this->flushHeaders(); while (ob_get_length() > 0 && @ob_end_flush()) ; exit(0); } }
true
285690172508cb1b5a1569909655bb062f687e41
PHP
chrislim1914/coinslide
/app/Http/Controllers/UserInfoController.php
UTF-8
3,525
2.546875
3
[]
no_license
<?php namespace App\Http\Controllers; use App\UserInfo; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Http\Request; use App\Http\Controllers\UtilityController; class UserInfoController extends Controller { /** * method to update userinformations collections * to be utilized under UserController to update Client info * * @param $iduser Array $userdata * * @return Bool */ public function updateUserInfo($iduser, Array $userdata){ $iduser = intval($iduser); //update userinformation with parameter $saveUser = DB::connection('mongodb')->collection('userinformations') ->where('iduser', '=', $iduser); //execute update if($saveUser->update([ 'gender' => $userdata['gender'], 'birth' => $userdata['birth'], 'country' => $userdata['country'], 'city' => $userdata['city'], 'mStatus' => $userdata['mStatus'] ])) { return true; } else { return false; } } public function updateProfilePhoto(Request $request, $iduser){ $iduser = intval($iduser); //check first if user exist $userinfo = UserInfo::where('iduser', $iduser) ->get(); if($userinfo->count() > 0){ //get the image file $photo = $request->file('image'); //instanciate ImageController for resize $resize = new UtilityController(); $newImage = $resize->profilephotoResize($photo); //set new name for image to save on database $newName = 'assets/profile/'.time().'.'.$photo->getClientOriginalExtension(); //set directory to save the file $destinationPath = $resize->public_path('/'); //save to image to public/assets/banner folder $newImage->save($destinationPath.'/'.$newName,80); //update userinformation with parameter $saveUser = DB::connection('mongodb')->collection('userinformations') ->where('iduser', '=', $iduser); //execute update if($saveUser->update([ 'profilephoto' => $newName, ])) { return response()->json([ 'message' => 'Profile photo updated', 'result' => false ]); } } else { return response()->json([ 'message' => 'client not found.', 'result' => false ]); } } /** * method to retrieved user profile photo * * @param $iduser * * @return $userinfo */ public function getUserPhoto($iduser){ //convert the $id to integer $iduser = intval($iduser); $userinfo = DB::connection('mongodb')->collection('userinformations') ->project(['_id' => 0]) ->select('profilephoto') ->where('iduser', '=', $iduser) ->get(); if($userinfo) { foreach($userinfo as $new){ return $new; } } else { return 'no photo'; } } }
true
e31e7f9f3d6106535dd6a4c1133196cbfffc9f46
PHP
BhavyaKalakata/Department-web-appplication
/backend/reg.php
UTF-8
752
2.546875
3
[]
no_license
<?php session_start(); $conn = mysqli_connect("localhost","root","","userdb"); $username = $_POST['name']; $email = $_POST['email']; $pwd = $_POST['psw']; $query = "select * from Users where name='$username'"; $check_result = mysqli_query($conn, $query); if(mysqli_num_rows($check_result) == 1) { echo "<h1>Username already taken<h1>"; } else { $ins_query = "insert into Users(name,password,email) VALUES ('$username','$pwd','$email');"; if(mysqli_query($conn, $ins_query)) { echo "Registration Successful"; header('location:login.html'); } else { echo "Registration Failed"; header('location:reg.html'); } //header('location:login.html'); } ?>
true
b88b5d04c2052ce74b4bdbfdefa48f431ca68ffa
PHP
instantjay/crontasksphp
/src/CronTask.php
UTF-8
2,401
2.921875
3
[ "MIT" ]
permissive
<?php namespace instantjay\crontasksphp; use Monolog\Logger; class CronTask { protected $callable; protected $successCallable; protected $failureCallable; protected $executed; protected $startTime; protected $endTime; protected $duration; protected $logger; /** * CronTask constructor. * @param $callable callable * @param $successCallable callable * @param $failureCallable callable */ public function __construct($callable, $successCallable, $failureCallable) { $this->callable = $callable; $this->successCallable = $successCallable; $this->failureCallable = $failureCallable; $this->executed = false; } /** * @param $logger Logger */ public function bindLogger($logger) { $this->logger = $logger; } /** * @throws \Exception */ public function execute() { if($this->executed) throw new \Exception('This task was already executed once.'); $this->startTimer(); $this->executed = true; try { $callable = $this->callable; $callable($this->logger); $this->succeeded(); } catch(\Exception $e) { $this->failed($e); } return new TaskExecutionResult($this); } protected function succeeded() { $callable = $this->successCallable; $callable($this->logger); $this->stopTimer(); } protected function failed(\Exception $e) { $callable = $this->failureCallable; $callable($this->logger); $this->stopTimer(); } protected function reset() { $this->executed = false; $this->startTime = null; $this->endTime = null; $this->duration = null; } private function startTimer() { $this->startTime = microtime(true); } /** * @throws \Exception */ private function stopTimer() { if(!$this->startTime) throw new \Exception('Task end time cannot be calculated because task was never started.'); $this->endTime = microtime(true); $this->duration = $this->endTime - $this->startTime; } public function executionTime() { if(!$this->executed) throw new \Exception('Task not yet executed.'); return $this->duration; } }
true
e38697a5281b163b022160cb359fd787216606a5
PHP
sondy94/php-techdegree-project01
/inc/functions.php
UTF-8
1,656
3.546875
4
[]
no_license
<?php // PHP - Random Quote Generator // Below is a multidimensional array containing a list of quotes, sources, citations and years. $quotes = [ [ "quote" => "The greatest glory in living lies not in never falling, but in rising every time we fall.", "source" => "Nelson Mandela" ], [ "quote" => "The way to get started is to quit talking and begin doing.", "source" => "Walt Disney" ], [ "quote" => "Good friends, good books, and a sleepy conscience: This is the ideal life.", "source" => "Mark Twain" ], [ "quote" => "If life were predictable it would cease to be life, and be without flavor.", "source" => "Eleanor Rosevelt" ], [ "quote" => "Never fear quarrels, but seek hazardous adventures.", "source" => "Alexandre Dumas", "citation" => "The three Muskeeters", "year" => "1844" ] ]; // A function called getRandomQuote created which purpose is to get random quote from the quotes array. function getRandomQuote($array) { return $array[rand(0, count($array) - 1)]; } // A function called printQuote is created which purpose is to print the quotes in the HTML page. function printQuote($array) { $quoteElements = getRandomQuote($array); $quoteItem = ''; $quoteItem .= "<p class=\"quote\">" . $quoteElements['quote'] . "</p>"; $quoteItem .= "<p class=\"source\">" . $quoteElements['source']; if(isset($quoteElements['citation'])){ $quoteItem .= "<span class=\"citation\">" . $quoteElements['citation'] . "</span>"; } if(isset($quoteElements['year'])){ $quoteItem .= "<span class=\"year\">" . $quoteElements['year'] . "</span></p>"; } return $quoteItem; }
true
03240313a5be8f0edf4eb9b06df7abc926617cc4
PHP
DaianaARuiz/E-commerce-
/FASE_INICIAL/functions.php
UTF-8
1,384
2.65625
3
[]
no_license
<?php function mostrarMensajes($rta){ switch($rta) { case "0x001": $mensaje="<span style=color:red>Nombre invalido</span>"; break; case "0x002": $mensaje="<span style=color:red>Email invalido</span>"; break; case "0x003": $mensaje="<span style=color:red>Mensaje Invalido</span>"; break; case "0x004": $mensaje="<span style=color:green>Email enviado</span>"; break; case "0x005": $mensaje="<span style=color:red>Email no enviado</span>"; break; return $mensaje; } } function CargarPagina($page) { $page=$page.".php"; if(file_exists($page)) { include $page; }else { include "404.php"; } } function mostrarProductos() { $archivo="listadoProductos.csv";//guardo el excel if($file=fopen($archivo,'r'));//lo abro para lectura { while(($data = fgetcsv($file,1000,","))!==FALSE) { // var_dump($data); ?> <div class="product-grid"> <div class="content_box"> <a href="./?page=producto"> <div class="left-grid-view grid-view-left"> <img src="images/productos/<?php echo $data[0];?>.jpg" class="img-responsive watch-right" alt=""/> </div> </a> <h4><a href="#"><?php echo $data[1]; ?></a></h4> <p><?php echo $data[5]; ?></p> <span><?php echo $data[2]; ?></span> </div> </div> <?php } fclose($file); } } ?>
true
add8ca8c52ac6683ba47ad558468b720c3c4ffbb
PHP
smedaer/info-h303_projet
/Horeca/signIn.php
UTF-8
2,238
2.828125
3
[]
no_license
<?php include "header.php"; include "connection.php"; $error = false; $errorMsg = null; $email = isset($_POST['email']) ? $_POST['email'] : null; $password = isset($_POST['password']) ? $_POST['password'] : null; if ($email === null) { $error = true; } else { $statement = $db->prepare("SELECT User_ID,PSWD,Is_Admin FROM Users WHERE Email = :email"); $statement->execute(array("email" => $email)); $res = $statement->fetchAll(PDO::FETCH_ASSOC); if (count($res) != 1) { $error = true; $errorMsg = "Error: Cet email n'appartient a aucun compte!"; } else { if ($password != $res[0]["PSWD"]){ $error = true; $errorMsg = "Error: Mot de passe incorrect!"; } } if (!$error) { // connection $_SESSION["User_ID"] = $res[0]["User_ID"]; $_SESSION["Email"] = $email; $_SESSION["Is_Admin"] = $res[0]["Is_Admin"]; header("Location: index.php"); } } ?> <body class="signInPage"> <br><br><br><br><br> <div class="row"> <form action="signIn.php" method="post"> <div class="col-md-9 col-md-offset-3 form-group"> <label for="email" class="control-label col-md-3"> <p style="color:white">Email</p> </label> <div class="col-md-5"> <input type="email" class="form-control" size="5" name="email" placeholder="Adresse email" value="<?php echo $email ?>" required autofocus> </div> </div> <div class="col-md-9 col-md-offset-3 form-group"> <label for="password" class="control-label col-md-3"> <p style="color:white">Mot de passe</p> </label> <div class="col-md-5"> <input type="password" class="form-control" name="password" placeholder="Mot de passe" value="<?php echo $password ?>" required> </div> </div> <div class="col-md-2 col-md-offset-5"> <div class="col-md-3 col-md-offset-5"> <input type="submit" class="btn btn-success" value="Sauver"> </div> <font color="red"><br><?php echo $errorMsg; ?></font> </div> </form> </div> <?php include "footer.php"; ?>
true
a8eea31a21ed8c2db949901d064c88c64c2fd768
PHP
prasanth-spark/login-and-register-multi-auth
/src/App/Listeners/WelcomeNewUserListener.php
UTF-8
693
2.53125
3
[ "MIT" ]
permissive
<?php namespace Sparkouttech\UserMultiAuth\App\Listeners; use Sparkouttech\UserMultiAuth\App\Jobs\WelcomEmailJob; use Sparkouttech\UserMultiAuth\App\Mail\WelcomeNewUserMail; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Support\Facades\Mail; use Log; class WelcomeNewUserListener implements ShouldQueue { /** * Handle the event. * * @param object $event * @return void */ public function handle($event) { try { // dispatch(new WelcomEmailJob($event->user)); } catch (\Exception $exception) { Log::error('Exception occurred on email'); Log::error(print_r($exception)); } } }
true
7256c5ded9d7d4f1558b77745a5a1c7cf9c6f11e
PHP
AminaInf/GPGISS
/Compagnie/modifierCompagnie.php
UTF-8
2,561
2.71875
3
[]
no_license
<html> <head> <meta charset="utf-8"> <title>modifier une compagnie</title> <meta charset="utf-8"> <link rel="stylesheet" href="stylec.css"> </head> <body> <div id ="conteneur"> <?php session_start(); /* if(!isset($_SESSION['login'])) { header("location:authentification.php?auth=Veuillez vous authentifier"); exit(); }*/ include('connexion.php'); if(isset($_GET['id'])) { $id=$_GET['id']; $result=mysql_query("select idUnite,idVil,nomComp,telephone,email from compagnie where idCompagnie='".$id."'"); while($liste=mysql_fetch_array($result)) { ?> <form action="modifierCompagnie.php" method="POST"> <table border="0" width="500px" cellpadding="10px" align="center"> <caption id="p">modifier une compagnie </caption> <br/><br/><br/> <tr><td>IdUnite:</td><td><input type="number" name="idUnite" value="<?php echo $liste['idUnite'];?>" size="35px" /></td></tr> <tr><td>IdVille:</td><td><input type="number" name="idVil" value="<?php echo $liste['idVil'];?>" size="35px" /></td></tr> <tr><td>NomCompagnie:</td><td><input type="text" name="nomComp" value="<?php echo $liste['nomComp'];?>" size="20px" /></td></tr> <tr><td>Telephone:</td><td><input type="number" name="telephone" value="<?php echo $liste['telephone'];?>" size="35px" /></td></tr> <tr><td>Email:</td><td><input type="text" name="email" value="<?php echo $liste['email'];?>" size="20px" /></td></tr> <tr><td colspan="2"><input type="hidden" name="idCompagnie" value="<?php echo $id;?> "size="35px" /></td></tr> <tr><td colspan="2"><input type="submit" name="modifier" value="modifier" id="btn"></td></tr> </table> </form> <?php } } ?> <?php if(isset($_GET['mod'])) { echo "<font color='red' size='4'><p align='center'>".$_GET['mod']."</p></font>"; } ?> <?php if(isset($_POST['modifier'])) { $idUnite=$_POST['idUnite']; $idVil=$_POST['idVil']; $nomComp=$_POST['nomComp']; $telephone=$_POST['telephone']; $email=$_POST['email']; $id=$_POST['idCompagnie']; $result=mysql_query("update compagnie set idUnite='".$idUnite."',idVil='".$idVil."',nomComp='".$nomComp."', telephone='".$telephone."',email='".$email."' where idCompagnie='".$id."'"); if($result) { //echo "Modification bien effectue"; header("location:listeCompagnie.php?mod=Modification bien effectuee"); exit(); } else { //echo "Echec de modification"; header("location:modifierCompagnie.php?mod=Echec modification&id=$id"); exit(); } } ?> </div> </body> </html>
true
876df4c1016d477c21e9f790b061e24b9d14e7f7
PHP
hulume/joydong
/app/Stario/Wesite/Repository/Eloquent/ArchiveRepo.php
UTF-8
441
2.734375
3
[]
no_license
<?php namespace Star\Wesite\Repository\Eloquent; use App\Archive; use Star\ICenter\Repository\Eloquent\BaseRepository; class ArchiveRepo extends BaseRepository { protected $model; // 定义字段用于前台vuetable检索 protected $fieldSearchable = [ 'name', 'mobile', 'identify', ]; /** * 必须在构造器中声明一下使用的模型 */ public function __construct(Archive $archive) { $this->model = $archive; } }
true
e49c1c72b38ca2c7c4919a7775e9fbd9a36b506e
PHP
googleads/googleads-php-lib
/src/Google/AdsApi/AdManager/v202302/CreativeAsset.php
UTF-8
4,677
2.625
3
[ "Apache-2.0" ]
permissive
<?php namespace Google\AdsApi\AdManager\v202302; /** * This file was generated from WSDL. DO NOT EDIT. */ class CreativeAsset { /** * @var int $assetId */ protected $assetId = null; /** * @var string $assetByteArray */ protected $assetByteArray = null; /** * @var string $fileName */ protected $fileName = null; /** * @var int $fileSize */ protected $fileSize = null; /** * @var string $assetUrl */ protected $assetUrl = null; /** * @var \Google\AdsApi\AdManager\v202302\Size $size */ protected $size = null; /** * @var \Google\AdsApi\AdManager\v202302\ClickTag[] $clickTags */ protected $clickTags = null; /** * @var string $imageDensity */ protected $imageDensity = null; /** * @param int $assetId * @param string $assetByteArray * @param string $fileName * @param int $fileSize * @param string $assetUrl * @param \Google\AdsApi\AdManager\v202302\Size $size * @param \Google\AdsApi\AdManager\v202302\ClickTag[] $clickTags * @param string $imageDensity */ public function __construct($assetId = null, $assetByteArray = null, $fileName = null, $fileSize = null, $assetUrl = null, $size = null, array $clickTags = null, $imageDensity = null) { $this->assetId = $assetId; $this->assetByteArray = $assetByteArray; $this->fileName = $fileName; $this->fileSize = $fileSize; $this->assetUrl = $assetUrl; $this->size = $size; $this->clickTags = $clickTags; $this->imageDensity = $imageDensity; } /** * @return int */ public function getAssetId() { return $this->assetId; } /** * @param int $assetId * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setAssetId($assetId) { $this->assetId = (!is_null($assetId) && PHP_INT_SIZE === 4) ? floatval($assetId) : $assetId; return $this; } /** * @return string */ public function getAssetByteArray() { return $this->assetByteArray; } /** * @param string $assetByteArray * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setAssetByteArray($assetByteArray) { $this->assetByteArray = $assetByteArray; return $this; } /** * @return string */ public function getFileName() { return $this->fileName; } /** * @param string $fileName * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setFileName($fileName) { $this->fileName = $fileName; return $this; } /** * @return int */ public function getFileSize() { return $this->fileSize; } /** * @param int $fileSize * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setFileSize($fileSize) { $this->fileSize = (!is_null($fileSize) && PHP_INT_SIZE === 4) ? floatval($fileSize) : $fileSize; return $this; } /** * @return string */ public function getAssetUrl() { return $this->assetUrl; } /** * @param string $assetUrl * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setAssetUrl($assetUrl) { $this->assetUrl = $assetUrl; return $this; } /** * @return \Google\AdsApi\AdManager\v202302\Size */ public function getSize() { return $this->size; } /** * @param \Google\AdsApi\AdManager\v202302\Size $size * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setSize($size) { $this->size = $size; return $this; } /** * @return \Google\AdsApi\AdManager\v202302\ClickTag[] */ public function getClickTags() { return $this->clickTags; } /** * @param \Google\AdsApi\AdManager\v202302\ClickTag[]|null $clickTags * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setClickTags(array $clickTags = null) { $this->clickTags = $clickTags; return $this; } /** * @return string */ public function getImageDensity() { return $this->imageDensity; } /** * @param string $imageDensity * @return \Google\AdsApi\AdManager\v202302\CreativeAsset */ public function setImageDensity($imageDensity) { $this->imageDensity = $imageDensity; return $this; } }
true
856286233fc84e3db0582711ab9f3519edc2d530
PHP
othercodes/rest
/src/Modules/Decoders/XMLRPCDecoder.php
UTF-8
721
2.640625
3
[ "MIT" ]
permissive
<?php namespace OtherCode\Rest\Modules\Decoders; /** * Class XMLRPCDecoder * @author Unay Santisteban <usantisteban@othercode.es> * @package OtherCode\Rest\Modules\Decoders */ class XMLRPCDecoder extends \OtherCode\Rest\Modules\Decoders\BaseDecoder { /** * The content type that trigger the decoder * @var string */ protected $contentType = 'text/xml'; /** * Decode the data of a request */ public function decode() { $response = xmlrpc_decode($this->body); if (is_array($response) && xmlrpc_is_fault($response)) { throw new \OtherCode\Rest\Exceptions\RestException($response['faultString'], $response['faultCode']); } $this->body = $response; } }
true
ae934e8e3f92260b5e76a1dd16b5c680cc822cbf
PHP
lushaoming/paypal
/src/Shannon/PayPal/Payment.php
UTF-8
7,941
2.59375
3
[]
no_license
<?php /** * Class Payment * @author 卢绍明<lusm@sz-bcs.com.cn> * @date 2019/8/29 */ namespace Shannon\PayPal; use PayPal\Api\Amount; use PayPal\Api\Details; use PayPal\Api\Item; use PayPal\Api\ItemList; use PayPal\Api\Payer; use PayPal\Api\PaymentExecution; use PayPal\Api\RedirectUrls; use PayPal\Api\Transaction; class Payment { private $items = array(); private $currency = 'USD'; private $productTotal = 0; private $shippingFee = 0; private $tax = 0; private $discount = 0; private $orderTotal = 0; private $orderNo; private $shipping; private $billing; private $payer; private $itemList; private $amount; private $detail; private $transaction; private $redirectUrl; private $applicationContext; public function init($data) { if (isset($data['products'])) $this->setItems($data['products']); if (isset($data['product_total'])) $this->setProductTotal($data['product_total']); if (isset($data['currency'])) $this->setCurrency($data['currency']); if (isset($data['tax'])) $this->setTax($data['tax']); $this->setOrderTotal(isset($data['order_total']) ? $data['order_total'] : 0); if (isset($data['shipping_fee'])) $this->setShippingFee($data['shipping_fee']); if (isset($data['discount'])) $this->setDiscount($data['discount']); if (isset($data['order_no'])) $this->setOrderNo($data['order_no']); if (isset($data['billing'])) $this->setBilling($data['billing']); if (isset($data['shipping'])) $this->setShipping($data['shipping']); if (isset($data['payer'])) $this->setPayer($data['payer']); if (isset($data['redirect_url'])) $this->setRedirectUrl($data['redirect_url']); if (isset($data['application_context'])) $this->setApplicationContext($data['application_context']); return $this; } public function setItems($products) { foreach ($products as $k => $product) { $this->items[$k] = new Item(); $this->items[$k]->setSku($product['sku']) ->setName($product['name']) ->setCurrency($this->currency) ->setQuantity($product['qty']) ->setPrice($product['price']) // setPrice():单价 ->setTax($product['line_tax']); $this->productTotal += $product['line_total']; } } public function setApplicationContext($applicationContext) { $this->applicationContext = $applicationContext; } public function setCurrency($currency) { $this->currency = $currency; } public function setTax($tax) { $this->tax = $tax; } public function setShippingFee($shippingFee) { $this->shippingFee = $shippingFee; } public function setDiscount($discount) { if (is_array($discount)) { $value = $discount['total']; $name = $discount['name']; } elseif (is_numeric($discount)) { $name = 'Discount'; $value = $discount; } else { throw new ShannonPaypalException('Param discount is invalid'); } $this->discount = $value; $discountItem = new Item(); $discountItem->setName($name) ->setCurrency($this->currency) ->setQuantity(1) ->setPrice($value) // setPrice():单价 ->setTax(0); $this->productTotal += $discount; $this->items[] = $discountItem; } public function setProductTotal($total) { $this->productTotal = $total; } public function setOrderTotal($total) { $this->orderTotal = $total; } public function setOrderNo($no) { $this->orderNo = $no; } public function getOrderNo() { if (empty($this->orderNo)) $this->orderNo = Core::createOrderNo(); return $this->orderNo; } public function setShipping($shipping) { $s = new ShippingAddress(); $s->setShippingAddress($shipping); $this->shipping = $s->getShippingAddress(); } public function setBilling($billing) { $s = new BillingAddress(); $s->setBillingAddress($billing); $this->billing = $s->getBillingAddress(); } public function setPayer($payer) { $payerInfo = new PayerInfo(); $p = $payerInfo->setPayerInfo($payer, $this->shipping, $this->billing); $this->payer = $payerInfo->setPayer(null, $p, 'paypal'); } public function setItemList(array $item, $shippingAddress) { $itemList = new ItemList(); if (count($item) > 0) $itemList->setItems($item); if ($shippingAddress) $itemList->setShippingAddress($shippingAddress); $this->itemList = $itemList; } public function setDetail(float $subTotal) { $detail = new Details(); // 运费,增值税 $detail->setShipping($this->shippingFee)->setTax($this->tax) ->setSubtotal($subTotal); $this->detail = $detail; } public function setAmount($detail, float $total) { if (empty($total)) throw new ShannonPaypalException('order_total is invalid'); $amount = new Amount(); $amount->setCurrency($this->currency) ->setTotal($total);// setTotal(): 订单总价,包含所有费用 if (!is_null($detail)) $amount->setDetails($detail); $this->amount = $amount; } public function setTransaction(Amount $amount, $itemList, string $orderNo) { $transaction = new Transaction(); $transaction->setAmount($amount) ->setInvoiceNumber($orderNo); if (!is_null($itemList)) $transaction->setItemList($itemList); $this->transaction = $transaction; } public function setRedirectUrl($redirect) { $redirectUrl = new RedirectUrls(); $redirectUrl->setReturnUrl($redirect['success']) ->setCancelUrl($redirect['cancel']); $this->redirectUrl = $redirectUrl; } /** * @param Payer $payer * @param Transaction $transaction * @param RedirectUrls $redirectUrl * @param string $paymentAction default sale * @return \PayPal\Api\Payment */ public function getPayment(Payer $payer, Transaction $transaction, RedirectUrls $redirectUrl, $paymentAction = 'sale') : \PayPal\Api\Payment { $payment = new \PayPal\Api\Payment(); $payment->setIntent($paymentAction) ->setPayer($payer) ->setRedirectUrls($redirectUrl) ->setTransactions([$transaction]); return $payment; } public function create($config = []) { $paypal = ApiContext::getInstance()->createContext($config); $this->setItemList($this->items, $this->shipping); $this->setDetail($this->productTotal); $this->setAmount($this->detail, $this->orderTotal); $orderNo = $this->getOrderNo(); $this->setTransaction($this->amount, $this->itemList, $orderNo); $payment = $this->getPayment($this->payer, $this->transaction, $this->redirectUrl); if ($this->applicationContext) { $payment->setApplicationContext($this->applicationContext); } $payment->create($paypal); return $payment; } public function receiptPayment($paymentId, $payerId) { $paypal = ApiContext::getInstance()->createContext(); $paymentExecute = new PaymentExecution(); $paymentExecute->setPayerId($payerId); $payment = new \PayPal\Api\Payment(); $payment->setId($paymentId)->execute($paymentExecute, $paypal); // 获取交易ID,可用于退款操作 $transaction = $payment->getTransactions(); $transactionId = $transaction[0]->related_resources[0]->sale->id; return $transactionId; } }
true
061927e06f37ffbe850579208ebc9eb20394181c
PHP
GlorianB/Camagru
/app/models/CommentModel.class.php
UTF-8
1,791
2.640625
3
[]
no_license
<?php class CommentModel { private $comment_id; private $user_id; private $image_id; private $content; public function __construct() {} public function add(UserModel $user) { ORM::getInstance()->insert("comment", ["user_id", "image_id", "content"], ["user_id" => $this->getUserId(), "image_id" => $this->getImageId(), "content" => $this->getContent()]); echo "Comment added with success!"; if ($user->getPreference() === "1")\ mail($user->getEmail(), "New comment", "Your image has received a new comment ! Checkout on http://localhost:8080/camagru/"); echo "<br><br>You will be redirected..."; App::delay_redirect(5, "/camagru/home"); } public static function commentators(array $comments, UserModel $user) { $result = array(); foreach ($comments as $comment) { $user = ORM::getInstance()->select("user", ["user_id" => $comment["user_id"]]); $result[] = ["login" => $user->getLogin(), "content" => $comment["content"]]; } return $result; } public function getCommentId() { return $this->comment_id; } public function getUserId() { return $this->user_id; } public function getImageId() { return $this->image_id; } public function getContent() { return $this->content; } public function setCommentId($comment) { $this->comment = $comment; } public function setUserId($user_id) { $this->user_id = $user_id; } public function setImageId($image_id) { $this->image_id = $image_id; } public function setContent($content) { $this->content = $content; } } ?>
true
2ea7c13caa29f8d140431e7b6f7c0d23246c4198
PHP
EPAMHackathons/2017-mogilev-hashtag
/include/misc/images.inc.php
UTF-8
3,111
2.625
3
[]
no_license
<? function resize_im($dir, $fname) { $res = false; $im = imagecreatefromstring(file_get_contents(DOC_ROOT . $dir . '/' . $fname)); if (!$im) return false; $w = $imw = imagesx($im); $h = $imh = imagesy($im); $th_w = $w; $th_h = $h; $move_w = $move_h = 0; $img_maxsize = 300; $th_w = $img_maxsize; $th_h = round($th_w * ($imh / $imw)); $resized = imageCreatetruecolor($th_w, $th_h); $created = fastimagecopyresampled($resized, $im, 0, 0, 0, 0, $th_w, $th_h, $imw, $imh); //Grab new image $res = imagejpeg($resized, DOC_ROOT . $dir . '/th-' . $fname, 80); return $res; } function fastimagecopyresampled(&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) { // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled. // Just include this function and change all "imagecopyresampled" references to "fastimagecopyresampled". // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting. // Author: Tim Eckel - Date: 12/17/04 - Project: FreeRingers.net - Freely distributable. // // Optional "quality" parameter (defaults is 3). Fractional values are allowed, for example 1.5. // 1 = Up to 600 times faster. Poor results, just uses imagecopyresized but removes black edges. // 2 = Up to 95 times faster. Images may appear too sharp, some people may prefer it. // 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled. // 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images. // 5 = No speedup. Just uses imagecopyresampled, highest quality but no advantage over imagecopyresampled. if (empty($src_image) || empty($dst_image)) { return false; } if ($quality <= 1) { $temp = imagecreatetruecolor($dst_w + 1, $dst_h + 1); imagecopyresized($temp, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w + 1, $dst_h + 1, $src_w, $src_h); imagecopyresized($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $dst_w, $dst_h); imagedestroy($temp); } elseif ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) { $tmp_w = $dst_w * $quality; $tmp_h = $dst_h * $quality; $temp = imagecreatetruecolor($tmp_w + 1, $tmp_h + 1); imagecopyresized($temp, $src_image, $dst_x * $quality, $dst_y * $quality, $src_x, $src_y, $tmp_w + 1, $tmp_h + 1, $src_w, $src_h); imagecopyresampled($dst_image, $temp, 0, 0, 0, 0, $dst_w, $dst_h, $tmp_w, $tmp_h); imagedestroy($temp); } else { imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); } return true; } function get_im_size($fname) { $res = array('w' => 0, 'h' => 0); $im = imagecreatefromstring( file_get_contents($fname) ); if (!$im) return false; $res['w'] = imagesx($im); $res['h'] = imagesy($im); return $res; } ?>
true
8d0b06dcb95aaa076f3bc198d63db3469c26696d
PHP
KhinZinZinThinn/phpPos
/pos/user_config.php
UTF-8
3,444
2.734375
3
[]
no_license
<?php include 'db_config.php'; session_start(); class User extends DB{ public function register($name,$email,$password,$password_again){ if($name){ if($email){ $sql_email="select email from users where email='$email'"; $db_email=$this->db->query($sql_email)->fetch(PDO::FETCH_ASSOC); if (!$db_email){ if ($password){ if ($password_again){ if ($password==$password_again){ $enc_password=md5($password); $insert="insert into users(name,email,password,created_at) values('$name','$email','$enc_password',now())"; $result=$this->db->query($insert); if ($result){ header("location: login.php"); }else{ $_SESSION['err']="The user account sign up have been failed!"; header("location: register.php"); } }else{ $_SESSION['err']="Password and password again do not match"; header("location: register.php"); } } else{ $_SESSION['err']="Password again field is required"; header("location: register.php"); } }else{ $_SESSION['err']="Password field is required"; header("location: register.php"); } } else{ $_SESSION['err']="This email is already registered!"; header("location: register.php"); } }else{ $_SESSION['err']="Email address field is required"; header("location: register.php"); } }else{ $_SESSION['err']="Username field is required"; header("location: register.php"); } } public function login($email,$password){ if ($email){ $sql="select id, name, email, password from users where email='$email'"; $row=$this->db->query($sql)->fetch(PDO::FETCH_ASSOC); if ($row['email']){ if ($password){ $enc_password=md5($password); $db_password=$row['password']; if ($enc_password==$db_password){ $_SESSION['login']=$row['name']; $_SESSION['user_id']=$row['id']; header("location:home.php"); }else{ $_SESSION['err']="Email and password do not match"; header("location: login.php"); } }else{ $_SESSION['err']="Password field is required"; header("location: login.php"); } }else{ $_SESSION['err']="The selected email is not found on server!!!"; header("location: login.php"); } }else{ $_SESSION['err']="Email field is required"; header("location: login.php"); } } }
true
eebf1bbf6603fcab95cc6fe8587502db7576a688
PHP
tbauer2811/gnd-wikibase-converter
/src/GndItem.php
UTF-8
1,558
3.234375
3
[]
no_license
<?php declare( strict_types = 1 ); namespace DNB\WikibaseConverter; /** * Information to construct a single Wikibase Item from. */ class GndItem { public const GND_ID = 'P150'; /** @var array<string, array<int, GndStatement>> */ private array $map = []; public function __construct( GndStatement ...$gndStatements ) { $this->addGndStatements( $gndStatements ); } /** * @param GndStatement[] $gndStatements */ public function addGndStatements( array $gndStatements ): void { foreach ( $gndStatements as $statement ) { $this->addGndStatement( $statement ); } } public function addGndStatement( GndStatement $gndStatement ): void { $this->map[$gndStatement->getPropertyId()][] = $gndStatement; } /** * @return array<int, string> */ public function getPropertyIds(): array { return array_keys( $this->map ); } /** * @return array<int, string> */ public function getMainValuesForProperty( string $propertyId ): array { $mainValues = []; foreach ( $this->map[$propertyId] ?? [] as $gndStatement ) { $mainValues[] = $gndStatement->getValue(); } return $mainValues; } /** * @return array<int, GndStatement> */ public function getStatementsForProperty( string $propertyId ): array { if ( array_key_exists( $propertyId, $this->map ) ) { return $this->map[$propertyId]; } return []; } public function getNumericId(): ?int { foreach ( $this->getMainValuesForProperty( self::GND_ID ) as $gndId ) { return ( new IdConverter() )->gndToNumericId( $gndId ); } return null; } }
true
db65fcc551fc3577d95ee650345566363a6e1f44
PHP
insafzakariya/kiki_cms_v2-
/core/app/Http/Controllers/SolrUploadController.php
UTF-8
17,456
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; ini_set('max_execution_time', 0); use App\Http\Controllers\Controller; use ArtistManage\Models\Artist; use Exception; use Illuminate\Http\Request; use Log; use PlaylistManage\Models\AudioPlaylist; use ProductManage\Models\Product; use SongManage\Models\Songs; class SolrUploadController extends Controller { private $solrController; private $limit; public function __construct(SolrController $solrController) { $this->solrController = $solrController; $this->limit = env("Solr_Limit", 1000); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } /** * Remove all solr document * @return string */ public function removeAllSolr() { try { $this->solrController->delete_all_music_client(); return "All records are deleted"; } catch (Exception $exception) { Log::error("solr remove all error " . $exception->getMessage()); } // $this->solrController->; } /** * refresh all songs solr documents * @return string */ public function allSongs() { try { $songs = Songs::with([ 'projects', 'products', 'writer', 'composer', 'publisher', 'subCategory', ])->take($this->limit)->get(); $this->solrController->delete_all_song(); foreach ($songs as $song) { $this->songSolr($song); } return $songs->count() . " songs records successfully updated"; } catch (Exception $exception) { Log::error("song solr bulk upload error " . $exception->getMessage()); } } /** * refresh song document by ID * @param $id * @return string */ public function song($id) { try { $song = Songs::with([ 'projects', 'products', 'writer', 'composer', 'publisher', 'subCategory', ]) ->where('songId', $id) ->first(); if ($song) { $this->solrController->kiki_song_delete_by_id($song->songId); $this->songSolr($song); return "Song ID -$id record successfully updated"; } else { return "Song ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("single song solr bulk upload error " . $exception->getMessage()); } } public function songDeleteAll() { try { $this->solrController->delete_all_song(); return "All songs record are deleted successfully"; } catch (Exception $exception) { Log::error("single song solr bulk upload error " . $exception->getMessage()); } } /** * Song solr document delete by ID * @param $id * @return string */ public function songDelete($id) { try { $song = Songs::where('songId', $id) ->first(); if ($song) { $this->solrController->kiki_song_delete_by_id($song->songId); return "song ID -$id record successfully Deleted"; } } catch (Exception $exception) { Log::error("single song solr bulk upload error " . $exception->getMessage()); } } /** * refresh artist document * @return string */ public function allArtist() { try { $artists = Artist::take($this->limit)->get(); //$artists = Artist::take(10)->get(); $this->solrController->delete_all_artist(); foreach ($artists as $artist) { //need to create a function //$this->solrController->kiki_artist_delete_by_id($artist->artistId); $this->artistSolr($artist); } return $artists->count() . " artists records successfully updated"; } catch (Exception $exception) { Log::error("artist solr bulk upload error " . $exception->getMessage()); } } /** * refresh artist document by ID * @param $id * @return string */ public function artist($id) { try { $artist = Artist::find($id); if ($artist) { $this->solrController->kiki_artist_delete_by_id($id); $this->artistSolr($artist); return "Artist ID -$id record successfully updated"; } else { return "Artist ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("single artist solr bulk upload error " . $exception->getMessage()); } } /** * delete all artist document * @return string */ public function artistDeleteAll() { try { $this->solrController->delete_all_artist(); return "All artists record are deleted successfully"; } catch (Exception $exception) { Log::error("single artist solr bulk upload error " . $exception->getMessage()); } } /** * Artist solr document delete by ID * @param $id * @return string */ public function artistDelete($id) { try { $artist = Artist::find($id); if ($artist) { $this->solrController->kiki_artist_delete_by_id($id); return "Artist ID -$id record successfully Deleted"; } else { return "Artist ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("single artist solr bulk upload error " . $exception->getMessage()); } } /** * refresh playlist document * @return string */ public function allPlaylist() { try { $playlists = AudioPlaylist::where('playlist_type', 'g')->take($this->limit)->get(); $this->solrController->delete_all_playlist(); foreach ($playlists as $playlist) { $this->playListSolr($playlist); } return $playlists->count() . " playlists records successfully updated"; } catch (Exception $exception) { Log::error("song solr bulk upload error " . $exception->getMessage()); } } /** * refresh playlist document by ID * @param $id * @return string */ public function playlist($id) { try { $playList = AudioPlaylist::where('playlist_type', 'g')->find($id); if ($playList) { $this->solrController->kiki_playlist_delete_by_id($id); $this->playListSolr($playList); return "Playlist ID -$id record successfully updated"; } else { return "Playlist ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("single playlist solr bulk upload error " . $exception->getMessage()); } } /** * * @return string */ public function playlistDeleteAll() { try { $this->solrController->delete_all_playlist(); return "All playlists record are deleted successfully"; } catch (Exception $exception) { Log::error("single playlist solr bulk upload error " . $exception->getMessage()); } } /** * playlist solr document delete by ID * @param $id * @return string */ public function playlistDelete($id) { try { $playList = AudioPlaylist::where('playlist_type', 'g')->find($id); if ($playList) { $this->solrController->kiki_playlist_delete_by_id($id); return "Playlist ID -$id record successfully Deleted"; } else { return "Playlist ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("single playlist solr bulk upload error " . $exception->getMessage()); } } /** * refresh album document * @return string */ public function allAlbum() { try { $products = Product::with('projectCategory') ->where('type', 'Album') ->take($this->limit) ->get(); $this->solrController->delete_all_product(); foreach ($products as $product) { $this->productSolr($product); } return $products->count() . " albums records successfully updated"; } catch (Exception $exception) { Log::error("Album solr bulk upload error " . $exception->getMessage()); } } /** * refresh album document by ID * @param $id * @return string */ public function album($id) { try { $product = Product::with('projectCategory') ->where('type', 'Album') ->find($id); if ($product) { $this->solrController->kiki_product_delete_by_id($id); $this->productSolr($product); return "Album ID -$id record successfully updated"; } else { return "Album ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("Album album solr bulk upload error " . $exception->getMessage()); } } /** * album solr document delete * @return string */ public function albumDeleteAll() { try { $this->solrController->delete_all_product(); return "All albums record are deleted successfully"; } catch (Exception $exception) { Log::error("Album album solr bulk upload error " . $exception->getMessage()); } } /** * album solr document delete by ID * @param $id */ public function albumDelete($id) { try { $product = Product::with('projectCategory') ->where('type', 'Album') ->find($id); if ($product) { $this->solrController->kiki_product_delete_by_id($id); return "Album ID -$id record successfully Deleted"; } else { return "Album ID -$id not found. Please recheck ID"; } } catch (Exception $exception) { Log::error("Album album solr bulk upload error " . $exception->getMessage()); } } /** * @param $song */ private function songSolr($song) { try { if ($song) { $data = array( 'id' => $song->songId, //id is required 'Name' => $song->name, 'Description' => $song->description, 'ISRC Code' => $song->isbc_code, 'Primary Category' => $song->category ? $song->category->name : '', 'Sub Category' => $song->subCategory ? $song->subCategory->name : '', //'Image URL' => $song->image ? Config('constants.bucket.url') . Config('filePaths.front.song-image') . $song->image : '', 'Image URL' => $song->image ? $song->image : '', 'Song URL' => $song->streamUrl ? $song->streamUrl : '', 'Primary Artist' => $song->primaryArtists()->lists('name')->toArray(), 'Featured Artist' => $song->featuredArtists()->lists('name')->toArray(), 'Search Tags' => $song->search_tag, 'Mood' => $song->mood()->lists('name')->toArray(), 'Genre' => $song->genres()->lists('Name')->toArray(), 'Duration' => $song->durations, 'Upload Date' => $song->uploaded_date, 'End Date' => $song->end_date, 'Release Date' => $song->release_date, 'Status' => $song->status == 1 ? 'Active' : "Inactive", ); $this->solrController->kiki_song_create_document($data); } } catch (Exception $exception) { Log::error("song solr bulk upload create error " . $exception->getMessage()); } } /** * @param $artist */ private function artistSolr($artist) { try { if ($artist) { $similar_id = $artist->similarArtists()->lists('similar_artist_id')->toArray(); $similarArtist = ''; if ($similar_id) { $similarArtist = Artist::whereIn('artistId', $similar_id)->lists('name')->toArray(); } $data = array( 'id' => $artist->artistId, //id is required 'Name' => $artist->name, 'Description' => $artist->description, //'Image URL' => $artist->image ? Config('constants.bucket.url').Config('filePaths.front.artist').$artist->image : '' , 'Image URL' => $artist->image ? $artist->image : '', 'Search Tags' => $artist->search_tag, 'Similar Artists' => $similarArtist, 'Status' => $artist->status == 1 ? 'Active' : "Inactive", ); $this->solrController->kiki_artist_create_document($data); } } catch (Exception $exception) { Log::error("artist solr bulk upload create error" . $exception->getMessage()); } } /** * @param $playList */ private function playListSolr($playList) { try { if ($playList) { $data = array( 'id' => $playList->id, //id is required 'Name' => $playList->name, 'Description' => $playList->description, 'Type' => $playList->type_name, 'Release Date' => $playList->release_date ? date('Y-m-d', strtotime($playList->release_date)) : '', 'Publish Date' => $playList->publish_date ? date('Y-m-d', strtotime($playList->publish_date)) : '', 'END Date' => $playList->expiry_date ? date('Y-m-d', strtotime($playList->expiry_date)) : '', //'Image URL' => $playList->image ? Config('constants.bucket.url'). Config('filePaths.front.playlist') .$playList->image : '', 'Image URL' => $playList->image ? $playList->image : '', 'Status' => $playList->status == 1 ? 'Active' : "Inactive", ); $this->solrController->kiki_playlist_create_document($data); } } catch (Exception $exception) { Log::error("Playlist solr bulk upload create error " . $exception->getMessage()); } } /** * @param $product */ private function productSolr($product) { try { if ($product) { $data = array( 'id' => $product->id, //id is required 'Name' => $product->name, 'Type' => $product->type, 'Description' => $product->description, 'Primary Artist' => $product->artists()->lists('name')->toArray(), //'Image URL' => $product->image ? Config('constants.bucket.url') . Config('filePaths.front.product') . $product->image : '', 'Image URL' => $product->image ? $product->image : '', 'Primary Category' => $product->projectCategory ? $product->projectCategory->name : '', 'Status' => $product->status == 1 ? 'Active' : "Inactive", ); $this->solrController->kiki_product_create_document($data); } } catch (Exception $exception) { Log::error("product solr error " . $exception->getMessage()); } } }
true
e8a2cfaaacf354951ffe74a905fd047b51064e1e
PHP
lobostome/FurryBear
/src/FurryBear/Http/Adapter/Curl.php
UTF-8
3,281
2.90625
3
[ "MIT" ]
permissive
<?php /** * FurryBear * * PHP Version 5.3 * * @category Congress_API * @package FurryBear * @author lobostome <lobostome@local.dev> * @license http://opensource.org/licenses/MIT MIT License * @link https://github.com/lobostome/FurryBear */ namespace FurryBear\Http\Adapter; use FurryBear\Common\Exception\NoResultException, FurryBear\Proxy\Curl as CurlProxy, FurryBear\Http\HttpAdapterInterface; /** * A HTTP adapter based on curl. * * @category Congress_API * @package FurryBear * @author lobostome <lobostome@local.dev> * @license http://opensource.org/licenses/MIT MIT License * @link http://curl.haxx.se/ */ class Curl implements HttpAdapterInterface { /** * The contents of the <code>"User-Agent: "</code> header to be used in a * HTTP request. * * @var string */ protected $userAgent = 'FurryBear via cURL'; /** * An array of HTTP header fields to set, in the format: * <code> * array('Content-type: text/plain', 'Content-length: 100') * </code> * * @var array */ protected $headers = array(); /** * A reference to a cURL proxy object. * * @var \FurryBear\Proxy\Curl */ protected $proxy = null; /** * Construct with an optional cURL proxy object. * * @param \FurryBear\Proxy\Curl $proxy A Curl proxy object. */ public function __construct($proxy = null) { if (!is_null($proxy)) { $this->proxy = $proxy; } } /** * {@inheritdoc} * * @param string $url A URL of the resource. * * @return string */ public function getContent($url) { if (is_null($this->proxy)) { $this->proxy = new CurlProxy($url); } $this->proxy->setOption(CURLOPT_RETURNTRANSFER, true); $this->proxy->setOption(CURLOPT_USERAGENT, $this->userAgent); if (!empty($this->headers)) { $this->proxy->setOption(CURLOPT_HTTPHEADER, $this->headers); } if (parse_url($url, PHP_URL_SCHEME) === 'https') { $this->proxy->setOption(CURLOPT_SSL_VERIFYHOST, 2); $this->proxy->setOption(CURLOPT_SSL_VERIFYPEER, 1); $this->proxy->setOption(CURLOPT_CAINFO, __DIR__ . '/cacert.pem'); } $content = $this->proxy->execute(); if ($content === false) { throw new NoResultException($this->proxy->getError()); } $this->proxy->close(); $this->proxy = null; return $content; } /** * {@inheritdoc} * * @param array $headers An array of HTTP headers. * * @return void */ public function setHeaders(array $headers) { $this->headers = $headers; } /** * {@inheritdoc} * * @param string $userAgent A custom user agent. * * @return void */ public function setUserAgent($userAgent) { $this->userAgent = $userAgent; } /** * Clean up the cURL proxy object */ public function __destruct() { if (!is_null($this->proxy)) { $this->proxy->close(); } $this->proxy = null; } }
true
3cfc7460513c40fdcf3a2d0438dc58706ad6e2da
PHP
richard5682/PrototypeAngular
/backend/lib/Session/SessionLibrary.php
UTF-8
1,578
2.828125
3
[]
no_license
<?php $GLOBAL_TIMEOUT = 3600; $TIMEOUT_SYNTAX = "_expiration"; session_start(); //USE TO CHECK TOKEN $token is the name of the Session variable function checkToken($token){ if(checkTimeout($token)){ return false; }else{ if(isset($_SESSION[$token])){ if($_SESSION[$token] == $_GET['token']){ return true; } }else{ return false; } } return false; } //USE TO GENERATE NEW TOKEN function generateToken($varname){ $token = bin2hex(random_bytes(16)); createSession($varname,$token); return $token; } //USE TO CREATE SESSION VARIABLE WITH VARNAME AND VALUE AND THE OPTIONAL //EXPIRATION TIME IN SECONDS function createSession($varname,$value,$expiration=null){ global $GLOBAL_TIMEOUT; global $TIMEOUT_SYNTAX; $_SESSION[$varname] = $value; if($expiration == null){ if($GLOBAL_TIMEOUT != null){ $_SESSION[$varname.$TIMEOUT_SYNTAX]=time()+$GLOBAL_TIMEOUT; } }else{ $_SESSION[$varname.$TIMEOUT_SYNTAX]=time()+$expiration; } } //DELETE THE SESSION WITH THE INDEX OF $varname function deleteSession($varname){ global $TIMEOUT_SYNTAX; if(isset($_SESSION[$varname])){ unset($_SESSION[$varname]); } if(isset($_SESSION[$varname.$TIMEOUT_SYNTAX])){ unset($_SESSION[$varname.$TIMEOUT_SYNTAX]); } } //CHECK IF THE SESSION IS EXPIRED function checkTimeout($varname){ global $TIMEOUT_SYNTAX; if(isset($_SESSION[$varname.$TIMEOUT_SYNTAX])){ if($_SESSION[$varname.$TIMEOUT_SYNTAX]<time()){ deleteSession($varname); return true; }else{ return false; } } return true; } ?>
true
aa1525089fb29186a83abbfd0882d1c79e26db97
PHP
bootiq/service-layer
/src/Response/ResponseInterface.php
UTF-8
494
2.5625
3
[ "Apache-2.0" ]
permissive
<?php namespace BootIq\ServiceLayer\Response; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; interface ResponseInterface { /** * @return bool */ public function isError(): bool; /** * @return int */ public function getHttpCode(): int; /** * @return string */ public function getResponseData(): string; /** * @return PsrResponseInterface */ public function getPsrResponse(): PsrResponseInterface; }
true
b28b11549f638942bace26fe60e0c406b47d5d85
PHP
ra5k/handlebars
/src/Script/Memory.php
UTF-8
1,247
2.734375
3
[ "MIT" ]
permissive
<?php /* * This file is part of the Ra5k Handlebars implementation * (c) 2019 Ra5k <ra5k@mailbox.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Ra5k\Handlebars\Script; // [imports] use Ra5k\Handlebars\{Script}; /** * * * */ final class Memory implements Script { /** * @var string */ private $name; /** * @var string */ private $hash; /** * @var string */ private $content; /** * @param string $content */ public function __construct(string $content, string $name = '') { $this->content = $content; $this->name = $name; } public function id(): string { return $this->hash(); } public function name(): string { return $this->name ?: $this->hash(); } public function content(): string { return $this->content; } public function exists(): bool { return true; } private function hash(): string { if ($this->hash === null) { $this->hash = sha1($this->content); } return $this->hash; } }
true
cf803c8d4f2311464cc484cd7a3823ae49633c4c
PHP
marfrancis/LojaVirtualComMySQL
/produto.php
UTF-8
1,563
2.515625
3
[]
no_license
<?php include_once 'conexao.php'; ?><!DOCTYPE html> <html lang="pt"> <?php include"head.php"; ?> <body> <?php include"header.php"; ?> <?php $produto = new Produto(['id'=>$_GET['produto']]); $produtos = Produto::pesquisarUm($produto); if(sizeof($produtos) != 1) die("Resultado não encontrado"); $produto = $produtos[0]; ?> <div class="container"> <div class="jumbotron"> <div class="row"> <div class="col-12"> <!-- Aqui temos um botão com um código JavaScript que muda o endereço do navegador para index.php --> <button onclick="window.location='index.php'" class="btn btn-info">👈 Voltar pra lista de produtos</button> </div> </div> <div class="mb-4"></div> <!-- Imprimimos na tela as informações do produto e sua foto --> <div class="row"> <div class="col-5"> <img class="img-fluid" src="<?php echo $produto->imagem ?>" /> </div> <div class="col-7"> <h1><?php echo $produto->nome ?></h1> <p>Descrição</p> <h5><?php echo $produto->descricao ?></h5> <p>Preço</p> <h5><?php echo $produto->preco ?></h5> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script> </body> </html>
true
2fb4c7492191f15c7964e03cc7e6260601714058
PHP
estefansilvi/php-snacks-b1
/index.php
UTF-8
1,883
2.953125
3
[]
no_license
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> </head> <body> <!-- snack-1 --> <?php echo '<h1><b>Snack 1 - Partite di Basket di un’ipotetica tappa del calendario</b></h1>'; $matches = [ [ 'homeTeam' => 'Dinamo Sassari', 'guestTeam' => 'Venezia', 'homeTeamPoints' => 96, 'guestTeamPoints' => 88 ], [ 'homeTeam' => 'Brindisi', 'guestTeam' => 'Trieste', 'homeTeamPoints' => 81, 'guestTeamPoints' => 74 ], [ 'homeTeam' => 'Cremona', 'guestTeam' => 'Trento', 'homeTeamPoints' => 95, 'guestTeamPoints' => 87 ], [ 'homeTeam' => 'Olimpia MIlano', 'guestTeam' => 'Fortitudo Bologna', 'homeTeamPoints' => 98, 'guestTeamPoints' => 72 ], [ 'homeTeam' => 'Cantù', 'guestTeam' => 'Treviso', 'homeTeamPoints' => 105, 'guestTeamPoints' => 54 ], [ 'homeTeam' => 'Brescia', 'guestTeam' => 'Reggiana', 'homeTeamPoints' => 42, 'guestTeamPoints' => 99 ] ]; for ($i = 0; $i < count($matches); $i++) { $partita = $matches[$i]; echo $partita['homeTeam'] . ' - ' . $partita['guestTeam'] . ' | ' . $partita['homeTeamPoints'] . ' - ' . $partita['guestTeamPoints'] . '<br><br>'; }; // SNACK 2********************************************************* echo '<h1><b> Snack 2 - Passare come parametri GET name, mail e age</b></h1>'; $name = $_GET['name']; $mail = $_GET['mail']; $age = $_GET['age']; if (strlen($name) > 3 && strpos($mail, '@') !== false && strpos($mail, '.') !== false && is_numeric($age)) { echo 'Accesso autorizzato. Benvenuto/a'; } else { echo 'Attenzione! Accesso negato!'; } ?> </body> </html>
true
d3c33e58925db816d4914b45df4a81843dfa4ab9
PHP
kaaterskil/phprt
/KM/IO/ObjectInput.php
UTF-8
3,142
2.6875
3
[]
no_license
<?php /** * Copyright (c) 2009-2014 Kaaterskil Management, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ namespace KM\IO; use KM\Lang\ClassNotFoundException; /** * ObjectInput extends the DataInput interface to include the reading of * objects. DataInput includes methods for the input of primitive types, * ObjectInput extends that interface to include objects, arrays, and Strings. * * @author Blair */ interface ObjectInput extends DataInput { /** * Read and return an object. The class that implements this interface * defines where the object is "read" from. * * @return \KM\Lang\Object The object read from the stream. * @throws ClassNotFoundException if the class of a serialized object cannot * be found. * @throws IOException if an I/O error has occurred. */ public function readObject(); /** * Reads into an array of bytes. This method will block until some input is * available. * * @param array $b The buffer into which the data is read. * @param int $off The start offset of the data. * @param int $len The maximum number of bytes read. * @return int The actual number of bytes read. -1 is returned when the end * of the stream is reached. * @throws IOException if an I/O error has occurred. */ public function read(array &$b, $off = 0, $len = null); /** * Skips n bytes of input. * * @param int $n The number of bytes to be skipped. * @return int The actual number of bytes skipped. * @throws IOException if an I/O error has occurred. */ public function skip($n); /** * Returns the number of bytes that can be read without blocking. * * @return int THe number of available bytes. * @throws IOException if an I/O error has occurred. */ public function available(); /** * Closes the input stream. Must be called to release any resources * associated with the stream. * * @throws IOException if an I/O error has occurred. */ public function close(); } ?>
true
6742678cc75b472d2825c1bd95af162984f0014e
PHP
ontzuevanhussen/bariblocksites
/modules/backup-database/backup.php
UTF-8
2,404
2.703125
3
[]
no_license
<?php session_start(); // memulai session // Mengecek AJAX Request if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' )) { // panggil file "config.php" untuk koneksi ke database require_once "../../config/config.php"; // panggil file "fungsi_backup_import.php" untuk backup database require_once "../../config/fungsi_backup_import.php"; // panggil file "fungsi_file_size.php" untuk mengetahui file size database require_once "../../config/fungsi_file_size.php"; try { // parameter backup database $date = gmdate("Ymd_His", time()+60*60*7); // waktu backup $dir = "../../database"; // direktori file hasil backup $name = $date.'_database'; // nama file sql hasil backup // jalankan perintah backup database $backup = backup_database( $dir, $name, $con['host'], $con['user'], $con['pass'], $con['db']); // mengecek proses backup database // jika backup database berhasil if ($backup) { // siapkan "data" $nama_file = $name.".sql.gz"; $ukuran_file = MakeReadable(filesize($dir."/".$nama_file)); // ambil "data" dari session $created_user = $_SESSION['id_user']; // sql statement untuk insert data ke tabel "sys_database" $query = "INSERT INTO sys_database(nama_file, ukuran_file, created_user) VALUES (:nama_file, :ukuran_file, :created_user)"; // membuat prepared statements $stmt = $pdo->prepare($query); // hubungkan "data" dengan prepared statements $stmt->bindParam(':nama_file', $nama_file); $stmt->bindParam(':ukuran_file', $ukuran_file); $stmt->bindParam(':created_user', $created_user); // eksekusi query $stmt->execute(); // cek query if ($stmt) { // jika berhasil tampilkan pesan "sukses" echo "sukses"; } } // tutup koneksi $pdo = null; } catch (PDOException $e) { // tampilkan pesan kesalahan echo $e->getMessage(); } } else { // jika tidak ada ajax request, maka alihkan ke halaman "login-error" echo '<script>window.location="../../login-error"</script>'; } ?>
true
38962c162fe70335a342701262bdb87bb8e4572e
PHP
shama/oven
/Console/Command/InitShell.php
UTF-8
2,433
2.734375
3
[ "MIT" ]
permissive
<?php App::uses('OvenAppShell', 'Oven.Console/Command'); /** * Init Shell * Inits Oven and creates a Config/database.php if it does not exist * * @package Oven * @author Kyle Robinson Young <kyle at dontkry.com> * @copyright 2012 Kyle Robinson Young */ class InitShell extends OvenAppShell { /** * uses * * @var array */ public $uses = array('Oven.Init'); /** * Options available * * @var array */ protected $_options = array( 'datasource' => array( 'short' => 's', 'help' => 'CakePHP DataSource.', 'default' => 'Database/Mysql', ), 'host' => array( 'short' => 'o', 'help' => 'Database host', 'default' => 'localhost', ), 'login' => array( 'short' => 'u', 'help' => 'Database login/username', 'default' => 'username', ), 'password' => array( 'short' => 'p', 'help' => 'Database password', 'default' => 'password', ), 'database' => array( 'short' => 'd', 'help' => 'Database name', 'default' => 'database', ), 'prefix' => array( 'short' => 'x', 'help' => 'Database table prefix', 'default' => '', ), ); /** * __construct * * @param ConsoleOutput $stdout * @param ConsoleOutput $stderr * @param ConsoleInput $stdin */ public function __construct($stdout = null, $stderr = null, $stdin = null) { parent::__construct($stdout, $stderr, $stdin); foreach ($this->_options as $key => $option) { $this->_options[$key]['help'] = __d('oven', $option['help']); } } /** * main */ public function main() { $this->_header(); $this->_gatherParams(); $this->out('Turning on the Oven... ', 0); try { $this->Init->all($this->params); } catch(Exception $e) { $this->out('<bad>failed!</bad>'); $this->out($e->getMessage()); return; } $this->out('<good>careful it\'s hot!</good>'); } /** * Gather missing params * * @return boolean */ protected function _gatherParams() { $required = array('login', 'password', 'database'); foreach ($required as $key) { if ($this->params[$key] == $this->_options[$key]['default']) { $this->params[$key] = $this->in('Database ' . $key . '?', null, $this->params[$key]); } } return true; } /** * getOptionParser * * @return array */ public function getOptionParser() { return ConsoleOptionParser::buildFromArray(array( 'command' => 'Oven.init', 'description' => array(__d('oven', 'Automatically initialize Oven')), 'options' => $this->_options, )); } }
true
7c2a295b58147f3b7512f1f418fb2c22eb6a0c6a
PHP
jovijovi-john/PHP7
/Aula-29/manipular_arrays.php
UTF-8
4,330
3.90625
4
[]
no_license
<html> <head> <meta charset="UTF-8"> <title>Aula 29 - Funções Nativas para manipulação de arrays</title> </head> <body> <?php /* * => is_array(array) Verifica se o parametro é um array * => array_keys(array) Retorna todas as chaves(keys/indices) de um array * => sort(array) -> retorna true ou false Ordena um array e reajusta seus índices. A ordenação é feita no proprio array que foi passado * => asort(array) Ordena um array preservando seus índices * => count(array) Conta a quantidade de elementos de um array * => array_merge(array) Funde um ou mais arrays * => explode(array) Divide uma string baseado num delimitador * => implode(array) Justa elementos de um array em uma string */ /* ? is_array $array = 'String'; $retorno = is_array($array); echo $retorno ? "É array <br/>" : "Não é array <br/>" */ /* ?array_keys $array = ["nome" => "john", "sobrenome" => "victor", "idade" => 19]; echo "<pre>"; print_r($array); echo "</pre>"; $chaves_array = array_keys($array); echo "<pre>"; print_r($chaves_array); echo "</pre>"; */ /* ?sort $array_compras = ["notebook", "placa de video", "mesa digitalizadora", "monitor", "cooler", "led"]; echo "<h2>Array desordenado:</h2><pre>"; print_r($array_compras); echo "</pre>"; sort($array_compras); echo "<h2>Array ordenado:</h2><pre>"; print_r($array_compras); echo "</pre>"; */ /* ?asort $array_compras = ["notebook", "placa de video", "mesa digitalizadora", "monitor", "cooler", "led"]; echo "<h2>Array desordenado:</h2><pre>"; print_r($array_compras); echo "</pre>"; asort($array_compras); echo "<h2>Array ordenado:</h2><pre>"; print_r($array_compras); echo "</pre>"; */ /* ? count $array_compras = ["notebook", "placa de video", "mesa digitalizadora", "monitor", "cooler", "led"]; echo "<h2>Array desordenado:</h2><pre>"; print_r($array_compras); echo "O array tem ".count($array_compras)." elementos."; echo "</pre>"; */ /* ? array_merge $array1 = ["osx", "windows"]; $array2 = array("linux"); $array3 = ["solaris"]; $novoArray = array_merge($array1, $array2, $array3); echo "<pre>"; print_r($novoArray); echo "</pre>"; */ /* ? explode $string = "28/07/2002"; $array_retorno = explode("/", $string); echo "$string<br/><pre>"; print_r($array_retorno); echo "</pre>"; echo "$array_retorno[2]-$array_retorno[1]-$array_retorno[0]"; */ $array = ["28","07", "2002"]; $stringRetorno = implode("/", $array); echo "<pre>"; print_r($array); echo "</pre>"; echo "$stringRetorno"; ?> </body> </html>
true
efd6b5242c2255e6fb8be64877ad015c8c5f4107
PHP
baguzwahyu/bitcoin-faucet-rotator-v2
/app/Listeners/Users/UpdateLastLoggedOutAt.php
UTF-8
1,119
2.59375
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
<?php namespace App\Listeners\Users; use App\Helpers\Constants; use Carbon\Carbon; use Illuminate\Auth\Events\Logout; use Illuminate\Http\Request; /** * Class UpdateLastLoggedOutAt * * @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com> * @package App\Listeners\Users */ class UpdateLastLoggedOutAt { private $request; /** * Create the event listener. * * @param Request $request */ public function __construct(Request $request) { $this->request = $request; } /** * Handle the event. * * @param Logout $event * @return void */ public function handle(Logout $event) { if (!empty($event->user)) { $user = $event->user; $user->last_logout_at = Carbon::now(); $user->save(); activity(Constants::AUTH_LOGOUT_LOG_NAME) ->causedBy($user) ->performedOn($user) ->withProperty('ip_address', $this->request->getClientIp()) ->log("User '" . $user->user_name . "' successfully logged out"); } } }
true
fd32652dec5f1850f3701ef7ab64ec2031695b59
PHP
LourivalJunior27/P2Upgrade
/P2Upgrade/pages/login/ler.php
UTF-8
384
2.984375
3
[]
no_license
<?php /** * Essa função faz a leitura da tabela usuários. * @param string $login * @return object */ function ler($login) { $sql = 'select * from usuarios where login = :login'; $connection = connection(); $result = $connection->prepare($sql); $result->bindValue(':login', $login); $result->execute(); return $result->fetchAll(PDO::FETCH_OBJ); };
true
e9f793fda96ca06b716057aad4de7a7750c1680e
PHP
mdx-dev/li3_hierarchy
/extensions/inheritance/Parser.php
UTF-8
5,760
2.75
3
[ "BSD-2-Clause" ]
permissive
<?php /** * Li3_Hierarchy Parser: Parses final template and replaces "blocks" with `block` * from the top level block in the `BlockSet`. * * @copyright Copyright 2012, Josey Morton (http://github.com/joseym) * @license http://opensource.org/licenses/bsd-license.php The BSD License */ /** * Todo List: * * 1. final block content section should be an array in the order of * rendered content */ namespace li3_hierarchy\extensions\inheritance; use \lithium\core\Libraries; use \lithium\util\String; use \li3_hierarchy\extensions\inheritance\BlockSet; use \li3_hierarchy\extensions\inheritance\Block; use \li3_hierarchy\extensions\inheritance\Lexer; use \li3_hierarchy\extensions\inheritance\Cache; class Parser { /** * Regexes used to track down blocks * @var array */ protected static $_terminals; /** * array of template files * @var array */ protected static $_templates; protected static $_template; protected static $_cacheFile; /** * `BlockSet` object, set from render method * @var object */ protected static $_blocks; /** * Parse the template * @param blob $source template source code * @param object $blocks `BlockSet` object * @return [type] [description] */ public static function parse($blocks, $data, $options){ $options += array( 'type' => 'html', ); $cache = new Cache(); static::$_terminals = array_flip(Lexer::terminals()); static::$_blocks = $blocks; static::$_cacheFile = substr(str_ireplace('/', '_', static::$_blocks->templates(0)), 1); $key = static::$_cacheFile . $options['type']; $_pattern = "/{:(block) \"({:block})\"(?: \[(.+)\])?}(.*){\\1:}/msU"; static::$_templates = array_reverse($blocks->templates()); if ($cache->file(sha1($key))) { return sha1($key); } else { $i = 0; while ($i < $count = count(static::$_templates)) { if($i == $count) break; $source = static::_read(static::$_templates[$i]); $template = static::_replace($source, $i, $options); $i++; } } // final parent template handler return static::$_template; } /** * Replaces blocks with content from `BlockSet` * @param blob $source template source * @param bool $final `true` if this template is this the last template * @param array $options * @return blob template source, replaced with blocks */ private static function _replace($source, $i, $options){ $cache = new Cache(); $cachePath = $cache->cacheDir()."/template/"; $pattern = "/{:(block) \"({:block})\"(?: \[(.+)\])?}(.*){\\1:}/msU"; preg_match_all(static::$_terminals['T_BLOCK'], $source, $matches); $_blocks = null; foreach($matches[2] as $index => $block){ $_pattern = String::insert($pattern, array('block' => $block)); $_block = static::$_blocks->blocks("{$block}"); $_blocks = static::$_blocks; /** * Top level content for block * @var string */ $content = trim($_block->content()); /** * The request for block content in the final template * @var string */ $request = $matches[4][$index]; /** * Parent/child matches/replacement */ $_parents = function($block) use (&$content, &$_parents, &$matches, &$index, &$_pattern){ $parent = $block->parent(); if(preg_match("/{:parent:}/msU", $content, $_matches)) { if($parent){ $content = preg_replace("/{:parent:}/msU", $parent->content(), $content); // go again return $_parents($block->parent(), $content); } else { // no parent, remove the request $content = preg_replace("/{:parent:}/msU", "", $content); } } return $content; }; /** * Parse the block and check to see if it's parents request it. * @var method */ $_children = function($block, $content = null) use (&$_children, &$matches, &$index, &$_pattern, &$_blocks){ $content = ($content == null) ? $block->content() : $content; $_block = $_blocks->blocks($block->name()); /** * If the block has a child then we're not at the bottom of the chain. * We need to move up until we cant * @var mixed `object` or `false` */ $child = $block->child(); /** * If the block has a parent then we cant be at the top of the chain. * As long as there's a parent we need to keep moving. * @var mixed `object` or `false` */ $parent = $block->parent(); if(preg_match("/{:child:}/msU", $content)) { // Block doesn't have a child block if(!$child){ // Also has no parent if(!$parent){ // clear the entire block $content = ""; } else { // Has a parent, still no child tho // just remove the call for child block $content = preg_replace("/{:child:}/msU", "", $content); return $_children($block, $content); } } // not asking for a child } else { // Has a parent if($parent){ if(preg_match("/{:child:}/msU", $parent->content())){ $content = preg_replace("/{:child:}/msU", $content, $parent->content()); return $_children($parent, $content); } } } // must return content so we dont muck up parent return $content; }; // parse children $content = $_children($_block); // parse parents $content = $_parents($_block); $source = preg_replace($_pattern, $content, $source); } // 0 should always be the final template if($i == 0){ if($cacheable = $cache->write($source, static::$_blocks->templates(0), $_blocks, $options)){ static::$_template = $cacheable; } } } private static function _read($template){ if(file_exists($template)){ $content = file_get_contents($template); return $content; } } }
true
59dd9ed04e125f56696bd14eae3bf21d76af9417
PHP
david14ka/ID23Pay
/app/Models/MyStudents.php
UTF-8
430
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Models; use CodeIgniter\Model; class MyStudents extends Model { protected $DBGroup = 'default'; protected $table = 'students'; protected $primaryKey = 's_id'; protected $returnType = 'array'; protected $useTimestamps = true; protected $allowedFields=['s_name','s_date','s_subject','s_update']; protected $createdField = 's_date'; protected $updatedField = 's_update'; }
true
320958cf9ee5094f1c7f61d23691d541d2f160f5
PHP
dungki/T1907A-Laravel
/database/seeds/DatabaseSeeder.php
UTF-8
712
2.796875
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $timestamp = date('Y-m-d H:i:s'); // $this->call(UsersTableSeeder::class); // \DB::table('students')->insert([ // 'fullname' => 'TRAN VAN A', // 'age' => 12, // 'address' => 'Nam Dinh', // 'created_at' => $timestamp, // 'updated_at' => $timestamp // ]); for ($i = 0; $i < 50; $i++) { \DB::table('students')->insert([ 'fullname' => 'TRAN VAN '.$i, 'age' => 12+$i, 'address' => 'Nam Dinh '.$i, 'created_at' => $timestamp, 'updated_at' => $timestamp ]); } } }
true
dd8982bc44b8ebabb373e24f2944ed8288c4bdd6
PHP
hcdisat/money
/src/Monetary/Exceptions/InvalidCurrencyOperationException.php
UTF-8
671
3.125
3
[]
no_license
<?php namespace HcDisat\Monetary\Exceptions; class InvalidCurrencyOperationException extends ExceptionBase { protected $message = '"%s currency cannot be added with %s currency'; /** * InvalidCurrencyOperationException constructor. * @param string $currentCurrency * @param string $otherCurrency * @param int $code * @param \Exception $previous */ public function __construct(string $currentCurrency, string $otherCurrency, $code = 0, \Exception $previous = null) { $this->message = sprintf($this->message, $currentCurrency, $otherCurrency); parent::__construct($this->message, $code, $previous); } }
true
fc5247525574ab0896568b582897ae06367377ad
PHP
thecodingmachine/safe
/generated/pcre.php
UTF-8
12,971
3.265625
3
[ "MIT" ]
permissive
<?php namespace Safe; use Safe\Exceptions\PcreException; /** * Returns the array consisting of the elements of the * array array that match the given * pattern. * * @param string $pattern The pattern to search for, as a string. * @param array $array The input array. * @param int $flags If set to PREG_GREP_INVERT, this function returns * the elements of the input array that do not match * the given pattern. * @return array Returns an array indexed using the keys from the * array array. * @throws PcreException * */ function preg_grep(string $pattern, array $array, int $flags = 0): array { error_clear_last(); $safeResult = \preg_grep($pattern, $array, $flags); if ($safeResult === false) { throw PcreException::createFromPhpError(); } return $safeResult; } /** * Searches subject for all matches to the regular * expression given in pattern and puts them in * matches in the order specified by * flags. * * After the first match is found, the subsequent searches are continued * on from end of the last match. * * @param string $pattern The pattern to search for, as a string. * @param string $subject The input string. * @param array|null $matches Array of all matches in multi-dimensional array ordered according to * flags. * @param int $flags Can be a combination of the following flags (note that it doesn't make * sense to use PREG_PATTERN_ORDER together with * PREG_SET_ORDER): * * * PREG_PATTERN_ORDER * * * Orders results so that $matches[0] is an array of full * pattern matches, $matches[1] is an array of strings matched by * the first parenthesized subpattern, and so on. * * * * * * ]]> * * The above example will output: * * example: , this is a test * example: , this is a test * ]]> * * * So, $out[0] contains array of strings that matched full pattern, * and $out[1] contains array of strings enclosed by tags. * * * * * If the pattern contains named subpatterns, $matches * additionally contains entries for keys with the subpattern name. * * * If the pattern contains duplicate named subpatterns, only the rightmost * subpattern is stored in $matches[NAME]. * * * * ]]> * * The above example will output: * * * [1] => bar * ) * ]]> * * * * * * * PREG_SET_ORDER * * * Orders results so that $matches[0] is an array of first set * of matches, $matches[1] is an array of second set of matches, * and so on. * * * * ]]> * * The above example will output: * * example: , example: * this is a test, this is a test * ]]> * * * * * * * PREG_OFFSET_CAPTURE * * * If this flag is passed, for every occurring match the appendant string * offset (in bytes) will also be returned. Note that this changes the value of * matches into an array of arrays where every element is an * array consisting of the matched string at offset 0 * and its string offset into subject at offset * 1. * * * * ]]> * * The above example will output: * * Array * ( * [0] => Array * ( * [0] => foobarbaz * [1] => 0 * ) * * ) * * [1] => Array * ( * [0] => Array * ( * [0] => foo * [1] => 0 * ) * * ) * * [2] => Array * ( * [0] => Array * ( * [0] => bar * [1] => 3 * ) * * ) * * [3] => Array * ( * [0] => Array * ( * [0] => baz * [1] => 6 * ) * * ) * * ) * ]]> * * * * * * * PREG_UNMATCHED_AS_NULL * * * If this flag is passed, unmatched subpatterns are reported as NULL; * otherwise they are reported as an empty string. * * * * * * Orders results so that $matches[0] is an array of full * pattern matches, $matches[1] is an array of strings matched by * the first parenthesized subpattern, and so on. * * * * * ]]> * * The above example will output: * * example: , this is a test * example: , this is a test * ]]> * * * So, $out[0] contains array of strings that matched full pattern, * and $out[1] contains array of strings enclosed by tags. * * * * The above example will output: * * So, $out[0] contains array of strings that matched full pattern, * and $out[1] contains array of strings enclosed by tags. * * If the pattern contains named subpatterns, $matches * additionally contains entries for keys with the subpattern name. * * If the pattern contains duplicate named subpatterns, only the rightmost * subpattern is stored in $matches[NAME]. * * * * ]]> * * The above example will output: * * * [1] => bar * ) * ]]> * * * * The above example will output: * * Orders results so that $matches[0] is an array of first set * of matches, $matches[1] is an array of second set of matches, * and so on. * * * * ]]> * * The above example will output: * * example: , example: * this is a test, this is a test * ]]> * * * * The above example will output: * * If this flag is passed, for every occurring match the appendant string * offset (in bytes) will also be returned. Note that this changes the value of * matches into an array of arrays where every element is an * array consisting of the matched string at offset 0 * and its string offset into subject at offset * 1. * * * * ]]> * * The above example will output: * * Array * ( * [0] => Array * ( * [0] => foobarbaz * [1] => 0 * ) * * ) * * [1] => Array * ( * [0] => Array * ( * [0] => foo * [1] => 0 * ) * * ) * * [2] => Array * ( * [0] => Array * ( * [0] => bar * [1] => 3 * ) * * ) * * [3] => Array * ( * [0] => Array * ( * [0] => baz * [1] => 6 * ) * * ) * * ) * ]]> * * * * The above example will output: * * If this flag is passed, unmatched subpatterns are reported as NULL; * otherwise they are reported as an empty string. * * If no order flag is given, PREG_PATTERN_ORDER is * assumed. * @param int $offset Orders results so that $matches[0] is an array of full * pattern matches, $matches[1] is an array of strings matched by * the first parenthesized subpattern, and so on. * * * * * ]]> * * The above example will output: * * example: , this is a test * example: , this is a test * ]]> * * * So, $out[0] contains array of strings that matched full pattern, * and $out[1] contains array of strings enclosed by tags. * * * * The above example will output: * * So, $out[0] contains array of strings that matched full pattern, * and $out[1] contains array of strings enclosed by tags. * * If the pattern contains named subpatterns, $matches * additionally contains entries for keys with the subpattern name. * * If the pattern contains duplicate named subpatterns, only the rightmost * subpattern is stored in $matches[NAME]. * * * * ]]> * * The above example will output: * * * [1] => bar * ) * ]]> * * * * The above example will output: * @return int|null Returns the number of full pattern matches (which might be zero). * @throws PcreException * */ function preg_match_all(string $pattern, string $subject, ?array &$matches = null, int $flags = 0, int $offset = 0): ?int { error_clear_last(); $safeResult = \preg_match_all($pattern, $subject, $matches, $flags, $offset); if ($safeResult === false) { throw PcreException::createFromPhpError(); } return $safeResult; } /** * Searches subject for a match to the regular * expression given in pattern. * * @param string $pattern The pattern to search for, as a string. * @param string $subject The input string. * @param string[]|null $matches If matches is provided, then it is filled with * the results of search. $matches[0] will contain the * text that matched the full pattern, $matches[1] * will have the text that matched the first captured parenthesized * subpattern, and so on. * @param int $flags flags can be a combination of the following flags: * * * PREG_OFFSET_CAPTURE * * * If this flag is passed, for every occurring match the appendant string * offset (in bytes) will also be returned. Note that this changes the value of * matches into an array where every element is an * array consisting of the matched string at offset 0 * and its string offset into subject at offset * 1. * * * * ]]> * * The above example will output: * * Array * ( * [0] => foobarbaz * [1] => 0 * ) * * [1] => Array * ( * [0] => foo * [1] => 0 * ) * * [2] => Array * ( * [0] => bar * [1] => 3 * ) * * [3] => Array * ( * [0] => baz * [1] => 6 * ) * * ) * ]]> * * * * * * * PREG_UNMATCHED_AS_NULL * * * If this flag is passed, unmatched subpatterns are reported as NULL; * otherwise they are reported as an empty string. * * * * ]]> * * The above example will output: * * * string(2) "ac" * [1]=> * string(1) "a" * [2]=> * string(0) "" * [3]=> * string(1) "c" * } * array(4) { * [0]=> * string(2) "ac" * [1]=> * string(1) "a" * [2]=> * NULL * [3]=> * string(1) "c" * } * ]]> * * * * * * * * If this flag is passed, for every occurring match the appendant string * offset (in bytes) will also be returned. Note that this changes the value of * matches into an array where every element is an * array consisting of the matched string at offset 0 * and its string offset into subject at offset * 1. * * * * ]]> * * The above example will output: * * Array * ( * [0] => foobarbaz * [1] => 0 * ) * * [1] => Array * ( * [0] => foo * [1] => 0 * ) * * [2] => Array * ( * [0] => bar * [1] => 3 * ) * * [3] => Array * ( * [0] => baz * [1] => 6 * ) * * ) * ]]> * * * * The above example will output: * * If this flag is passed, unmatched subpatterns are reported as NULL; * otherwise they are reported as an empty string. * * * * ]]> * * The above example will output: * * * string(2) "ac" * [1]=> * string(1) "a" * [2]=> * string(0) "" * [3]=> * string(1) "c" * } * array(4) { * [0]=> * string(2) "ac" * [1]=> * string(1) "a" * [2]=> * NULL * [3]=> * string(1) "c" * } * ]]> * * * * The above example will output: * @param int $offset If this flag is passed, for every occurring match the appendant string * offset (in bytes) will also be returned. Note that this changes the value of * matches into an array where every element is an * array consisting of the matched string at offset 0 * and its string offset into subject at offset * 1. * * * * ]]> * * The above example will output: * * Array * ( * [0] => foobarbaz * [1] => 0 * ) * * [1] => Array * ( * [0] => foo * [1] => 0 * ) * * [2] => Array * ( * [0] => bar * [1] => 3 * ) * * [3] => Array * ( * [0] => baz * [1] => 6 * ) * * ) * ]]> * * * * The above example will output: * @return int preg_match returns 1 if the pattern * matches given subject, 0 if it does not. * @throws PcreException * */ function preg_match(string $pattern, string $subject, ?iterable &$matches = null, int $flags = 0, int $offset = 0): int { error_clear_last(); $safeResult = \preg_match($pattern, $subject, $matches, $flags, $offset); if ($safeResult === false) { throw PcreException::createFromPhpError(); } return $safeResult; } /** * Split the given string by a regular expression. * * @param string $pattern The pattern to search for, as a string. * @param string $subject The input string. * @param int|null $limit If specified, then only substrings up to limit * are returned with the rest of the string being placed in the last * substring. A limit of -1 or 0 means "no limit". * @param int $flags flags can be any combination of the following * flags (combined with the | bitwise operator): * * * PREG_SPLIT_NO_EMPTY * * * If this flag is set, only non-empty pieces will be returned by * preg_split. * * * * * PREG_SPLIT_DELIM_CAPTURE * * * If this flag is set, parenthesized expression in the delimiter pattern * will be captured and returned as well. * * * * * PREG_SPLIT_OFFSET_CAPTURE * * * If this flag is set, for every occurring match the appendant string * offset will also be returned. Note that this changes the return * value in an array where every element is an array consisting of the * matched string at offset 0 and its string offset * into subject at offset 1. * * * * * * If this flag is set, for every occurring match the appendant string * offset will also be returned. Note that this changes the return * value in an array where every element is an array consisting of the * matched string at offset 0 and its string offset * into subject at offset 1. * @return array Returns an array containing substrings of subject * split along boundaries matched by pattern. * @throws PcreException * */ function preg_split(string $pattern, string $subject, ?int $limit = -1, int $flags = 0): array { error_clear_last(); $safeResult = \preg_split($pattern, $subject, $limit, $flags); if ($safeResult === false) { throw PcreException::createFromPhpError(); } return $safeResult; }
true
678d473e2f8656419803062ebd53792ec547d863
PHP
iborodikhin/php-glue
/src/Glue/Storage/Index.php
UTF-8
2,439
3.09375
3
[]
no_license
<?php namespace Glue\Storage; class Index extends AbstractFile { /** * File extension * * @var string */ protected $extension = 'idx'; /** * Save meta-data to index * * @param string $key * @param integer $offset * @param integer $length * @param string $meta * @return boolean|integer */ public function save($key, $offset, $length, $meta = "") { $data = sprintf( "%s\t%s\t%s\t%s" . PHP_EOL, $key, $offset, $length, $meta ); $fh = $this->open(); flock($fh, LOCK_EX); fseek($fh, $this->size()); $result = fputs($fh, $data); flock($fh, LOCK_UN); return $result; } /** * Reads meta-data from index * * @param string $key * @return array|boolean */ public function read($key) { return $this->findOrDelete($key, false); } /** * Deletes meta-data from index * * @param string $key * @return boolean */ public function delete($key) { return $this->findOrDelete($key, true); } /** * Finds or deletes meta-data in index * * @param string $key * @param boolean $delete * @return array|boolean */ protected function findOrDelete($key, $delete = false) { $found = false; $fh = $this->open(); flock($fh, ($delete ? LOCK_EX : LOCK_SH)); fseek($fh, 0); do { $string = fgets($fh); if (false !== strpos($string, $key)) { $found = true; } } while (!feof($fh) && !$found); if ($found) { $result = explode("\t", trim($string)); $hash = array_shift($result); if (trim($hash) == trim($key)) { if (!$delete) { flock($fh, LOCK_UN); return $result; } else { if (-1 !== fseek($fh, 0 - strlen($string), SEEK_CUR)) { fputs($fh, str_repeat(chr(0), strlen(trim($string)))); flock($fh, LOCK_UN); return $result; } } } } flock($fh, LOCK_UN); return false; } }
true
4dcd6c525c4843398d44119968eb42fb7ca1f970
PHP
hungvt13/restaurant-admin
/api/product/modTable.php
UTF-8
1,269
2.640625
3
[]
no_license
<?php // required headers header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); header("Access-Control-Max-Age: 3600"); header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"); // include database and object files include_once '../config/database.php'; $database = new Database(); $db = $database->getConnection(); // get posted data $data = json_decode(file_get_contents("php://input")); $active; if($data->isActive == true){ $active = 1; } else{ $active = 0; } // query to insert record //$sql = "INSERT INTO Items (name,price,uid) VALUES ('$data->itemName','$data->itemPrice', '$data->itemUID')"; //1 = add | 2 = delete if($data->command == 1){ $sql = "INSERT INTO tableList (id,active) VALUES ('$data->tableNo','$active')"; }elseif($data->command == 2){ $sql = "DELETE FROM Items WHERE id ='$data->tableNo'"; } //prepare query $stmt = $db->prepare($sql); //execute query if($stmt->execute()){ echo '{'; echo '"message": "Thành công (bàn)"'; echo '}'; }else{ echo '{'; echo '"message": "Thất bại (bàn)"'; echo '}'; } ?>
true
5689e61fe96863f9b1e406e7207156c8a4d4f69c
PHP
enanlara/academicoweb
/Controllers/cursocontroller.class.php
UTF-8
3,305
2.90625
3
[]
no_license
<?php /** * Classe Controller de Cursos * */ require_once "../Views/cursoview.class.php"; require_once "../Models/cursomodel.class.php"; require_once "../Ados/cursoado.class.php"; class CursoController { private $cursoView = null; private $cursoModel = null; private $cursoAdo = null; private $acao = null; public function __construct() { $this->cursoView = new CursoView(); $this->cursoModel = new CursoModel(); $this->cursoAdo = new CursoAdo(); $this->acao = $this->cursoView->getAcao(); switch ($this->acao) { case 'con' : $this->buscaCurso(); break; case 'inc' : $this->incluiCurso(); break; case 'alt' : $this->alteraCurso(); break; case 'exc' : $this->excluiCurso(); break; default: break; } $this->cursoView->displayInterface($this->cursoModel); } public function __destruct() { } /** * Busca cursos * */ private function buscaCurso() { $this->cursoModel = $this->cursoView->getDados(); $this->cursoModel = $this->cursoAdo->buscaCurso($this->cursoModel->getCursId()); if ($this->cursoModel) { //continue } else { // $this->cursoModel = new MatriculaModel(); $this->cursoView->adicionaMsgSucesso($this->cursoAdo->getMensagem()); return; } } /** * Inclui cursos * */ private function incluiCurso() { $this->cursoModel = $this->cursoView->getDados(); if ($this->cursoModel->VerificaObjeto($this->cursoModel)) {} else { $this->cursoView->adicionaMsgErro('Preencha todos os campos.'); return false; } try { if ($this->cursoAdo->insereObjeto($this->cursoModel)) { // Limpa os dados $this->cursoModel = new cursomodel(); } $this->cursoView->adicionaMsgSucesso($this->cursoAdo->getMensagem()); } catch (ErroNoBD $e) { $this->cursoView->adicionaMensagem("Erro na inclusão. contate o analista."); //descomente para debugar //$this->cursoView->adicionaMensagem($e->getMessage()); } } /** * altera cursos */ private function alteraCurso() { $this->cursoModel = $this->cursoView->getDados(); try { $this->cursoAdo->alteraObjeto($this->cursoModel); $this->cursoView->adicionaMensagem($this->cursoAdo->getMensagem()); } catch (ErroNoBD $e) { $this->cursoView->adicionaMensagem($e->getMessage()); } } /** * exclui cursos */ private function excluiCurso() { $this->cursoModel = $this->cursoView->getDados(); try { $this->cursoAdo->excluiObjeto($this->cursoModel); $this->cursoView->adicionaMsgSucesso($this->cursoAdo->getMensagem()); $this->cursoModel = new CursoModel(); } catch (ErroNoBD $e) { $this->cursoView->adicionaMensagem($e->getMessage()); } } } ?>
true
c426228729eecf7339dfa20635297454a091fe02
PHP
loyalpy/dns
/1dns/model/classes/cls_ipv4.php
UTF-8
1,357
3.09375
3
[]
no_license
<?php // IPv4 class class cls_ipv4{ var $address; var $netbits; var $endaddress; //-------------- // Create new class function cls_ipv4($address,$endaddress,$netbits=1){ $this->address = $address; $this->netbits = $netbits; $this->endaddress = $endaddress; } //-------------- // Return the IP address function address() { return ($this->address); } //-------------- // Return the netbits function netbits() { return ($this->netbits); } //-------------- // Return the netmask function netmask(){ return (long2ip(ip2long("255.255.255.255") << (32-$this->netbits))); } // Return the network that the address sits in function network(){ return (long2ip((ip2long($this->address)) & (ip2long($this->netmask())))); } //-------------- // Return the broadcast that the address sits in function broadcast(){ return (long2ip(ip2long($this->network()) | (~(ip2long($this->netmask()))))); } //-------------- // Return the inverse mask of the netmask function inverse(){ return (long2ip(~(ip2long("255.255.255.255") << (32-$this->netbits)))); } //Return the function inverse2(){ $this->netbits = (32-strlen(decbin(ip2long($this->endaddress) - ip2long($this->address))."")); return $this->address."/".$this->netbits; } } ?>
true
750918812b6ce492a6ccec476c0d8a1634f4a7f2
PHP
niko-afv/conquistadoresrejassur.cl
/apps/models/sub_categoria_flujo_caja.php
UTF-8
3,301
2.65625
3
[]
no_license
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of sub_categoria_flujo_caja * * @author nks */ class Sub_Categoria_Flujo_Caja extends CI_Model{ private $id; private $nombre; private $flujos; private $periodos = array(); private $totalIngreso; private $totalEgreso; public function __construct() { parent::__construct(); $this->flujos = new ArrayObject(); $this->load->model('flujo_caja'); } public function setId($val){ $this->id = $val; $this->db->where('ID',$this->id); $res = $this->db->get('FLUJO_CAJA_CATEGORIAS'); if(count($res->result()) > 0){ $categoria = $res->result(); $this->setNombre($categoria[0]->NOMBRE); $this->db->select('ID'); $this->db->where('FLUJO_CAJA_CATEGORIA_ID',$this->id); $res2 = $this->db->get('FLUJO_CAJA'); if(count($res2->result()) > 0){ foreach($res2->result() as $item => $val2){ $oFlujoCaja = new $this->flujo_caja(); $oFlujoCaja->setId($val2->ID); $this->addFlujo($oFlujoCaja); } } $this->calculaTotal(); } } public function setNombre($val){$this->nombre = $val;} public function setTotalIngreso($val){$this->totalIngreso = $val;} public function setTotalEgreso($val){$this->totalEgreso = $val;} public function getId(){return $this->id;} public function getNombre(){return $this->nombre;} public function getTotalIngreso(){return $this->totalIngreso;} public function getTotalEgreso(){return $this->totalEgreso;} public function getPeriodos(){return $this->periodos;} public function addFlujo($oFlujoCaja){ $this->flujos->append($oFlujoCaja); } public function countFlujos(){ return $this->flujos->count(); } public function getFlujo($index){ return $this->flujos->offsetGet($index); } public function removeFlujo($index){ $this->flujos->offsetUnset($index); } private function calculaTotal(){ $fecha = date('Y-m',strtotime(date('Y-m')." -5 month")); for($x = 0; $x <= 5; $x++){ $fechaPlus = date("Y-m", strtotime($fecha." +$x month")); $this->periodos[$fechaPlus]['montos'] = 0; $monto = 0; for($i = 0; $i < $this->countFlujos(); $i++){ if(strstr($this->getFlujo($i)->getFecha(),$fechaPlus)){ $monto += $this->getFlujo($i)->getMonto(); } } $this->periodos[$fechaPlus]['montos'] = $monto; } } public function toArray(){ $array = array(); $array['nombre'] = $this->getNombre(); $array['id'] = $this->getId(); $array['periodos'] = $this->periodos; $array['flujos'] = array(); for($i=0; $i<$this->countFlujos(); $i++){ $array['flujos'][$i] = $this->getFlujo($i)->toArray(); } return $array; } } ?>
true
f922bca80c7a840e7bbf3453f7a10ccb2ee70dd4
PHP
vance-page/Code-Help
/Admin/APP/Common/Controller/BaseController.class.php
UTF-8
2,107
2.578125
3
[]
no_license
<?php namespace Common\Controller; use Think\Controller; /** * Created by PhpStorm. * User: Administrator * Date: 2017/8/29 * Time: 11:55 */ class BaseController extends Controller { public function __construct() { parent::__construct(); if (method_exists($this, '__init')) { $this->__init(); } } //保存数据 public function store(Model $model, $data, \Closure $callback = null) { $res = $model->store($data); if ($res['status'] == 'success' && $callback instanceof \Closure) { $callback($res); } else { $this->message($res); } } //响应信息 protected function message(array $data) { if ($data['status'] == 'success') { $this->success($data['message']); } else { $this->error($data['message']); } exit; } //分配菜单 public function assignModuelMenu() { $nav_data=D('Nav')->getTree('level','order_number,id'); $this->assign('nav_data',$nav_data); } /* 处理上传exl数据 * $file_name 文件路径 */ public function import_exl($file_name){ Vendor("PHPExcel.PHPExcel"); // 这里不能漏掉 Vendor("PHPExcel.PHPExcel.IOFactory"); Vendor("PHPExcel.PHPExcel.Reader.Excel2007"); $objReader =\PHPExcel_IOFactory::createReader('Excel2007'); $objPHPExcel = $objReader->load($file_name,$encode='utf-8'); $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得总行数 $highestColumn = $sheet->getHighestColumn(); // 取得总列数 $data=array(); //从第二行开始读取数据 for($j=2;$j<=$highestRow;$j++){ //从A列读取数据 for($k='A';$k<$highestColumn;$k++){ // 读取单元格 $data[$j][]=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue(); } } return $data; } }
true
3d35bd2bbaa896eaba73a6e776f4c0a1ea704c66
PHP
swoole/swoole-src
/tests/swoole_table/del.phpt
UTF-8
1,395
2.65625
3
[ "Apache-2.0" ]
permissive
--TEST-- swoole_table: clear all columns --SKIPIF-- <?php require __DIR__ . '/../include/skipif.inc'; ?> --FILE-- <?php require __DIR__ . '/../include/bootstrap.php'; $table = new Swoole\Table(1024, 0.25); $table->column('state', Swoole\Table::TYPE_INT); $table->column('remainLen', Swoole\Table::TYPE_INT); $table->column('data', Swoole\Table::TYPE_STRING, 64); $table->create(); function data($table) { $table_key = 'table'; $table->incr($table_key, 'state'); $state = $table->get($table_key, 'state'); var_dump($state); $data = $table->get($table_key, 'data'); $data .= 'abc'; $table->set($table_key, ['data' => $data]); var_dump($table->get($table_key)); if ($state === 1) { $table->incr($table_key, 'remainLen', 3); } else { $remainLen = $table->get($table_key, 'remainLen'); if ($remainLen === 3) { $res = $table->del($table_key); var_dump($res); var_dump($table->get($table_key)); } } } data($table); data($table); data($table); ?> --EXPECT-- int(1) array(3) { ["state"]=> int(1) ["remainLen"]=> int(0) ["data"]=> string(3) "abc" } int(2) array(3) { ["state"]=> int(2) ["remainLen"]=> int(3) ["data"]=> string(6) "abcabc" } bool(true) bool(false) int(1) array(3) { ["state"]=> int(1) ["remainLen"]=> int(0) ["data"]=> string(3) "abc" }
true
d577040fbfcd2b713a2717cb1b593a5dc8454df9
PHP
carlomagno83/souko
/app/controllers/UsersController.php
UTF-8
3,510
2.625
3
[ "MIT" ]
permissive
<?php class UsersController extends BaseController { /** * User Repository * * @var User */ protected $user; public function __construct(User $user) { $this->user = $user; } /** * Display a listing of the resource. * * @return Response */ public function index() { $users = $this->user->all(); return View::make('users.index', compact('users')); } /** * Show the form for creating a new resource. * * @return Response */ public function create() { return View::make('users.create'); } /** * Store a newly created resource in storage. * * @return Response */ public function store() { $input = Input::all(); $input['password']=Hash::make($input['password']); $validation = Validator::make($input, User::$rules); if ($validation->passes()) { $user = new User(); $user->username = Input::get('username'); $user->desusuario = Input::get('desusuario'); $user->rolusuario = Input::get('rolusuario'); $user->estado = 'ACT'; $user->password = Hash::make(Input::get('password')); //$user->usuario_id = Input::get('usuario_id'); $user->usuario_id = 1; $user->save(); //$this->user->create($input); obviar el modo automatico return Redirect::route('users.index'); } return Redirect::route('users.create') ->withInput() ->withErrors($validation) ->with('message', 'There were validation errors.'); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $user = $this->user->findOrFail($id); return View::make('users.show', compact('user')); } /** * Show the form for editing the specified resource. * * @param int $id * @return Response */ public function edit($id) { $user = $this->user->find($id); if (is_null($user)) { return Redirect::route('users.index'); } return View::make('users.edit', compact('user')); } /** * Update the specified resource in storage. * * @param int $id * @return Response */ public function update($id) { $input = array_except(Input::all(), '_method'); $validation = Validator::make($input, User::$rules); if ($validation->passes()) { $user = User::find($id); $user->username = Input::get('username'); $user->desusuario = Input::get('desusuario'); $user->rolusuario = Input::get('rolusuario'); if(Input::get('password')<>"") { $user->password = Hash::make(Input::get('password')); } //$user->usuario_id = Input::get('usuario_id'); $user->usuario_id = 1 ; $user->save(); //$user->update($input); //evitar el modo automatico return Redirect::route('users.show', $id); } return Redirect::route('users.edit', $id) ->withInput() ->withErrors($validation) ->with('message', 'There were validation errors.'); } /** * Remove the specified resource from storage. * * @param int $id * @return Response */ public function destroy($id) { $this->user->find($id)->delete(); return Redirect::route('users.index'); } public function activar() { $users = $this->user->all(); return View::make('users.activar', compact('users')); } public function cambiarestado($id) { $user = User::find($id); $estado = $user->estado; if($estado == 'ACT') { $user->estado = 'INA' ; } else { $user->estado = 'ACT'; } $user->save(); $users = $this->user->all(); return View::make('users.activar', compact('users')); } }
true
965bd4929605c8ad42bedb7cb4f26836a11f3397
PHP
davidredsox/hitmaps
/api/BusinessLogic/Authentication/RegisterNewUserCommand.php
UTF-8
1,355
2.8125
3
[ "MIT" ]
permissive
<?php namespace BusinessLogic\Authentication; use BusinessLogic\Emailer; use DataAccess\Models\User; use DataAccess\Models\UserRole; use Doctrine\ORM\EntityManager; class RegisterNewUserCommand { private $entityManager; private $emailer; public function __construct(EntityManager $entityManager, Emailer $emailer) { $this->entityManager = $entityManager; $this->emailer = $emailer; } public function execute(string $name, string $email, string $password, \Twig_Environment $twig): void { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $verificationToken = sha1($name . $email . uniqid()); $user = new User(); $user->setName($name); $user->setPassword($hashedPassword); $user->setEmail($email); $user->setVerificationToken($verificationToken); $role = $this->entityManager->getRepository(UserRole::class)->findOneBy(['id' => 2]); $user->getRoles()->add($role); $this->entityManager->persist($user); $this->entityManager->flush(); $model = new \stdClass(); $model->verificationToken = $verificationToken; $model->name = $name; $model->email = $email; $this->emailer->sendEmail('email/user/verify-account.twig', $model, $email, $twig); } }
true
46bc624fc73dae1d50e302d6fe2f4515151817f4
PHP
ketianlin/mymvc
/test/demo01/d03.php
UTF-8
1,106
3.421875
3
[]
no_license
<?php //第一步:创建随机字符串 //1.1 创建字符数组 $all_array = array_merge(range('a', 'z'), range('A', 'Z'), range('0', '9'));//所有字符数组 $div_array = ['1','l','0','o','O','I','9','g']; //去除容易混淆的字符 $array = array_diff($all_array, $div_array);//剩余的字符数组 unset($all_array, $div_array);//销毁不需要使用的数组 //1.2 随机获取4个字符 $index = array_rand($array, 4);//随机取4个字符,返回字符下标,按先后顺序排列 shuffle($index); //打乱字符 //1.3 通过下标拼接字符串 $code = ''; foreach ($index as $i){ $code .= $array[$i]; } //第二步:创建画布 $img = imagecreate(150, 30); imagecolorallocate($img, 255, 0, 0);//分配背景色 $color = imagecolorallocate($img,255,255,255); //分配前景色 //第三步:将字符串写到画布上 $font = 5; //内置5号字体 $x = (imagesx($img) - imagefontwidth($font)*strlen($code))/2; $y = (imagesy($img) - imagefontheight($font))/2; imagestring($img, $font, $x, $y, $code, $color); //显示验证码 header('content-type:image/gif'); imagegif($img);
true
7b80b03386d7f804e7f6efc89ae7cd39c2e04172
PHP
wandersonwhcr/balance
/module/Balance/src/Balance/View/Table/Table.php
UTF-8
4,813
2.78125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace Balance\View\Table; use ArrayIterator; use Traversable; use Zend\Form\Form; use Zend\Stdlib\Hydrator\HydratorInterface; /** * Tabela para Renderização de Elementos em Visualização */ class Table { /** * Formulário * @type Form */ protected $form = null; /** * Título da Tabela * @type string */ protected $title = ''; /** * Colunas Configuradas * @type array[] */ protected $columns = []; /** * Elementos para Renderização * @type Traversable */ protected $elements = null; /** * Ações Configuradas * @type string[][] */ protected $actions = []; /** * Ações de Elementos Configuradas * @type string[][] */ protected $elementActions = []; /** * Hidratador de Linhas * @type HydratorInterface */ protected $hydrator; /** * Configurar Formulário * * @param Form $form Elemento para Configuração * @return Table Próprio Objeto para Encadeamento */ public function setForm(Form $form) { $this->form = $form; return $this; } /** * Apresentar Formulário * * @return Form Elemento Solicitado */ public function getForm() { return $this->form; } /** * Configuração de Título da Tabela * * @param string $title Valor para Configuração * @return Table Próprio Objeto para Encadeamento */ public function setTitle($title) { $this->title = $title; return $this; } /** * Apresentação de Título da Tabela * * @return string Valor Configurado */ public function getTitle() { return $this->title; } /** * Configurar Coluna * * @param string $identifier Identificador da Coluna * @param array $params Parâmetros para Coluna * @return Table Próprio Objeto para Encadeamento */ public function setColumn($identifier, array $params = []) { $this->columns[$identifier] = $params; return $this; } /** * Apresentação de Colunas * * @return array[] Conjunto de Elementos Solicitados */ public function getColumns() { return $this->columns; } /** * Configuração de Elementos * * @param Traversable $elements Conjunto de Elementos * @return Table Próprio Objeto para Encadeamento */ public function setElements(Traversable $elements) { $this->elements = $elements; return $this; } /** * Apresentação de Elementos * * @return Traversable Conjunto de Elementos Solicitados */ public function getElements() { // Elementos Configurados? if ($this->elements === null) { // Inicializar Elementos Vazios $this->setElements(new ArrayIterator()); } // Apresentação return $this->elements; } /** * Configurar Ação * * @param string $identifier Identificador da Ação * @param string[] $params Parâmetros para Captura em Ação * @return Table Próprio Objeto para Encadeamento */ public function setAction($identifier, array $params) { $this->actions[$identifier] = $params; return $this; } /** * Apresentação de Ações * * @return string[][] Conjunto de Elementos Solicitados */ public function getActions() { return $this->actions; } /** * Configurar Ação de Elemento * * @param string $identifier Identificador da Ação * @param string[] $params Parâmetros para Captura em Ação * @return Table Próprio Objeto para Encadeamento */ public function setElementAction($identifier, array $params = []) { $this->elementActions[$identifier] = $params; return $this; } /** * Apresentação de Ações de Elemento * * @return string[][] Conjunto de Elementos Solicitados */ public function getElementActions() { return $this->elementActions; } /** * Configuração do Hidratador de Linhas * * @param HydratorInterface $hydrator Elemento para Configuração * @return Table Próprio Objeto para Encadeamento */ public function setHydrator(HydratorInterface $hydrator) { $this->hydrator = $hydrator; return $this; } /** * Apresentação de Hidratador de Linhas * * @return HydratorInterface Elemento Solicitado */ public function getHydrator() { return $this->hydrator; } }
true
192af26f7036a54bf357d6ccde21802255c840d4
PHP
xiangxiang0826/phpunit
/application/models/NewsCategory.php
UTF-8
4,912
2.578125
3
[]
no_license
<?php /** * 扩展分类Model * * @author xiangxiang<xiangxiang@wondershare.cn> * @date 2014-10-10 */ class Model_NewsCategory extends ZendX_Model_Base { /** * 设置是否允许删除 * * @var boolean */ public $isDelete = TRUE; protected $_schema = 'website'; protected $_table = 'EZ_NEWS_CATEGORY'; protected $_map_table = 'EZ_NEWS'; protected $pk = 'id'; function __construct() { parent::__construct('website'); } /** * 树显示类别 */ public function dumpTree($all = false) { $where = !$all ? "status='enable'" : 1; $sql = "SELECT id,name,parent_id,layer,sort FROM `{$this->_table}` WHERE {$where} ORDER BY sort DESC"; $category = $this->get_db()->fetchAll($sql); $treeArr = ZendX_Array::array_to_tree($category, 'id', 'parent_id'); return ZendX_Array::dumpArrayTree($treeArr); } function getList($start, $count, $search=array()) { $where = '1'; $search[] = 'status = "enable"'; $where = implode(' AND ', $search); $total = $this->get_db()->fetchOne("SELECT count(*) FROM `{$this->_table}` WHERE {$where}"); $sql = "SELECT * FROM `{$this->_table}` WHERE {$where} ORDER BY `id` ASC LIMIT {$start}, {$count}"; $rows = $this->get_db()->fetchAll($sql); return compact('total', 'rows'); } function getMapList($start, $count, $search=array()) { $where = '1'; if($search && !empty($search)){ $where = implode(' AND ', $search); } $total = $this->get_db()->fetchOne("SELECT count(*) FROM `{$this->_map_table}` WHERE status='enable' AND {$where}"); $sql = "SELECT * FROM `{$this->_map_table}` WHERE status='enable' AND {$where} ORDER BY `id` ASC LIMIT {$start}, {$count}"; $rows = $this->get_db()->fetchAll($sql); return compact('total', 'rows'); } function getIdByName($name) { return $this->get_db()->fetchOne("SELECT `id` FROM `{$this->_table}` WHERE `name`='{$name}'"); } //根据uid,批量获取分类权限 function GetGroupByUids($uids) { if(!$uids || !is_array($uids)) return false; $uids = implode(',',$uids); return $this->get_db()->fetchALl("SELECT a.*,b.user_id FROM `{$this->_table}` a INNER JOIN SYSTEM_USER_GROUP_MAP b ON a.id = b.user_group_id WHERE b.`user_id` IN ({$uids})"); } /** * 获得总记录数 */ public function getTotal($query = "") { if(empty($query)){ $sql = "SELECT count(*) AS total FROM `{$this->_table}` AS t"; }else{ $sql = "SELECT count(*) AS total FROM `{$this->_table}` AS t WHERE ".$query; } return $this->get_db()->fetchAll($sql); } /** * 获得总记录数 */ public function getTotalByGroup($query = "") { if(empty($query)){ $sql = 'SELECT category_id AS cid, COUNT(*) AS total FROM '.$this->_map_table.' as t WHERE status="enable" GROUP BY category_id'; }else{ $sql = 'SELECT category_id AS cid, COUNT(*) AS total FROM '.$this->_map_table.' as t WHERE status="enable" AND'.$query.' GROUP BY user_group_id'; } return $this->get_db()->fetchAll($sql); } /* 根据key=>value找记录 */ public function getCategoryRowByField($fields, $params = array(), $paramsWithout = array()) { $select = $this->select(); $select->from($this->_table, $fields); foreach($params as $field => $value) { $select->where("`{$field}` = ?", $value); } foreach($paramsWithout as $field => $value) { $select->where("`{$field}` != ?", $value); } $result = $this->get_db()->fetchRow($select); return $result; } /** * 插入记录 * @param array $data * @return bool */ public function insertCategory($data) { $ret = $this->get_db()->insert($this->_table, $data); return $ret ? $this->get_db()->lastInsertId($this->_table) : false; } /** * 插入记录 * @param array $data * @return bool */ public function updateCategory($data, $where) { $ret = $this->get_db()->update($this->_table, $data, $where); return $ret ? TRUE : false; } /** * 删除记录 * @param array $where * @return bool */ public function deleteCategory($where) { $result = $this->get_db()->delete($this->_table, $where); return $result; } /* 设置分类 */ public function updateUserGroup($group_id, $user_id) { if(empty($user_id) || empty($group_id) || !is_array($group_id)) return false; $sql = "DELETE FROM {$this->_table} WHERE user_id = '{$user_id}'"; $this->get_db()->exec($sql); $tmp_ary = array(); foreach($group_id as $gid) { $tmp_ary[] = "('{$user_id}','{$gid}')"; } $insert_str = implode(',',$tmp_ary); $sql = "INSERT INTO {$this->_table}(user_id,user_group_id) VALUES {$insert_str}"; return $this->get_db()->exec($sql); } /* 插入分类 */ public function addCategory($data) { $ret = $this->get_db()->insert($this->_table, $data); return $ret ? $this->get_db()->lastInsertId($this->_table) : false; } }
true
1f1c5fd327d26fe285fea0f305206eb5da8f5061
PHP
Lamapups/heiha
/www/uploadaction.php
UTF-8
9,213
2.703125
3
[]
no_license
<?php session_start(); require('password.php'); try { // including the file containing definitions for the regular expressions include('regexp.php'); // filtering the POST data using the function filter_input // saving the data given by the user into simpler variables, e. g. $username // and validating type etc // $username = $_SESSION['username']; if(!($title = filter_input(INPUT_POST, 'title', FILTER_VALIDATE_REGEXP, $regexp_options['regexp_title']))) throw new RuntimeException('invalid_title'); $subtitle = filter_input(INPUT_POST, 'subtitle', FILTER_VALIDATE_REGEXP, $regexp_options['regexp_subtitle']); // NULL means $subtitle is not set, FALSE means that it is not valid according to the regexp if($subtitle === FALSE) throw new RuntimeException('invalid_subtitle'); $abstract = $_POST['abstract']; // only validate $email if a value is entered at all if (isset($email)) { $email = filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL); if($email === FALSE) throw new RuntimeException('invalid_email'); } if (isset($universiy)) { $university = filter_input(INPUT_POST, 'university', FILTER_VALIDATE_REGEXP, $regexp_options['regexp_university']); if($university === FALSE) throw new RuntimeException('invalid_university'); } if (isset($forename)) { $forename = filter_input(INPUT_POST, 'forename', FILTER_VALIDATE_REGEXP,$regexp_options['regexp_forename']); if($forename === FALSE) throw new RuntimeException('invalid_forename'); } if (isset($surname)) { $surname = filter_input(INPUT_POST, 'surname', FILTER_VALIDATE_REGEXP,$regexp_options['regexp_surname']); if($surname === FALSE) throw new RuntimeException('invalid_surname'); } $field1_id = $_POST['field1_id']; $field2_id = $_POST['field2_id']; $field3_id = $_POST['field3_id']; $type = $_POST['type']; $email_public = $_POST['email_public']; if (isset($compositiondate)) { $compositiondate = filter_input(INPUT_POST, 'compositiondate', FILTER_VALIDATE_REGEXP,$regexp_options['regexp_date']); if($compositiondate === FALSE) throw new RuntimeException('invalid_compositiondate'); } $replace_titlepage = $_POST['replace_titlepage']; // old code without filtering /* // saving the data given by the user into simpler variables $title = $_POST['title']; $subtitle = $_POST['subtitle']; $abstract = $_POST['abstract']; $username = $_SESSION['username']; $email= $_POST['email']; $forename = $_POST['forename']; $surname= $_POST['surname']; $university = $_POST['university']; $field1_id = $_POST['field1_id']; $field2_id = $_POST['field2_id']; $field3_id = $_POST['field3_id']; $type = $_POST['type']; $email_public = $_POST['email_public']; $compositiondate = $_POST['compositiondate']; */ $id_of_empty_field = 60; // see the table users.fields $utc_timestamp = time(); $cet_timestamp = time() - (60*60); $the_title = 'Arbeit hochladen'; $the_content = '<p>Hochladen &#8230</p>'; $the_content = '<p>'.$compositiondate.'</p>'; //$the_content .= '<p>'.ini_get('upload_max_filesize').'</p>'; $the_content .= '<p>'.$field1_id.'</p>'; $the_content .= '<p>'.$field2_id.'</p>'; $the_content .= '<p>'.$field3_id.'</p>'; $mysqli = new mysqli("localhost", "debian-sys-maint", "U4wbbBBJf8KACpVv", "users"); // Checking connection if($mysqli->connect_errno) { $connection_error = $mysqli->connect_error; throw new RuntimeException('connection_failed'); } $mysqli->query("SET NAMES 'utf8'"); // Put an empty string into field1 if the user specified the id of the empty field if ($field1_id == $id_of_empty_field) $field1 = ''; else { // Getting all the data from the fields table $query_for_field1 = sprintf("SELECT * FROM fields WHERE id='%s'",$mysqli->real_escape_string($field1_id)); $result_for_field1 = $mysqli->query($query_for_field1); if (!$result_for_field1->num_rows) throw new RuntimeException('no_field1'); // Putting the appropriate name into field1 if ($field1_row = $result_for_field1->fetch_assoc()) $field1 = $field1_row['field_unicode']; } // Put an empty string into field2 if the user specified the id of the empty field if ($field2_id == $id_of_empty_field) $field2 = ''; else { // Getting all the data from the fields table $query_for_field2 = sprintf("SELECT * FROM fields WHERE id='%s'",$mysqli->real_escape_string($field2_id)); $result_for_field2 = $mysqli->query($query_for_field2); if (!$result_for_field2->num_rows) throw new RuntimeException('no_field2'); // Putting the appropriate name into field2 if ($field2_row = $result_for_field2->fetch_assoc()) $field2 = $field2_row['field_unicode']; } // Put an empty string into field3 if the user specified the id of the empty field if ($field3_id == $id_of_empty_field) $field3 = ''; else { // Getting all the data from the fields table $query_for_field3 = sprintf("SELECT * FROM fields WHERE id='%s'",$mysqli->real_escape_string($field3_id)); $result_for_field3 = $mysqli->query($query_for_field3); if (!$result_for_field3->num_rows) throw new RuntimeException('no_field3'); // Putting the appropriate name into field3 if ($field3_row = $result_for_field3->fetch_assoc()) $field3 = $field3_row['field_unicode']; } if(!$title) throw new RuntimeException('no_title'); // Getting rows with same title entered $query_for_title= sprintf("SELECT title FROM papers WHERE title = '%s'", $mysqli->real_escape_string($title)); $result_for_title = $mysqli->query($query_for_title); // Checking if title is already taken if ($result_for_title->num_rows) throw new RuntimeException('title_taken'); // Undefined | Multiple Files | $_FILES Corruption Attack // If this request falls under any of them, treat it invalid. if ( !isset($_FILES['paper']['error']) || is_array($_FILES['paper']['error']) ) { throw new RuntimeException('invalid_parameters'); } // Checking $_FILES['paper']['error'] value. switch ($_FILES['paper']['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: throw new RuntimeException('no_file'); case UPLOAD_ERR_PARTIAL: throw new RuntimeException('partial'); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: throw new RuntimeException('size'); default: throw new RuntimeException('unknown'); } /*// Checking file size again. if ($_FILES['paper']['size'] > 1000000) { throw new RuntimeException('Datei zu groß.'); } */ // $_FILES['paper']['mime'] value cannot be trusted. // Checking MIME type. /* $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === $ext = array_search( $finfo->file($_FILES['paper']['tmp_name']), array( 'pdf' => 'application/pdf', ), true )) { throw new RuntimeException('Invalid file format.'); } */ // Checking if file is a pdf $finfo = new finfo(FILEINFO_MIME_TYPE); if (!($finfo->file($_FILES['paper']['tmp_name']) === 'application/pdf')) throw new RuntimeException('no_pdf'); // Moving paper to directory /papers/ $newlocation = sprintf('papers/%s.pdf', $title); $file_moved = move_uploaded_file($_FILES['paper']['tmp_name'],$newlocation); //$the_content .= '<p>'.$newlocation.'</p>'; // Checking if the file was successfully moved if (!$file_moved) throw new RuntimeException('not_moved'); // Replacing titlepage if the user wishes so if($replace_titlepage == 1) { // Defining a command to delete the titlepage // using the bash script deletetitlepage.sh // Setting locale to allow for unicode shell arguments setlocale(LC_TYPE, "en_US.UTF-8"); $cmd = sprintf("./deletetitlepage.sh %s", escapeshellarg($newlocation)); // Executing the command exec($cmd); } $viewpaper_url = 'viewpaper.php?title='.$title; $query_to_insert = sprintf("INSERT INTO users.papers (id, url, title, subtitle, abstract, username, email, email_public, forename, surname, university, field1, field2, field3, type, uploaddate, compositiondate) VALUES (NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', FROM_UNIXTIME(%s), '%s')", $mysqli->real_escape_string($newlocation), $mysqli->real_escape_string($title), $mysqli->real_escape_string($subtitle), $mysqli->real_escape_string($abstract), $mysqli->real_escape_string($username), $mysqli->real_escape_string($email), $mysqli->real_escape_string($email_public), $mysqli->real_escape_string($forename), $mysqli->real_escape_string($surname), $mysqli->real_escape_string($university), $mysqli->real_escape_string($field1), $mysqli->real_escape_string($field2), $mysqli->real_escape_string($field3), $mysqli->real_escape_string($type), $mysqli->real_escape_string($cet_timestamp), $mysqli->real_escape_string($compositiondate) ); $mysqli->query($query_to_insert); //$the_content .= '<p>'.$query_to_insert.'</p>'; header('Location:uploadreport.php?viewpaper_url='.$viewpaper_url); exit(); } catch (RuntimeException $e) { header('Location:uploadreport.php?error='.$e->getMessage().'&connection_error='.$connection_error); exit(); } unset($_POST); ?> <?php include('single.php'); ?>
true