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
ebcc2a70cd3b5ec6769eed89f0ebf49b0e83a609
PHP
AFONSECAM/phone_sh0p
/includes/class_brand.php
UTF-8
2,565
2.75
3
[]
no_license
<?php include_once ("class_conection.php"); class Brand extends Conection { private $nombre; private $tipo; private $conexion_bd; function __construct() { $this->conexion_bd = new Conection(); $this->conexion_bd = $this->conexion_bd->connect(); } function createBrand($nombre_form, $tipo_form) { $this->nombre = $nombre_form; $this->tipo = $tipo_form; $query = "INSERT INTO tb_brand (brand_name, type) VALUES(?,?);"; $insert = $this->conexion_bd->prepare($query); $data_array = array($this->nombre, $this->tipo); $insert->execute($data_array); $last_id = $this->conexion_bd->lastInsertId(); return $last_id; } function query_brand() { $query_brand_2 = "SELECT * FROM tb_brand"; $query_brand_3 = $this->conexion_bd->prepare($query_brand_2); $result = $query_brand_3->fetchall(PDO::FETCH_ASSOC); return $result; } function update_brand($id_brand, $nombre_marca) { $this->mar = $nombre_marca; $query = "INSERT INTO tb_brand (brand_name, type) VALUES(?,?);"; $insert = $this->conexion_bd->prepare($query); $data_array = array($this->nombre, $this->tipo); $insert->execute($data_array); $last_id = $this->conexion_bd->lastInsertId(); return $last_id; } function showBrands(){ $query_show = "SELECT * FROM tb_brand"; $consulta = $this->conexion_bd->query($query_show); $response = $consulta->fetchall(PDO::FETCH_ASSOC); return $response; } function searchById($id){ $queryById = "SELECT id_brand, brand_name, type FROM tb_brand WHERE id_brand = ?"; $consulta = $this->conexion_bd->prepare($queryById); $arrayId = array($id); $consulta->execute($arrayId); $response = $consulta->fetch(PDO::FETCH_ASSOC); return $response; } function updateBrand($id, $name, $tipo){ $this->nombre = $name; $this->tipo = $tipo; $queryUpdate = "UPDATE tb_brand SET brand_name = ?, type = ? WHERE id_brand = ". $id; $update = $this->conexion_bd->prepare($queryUpdate); $data = array($this->nombre, $this->tipo); $response = $update->execute($data); return "Actualizado con exito, para verificar de <a href='../brand/show_brands.php'>clíc aquí</a>"; } } }
true
fe71a8db72f26f22e9035e874cf50e14729a0f16
PHP
bigdropinc/yii2-docker-template
/app/backend/models/User.php
UTF-8
513
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Created by PhpStorm. * User: bigdrop * Date: 11.09.17 * Time: 11:02 */ namespace backend\models; /** * Class User * * @package backend\models */ class User extends \common\models\User { /** * Finds user by username * * @param string $username * @return static|null */ public static function findByUsername($username) { return static::findOne(['username' => $username, 'status' => self::STATUS['ACTIVE'], 'role' => self::ROLE['ADMIN']]); } }
true
caf69def16e79d14800766f2d757583a78761a94
PHP
ArtemBrovko/tw-sa-sync
/src/App/Utils/PrintTableTrait.php
UTF-8
718
2.71875
3
[]
no_license
<?php namespace App\Utils; use Symfony\Component\Console\Helper\Table; use Symfony\Component\PropertyAccess\PropertyAccessor; trait PrintTableTrait { private function printTable(Table $table, $json) { $propertyAccessor = new PropertyAccessor(); if (count($json)) { $table->setHeaders(array_keys(get_object_vars($json[0]))); foreach ($json as $row) { if ($propertyAccessor->isReadable($row, 'details')) { $row->details = implode(';', array_values(get_object_vars($row->details))); } $table->addRow(array_values(get_object_vars($row))); } $table->render(); } } }
true
2e7b8788a8144a504a039d11069acd97ed87e6e2
PHP
Alfatyhin/test-07
/app/Servises/ParserCsvService.php
UTF-8
1,730
3.21875
3
[ "MIT" ]
permissive
<?php namespace App\Servises; class ParserCsvService { private $headers; private $collectionLines = []; public function __construct() { } public function addCollectionLies(array $data) : self // типизация - то чо должна возвращать функция?? { if (!$this->headers) { $this->headers = $data; } else { $collection = $this->collectionLines; $collection[] = $data; $this->collectionLines = $collection; } return $this; } public function toArray() : array { foreach ($this->collectionLines as $item) { $itemData[] = array_combine($this->headers, $item); } return $itemData; } public static function parseCsvStringToArray(string $str) : array { if (empty($str)) { $str = 'None'; } $str = str_replace(', ', ',', $str); $data = explode(',', $str); return $data; } public static function getSubArrayUnicue(array $data) : array { $valueData = array_unique($data); foreach ($valueData as $str) { if (empty($str)) { $str = 'None'; } $strArray = self::parseCsvStringToArray($str); foreach ($strArray as $valName) { $valName = trim($valName); $subData[] = $valName; } } $subData = array_unique($subData); return $subData; } public function getCollectionLines() : array { return $this->collectionLines; } public function getHeaders() { return $this->headers; } }
true
dac7845f866dbfef9c2cd2826a85738b4de3e737
PHP
Gilles-boyer/epitech
/Transfert/pool_php_02/ex_02/ex_02.php
UTF-8
316
2.96875
3
[]
no_license
<?php function my_create_map(...$array) { $newarray = array(); foreach ($array as $key => $value) { if(count($value) > 2) { echo "The given arguments aren't valid."; return NULL; } $newarray[$value[0]] = $value[1]; } return $newarray; }
true
22852ec323887fc5706ed65543c1bd4afa463000
PHP
pieshop/portfolio
/api/system/app/Models/api_v2/Nextstep.php
UTF-8
1,227
2.734375
3
[ "MIT" ]
permissive
<?php namespace App\Models\api_v2; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Facades\Log; use Illuminate\Database\Eloquent\Model; class Nextstep extends Model { public static function get_data($id) { Log::info('Nextstep.get_data: ' . $id); try { $file = Storage::disk('public')->get($id.'.json'); $result = self::jsonResponse(json_decode($file, true), 200); } catch (\Exception $e) { $result = self::jsonResponse(['errorText' => $id . ' does not exist.'], 500); } return $result; } public static function save_data($id, $data) { Log::info('Nextstep.save_data: ' . $id); try { $save = Storage::disk('public')->put($id.'.json', json_decode(json_encode($data, true),true)); $result = response()->json(['response' => 'ok'], 200); } catch (\Exception $e) { $result = self::jsonResponse(['errorText' => $id . ' save failed.'], 500); } return $result; } /** * Returns json response. * * @param array|null $payload * @param int $statusCode * @return \Illuminate\Http\JsonResponse */ protected static function jsonResponse(array $payload = null, $statusCode = 404) { $payload = $payload ?: []; return response()->json($payload, $statusCode); } }
true
b3c50e5ed8b0374491bfb4ded5b15c19726c8c11
PHP
Rizki-Syafa-Nirmala/01PHP_XIRPL2_6
/tangkap.php
UTF-8
567
2.671875
3
[]
no_license
<?php echo $_GET['v1']; echo ""; echo $_GET['v2']; ?> <!DOCTYPE html> <html> <head> <title>Belajar PHP</title> </head> <body> <fieldset id="ini"> <label for="ini">DATA</label> <form method="POST" action="proses1.php"> <p>Nama : <input type="text" name="nama"></p> <p>Alamat : <input type="text" name="alamat"></p> <p><input type="submit" value="Proses" name="submit"></p> </form> </fieldset> </body> </html>
true
d942c84df24414d633418abc70dd3df937224379
PHP
Shardj/zf1-future
/library/Zend/Memory/Container/Movable.php
UTF-8
6,923
2.59375
3
[ "JSON", "LicenseRef-scancode-generic-cla" ]
permissive
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Memory * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** Zend_Memory_Container */ require_once 'Zend/Memory/Container.php'; /** Zend_Memory_Value */ require_once 'Zend/Memory/Value.php'; /** * Memory value container * * Movable (may be swapped with specified backend and unloaded). * * @category Zend * @package Zend_Memory * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Memory_Container_Movable extends Zend_Memory_Container { /** * Internal object Id * * @var integer */ protected $_id; /** * Memory manager reference * * @var Zend_Memory_Manager */ private $_memManager; /** * Value object * * @var Zend_Memory_Value */ private $_value; /** Value states */ const LOADED = 1; const SWAPPED = 2; const LOCKED = 4; /** * Value state (LOADED/SWAPPED/LOCKED) * * @var integer */ private $_state; /** * Object constructor * * @param Zend_Memory_Manager $memoryManager * @param integer $id * @param string $value */ public function __construct(Zend_Memory_Manager $memoryManager, $id, $value) { $this->_memManager = $memoryManager; $this->_id = $id; $this->_state = self::LOADED; $this->_value = new Zend_Memory_Value($value, $this); } /** * Lock object in memory. */ public function lock() { if ( !($this->_state & self::LOADED) ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } $this->_state |= self::LOCKED; /** * @todo * It's possible to set "value" container attribute to avoid modification tracing, while it's locked * Check, if it's more effective */ } /** * Unlock object */ public function unlock() { // Clear LOCKED state bit $this->_state &= ~self::LOCKED; } /** * Return true if object is locked * * @return int */ public function isLocked() { return $this->_state & self::LOCKED; } /** * Get handler * * Loads object if necessary and moves it to the top of loaded objects list. * Swaps objects from the bottom of loaded objects list, if necessary. * * @param string $property * @return Zend_Memory_Value * @throws Zend_Memory_Exception */ public function __get($property) { if ($property != 'value') { require_once 'Zend/Memory/Exception.php'; throw new Zend_Memory_Exception('Unknown property: Zend_Memory_container::$' . $property); } if ( !($this->_state & self::LOADED) ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } return $this->_value; } /** * Set handler * * @param string $property * @param string $value * @throws Zend_Exception */ public function __set($property, $value) { if ($property != 'value') { require_once 'Zend/Memory/Exception.php'; throw new Zend_Memory_Exception('Unknown property: Zend_Memory_container::$' . $property); } $this->_state = self::LOADED; $this->_value = new Zend_Memory_Value($value, $this); $this->_memManager->processUpdate($this, $this->_id); } /** * Get string value reference * * _Must_ be used for value access before PHP v 5.2 * or _may_ be used for performance considerations * * @return &string */ public function &getRef() { if ( !($this->_state & self::LOADED) ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } return $this->_value->getRef(); } /** * Signal, that value is updated by external code. * * Should be used together with getRef() */ public function touch() { $this->_memManager->processUpdate($this, $this->_id); } /** * Process container value update. * Must be called only by value object * * @internal */ public function processUpdate() { // Clear SWAPPED state bit $this->_state &= ~self::SWAPPED; $this->_memManager->processUpdate($this, $this->_id); } /** * Start modifications trace * * @internal */ public function startTrace() { if ( !($this->_state & self::LOADED) ) { $this->_memManager->load($this, $this->_id); $this->_state |= self::LOADED; } $this->_value->startTrace(); } /** * Set value (used by memory manager when value is loaded) * * @internal */ public function setValue($value) { $this->_value = new Zend_Memory_Value($value, $this); } /** * Clear value (used by memory manager when value is swapped) * * @internal */ public function unloadValue() { // Clear LOADED state bit $this->_state &= ~self::LOADED; $this->_value = null; } /** * Mark, that object is swapped * * @internal */ public function markAsSwapped() { // Clear LOADED state bit $this->_state |= self::LOADED; } /** * Check if object is marked as swapped * * @return int * @internal */ public function isSwapped() { return $this->_state & self::SWAPPED; } /** * Get object id * * @internal * @return integer */ public function getId() { return $this->_id; } /** * Destroy memory container and remove it from memory manager list * * @internal */ public function destroy() { /** * We don't clean up swap because of performance considerations * Cleaning is performed by Memory Manager destructor */ $this->_memManager->unlink($this, $this->_id); } }
true
4680944b3f467046b9cfefc6e8f53d24a1951cc4
PHP
gdm-1718-annadela/RisicovolSpelen
/web/app/themes/zakra/inc/class-zakra-dynamic-filter.php
UTF-8
2,975
2.609375
3
[ "GPL-3.0-or-later", "OFL-1.1", "GPL-2.0-only", "LicenseRef-scancode-public-domain", "GPL-1.0-or-later", "CC0-1.0", "GPL-3.0-only", "MIT" ]
permissive
<?php /** * Filter array values. * * @package ThemeGrill * @subpackage Zakra * @since Zakra 1.1.7 */ // Exit if accessed directly. defined( 'ABSPATH' ) || exit; /*========================================== HEADER > HEADER TOP BAR ==========================================*/ if ( ! class_exists( 'Zakra_Dynamic_Filter' ) ) : /** * Filter array values. */ class Zakra_Dynamic_Filter { /** * Array of filter name and css classes. * * @since 1.1.7 * @access private * @var array $css_class_arr Filter tag and class list. */ private static $css_class_arr = array(); /** * Get filter tag and class list in Array. * * @since 1.1.7 * @access public * * @return array Filter tag and class list. */ public static function css_class_list() { self::$css_class_arr = array( 'zakra_header_class' => array( 'site-header', 'tg-site-header', ), 'zakra_header_main_container_class' => array( 'tg-header-container', 'tg-container', 'tg-container--flex', 'tg-container--flex-center', 'tg-container--flex-space-between', ), 'zakra_header_top_class' => array( 'tg-site-header-top', ), 'zakra_header_top_container_class' => array( 'tg-header-container', 'tg-container', 'tg-container--flex', 'tg-container--flex-center', ), 'zakra_page_header_container_class' => array( 'tg-container', 'tg-container--flex', 'tg-container--flex-center', 'tg-container--flex-space-between', ), 'zakra_nav_class' => array( 'main-navigation', 'tg-primary-menu', ), 'zakra_header_action_class' => array( 'tg-header-action', ), 'zakra_read_more_wrapper_class' => array( 'tg-read-more-wrapper', 'clearfix', ), 'zakra_footer_widgets_container_class' => array( 'tg-container', ), 'zakra_footer_bottom_bar_container_class' => array( 'tg-container', 'tg-container--flex', 'tg-container--flex-top', ), 'zakra_scroll_to_top_class' => array( 'tg-scroll-to-top', ), 'zakra_mobile_nav_class' => array( 'tg-mobile-navigation', ), ); return apply_filters( 'zakra_css_class_list', self::$css_class_arr ); } /** * Filter the array according to key. * * @since 1.1.7 * @access public * * @param string $tag Filter tag. * * @return array Filter tag and class list. */ public static function filter_via_tag( $tag ) { $css_class = self::css_class_list(); $filtered = array(); if ( isset( $css_class[ $tag ] ) ) { $filtered = $css_class[ $tag ]; } return $filtered; } } endif;
true
e1d711aa5b26eacf87dff876c37c67f34b3cda85
PHP
joyhooei/pincong-wecenter
/system/Services/WhereBuilder.php
UTF-8
6,924
3.109375
3
[]
no_license
<?php class Services_WhereBuilder { private static $condition_operators = array( 'isNull', 'isNotNull', 'between', 'notBetween', 'like', 'notLike', 'in', 'notIn', 'eq', 'notEq', 'lt', 'gt', 'lte', 'gte', ); private static $concatenation_operators = array( 'and', 'or', ); private static $data_types = array( 'i', 'd', 's', ); private static function _is_safe_string($string) { for ($i = 0, $l = strlen($string); $i < $l; $i++) { $c = ord($string[$i]); if ($c == 0x5f) // _ { continue; } elseif ($c >= 0x30 AND $c <= 0x39) // 0-9 { continue; } elseif ($c >= 0x41 AND $c <= 0x5a) // A-Z { continue; } elseif ($c >= 0x61 AND $c <= 0x7a) // a-z { continue; } return false; } return true; } private static function _convert_data_string($val, &$prepared_values) { if (!self::_is_safe_string($val)) { if (!is_array($prepared_values)) { $prepared_values = []; } $prepared_values[] = $val; return '?'; } else { return "'" . $val . "'"; } } private static function _convert_data_auto($val, &$prepared_values) { if (is_int($val)) { return $val; } elseif (is_float($val)) { if (is_infinite($val) OR is_nan($val)) { return 0; } return $val; } elseif (is_string($val)) { return self::_convert_data_string($val, $prepared_values); } else { return intval($val); } } private static function _convert_data($val, $type, &$prepared_values) { if (!isset($type)) { return self::_convert_data_auto($val, $prepared_values); } if ($type === true) { return $val; } if (!is_string($type) OR !in_array($type, self::$data_types)) { return intval($val); } if ($type == 'i') { return intval($val); } elseif ($type == 'd') { $val = floatval($val); if (is_infinite($val) OR is_nan($val)) { return 0; } return $val; } elseif ($type == 's') { return self::_convert_data_string(strval($val), $prepared_values); } } // e.g. ['id', 'between', 1, 99] private static function _parse_condition_between($params, $not, &$prepared_values) { if (count($params) < 4) { return false; } $type = $params[4] ?? null; $from = self::_convert_data($params[2], $type, $prepared_values); $to = self::_convert_data($params[3], $type, $prepared_values); $result = "BETWEEN {$from} AND {$to}"; if ($not) { $result = 'NOT ' . $result; } return $result; } // e.g. ['name', 'like', 'admin%'] private static function _parse_condition_like($params, $not, &$prepared_values) { if (count($params) < 3) { return false; } $type = $params[3] ?? null; $val = self::_convert_data($params[2], $type, $prepared_values); $result = "LIKE {$val}"; if ($not) { $result = 'NOT ' . $result; } return $result; } // e.g. ['id', 'in', [1, 2, 3]] private static function _parse_condition_in($params, $not, &$prepared_values) { if (count($params) < 3) { return false; } $array = $params[2]; if (!is_array($array) OR count($array) < 1) { return false; } $type = $params[3] ?? null; foreach ($array as &$val) { $val = self::_convert_data($val, $type, $prepared_values); } unset($val); $array = implode(', ', $array); $result = "IN ({$array})"; if ($not) { $result = 'NOT ' . $result; } return $result; } // e.g. ['id', 'eq', 3] private static function _parse_condition_comparison($params, $operator, &$prepared_values) { if (count($params) < 3) { return false; } $type = $params[3] ?? null; $val = self::_convert_data($params[2], $type, $prepared_values); return $operator . ' ' . $val; } private static function _parse_condition($params, &$prepared_values) { $column = $params[0]; if (!is_string($column) OR $column == '' OR !self::_is_safe_string($column)) { return false; } switch ($params[1]) { case 'isNull': $result = 'IS NULL'; break; case 'isNotNull': $result = 'IS NOT NULL'; break; case 'between': $result = self::_parse_condition_between($params, 0, $prepared_values); break; case 'notBetween': $result = self::_parse_condition_between($params, 'not', $prepared_values); break; case 'like': $result = self::_parse_condition_like($params, 0, $prepared_values); break; case 'notLike': $result = self::_parse_condition_like($params, 'not', $prepared_values); break; case 'in': $result = self::_parse_condition_in($params, 0, $prepared_values); break; case 'notIn': $result = self::_parse_condition_in($params, 'not', $prepared_values); break; case 'eq': $result = self::_parse_condition_comparison($params, '=', $prepared_values); break; case 'notEq': $result = self::_parse_condition_comparison($params, '<>', $prepared_values); break; case 'lt': $result = self::_parse_condition_comparison($params, '<', $prepared_values); break; case 'gt': $result = self::_parse_condition_comparison($params, '>', $prepared_values); break; case 'lte': $result = self::_parse_condition_comparison($params, '<=', $prepared_values); break; case 'gte': $result = self::_parse_condition_comparison($params, '>=', $prepared_values); break; default: return false; } if ($result === false) { return false; } return "`{$column}` {$result}"; } private static function _append(&$where, $part) { if (!$part) { return; } if ($part == 'AND' OR $part == 'OR') { if (!$where OR substr($where, -1, 1) != ')') { return; } $where .= ' '; $where .= $part; return; } if (!$where) { $where .= $part; return; } if (substr($where, -1, 1) == ')') { $where .= ' AND '; } else { $where .= ' '; } $where .= $part; return; } private static function _parse_array($array, &$prepared_values) { $result = ''; for ($i = 0, $l = count($array); $i < $l; $i++) { $val = $array[$i]; if (!is_array($val)) // string { if ($i == 0 AND $l > 1 AND in_array($array[$i + 1], self::$condition_operators)) { $r = self::_parse_condition($array, $prepared_values); if ($r === false) { return false; } self::_append($result, $r); break; } elseif (in_array($val, self::$concatenation_operators)) // and, or { self::_append($result, strtoupper($val)); } else { return false; } } else { $r = self::_parse_array($val, $prepared_values); if ($r === false) { return false; } if (!!$r) { self::_append($result, '('. $r . ')'); } } } return $result; } public static function build($array, &$prepared_values) { if (!is_array($array)) { return false; } return self::_parse_array($array, $prepared_values); } }
true
84781623b904de9bee6c64d33f9df7699d33bdd4
PHP
MrNiceRicee/Database_Applications1_BlogPost
/getAllUsers.php
UTF-8
1,018
3.3125
3
[]
no_license
<?php //Credentials for accessing the database $dbservername="localhost"; $dbusername="root"; $dbpassword = "root"; $dbname = "fridaynotes_1.10.2020"; //create connection $conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname,3306); if ($conn ->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT USER_ID, FIRST_NAME, LAST_NAME FROM users"; //sql select all of these things, FROM the users table $result = $conn->query($sql); if ($result->num_rows > 0){ //check if it works //Loop through the users that returned from the database while ($row = $result -> fetch_assoc()){ echo "userID: " .$row["USER_ID"]. " Name: " .$row["FIRST_NAME"]. " " .$row["LAST_NAME"]. "<br>"; } }elseif($result->num_rows ==0){ echo "There are no users in the database."; }else{ echo "Error: " .$sql. "<br>" .$conn->error; } $conn->close(); ?>
true
ed3fbb7adac8fc2ad33528d763adf118a6210290
PHP
stonegithubs/Thinkphp5-wxpay
/wxpay/WxOrderQuery.php
UTF-8
3,144
2.734375
3
[ "Apache-2.0" ]
permissive
<?php namespace wxpay; /** * 微信支付订单的查询 * * 使用: * 将本文件放到extend目录下即可 * * 用法: * 调用 \wxpay\WxOrderQuery::query($order_no) 即可完成订单查询 * * 注意: * 1.错误采用抛出异常的方式, 可根据自己的业务在统一接口进行修改 * 2.默认通过商户订单号(out_trade_no)查询, 可以通过修改常量ORDER_TYPE更改为 微信订单号(transaction_id) * * ----------------- 求职 ------------------ * 姓名: zhangchaojie 邮箱: zhangchaojie_php@qq.com 应届生 * 期望职位: PHP初级工程师 薪资: 3500 地点: 深圳(其他城市亦可) * 能力: * 1.熟悉小程序开发, 前后端皆可, 前端一日可做5-10个页面, 后端可写接口 * 2.后端, PHP基础知识扎实, 熟悉ThinkPHP5框架, 用TP5做过CMS, 商城, API接口 * 3.MySQL, Linux都在进行进一步学习 * * 如有大神收留, 请发送邮件告知, 必将感激涕零! */ class WxOrderQuery extends WxBase { // REQUEST_URL: 请求地址 const REQUEST_URL = 'https://api.mch.weixin.qq.com/pay/orderquery'; // 查询方式默认为 商户订单号(out_trade_no), 可改为 微信订单号(transaction_id) const ORDER_TYPE = 'out_trade_no'; /** * 主入口 * @param string $order_no 订单号 */ static public function query($order_no) { // 1.校检数据 if (empty($order_no)) { self::processError('订单号不能为空'); } // 2.获取请求数组 $postArr = self::generateParam($order_no); // 3.生成签名 并 添加到数组中 $sign = self::makeSign($postArr); $postArr['sign'] = $sign; // 4.数组转化为xml格式 $postXml = self::arrayToXml($postArr); // 5.发送请求 $response = self::http(self::REQUEST_URL, $postXml); // 6.xml格式转为数组格式 $response = self::xmlToArray($response); // 7.进行结果处理 $result = self::processResponse($response); return $result; } /** * 处理请求结果 * @param xml $response 请求结果 */ static private function processResponse($response) { // 1.判断信息是否返回成功 if ($response['return_code'] == 'SUCCESS') { // 2. 判断订单是否存在 if ($response['result_code'] == 'SUCCESS') { return $response; } else { self::processError($response['err_code_des']); } } else { self::processError($response['return_msg']); } } /** * 生成请求数组 */ static private function generateParam($order_no) { $arr = [ 'appid' => self::APPID, 'mch_id' => self::MCHID, 'nonce_str' => self::getNoncestr(), ]; // 商户订单号 or 微信订单号 if(self::ORDER_TYPE == 'out_trade_no') { $arr['out_trade_no'] = $order_no; } else { $arr['transaction_id'] = $order_no; } return $arr; } }
true
5e1ca678f223d1fbdcc7e79fb2888b7cbdde235c
PHP
aternosorg/php-model
/src/Driver/Cassandra/Cassandra.php
UTF-8
6,847
2.75
3
[ "MIT" ]
permissive
<?php /** @noinspection PhpComposerExtensionStubsInspection */ namespace Aternos\Model\Driver\Cassandra; use Aternos\Model\Driver\Driver; use Aternos\Model\Driver\Features\CRUDAbleInterface; use Aternos\Model\Driver\Features\QueryableInterface; use Aternos\Model\ModelInterface; use Aternos\Model\Query\Generator\SQL; use Aternos\Model\Query\Query; use Aternos\Model\Query\QueryResult; use Cassandra\Exception; use Cassandra\Rows; use Cassandra\Session; use Cassandra\SimpleStatement; /** * Class Cassandra * * Inherit this class, overwrite the connect function * and/or the protected connection specific properties * and register the new class in the driver factory * for other credentials or connect specifics * * @package Aternos\Model\Driver */ class Cassandra extends Driver implements CRUDAbleInterface, QueryableInterface { public const ID = "cassandra"; protected string $id = self::ID; /** * Host address (localhost by default) * * Can actually be one or multiple comma separated hosts (contact points) * * @var null|string */ protected ?string $host = null; /** * Host port * * @var int|null */ protected ?int $port = null; /** * Authentication username * * @var null|string */ protected ?string $user = null; /** * Authentication password * * @var null|string */ protected ?string $password = null; /** * Keyspace name * * @var string */ protected string $keyspace = "data"; /** * @var Session|null */ protected ?Session $connection = null; /** * Cassandra constructor. * * @param string|null $host * @param int|null $port * @param string|null $user * @param string|null $password * @param string $keyspace */ public function __construct(?string $host = null, ?int $port = null, ?string $user = null, ?string $password = null, string $keyspace = "data") { $this->host = $host ?? $this->host; $this->port = $port ?? $this->port; $this->user = $user ?? $this->user; $this->password = $password ?? $this->password; $this->keyspace = $keyspace ?? $this->keyspace; } /** * Connect to cassandra database */ protected function connect(): void { if ($this->connection) { return; } $builder = \Cassandra::cluster(); if ($this->host) { $builder->withContactPoints($this->host); } if ($this->port) { $builder->withPort($this->port); } if ($this->user && $this->password) { $builder->withCredentials($this->user, $this->password); } $cluster = $builder->build(); $this->connection = $cluster->connect($this->keyspace); } /** * Execute a cassandra query * * @param string $query * @return Rows * @throws Exception */ protected function rawQuery(string $query): Rows { $this->connect(); $statement = new SimpleStatement($query); return $this->connection->execute($statement, null); } /** * Save the model * * @param ModelInterface $model * @return bool * @throws Exception */ public function save(ModelInterface $model): bool { $table = $model::getName(); $data = json_encode($model); $data = str_replace("'", "''", $data); $query = "INSERT INTO " . $table . " JSON '" . $data . "';"; $this->rawQuery($query); return true; } /** * Get the model * * @param class-string<ModelInterface> $modelClass * @param mixed $id * @param ModelInterface|null $model * @return ModelInterface|null * @throws Exception */ public function get(string $modelClass, mixed $id, ?ModelInterface $model = null): ?ModelInterface { $table = $modelClass::getName(); $id = str_replace("'", "''", $id); $query = "SELECT * FROM " . $table . " WHERE " . $modelClass::getIdField() . " = '" . $id . "'"; $rows = $this->rawQuery($query); if ($rows->count() === 0) { return null; } $current = $rows->current(); if ($model) { return $model->applyData($current); } return $modelClass::getModelFromData($current); } /** * Delete the model * * @param ModelInterface $model * @return bool * @throws Exception */ public function delete(ModelInterface $model): bool { $table = $model::getName(); $id = str_replace("'", "''", $model->getId()); $query = "DELETE FROM " . $table . " WHERE " . $model->getIdField() . " = '" . $id . "'"; $this->rawQuery($query); return true; } /** * Execute a SELECT, UPDATE or DELETE query * * @param Query $query * @return QueryResult * @throws Exception */ public function query(Query $query): QueryResult { $this->connect(); $generator = new SQL(function ($value) { return str_replace("'", "''", $value); }); $generator->columnEnclosure = ""; $generator->tableEnclosure = ""; $queryString = $generator->generate($query); $rawQueryResult = $this->rawQuery($queryString); $result = new QueryResult((bool)$rawQueryResult); $result->setQueryString($queryString); foreach ($rawQueryResult as $resultRow) { /** @var class-string<ModelInterface> $modelClass */ $modelClass = $query->modelClassName; $model = $modelClass::getModelFromData($resultRow); $result->add($model); } return $result; } /** * @param string|null $host * @return Cassandra */ public function setHost(?string $host): Cassandra { $this->host = $host; return $this; } /** * @param int|null $port * @return Cassandra */ public function setPort(?int $port): Cassandra { $this->port = $port; return $this; } /** * @param string|null $user * @return Cassandra */ public function setUser(?string $user): Cassandra { $this->user = $user; return $this; } /** * @param string|null $password * @return Cassandra */ public function setPassword(?string $password): Cassandra { $this->password = $password; return $this; } /** * @param string $keyspace * @return Cassandra */ public function setKeyspace(string $keyspace): Cassandra { $this->keyspace = $keyspace; return $this; } }
true
a3a1807bd09cef38a715f31094c05bf04d8832c5
PHP
ljuraszek/symfony-graphql
/src/Repository/Query/PostQuery.php
UTF-8
308
2.59375
3
[]
no_license
<?php declare(strict_types = 1); namespace App\Repository\Query; use App\Repository\PostRepository; abstract class PostQuery { /** @var PostRepository */ protected $repository; public function __construct(PostRepository $repository) { $this->repository = $repository; } }
true
aa45e1eddd5c28a31d7f58c2223c3609da18a4b8
PHP
wilterson/softcars
/admin/cad_carros.php
UTF-8
1,071
2.59375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Wilterson Garcia * Date: 20/06/2016 * Time: 00:49 */ include('config/initialize.php'); include('config/Conn/Conn.class.php'); session_start(); // Recebe e valida as variaveis $marca = filter_var(mb_strtolower( $_POST['marcaCar'] ), FILTER_SANITIZE_STRING); $modelo = filter_var(mb_strtolower( $_POST['modelo'] ), FILTER_SANITIZE_STRING); $placa = filter_var(mb_strtolower( $_POST['placa'] ), FILTER_SANITIZE_STRING); $ano = filter_var(mb_strtolower( $_POST['ano'] ), FILTER_SANITIZE_NUMBER_INT); $cor = filter_var(mb_strtolower( $_POST['cor'] ), FILTER_SANITIZE_STRING); $result = false; // Monta array para cadastro de rota (tabela rota) $dados = array("id_usuario" => $_SESSION['user_id'], "marca" => $marca, "modelo" => $modelo, "placa" => $placa, "ano" => $ano, "cor" => $cor ); //executa o create de carros $carro = new Create(); $carro->ExeCreate('carros', $dados); //Cadastro efetuado com sucesso if($carro->getStatus()){ $msg = "success"; echo $msg; }else{ $msg = "error"; echo $msg; }
true
380df2a1c3fe18373d078527cbc0bd6ca9aca0dd
PHP
jh3/drushexts
/lightcron.drush.inc
UTF-8
2,103
2.6875
3
[]
no_license
<?php /** * Implementation of hook_drush_command(). */ function lightcron_drush_command() { $items = array(); $items['run-cron-hooks'] = array( 'description' => "Run a cron hook for a specific module or set of modules", 'arguments' => array( 'modules' => 'The modules that have the cron hooks you want to execute', ), 'examples' => array( 'drush rch scheduler' => 'Run the scheduler cron hook', 'drush rch feeds xmlsitemap' => 'Run the cron hooks for feeds and xmlsitemap', ), 'aliases' => array('rch'), 'bootstrap' => DRUSH_BOOTSTRAP_DRUPAL_FULL, ); return $items; } /** * Implementation of hook_drush_help(). */ function lightcron_drush_help($section) { switch ($section) { case 'drush:run-cron-hooks': return dt("This command will let you run cron hooks for one or more modules."); } } /** * Callback for the run-cron-hooks command */ function drush_lightcron_run_cron_hooks() { $modules = lightcron_parse_arguments(func_get_args(), FALSE); foreach ($modules as $module) { if (module_exists($module)) { $callback = $module . '_cron'; if (function_exists($callback)) { $callback(); drush_log(dt('!module (!date): cron hook executed.', array('!module' => $module, '!date' => date('Y-m-d H:i:s O'))), 'ok'); } else { drush_log(dt('!module does not have a cron hook.', array('!module' => $module)), 'error'); } } else { drush_log(dt('!module does not exist i.e. not installed and enabled.', array('!module' => $module)), 'error'); } } } /** * Sanitize user provided arguments * * Return an array of arguments off a space and/or comma separated values. * * @see drush/commands/pm/pm.drush.inc */ function lightcron_parse_arguments($args, $dashes_to_underscores = TRUE) { // @see drush/includes/drush.inc for _convert_csv_to_array($args) $arguments = _convert_csv_to_array($args); foreach ($arguments as $key => $argument) { $argument = ($dashes_to_underscores) ? strtr($argument, '-', '_') : $argument; } return $arguments; }
true
849e5602f3faf005586c6d272acad4d202cfea7d
PHP
simonbacquie/shift-api
/src/Model/Shift.php
UTF-8
2,688
2.703125
3
[]
no_license
<?php //User Model namespace ShiftApi\Model; use Illuminate\Database\Eloquent\Model as Eloquent; use Illuminate\Validation\Factory as ValidatorFactory; use Symfony\Component\Translation\Translator; class Shift extends Eloquent { protected $table = 'shifts'; protected $guarded = ['id']; // don't accept id in mass assignment, must auto-increment private $validation_rules = [ 'start_time' => 'required', 'end_time' => 'required' ]; public function validate($data) { $factory = new ValidatorFactory(new Translator('en')); $v = $factory->make($data, $this->validation_rules); return $v->passes(); } public function manager() { return $this->belongsTo('ShiftApi\Model\User', 'manager_id', 'id') ->select('id', 'name', 'email', 'phone'); } public function employee() { return $this->hasOne('ShiftApi\Model\User', 'id', 'employee_id') ->select('id', 'name', 'email', 'phone'); } // public function employeesForShift($shift_id) { // return $this->where('id', $shift_id) // // } // public function coworkers($employee_id) { // return $this->hasMany('ShiftApi\Model\User', 'employee_id', 'id') // ->select('id', 'name', 'email', 'phone') // ->where('', '>=', $this->start_time); // } // public function overlapping_shifts() { // return $this->where('start_time', '>=', $this->start_time) // ->andWhere('end_time', '<=', $this->end_time); // } public static function shiftsInTimeRange($start_time, $end_time) { return self::where('start_time', '>=', $start_time) ->where('end_time', '<=', $end_time); } public static function hoursByWeek($week_of, $employee_id) { $week_of_time = strtotime($week_of); $begin_string = date("l", $week_of_time) == 'Sunday' ? 'this Sunday' : 'last Sunday'; $end_string = 'next Sunday'; $week_begins = date('Y-m-d H:i:s', strtotime($begin_string, strtotime($week_of))); $week_ends = date('Y-m-d H:i:s', strtotime($end_string, strtotime($week_of))); $shifts_in_week = self::where('employee_id', $employee_id) ->where('start_time', '>=', $week_begins) ->where('start_time', '<=', $week_ends)->get(); $unix_seconds = 0; foreach ($shifts_in_week as $shift) { $start_time = new \DateTime($shift->start_time); $end_time = new \DateTime($shift->end_time); $unix_seconds += $end_time->getTimestamp() - $start_time->getTimestamp(); } $hours = $unix_seconds / 60 / 60; return [ 'week_begins' => $week_begins, 'week_ends' => $week_ends, 'hours' => $hours, 'shifts' => $shifts_in_week->toArray() ]; } }
true
f952b6915427673a78e2a6cdad4550143de5d326
PHP
bmvc-php/bmvc-app
/vendor/mirarus/bmvc-exception/src/ClassException.php
UTF-8
676
2.875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * ClassException * * Mirarus BMVC * @package BMVC\Exception * @author Ali Güçlü (Mirarus) <aliguclutr@gmail.com> * @link https://github.com/mirarus/bmvc-exception * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version 0.3 */ namespace BMVC\Exception; use Exception; class ClassException extends Exception { private $namespaces = [ 'BMVC\\Core', 'BMVC\\Libs', 'BMVC\\Exception' ]; public function __construct($message, $class=null) { if ($class && @class_exists($class)) { $class = str_replace($this->namespaces, null, $class); $message = '"' . $class . '" Class Error! | ' . $message; } parent::__construct($message); } }
true
6f967eef9aaf3ea05e5a7ae684b8ec1b18adeb89
PHP
mireq/Shakal
/system/ShakalExceptions.php
UTF-8
3,272
2.75
3
[]
no_license
<?php /** * \file * \author Miroslav Bendík * \brief Výnimky používane v Shakal CMS. */ namespace Shakal; /** * \brief Základná výnimka v Shakal CMS. * \ingroup Shakal_Exceptions * \licenses \gpl * * Na rozdiel od štandardných výnimiek v PHP má táto výnimka * navyše ple \e data používané pre rozšírené informácie * o chybe, ktorá nastala. */ abstract class BaseException extends \Exception { private $data; /** * Vytvorenie novej vynimky. * * \param string code Kód výnimky. * \param int msg Správa pre užívateľa. * \param mixed data Rozšírené informácie o výnimke. */ public function __construct($msg = '', $code = 0, $data = null) { parent::__construct($msg, $code); $this->data = $data; } /** * Získanie rozšírených dát k výnimke. * * @return mixed */ public final function getData() { return $this->data; } } /** * \brief Systémová výnimka. * \ingroup Shakal_Exceptions * \licenses \gpl * * Táto výnimka má za následok zastavenie behu aplikácie. * Užívateľa o chybe informuje samostatnou stránkou. */ class SystemException extends BaseException { /// Nešpecifikovaná chyba. const OtherError = 0; /// Chyba pri includovaní súboru. const IncludeError = 1; /// Chyba vyvolaná pri neexistujúcej stránke. const NotFound = 2; /// Chýbajúca trieda. const ClassNotFound = 3; /** * Vytvorenie novej systémovej výnimky. * * \param string msg Správa, ktorá sa zobrazí užívateľovi pri vyvolaní výnimky. * \param int code Typ vyvolanej výnimky. * \param mixed data Dáta spresňujúce výnimku. */ public function __construct($msg = '', $code = self::OtherError, $data = null) { parent::__construct($msg, $code, $data); } } /** * \brief Užívateľská výnimka. * \ingroup Shakal_Exceptions * \licenses \gpl * * Vyvolanie tejto výnimky spôsobí jej zobrazenie * na stránke, ktorú navštívil užívateľ. */ class UserException extends BaseException { const UserNotice = 0; /**< Poznámka, ktorá má minimálny vplyv na ďalší beh aplikácie. */ const UserWaring = 1; /**< Varovanie pri akciách ktoré je možné napriek tomu dokončiť. */ const UserError = 2; /**< Chyba pri vykonávaní akcie. */ /** * Vytvorenie novej užívateľskej výnimky. * * \param string msg Správa pre užívateľa. * \param int code Typ výnimky. * \param mixed data Dodatočné dáta. */ public function __construct($msg = '', $code = self::UserNotice, $data = null) { parent::__construct($msg, $code, $data); } } /** * \brief Chyba pri spúšťaní %SQL príkazu. * \ingroup Shakal_SQL Shakal_Exceptions * \licenses \gpl * * Výnimka pri spúšťaní SQL príkazu. */ class SQLException extends BaseException { /** * Vytvorenie SQL výnimky. * * \param string msg Chybová správa. * \param int code Chybový kód vrátený databázou. * \param string query Dotaz, pri ktorom došlo k výnimke. */ public function __construct($msg, $code = 0, $query = null) { parent::__construct($msg, $code, $query); } /** * Dotaz, pri ktorom nastala výnimka. * * \return string */ public function query() { return parent::data(); } } ?>
true
2b0ab0644dc940a4a4d7d220c74e264aaf7a5521
PHP
flyplay91/acellemail
/app/Model/IpLocation.php
UTF-8
3,904
2.703125
3
[]
no_license
<?php /** * IpLocation class. * * Model class for IP Locations * * LICENSE: This product includes software developed at * the Acelle Co., Ltd. (http://acellemail.com/). * * @category MVC Model * * @author N. Pham <n.pham@acellemail.com> * @author L. Pham <l.pham@acellemail.com> * @copyright Acelle Co., Ltd * @license Acelle Co., Ltd * * @version 1.0 * * @link http://acellemail.com */ namespace Acelle\Model; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Log as LaravelLog; class IpLocation extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'country_code', 'country_name', 'region_code', 'region_name', 'city', 'zipcode', 'latitude', 'longitude', 'metro_code', 'areacode', ]; /** * Add new IP. * * return Location */ public static function add($ip) { //SELECT * FROM `ip2location_db11` WHERE INET_ATON('116.109.245.204') <= ip_to LIMIT 1 $location = self::where('ip_address', '=', $ip)->first(); if (!is_object($location)) { $location = new self(); } $location->ip_address = $ip; // Get info try { if (!(strpos($ip, ":") > -1)) { // Code for IPv4 address $ip_address... $location_table = table('ip2location_db11'); } else { // Code for IPv6 address $ip_address...ip2location_db11_ipv6 $location_table = table('ip2location_db11_ipv6'); } $location_tables = \DB::select('SHOW TABLES LIKE "'.$location_table.'"'); // Local service if (count($location_tables)) { // Check for ipv4 or ipv6 if (!(strpos($ip, ":") > -1)) { $aton = $ip; $records = \DB::select("SELECT * FROM `".$location_table."` WHERE INET_ATON(?) <= ip_to LIMIT 1", [$aton]); } else { $aton = Dot2LongIPv6($ip); $records = \DB::select("SELECT * FROM `".$location_table."` WHERE ? <= ip_to LIMIT 1", [$aton]); } if (count($records)) { $record = $records[0]; $location->country_code = $record->country_code; $location->country_name = $record->country_name; $location->region_name = $record->region_name; $location->city = $record->city_name; $location->zipcode = $record->zip_code; $location->latitude = $record->latitude; $location->longitude = $record->longitude; } else { throw new \Exception("IP address [$ip] can not be found in local database: "); } // Remote service } else { $result = file_get_contents('http://freegeoip.net/json/'.$ip); $values = json_decode($result, true); $location->fill($values); } } catch (\Exception $e) { echo $e->getMessage(); // Note log LaravelLog::warning('Cannot get IP location info: ' . $e->getMessage()); } $location->save(); return $location; } /** * Location name. * * return Location */ public function name() { $str = []; if (!empty($this->city)) { $str[] = $this->city; } if (!empty($this->region_name)) { $str[] = $this->region_name; } if (!empty($this->country_name)) { $str[] = $this->country_name; } $name = implode(', ', $str); return (empty($name) ? trans('messages.unknown') : $name); } }
true
20c08622e90c7dbf8f575813c0a9006ba67055a4
PHP
naknak987/ForkingDaemon
/Daemon/doJob.php
UTF-8
2,694
2.984375
3
[]
no_license
<?php /** * Do Job * * This is the code that will pull jobs from beanstalkd and * execute the job. The code here depends a lot on the job * what you're trying to accoplish with the daemon. * * PHP Version 7.1.19 * * @category Job * @package ForkingDaemon * @author Matthew Goheen <matthew.goheen@guardianeldercare.net> * @license MIT License (see https://www.tldrlegal.com/l/mit) * @link https://github.com/naknak987/ForkingDaemon */ namespace Daemon\JobHandler; use Pheanstalk\Pheanstalk; /** * Do Job * * This is where you would define methods for the jobs you * want the daemon to be able to handle. * * @category Job * @package ForkingDaemon * @author Matthew Goheen <matthew.goheen@guardianeldercare.net> * @license MIT License (see https://www.tldrlegal.com/l/mit) * @link https://github.com/naknak987/ForkingDaemon */ class DoJob { protected $queue = null; /** * Constructor * * Create a connection to the beanstalk server. * * @return null */ public function __construct() { $this->queue = new Pheanstalk('localhost', '11300', null, true); } /** * Destructor * * Disconnect from the beanstalk server. * * @return null */ public function __destruct() { unset($this->queue); } /** * Execute Job * * Fetch a job from the queue, and route it to the * correct job handler. * * @return null */ public function executeJob() { // Fetch a job echo "_"; $job = $this->queue ->watch('testtube') ->ignore('default') ->reserve(); // Ensure we got a job. if ($job !== false) { // Extract job data. $jobData = json_decode($job->getData()); switch ($jobData->Name) { case 'Wait': $result = $this->wait($jobData->Time); break; default: // Job definition unknown. break; } if (isset($result) && $result === true) { // Job succeeded. Remove it. $this->queue->delete($job); } else { // Job Failed. Bury it. $this->queue->bury($job); } } } /** * Wait * * This performs the actions described in our example job. * * @param array $ttw The time to wait. * * @return bool */ public function wait($ttw) { try{ sleep($ttw); return true; } catch(Exception $e) { return $e->getMessage(); } } } ?>
true
f12f360c703b60cb9ac532f0dd114e7fe5c2cd5d
PHP
c3limited/magento-remember-settings
/src/web-root/app/code/local/C3/RememberSettings/Model/Admin/Observer.php
UTF-8
4,117
2.640625
3
[]
no_license
<?php /** * Class C3_RememberSettings_Model_Admin_Observer */ class C3_RememberSettings_Model_Admin_Observer { const GRID_PREFIX = 'grid'; /** * Load admin user preferences to session * * @param $observer */ public function loadGridPreferences($observer) { // Get extra (preferences) data from admin user $adminUser = Mage::getSingleton('admin/session')->getUser(); if ($adminUser === null) return; $extra = $this->_getUserExtra($adminUser); // If preferences are saved, load them into session if (isset($extra['session_store']) && is_array($extra['session_store'])) { $session = Mage::getSingleton('adminhtml/session'); foreach ($extra['session_store'] as $key => $data) { $session->setData($key, $data); } } } /** * Save admin user preferences from session * * @param $observer */ public function saveGridPreferences($observer) { // Get admin session $session = Mage::getSingleton('adminhtml/session'); // Get current data from admin user /** @var C3_RememberSettings_Model_Admin_User $adminUser */ $adminUser = Mage::getSingleton('admin/session')->getUser(); if ($adminUser === null) return; $extra = $this->_getUserExtra($adminUser); // Set any matched data from session to admin user extra $changed = false; foreach ($session->getData() as $key => $data) { if ($this->_isSessionKeyStorable($key)) { // If data exists in extra, only set if different. If data does not exist, always set if ((isset($extra['session_store'][$key]) && $extra['session_store'][$key] !== $data) || !isset($extra['session_store'][$key])) { $changed = true; // If value is blank, then remove the entry if ($data === '') { unset($extra['session_store'][$key]); } else { $extra['session_store'][$key] = $data; } } } else if (isset($extra['session_store'][$key])) { // If we are not going to store this, but it was stored before, we need to save the user unset($extra['session_store'][$key]); $changed = true; } // If neither match, then we are not storing the data and no value was stored, so ignore } // Save user on change if ($changed) { Mage::log('Saving admin user to store changed grid options from session'); $adminUser->setExtra($extra); $adminUser->saveExtra($extra); } } /** * Get extra data from admin-user * * @param C3_RememberSettings_Model_Admin_User $adminUser * @return null|array */ protected function _getUserExtra($adminUser) { $extra = $adminUser->getExtra(); if (!is_array($extra)) { if (empty($extra)) { return array(); } else { $extra = unserialize($extra); } } return $extra; } /** * Is this session param name one that should be stored? * Ensures that this is of the grid parameters that has been chosen to be stored * * @param string $key Session param name * @return bool */ protected function _isSessionKeyStorable($key) { $allowedActions = Mage::helper('c3_remembersettings')->getAllowedActions(); // Foreach allowed action, use to match end of session param names foreach ($allowedActions as $action) { $actionLen = strlen($action); $offset = 4 + $actionLen; if (substr_compare($key, self::GRID_PREFIX . $action,-$offset,$offset,true) === 0) { return true; } } // If did not match any allowed action, then this key is not allowed return false; } }
true
eb4d4b4f0ef7490afbaace97feb9f1fe8836e0db
PHP
mohitoshpm/Hr
/framework/Enum.php
UTF-8
448
2.953125
3
[]
no_license
<?php //Gender Enum class Gender { var $Male = 1; var $Female = 2; var $Other = 3; } function GenderEnumList(){ $gender = new Gender(); $class_vars = get_class_vars(get_class($gender)); return $class_vars; } //User Type Enum class UserTypeEnum { var $Hr = 1; var $Employee = 2; } function UserTypeEnumList(){ $obj = new UserTypeEnum(); $class_vars = get_class_vars(get_class($obj)); return $class_vars; } ?>
true
4a1d17d0c7f77ef96243b0fa872aa4827101700e
PHP
eliud03/blog
/application/views/show_entries.php
UTF-8
618
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<div class="container"> <?php if (!empty($entries)) : ?> <?php foreach($entries as $entry) : ?> <h2><a href="<?=base_url().'blog/view/'.$entry->id?>"><?=$entry->title?></a></h2> <p><span class="textAzul">Author:</span> <?=$entry->author?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span class="textAzul">Date:</span> <?=convertDateTimetoTimeAgo($entry->date)?></p> <hr /> <?php endforeach; ?> <?php else : ?> <h1>No entries</h1> <?php endif; ?> </div>
true
4cd48bfec02037fd1b494e351f34f89a0a1c6ff8
PHP
NotYannis/portfolio
/lib/auth.php
UTF-8
968
2.859375
3
[]
no_license
<?php session_start(); // Redirige vers la page login si pas identifié if(!isset($auth)){ if(!isset($_SESSION['Auth']['id'])){ header('Location:' . WEBROOT . 'login.php'); die(); } } /** * Créé un jeton csrf pour éviter d'avoir les informations sur les actions * en clair dans l'url lorsqu'on est loggé admin **/ if(!isset($_SESSION['csrf'])){ $_SESSION['csrf'] = md5(time() + rand()); } //Donne le contenu du jeton csrf pour la session en cours function csrf(){ return 'csrf=' . $_SESSION['csrf']; } //Renvoie sur une page si le contenu de csrf est différent de celui de la session ou vide function checkCsrf(){ if( (isset($_POST['csrf']) && $_POST['csrf'] == $_SESSION['csrf']) || (isset($_GET['csrf']) && $_GET['csrf'] == $_SESSION['csrf']) ){ return true; } header('Location:' . WEBROOT . '/csrf.php'); die(); } function csrfInput(){ return '<input type="hidden" value="' . $_SESSION['csrf'] . '" name="csrf">'; } ?>
true
297747b784c441e903d095a6b5025e268416a518
PHP
dc769319/tiny
/app/core/App.php
UTF-8
5,974
2.875
3
[]
no_license
<?php namespace app\core; class App { /** * 存储配置项的数组 * @var array */ public static $conf; /** * @var string 默认访问的控制器名称 */ private $defaultController; /** * @var string 默认访问的方法名称 */ private $defaultAction; /** * @var \app\core\Route 的引用 */ private $route; /** * @var array 核心文件路径映射表 */ public static $classMap; public function __construct($mainConfigPath) { //加载配置信息 self::$conf = $this->loadConfig($mainConfigPath); //加载默认的路由配置信息 $this->loadDefaultRoute(); $this->route = new Route(); } /** * 加载配置文件 保证只加载一次 * @param string $mainConfigPath 主配置文件路径 * @return array|mixed */ private function loadConfig($mainConfigPath) { if (!empty(self::$conf)) { return self::$conf; } else { return include "{$mainConfigPath}"; } } /** * 加载默认路由 */ private function loadDefaultRoute() { $this->defaultController = isset(self::$conf['app']['defaultController']) ? self::$conf['app']['defaultController'] : 'home'; $this->defaultAction = isset(self::$conf['app']['defaultAction']) ? self::$conf['app']['defaultAction'] : 'index'; } /** * 自动引入类文件 * @param $class * @throws */ public static function loadClass($class) { //优先使用核心文件路径映射表来获取文件路径 if (isset(self::$classMap[$class])) { $classFile = self::$classMap[$class]; } else { //如果核心文件路径映射表中找不到该文件的路径,则解析 $class = str_replace('\\', '/', $class); $class = trim($class, '/'); $classFile = BASE_PATH . DIRECTORY_SEPARATOR . $class . ".php"; } if (!is_file($classFile)) { throw new \Exception('File ' . $classFile . ' not found'); } include($classFile); } /** * 应用驱动 */ public function run() { //获从Url中得到,控制器段、方法段 list($c, $a) = $this->route(); //解析成对应的控制器类文件名称 $controllerName = $this->parseController($c); //解析成对应的方法名称 $actionName = $this->parseAction($a); //带完整命名空间的控制器 $controllerClass = "app\\controller\\{$controllerName}"; if (!class_exists($controllerClass)) { throw new \Exception('Class ' . $controllerClass . ' not found'); } $app = new $controllerClass; if (!method_exists($app, $actionName)) { throw new \Exception('Method ' . $actionName . ' not found'); } $app->$actionName(); } /** * 解析控制器名称 * 例如:url中的控制器部分为user-info,则解析出来的控制器名称为UserInfoController * @param $c * @return string */ private function parseController($c) { $controllerDirt = explode('-', strtolower($c)); $controllerDirt = array_map('ucfirst', $controllerDirt); //控制器名称后面添加Controller后缀 return implode('', $controllerDirt) . 'Controller'; } /** * 解析方法名称 * 例如:url中的方法部分为get-info,则解析出来的方法名称为actionGetInfo * @param $a * @return string */ private function parseAction($a) { $actionDirt = explode('-', strtolower($a)); $actionDirt = array_map('ucfirst', $actionDirt); //添加action前缀 return 'action' . implode('', $actionDirt); } /** * 以自定义格式显示错误 * @param $exception \Exception */ public static function handleException($exception) { //如果开启了debug则显示完整错误信息,否则只显示发生错误 if (DEBUG) { //以特定格式输出错误信息 $errorMsg = '<div style="font-size: 20px;color:#FF3030;font-weight:bold">An Error Occurred</div><div>' . $exception->getMessage() . '</div><div>Filename: <i>' . $exception->getFile() . '</i></div><div>Line Number: <i>' . $exception->getLine() . '</i></div>'; echo $errorMsg; } else { echo '<div style="color: #636363;font-size: 20px;">An internal server error occurred.</div>'; } } /** * 路由方法,负责从url中获得控制器、方法 * @return array */ private function route() { /*从URL中解析,请求指向的控制器、方法*/ $routeStr = $this->route->parse(); $routeDirt = (empty($routeStr)) ? [$this->defaultController, $this->defaultAction] : explode('/', $routeStr); $routeLen = sizeof($routeDirt); if ($routeLen < 2) { //控制器 $controllerName = isset($routeDirt[0]) ? trim($routeDirt[0]) : $this->defaultController; //方法 $actionName = $this->defaultAction; } else { //控制器 $controllerName = isset($routeDirt[$routeLen - 2]) ? trim($routeDirt[$routeLen - 2]) : $this->defaultController; //方法 $actionName = isset($routeDirt[$routeLen - 1]) ? trim($routeDirt[$routeLen - 1]) : $this->defaultAction; } return [$controllerName, $actionName]; } } //加载核心文件路径映射表 App::$classMap = require __DIR__ . '/Classes.php'; //初始化不存在的类时,自动引入该类文件 spl_autoload_register(['\\app\\core\\App', 'loadClass'], true, true); //注册顶层错误处理方法 set_exception_handler(['\\app\\core\\App', 'handleException']); ?>
true
c64b79eb0dc0b029cada2a308bd0a076df65fe1c
PHP
mpscholten/github-api
/src/Api/AbstractApi.php
UTF-8
2,576
2.765625
3
[ "MIT" ]
permissive
<?php namespace MPScholten\GitHubApi\Api; use Guzzle\Http\ClientInterface; use Guzzle\Http\Message\RequestInterface; use MPScholten\GitHubApi\Exception\GithubException; use MPScholten\GitHubApi\ResponseDecoder; class AbstractApi { protected $client; public function __construct(ClientInterface $client = null) { $this->client = $client; } protected function get($url, $query = []) { if (!$this->client) { throw new \RuntimeException(vsprintf( 'Did you forget to pass the http-client in the constructor of %s?', get_class($this) )); } $request = $this->client->get($url); $request->getQuery()->merge($query); $response = $this->sendRequest($request); return ResponseDecoder::decode($response); } protected function post($url, $payload = []) { if (!$this->client) { throw new \RuntimeException(vsprintf( 'Did you forget to pass the http-client in the constructor of %s?', get_class($this) )); } $request = $this->client->post($url, null, json_encode($payload)); $response = $this->sendRequest($request); return ResponseDecoder::decode($response); } protected function delete($url) { if (!$this->client) { throw new \RuntimeException(vsprintf( 'Did you forget to pass the http-client in the constructor of %s?', get_class($this) )); } $request = $this->client->delete($url); $this->sendRequest($request); } private function sendRequest(RequestInterface $request) { try { return $request->send(); } catch (\Exception $e) { throw new GithubException('Unexpected response.', 0, $e); } } protected function createPaginationIterator($url, $class, $query = []) { $request = $this->client->get($url); foreach ($query as $key => $value) { $request->getQuery()->add($key, $value); } return new PaginationIterator( $this->client, $request, function ($response) use ($class) { $models = []; foreach ($response as $data) { $model = new $class($this->client); $model->populate($data); $models[] = $model; } return $models; } ); } }
true
6bad174ecac827405c3a1edd71f704dcdaa7e9ce
PHP
astandre/ingenieria_web
/practicaPHP/internas/procesar.php
UTF-8
734
3.28125
3
[]
no_license
<?php extract($_POST); //$var1 = 2; //$var2 = "3"; //echo $res = $var1 + $var2; $fecha_actual = "2018-05-10"; $tiempo = strtotime($fecha_nacimiento); $ahora = time(); $edad = ($ahora - $tiempo) / (60*60*24*365.25); $edad = floor($edad); echo "Hola PHP <br> Bienvenidos ".$nombres." ".$apellidos; print "<br> Ud tiene: ". $edad . " años de edad,"; print "<br>"; //Condiciones if($edad >=18){ print "Usted es mayor de edad"; }else{ print "Usted es menor de edad"; } //Lista $lista[0] = "Docente"; $lista[1] = "Estudiante"; $lista[2] = "Abogado"; $lista[3] = "Ingeniero"; $lista[4] = "Doctor"; $lista[5] = "Policia"; //For for($i = 0; $i<count($lista); $i++){ print "Elemnto: ". $i . " contenido: ". $lista[$i]."<br>"; } ?>
true
f634caa5ab217d8f3b2cf18b82695ae90dc06334
PHP
nimanym/fliquer
/veralbum.php
UTF-8
1,691
2.8125
3
[]
no_license
<?php // Título de la página, se muestra en <title> y en el cuerpo de la página con <h2> $title = "Ver Álbum - Fliquer"; $nombre = "Ver Álbum"; require_once("cabecera.inc"); if(!isset($_SESSION['nombreUsu'])){ header('Location: nuevoUsuario.php'); } ?> <script src="cambioEstilos.js"></script> <script src="validacion.js"></script> <?php // Conecta con el servidor de MySQL $link = @mysqli_connect( 'localhost', // El servidor 'root', // El usuario '', // La contraseña 'pibd'); // La base de datos if(!$link) { echo '<p>Error al conectar con la base de datos: ' . mysqli_connect_error(); echo '</p>'; exit; } // Ejecuta una sentencia SQL $sentencia = 'SELECT f.* FROM albumes a, fotos f WHERE f.Album=a.IdAlbum and IdAlbum=' . $_GET["albumId"]; if(!($resultado = @mysqli_query($link, $sentencia))) { echo "<p>Error al ejecutar la sentencia <b>$sentencia</b>: " . mysqli_error($link); echo '</p>'; exit; } echo '<table style="margin: 0 auto;"><tr>'; echo '<th>Ficher</th><th>Titulo</th><th>Fecha</th><th>Pais</th><th>FRegistro</th>'; echo '</tr>'; // Recorre el resultado y lo muestra en forma de tabla HTML while($fila = mysqli_fetch_assoc($resultado)) { echo '<tr>'; echo '<td>' . '<a href="detallefoto.php?foto='. $fila['IdFoto'] .'" > <img src="' . $fila['Fichero'] . '_thumb.jpg' . '"</img></a></td>'; echo '<td>' . $fila['Titulo'] . '</td>'; echo '<td>' . $fila['Fecha'] . '</td>'; echo '<td>' . $fila['Pais'] . '</td>'; echo '<td>' . $fila['FRegistro'] . '</td>'; echo '</tr>'; } echo '</table>'; // Libera la memoria ocupada por el resultado mysqli_free_result($resultado); // Cierra la conexión mysqli_close($link); ?> <?php require_once("footer.inc"); ?>
true
76e36fb40df7d0e942f74b664426fd7e1ebe0032
PHP
Skaras85/legitymacje
/framework/engine/lang.class.php
UTF-8
9,995
2.640625
3
[]
no_license
<?php class lang{ public static $msg = ''; //komunikat ustawiany przy wielu metodach public static function set_lang($lang=false) { $default_lang = self::get_default_lang(); if($lang) { //sprawdzamy czy taki język istnieje $is_exists = db::get_one("SELECT 1 FROM langs WHERE short='$lang' AND is_active=1"); //jezeli istnieje if($is_exists) { //sprawdzamy, czy taki jezyk nie jest juz ustawiony //if((isset($_SESSION['lang']) && $_SESSION['lang']!=$lang) || !isset($_SESSION['lang'])) { $_SESSION['lang'] = $lang; self::get_lang_texts(); } } else { //jezeli taki jezyk nie istnieje to ustawiamy na domyslny if(isset($_SESSION['lang']) && $_SESSION['lang']!=$default_lang) $_SESSION['lang'] = $default_lang; } } else { //jezeli nie ma zadnego jezyka ustawiamy na domyslny //if(!isset($_SESSION['lang'])) { $_SESSION['lang'] = $default_lang; self::get_lang_texts(); } } return true; } public static function get_default_lang() { return db::get_one("SELECT short FROM langs WHERE is_default=1"); } public static function get_lang_texts() { $a_texts = db::get_all('lang_texts','',"name,value_{$_SESSION['lang']}"); foreach($a_texts as $a_text) { $_SESSION['lang_texts'][$a_text['name']] = $a_text["value_{$_SESSION['lang']}"]; } } public static function get_langs($only_active=false,$without_default=false) { $sql_active = $only_active ? "AND is_active=1" : ''; $sql_without_default = $without_default ? "AND is_default<>1" : ''; return db::get_many("SELECT * FROM langs WHERE 1=1 $sql_active $sql_without_default ORDER BY `order`"); } public static function add_lang($ia_lang) { if(db::get_one("SELECT 1 FROM langs WHERE short='{$ia_lang['short']}'")) { app::err('Masz już język o skrócie '.$ia_lang['short']); return false; } $is_active = isset($ia_lang['is_active']) ? 1 : 0; $id = db::insert('langs', array('name'=>$ia_lang['name'],'short'=>$ia_lang['short'],'is_active'=>$is_active)); if(!$id) { app::err('Błąd bazy danych'); return false; } if(isset($ia_lang['is_default'])) { db::update('langs','1=1',array('is_default'=>0)); db::update('langs','id_langs='.$id,array('is_default'=>1)); } db::update('langs','id_langs='.$id,array('langs.order'=>$id)); db::query("ALTER TABLE sites ADD COLUMN title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE sites ADD COLUMN text_{$ia_lang['short']} TEXT NULL AFTER text"); db::query("ALTER TABLE sites ADD COLUMN appetizer_{$ia_lang['short']} TEXT NULL AFTER appetizer"); db::query("ALTER TABLE sites ADD COLUMN sludge_{$ia_lang['short']} TEXT NULL AFTER sludge"); db::query("ALTER TABLE sites ADD COLUMN seo_title_{$ia_lang['short']} TEXT NULL AFTER seo_title"); db::query("ALTER TABLE sites ADD COLUMN seo_keywords_{$ia_lang['short']} TEXT NULL AFTER seo_keywords"); db::query("ALTER TABLE sites ADD COLUMN seo_description_{$ia_lang['short']} TEXT NULL AFTER seo_description"); db::query("ALTER TABLE galleries ADD COLUMN title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE galleries ADD COLUMN sludge_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE galleries ADD COLUMN seo_title_{$ia_lang['short']} TEXT NULL AFTER seo_title"); db::query("ALTER TABLE galleries ADD COLUMN seo_keywords_{$ia_lang['short']} TEXT NULL AFTER seo_keywords"); db::query("ALTER TABLE galleries ADD COLUMN seo_description_{$ia_lang['short']} TEXT NULL AFTER seo_description"); db::query("ALTER TABLE article_categories ADD COLUMN title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE article_categories ADD COLUMN sludge_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE article_categories ADD COLUMN seo_title_{$ia_lang['short']} TEXT NULL AFTER seo_title"); db::query("ALTER TABLE article_categories ADD COLUMN seo_keywords_{$ia_lang['short']} TEXT NULL AFTER seo_keywords"); db::query("ALTER TABLE article_categories ADD COLUMN seo_description_{$ia_lang['short']} TEXT NULL AFTER seo_description"); db::query("ALTER TABLE slides ADD COLUMN title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE slides ADD COLUMN link_{$ia_lang['short']} TEXT NULL AFTER link"); db::query("ALTER TABLE lang_texts ADD COLUMN value_{$ia_lang['short']} TEXT NULL AFTER value_PL"); db::query("ALTER TABLE menu ADD COLUMN name_{$ia_lang['short']} TEXT NULL AFTER name"); app::ok('Dodano nowy język'); return $id; } public static function edit_langs($ia_langs,$id_default) { foreach($ia_langs as $id_langs=>$ia_lang) { if(db::get_one("SELECT 1 FROM langs WHERE short='{$ia_lang['short']}' AND id_langs<>$id_langs")) { app::err('Masz już język o skrócie '.$ia_lang['short']); return false; } db::deb(); $old_short = db::get_one("SELECT short FROM langs WHERE id_langs=$id_langs"); $is_active = isset($ia_lang['is_active']) ? 1 : 0; db::update('langs', "id_langs=$id_langs",array('name'=>$ia_lang['name'],'short'=>$ia_lang['short'],'is_active'=>$is_active)); db::update('langs','1=1',array('is_default'=>0)); db::update('langs','id_langs='.$id_default,array('is_default'=>1)); if($old_short!=$ia_lang['short']) { db::query("ALTER TABLE sites CHANGE title_{$old_short} title_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE text_{$old_short} text_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE appetizer_{$old_short} appetizer_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE sludge_{$old_short} sludge_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE seo_title_{$old_short} seo_title_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE seo_keywords_{$old_short} seo_keywords_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE sites CHANGE seo_description_{$old_short} seo_description_{$ia_lang['short']} TEXT NULL"); db::query("ALTER TABLE galleries CHANGE title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE galleries CHANGE sludge_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE galleries CHANGE seo_title_{$ia_lang['short']} TEXT NULL AFTER seo_title"); db::query("ALTER TABLE galleries CHANGE seo_keywords_{$ia_lang['short']} TEXT NULL AFTER seo_keywords"); db::query("ALTER TABLE galleries CHANGE seo_description_{$ia_lang['short']} TEXT NULL AFTER seo_description"); db::query("ALTER TABLE article_categories CHANGE title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE article_categories CHANGE sludge_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE article_categories CHANGE seo_title_{$ia_lang['short']} TEXT NULL AFTER seo_title"); db::query("ALTER TABLE article_categories CHANGE seo_keywords_{$ia_lang['short']} TEXT NULL AFTER seo_keywords"); db::query("ALTER TABLE article_categories CHANGE seo_description_{$ia_lang['short']} TEXT NULL AFTER seo_description"); db::query("ALTER TABLE slides CHANGE title_{$ia_lang['short']} TEXT NULL AFTER title"); db::query("ALTER TABLE slides CHANGE link_{$ia_lang['short']} TEXT NULL AFTER link"); db::query("ALTER TABLE menu CHANGE name_{$old_short} name_{$ia_lang['short']} TEXT NULL AFTER name"); db::query("ALTER TABLE lang_texts CHANGE value_{$old_short} value_{$ia_lang['short']} TEXT NULL"); } } app::ok('Języki zostały zapisane'); return true; } public static function delete_lang($id_lang) { $short = db::get_one("SELECT short FROM langs WHERE id_langs=".$id_lang); db::query("DELETE FROM langs WHERE id_langs=".$id_lang); db::query("ALTER TABLE sites DROP title_{$short}"); db::query("ALTER TABLE sites DROP text_{$short}"); db::query("ALTER TABLE sites DROP appetizer_{$short}"); db::query("ALTER TABLE sites DROP sludge_{$short}"); db::query("ALTER TABLE sites DROP seo_title_{$short}"); db::query("ALTER TABLE sites DROP seo_keywords_{$short}"); db::query("ALTER TABLE sites DROP seo_description_{$short}"); db::query("ALTER TABLE galleries DROP title_{$ia_lang['short']}"); db::query("ALTER TABLE galleries DROP sludge_{$ia_lang['short']}"); db::query("ALTER TABLE galleries DROP seo_title_{$ia_lang['short']}"); db::query("ALTER TABLE galleries DROP seo_keywords_{$ia_lang['short']}"); db::query("ALTER TABLE galleries DROP seo_description_{$ia_lang['short']}"); db::query("ALTER TABLE article_categories DROP title_{$ia_lang['short']}"); db::query("ALTER TABLE article_categories DROP sludge_{$ia_lang['short']}"); db::query("ALTER TABLE article_categories DROP seo_title_{$ia_lang['short']}"); db::query("ALTER TABLE article_categories DROP seo_keywords_{$ia_lang['short']}"); db::query("ALTER TABLE article_categories DROP seo_description_{$ia_lang['short']}"); db::query("ALTER TABLE slides DROP title_{$ia_lang['short']}"); db::query("ALTER TABLE slides DROP link_{$ia_lang['short']}"); db::query("ALTER TABLE menu DROP name_{$short}"); db::query("ALTER TABLE lang_texts DROP value_{$short}"); } public static function get($name,$is_return=0) { if(isset($_SESSION['lang_texts'][$name])) { if($is_return===0) echo $_SESSION['lang_texts'][$name]; else return $_SESSION['lang_texts'][$name]; } else { if($is_return===0) echo 'xxx'; else return 'xxx'; } } public static function get_lang() { if(isset($_SESSION['lang'])) return $_SESSION['lang']; else return self::get_default_lang(); } } ?>
true
88ad1fe13e66a70a7422cfd7be7518d8bc0734a8
PHP
pitchpro/pitchpro_plugin
/lib/helpers.php
UTF-8
2,671
3.09375
3
[]
no_license
<?php /** * These functions should exist in WordPress or PHP already * but they don't :( */ if( !function_exists( 'is_post_type' ) ){ function is_post_type( $type ){ global $wp_query; if( ( is_array($type) && in_array( get_post_type( $wp_query->post->ID ), $type ) ) || $type == get_post_type( $wp_query->post->ID ) ) return true; return false; } } if( !function_exists( 'get_last_path_segment' ) ){ function get_last_path_segment($url) { $path = parse_url($url, PHP_URL_PATH); // to get the path from a whole URL $pathTrimmed = trim($path, '/'); // normalise with no leading or trailing slash $pathTokens = explode('/', $pathTrimmed); // get segments delimited by a slash if (substr($path, -1) !== '/') { array_pop($pathTokens); } return end($pathTokens); // get the last segment } } if( !function_exists( 'is_valid_guid' ) ){ function is_valid_guid( $guid ){ return !(preg_match('/^\{?[A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12}\}?$/', $guid )); } } /** * Returns a GUIDv4 string * * Uses the best cryptographically secure method * for all supported pltforms with fallback to an older, * less secure version. * * @param bool $trim * @return string */ if( !function_exists( 'create_unique_GUIDv4' ) ){ function create_unique_GUIDv4 ($trim = true) { // Windows if (function_exists('com_create_guid') === true) { if ($trim === true) return trim(com_create_guid(), '{}'); else return com_create_guid(); } // OSX/Linux if (function_exists('openssl_random_pseudo_bytes') === true) { $data = openssl_random_pseudo_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } // Fallback (PHP 4.2+) mt_srand((double)microtime() * 10000); $charid = strtolower(md5(uniqid(rand(), true))); $hyphen = chr(45); // "-" $lbrace = $trim ? "" : chr(123); // "{" $rbrace = $trim ? "" : chr(125); // "}" $guidv4 = $lbrace. substr($charid, 0, 8).$hyphen. substr($charid, 8, 4).$hyphen. substr($charid, 12, 4).$hyphen. substr($charid, 16, 4).$hyphen. substr($charid, 20, 12). $rbrace; return $guidv4; } }
true
63aa867cf09108fed5d5540df173a83b64da21e5
PHP
klonekreyesm/Codeup_Exercises
/FizzBuzz.php
UTF-8
779
4.125
4
[]
no_license
<?php //set a start variable $number; while this condition is met; incrementor - increment number each loop for ($number=0; $number <= 100; $number++){ if($number % 3 == 0 && $a % 5 == 0){ echo "$number FizzBuzz".PHP_EOL; } // if the divisble of 3 is remainder 0 print FIZZLE if ($number % 3 == 0){ echo "FIZZle".PHP_EOL; } //elseif the divisible of 5 is remainder 0 print Buzz-izzle elseif ($number % 5 == 0){ echo "Buzz-izzle";.PHP_EOL; } //if it is neither, just print the number else { echo "$number".PHP_EOL; } } ?>
true
ead160bb44d8cf195ffc3f27a864a7a87b191a3f
PHP
nurasma1604/reruncloud
/movie_search.php
UTF-8
1,375
2.859375
3
[]
no_license
<?php include("dataconnection.php"); ?> <html> <head><title>Search Movie</title> <link href="design.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="wrapper"> <div id="left"> <?php include("menu.php"); ?> </div> <div id="right"> <h1>Search for a Movie</h1> <form name="addfrm" method="post" action=""> <p><label>Title:</label><input type="text" name="mov_title" size="80"> <p><input type="submit" name="searchbtn" value="SEARCH MOVIE"> </form> <?php if (isset($_POST["searchbtn"])) { $mtitle = $_POST["mov_title"]; $result = mysqli_query($conn, "select * from movie where movie_title like '%$mtitle%'"); $count = mysqli_num_rows($result); if ($count<1) echo "Sorry, no records were found for $mtitle<br><br>"; else { ?> <h2>Results:</h2> <table border="1"> <tr> <th>Movie ID</th> <th>Movie Title</th> <th>Movie Ticket Price</th> </tr> <?php while($row = mysqli_fetch_assoc($result)) { ?> <tr> <td><?php echo $row["movie_id"]; ?></td> <td><?php echo $row["movie_title"]; ?></td> <td><?php echo $row["movie_ticket_price"]; ?></td> </tr> <?php } ?> </table> <p> <?php echo $count; ?> records found</p> <?php } } ?> </div> </div> </body> </html>
true
3c40b8a53a50fc35cda4e349b95795cc7efa2adb
PHP
wahyu-pro/phptask5
/004.php
UTF-8
1,899
3
3
[]
no_license
<?php require_once 'dompdf/autoload.inc.php'; require_once 'simple_html_dom.php'; use Dompdf\Dompdf; class ComingSoon { function __construct() { $this->getInfo(); } function getInfo() { $html = file_get_html("http://www.cgv.id/en/loader/home_movie_list"); $mainUrl = "https://www.cgv.id"; $html = $html->find('a'); $url = []; for ($i = 0; $i < count($html); $i++) { $getUrl = str_replace('\\', '', $html[$i]->attr['href']); // untuk mengganti backslash menjadi kosong $getUrl = str_replace('"', '', $getUrl); // untuk mengganti "" menajadi kosong $newUrl = $mainUrl . $getUrl; array_push($url, $newUrl); } $info = []; $groupInfo = []; for ($i = 0; $i < count($url); $i++) { $first = file_get_html($url[$i]); // membuat key dan element yang akan di masukan ke dalam variabel $group $info['title'] = $first->find('div.movie-info-title', 0)->plaintext; $info['info'] = $first->find('div.movie-add-info', 0)->innertext; $info['synopsis'] = $first->find('div.movie-synopsis', 0)->innertext; // $info['info'] = $first->find('div.synopsis-section', 0)->innertext; array_push($groupInfo, $info); } // save to pdf $this->save_to_pdf($groupInfo); } function save_to_pdf($info) { $infoFilm = "<body style='font-family:Helvetica'>"; $no = 1; foreach ($info as $value) { $infoFilm .= "<hr>"; $infoFilm .= $no.") ".$value['title'] . "<br>"; $infoFilm .= "<hr>"; $infoFilm .= $value['info'] . "<br>"; $infoFilm .= "<h4>Synopsis</h4>"; $infoFilm .= $value['synopsis'] . "<br>"; $infoFilm .= "<hr>"; $no++; } $infoFilm .= "</body>"; $pdf = new Dompdf(); $pdf->load_html($infoFilm); $pdf->setPaper('A4', 'portrait'); $pdf->render(); $printOutput = $pdf->output(); if (file_put_contents('infoFilm.pdf', $printOutput)) { echo "Data berhasil disimpan ke dalam PDF"; } } } new ComingSoon();
true
4d8b9fcb277ee89d43bbeea323e11a1b30a01bb8
PHP
AmenokoEnginner/Like_btn
/like_btn_sample/Like.php
UTF-8
6,333
3.03125
3
[]
no_license
<?php namespace MyApp; class Like { private $db; public function __construct() { $this->connectDB(); $this->createToken(); } private function connectDB() { try { $this->db = new \PDO(PDO_DSN, DB_USERNAME, DB_PASSWORD); $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } catch (\PDOException $e) { throw new \Exception('データベースの接続に失敗しました'); } } private function createToken() { if (!isset($_SESSION['token'])) { $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(16)); } } private function validateToken() { if ( !isset($_SESSION['token']) || !isset($_POST['token']) || $_SESSION['token'] !== $_POST['token'] ) { throw new \Exception('invalid token!'); } } public function validateName($name) { // リロード時はエラーを出さない if (!isset($name)) { return false; } // 名前が入力されていなかったらエラー if (empty($name)) { return 'blank'; } // 名前が3文字以上でなかったらエラー if (mb_strlen($name) < 3) { return 'length'; } if ($_SERVER['REQUEST_URI'] == '/register.php') { $sql = 'SELECT * FROM users'; $users = $this->db->query($sql); // 同じ名前が見つかったらエラー while ($user = $users->fetch()) { if ($user['name'] == $name) { return 'same'; } } } if ($_SERVER['REQUEST_URI'] == '/register.php') { // 登録処理 $this->register($name); } else { // ログイン処理 $this->login($name); } } private function register($name) { // usersテーブルにデータを追加 $sql = 'INSERT INTO users SET name=?'; $statement = $this->db->prepare($sql); $statement->execute([$name]); header('Location: http://' . $_SERVER['HTTP_HOST'] . '/login.php'); exit; } private function login($name) { $sql = 'SELECT * FROM users'; $users = $this->db->query($sql); foreach ($users->fetchAll() as $user) { // usersテーブルにフォームから入力した名前があるか if ($user['name'] == $name) { // ログイン情報を保存 $this->createCookieAndSession($user['id'], $name); header('Location: http://' . $_SERVER['HTTP_HOST'] . '/index.php'); exit; } } // error message(its username not founded) header('Location: http://' . $_SERVER['HTTP_HOST'] . '/login.php'); exit; } public function verify() { $this->checkLogout(); $this->checkLogin(); } private function checkLogin() { if (!empty($_COOKIE['user_id']) && !empty($_COOKIE['name'])) { // ログイン済みの時の処理 // ログインを記憶する $this->createCookieAndSession($_COOKIE['user_id'], $_COOKIE['name']); if ($_SERVER['REQUEST_URI'] != '/index.php') { header('Location: http://' . $_SERVER['HTTP_HOST'] . '/index.php'); exit; } } else { // 未ログインの時の処理 if ( $_SERVER['REQUEST_URI'] != '/register.php' && $_SERVER['REQUEST_URI'] != '/login.php' ) { header('Location: http://' . $_SERVER['HTTP_HOST'] . '/login.php'); exit; } } } private function checkLogout() { if ($_GET['action'] == 'logout') { setcookie('user_id', ' ', time() - 60); setcookie('name', ' ', time() - 60); setcookie('post_id', ' ', time() - 60); unset($_COOKIE); $_SESSION = []; session_destroy(); } } private function createCookieAndSession($id, $name) { setcookie('user_id', $id, time() + 60 * 10); setcookie('name', $name, time() + 60 * 10); $sql = 'SELECT * FROM posts ORDER BY id ASC LIMIT 1'; $posts = $this->db->query($sql); $post = $posts->fetch(); setcookie('post_id', $post['id'], time() + 60 * 10); $_SESSION['user_id'] = $_COOKIE['user_id']; $_SESSION['post_id'] = $_COOKIE['post_id']; $sql = 'SELECT * FROM likes WHERE user_id=? AND post_id=?'; $like = $this->db->prepare($sql); $like->bindParam(1, $_SESSION['user_id'], \PDO::PARAM_INT); $like->bindParam(2, $_SESSION['post_id'], \PDO::PARAM_INT); $like->execute(); if ($like->rowCount() > 0) { $_SESSION['btn'] = 'on'; } else { $_SESSION['btn'] = 'off'; } } public function readLikesCount() { $sql = 'SELECT * FROM posts ORDER BY id ASC LIMIT 1'; $posts = $this->db->query($sql); $post = $posts->fetch(); return $post['likes_count']; } public function updateLikesCount() { $this->validateToken(); // likesテーブルからデータを取り出す $sql = 'SELECT * FROM likes WHERE user_id=? AND post_id=?'; $like = $this->db->prepare($sql); $like->bindParam(1, $_SESSION['user_id'], \PDO::PARAM_INT); $like->bindParam(2, $_SESSION['post_id'], \PDO::PARAM_INT); $like->execute(); // postsテーブルから1つのデータのlikes_countを取り出す $sql = 'SELECT * FROM posts ORDER BY id ASC LIMIT 1'; $posts = $this->db->query($sql); $post = $posts->fetch(); $likes_count = $post['likes_count']; // likesテーブル内のデータを更新or削除 // postsテーブル内のデータのlikes_countを調整 if ($like->rowCount() > 0) { $sql = 'DELETE FROM likes WHERE user_id=? AND post_id=?'; $stmt = $this->db->prepare($sql); $stmt->bindParam(1, $_SESSION['user_id'], \PDO::PARAM_INT); $stmt->bindParam(2, $_SESSION['post_id'], \PDO::PARAM_INT); $stmt->execute(); $likes_count--; } else { $sql = 'INSERT INTO likes (user_id, post_id) VALUES(?, ?)'; $stmt = $this->db->prepare($sql); $stmt->bindParam(1, $_SESSION['user_id'], \PDO::PARAM_INT); $stmt->bindParam(2, $_SESSION['post_id'], \PDO::PARAM_INT); $stmt->execute(); $likes_count++; } // postsテーブルの1つのデータのlikes_countを更新 $sql = 'UPDATE posts SET likes_count=? WHERE id=?'; $stmt = $this->db->prepare($sql); $stmt->bindParam(1, $likes_count, \PDO::PARAM_INT); $stmt->bindParam(2, $_SESSION['post_id'], \PDO::PARAM_INT); $stmt->execute(); } }
true
4fa8dcd4ed549c43d928ae387aeeb9115d14ee93
PHP
RamilYumaev/aa_dev
/modules/dictionary/models/RegisterCompetitionList.php
UTF-8
4,289
2.546875
3
[]
permissive
<?php namespace modules\dictionary\models; use dictionary\models\DictCompetitiveGroup; use dictionary\models\DictSpeciality; use dictionary\models\Faculty; use yii\db\ActiveRecord; /** * This is the model class for table "{{%register_competition_list}}". * * @property integer $id * @property integer $ais_cg_id * @property integer $se_id * @property integer $status * @property integer $type_update * @property integer $number_update * @property integer $speciality_id; * @property integer $faculty_id; * @property string $date * @property string $time * @property string $error_message **/ class RegisterCompetitionList extends ActiveRecord { const TYPE_AUTO = 1; const TYPE_HANDLE = 2; const STATUS_QUEUE = 0; const STATUS_SEND = 1; const STATUS_SUCCESS = 2; const STATUS_ERROR = 3; const STATUS_NOT = 4; public function data($aisCgId, $typeUpdate, $numberUpdate, $specialityId, $facultyId, $seId) { $this->ais_cg_id = $aisCgId; $this->type_update = $typeUpdate; $this->speciality_id = $specialityId; $this->faculty_id = $facultyId; $this->se_id = $seId; $this->number_update = $numberUpdate; $this->date = date("Y-m-d"); $this->time = date("H:i:s"); } public function setStatus($status) { $this->status = $status; } public function listType() { return [self::TYPE_AUTO => 'auto', self::TYPE_HANDLE => 'handle']; } public function getTypeName() { return $this->listType()[$this->type_update]; } public function listStatus() { return [ self::STATUS_QUEUE => 'отправлено в очередь', self::STATUS_SEND => 'отправлено в АИС ВУЗ', self::STATUS_SUCCESS => 'успешно обновлен', self::STATUS_ERROR => 'ошибка', self::STATUS_NOT => 'нет списка', ]; } public function getStatusName() { return $this->listStatus()[$this->status]; } public function isStatusError() { return $this->status == self::STATUS_ERROR; } public function isStatusSend() { return $this->status == self::STATUS_SEND; } public function setErrorMessage($message) { $this->error_message = $message; } public static function tableName() { return "{{%register_competition_list}}"; } public function getSettingCompetitionList() { return $this->hasOne(SettingCompetitionList::class,['se_id'=> 'se_id']); } public function getSettingEntrant() { return $this->hasOne(SettingEntrant::class,['id'=> 'se_id']); } public function getCompetitionList() { return $this->hasMany(CompetitionList::class,['rcl_id'=> 'id']); } public function getCompetitionListNo() { return $this->getCompetitionList()->andWhere(['type'=> 'list']); } public function getCompetitionListBvi() { return $this->getCompetitionList()->andWhere(['type'=> 'list_bvi']); } public function getCg() { return $this->hasOne(DictCompetitiveGroup::class, ['ais_id' => 'ais_cg_id'])->currentAutoYear(); } public function getCgFacultyAndSpeciality() { return $this->hasOne(DictCompetitiveGroup::class, ['speciality_id' => 'speciality_id', 'faculty_id' => 'faculty_id'])->andWhere(['financing_type_id'=>2])->currentAutoYear(); } public function getFaculty() { return $this->hasOne(Faculty::class, ['id' => 'faculty_id']); } public function getSpeciality() { return $this->hasOne(DictSpeciality::class, ['id' => 'speciality_id']); } public function attributeLabels() { return [ 'ais_cg_id' => "АИС КГ ИД", 'status' => "Статус", 'type_update' => "Тип обновления", 'number_update' => "Номер обновления", 'date' => "Дата обновления", 'time' => "Время обновления", 'error_message' => 'Сообщение об ошибке', 'se_id' => "ИД настройки приема" ]; } }
true
e32df488ab6ad0a84c78dd6b1ad503415c0986f1
PHP
phoice/phlexa
/test/Response/OutputSpeech/PlainTextTest.php
UTF-8
1,260
2.640625
3
[]
no_license
<?php /** * Build voice applications for Amazon Alexa with phlexa and PHP * * @author Ralf Eggert <ralf@travello.audio> * @license http://opensource.org/licenses/MIT The MIT License (MIT) * @link https://github.com/phoice/phlexa * @link https://www.phoice.tech/ * @link https://www.travello.audio/ */ declare(strict_types=1); namespace PhlexaTest\Response\OutputSpeech; use Phlexa\Response\OutputSpeech\PlainText; use PHPUnit\Framework\TestCase; /** * Class PlainTextTest * * @package PhlexaTest\Response\OutputSpeech */ class PlainTextTest extends TestCase { /** * */ public function testInstantiationWithLongValues() { $outputSpeech = new PlainText( str_pad('text', 7000, 'text') ); $expected = [ 'type' => 'PlainText', 'text' => str_pad('text', 6000, 'text'), ]; $this->assertEquals($expected, $outputSpeech->toArray()); } /** * */ public function testInstantiationWithShortValues() { $outputSpeech = new PlainText('text'); $expected = [ 'type' => 'PlainText', 'text' => 'text', ]; $this->assertEquals($expected, $outputSpeech->toArray()); } }
true
899c99fc38a9efe499be834f1d46815eae96b96c
PHP
AASavelyev/test
/application/controllers/controller_admin.php
UTF-8
2,031
2.65625
3
[]
no_license
<?php require_once $_SERVER['DOCUMENT_ROOT'].'/application/models/comment.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/application/repositories/commentRepository.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/application/repositories/adminRepository.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/application/core/controller.php'; class Controller_Admin extends Controller { private $adminRepository; private $commentRepository; public function __construct() { $this->adminRepository = new AdminRepository(); $this->commentRepository = new CommentRepository(); $this->view = new View(); } function action_index() { $username = array_key_exists('username', $_POST) ? htmlspecialchars($_POST['username']) : ""; $password = array_key_exists('password', $_POST) ? htmlspecialchars($_POST['password']) : ""; if ($this->adminRepository->isAuth() || $this->adminRepository->login($username, $password)){ $data = $this->commentRepository->getAll(); $this->view->generate('admin/admin_view.php', 'template_view.php', $data); } else { header("Location: /admin/login"); $this->action_login(); } } function action_login() { $this->view->generate('admin/login_view.php', 'template_view.php'); } function action_approve($id) { $this->commentRepository->approve($id); header("Location: /admin"); $this->action_index(); } function action_unapprove($id) { $this->commentRepository->unapprove($id); header("Location: /admin"); $this->action_index(); } function action_remove($id) { $this->commentRepository->remove($id); header("Location: /admin"); $this->action_index(); } function action_update($id){ $comment = $this->commentRepository->getById($id); $this->view->generate('admin/update_view.php', 'template_view.php', $comment); } }
true
7045a53a62c38ba605c28e058821f2b89c930c88
PHP
Dre90/Web2
/Labs/lab4/solutions/task4/person_class.php
UTF-8
488
3.65625
4
[]
no_license
<?php class Person { //define protected properties protected $name; protected $owned_car; //this construct method only accepts name public function __construct($n){ $this -> name = $n; } //setter methods public function set_name($n) { $this -> name = $n; } public function set_owned_car($c) { $this -> owned_car = $c; } //getter methods public function get_name() { return $this -> name; } public function get_owned_car() { return $this -> owned_car; } } ?>
true
d153b03235e18b5347228068bc09dadf1c06ff93
PHP
homoludens/ffs
/tests/Simplex/Tests/FrameworkTest.php
UTF-8
2,960
2.53125
3
[ "MIT" ]
permissive
<?php // example.com/tests/Simplex/Tests/FrameworkTest.php namespace Simplex\Tests; use PHPUnit\Framework\TestCase; use Simplex\Framework; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\Routing; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Controller\ArgumentResolver; use Symfony\Component\HttpKernel\Controller\ControllerResolver; class FrameworkTest extends TestCase { public function testNotFoundHandling() { $framework = $this->getFrameworkForException(new ResourceNotFoundException()); $response = $framework->handle(new Request()); $this->assertEquals(404, $response->getStatusCode()); } private function getFrameworkForException($exception) { $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); // use getMock() on PHPUnit 5.3 or below // $matcher = $this->getMock(Routing\Matcher\UrlMatcherInterface::class); $matcher ->expects($this->once()) ->method('match') ->will($this->throwException($exception)) ; $matcher ->expects($this->once()) ->method('getContext') ->will($this->returnValue($this->createMock(Routing\RequestContext::class))) ; $controllerResolver = $this->createMock(ControllerResolverInterface::class); $argumentResolver = $this->createMock(ArgumentResolverInterface::class); return new Framework($matcher, $controllerResolver, $argumentResolver); } public function testErrorHandling() { $framework = $this->getFrameworkForException(new \RuntimeException()); $response = $framework->handle(new Request()); $this->assertEquals(500, $response->getStatusCode()); } public function testControllerResponse() { $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); // use getMock() on PHPUnit 5.3 or below // $matcher = $this->getMock(Routing\Matcher\UrlMatcherInterface::class); $matcher ->expects($this->once()) ->method('match') ->will($this->returnValue([ '_route' => 'is_leap_year/{year}', 'year' => '2000', '_controller' => [new LeapYearController(), 'index'] ])) ; $matcher ->expects($this->once()) ->method('getContext') ->will($this->returnValue($this->createMock(Routing\RequestContext::class))) ; $controllerResolver = new ControllerResolver(); $argumentResolver = new ArgumentResolver(); $framework = new Framework($matcher, $controllerResolver, $argumentResolver); $response = $framework->handle(new Request()); $this->assertEquals(200, $response->getStatusCode()); $this->assertStringContainsString('Yep, this is a leap year!', $response->getContent()); } }
true
7dcac345a2e9476193eb8f337ad2d9266b05e925
PHP
saviosvm/app_super_gestao
/database/migrations/2021_09_06_180100_create_clientes_pedidos_produtos.php
UTF-8
1,657
2.53125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateClientesPedidosProdutos extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('clientes', function (Blueprint $table) { $table->id(); $table->string('nome', 50); $table->timestamps(); }); Schema::create('pedidos', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('cliente_id'); // aqui estou indicando que um cliente pode ter muitos pedidos $table->timestamps(); $table->foreign('cliente_id')->references('id')->on('clientes'); }); Schema::create('pedidos_produtos', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('pedido_id'); $table->unsignedBigInteger('produto_id'); $table->timestamps(); // Pedidos N---->N Produtos $table->foreign('pedido_id')->references('id')->on('pedidos'); $table->foreign('produto_id')->references('id')->on('produtos'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::disableForeignKeyConstraints(); // desativva foreign para apagar Schema::dropIfExists('pedidos_produtos'); Schema::dropIfExists('pedidos'); Schema::dropIfExists('clientes'); Schema::enableForeignKeyConstraints(); //habilita elas novamente } }
true
54adb7cc393aabbb5bfdc5aa26eaa4a93d9526b6
PHP
viender/viender
/apps/topic/src/Repositories/TopicsRepository.php
UTF-8
645
2.53125
3
[]
no_license
<?php namespace Viender\Topic\Repositories; use App\User; use Viender\Topic\Models\Topic; use Viender\Follow\Models\Follow; class TopicsRepository extends Repository { public function model() { return 'Viender\Topic\Models\Topic'; } public function userFollowTopic(User $user, Topic $topic) { if($user->followedTopics()->where([ 'followable_id' => $topic->id, ])->exists()) { $user->followedTopics()->detach($topic); return false; } else { $user->followedTopics()->attach($topic); return true; } return false; } }
true
f998606bd1a17e00431ad180f81177fbee1d9024
PHP
ArtemNehoda/pa-parser
/tests/Feature/SpiralShapeFormatterTest.php
UTF-8
907
2.78125
3
[]
no_license
<?php namespace Tests\Feature; use App\Helpers\Formatters\SpiralShapeFormatter; use Tests\TestCase; class SpiralShapeFormatterTest extends TestCase { public function getFormatter() { $formatter = new SpiralShapeFormatter; return $formatter; } public function test_formatting_a_spiral1() { $data = [ "primariga", "secondariga", "terzariga", ]; $result = $this->getFormatter()->format($data); $expected = file_get_contents(base_path('tests/testdata/spiral.txt')); $this->assertTrue($result === $expected); } public function test_formatting_a_spiral_with_one_string() { $data = [ "onlyonestring", ]; $result = $this->getFormatter()->format($data); $expected = "onlyonestring"; $this->assertTrue($result === $expected); } }
true
4604d8db5a79eaa526e7355174a71706beba935e
PHP
3plo/ServicePlatform
/models/active_record/user_active_record/UserActiveRecord.php
UTF-8
2,393
2.703125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: user * Date: 25.01.2018 * Time: 23:04 */ namespace models\active_record\user_active_record; use application\Application; use models\active_record\ActiveRecord; use models\models_exceptions\db_exceptions\DBException; final class UserActiveRecord extends ActiveRecord { /** * @var string */ private $password; /** * @var string */ private $login; /** * @var string */ private $firstname; /** * @var string */ private $lastname; /** * @var string */ private $email; /** * @var ?string */ private $info; /** * @var bool */ private $active; /** * @var string */ private $updated_at; /** * @var int */ private $updated_by; /** * @var array */ protected static $attributes = [ 'id', 'password', 'login', 'firstname', 'lastname', 'email', 'phone', 'info', 'active', 'updated_at', 'updated_by' ]; /** * @var array */ protected static $rules = [ 'id' => ['type' => 'int', 'length' => 10, 'is_null' => 0, 'mutable' => 0, 'unsigned' => 1, 'default' => null], 'password' => ['type' => 'string', 'length' => 25, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'login' => ['type' => 'string', 'length' => 25, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'firstname' => ['type' => 'string', 'length' => 25, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'lastname' => ['type' => 'string', 'length' => 25, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'email' => ['type' => 'string', 'length' => 50, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'phone' => ['type' => 'string', 'length' => 15, 'is_null' => 0, 'mutable' => 1, 'default' => null], 'info' => ['type' => 'text', 'length' => 65535, 'is_null' => 1, 'mutable' => 1, 'default' => null], 'active' => ['type' => 'bool', 'length' => 1, 'is_null' => 0, 'mutable' => 1, 'default' => 1], 'updated_at' => ['type' => 'datetime', 'is_null' => 0, 'mutable' => 0, 'default' => DATETIME], 'updated_by' => ['type' => 'int', 'length' => 11, 'unsigned' => 1, 'is_null' => 0, 'mutable' => 0], ]; }
true
3d31b4847e697c1d811931f212864b30588b1b42
PHP
AlexisAnd/Pizza_Patron_Symfony_3
/src/AppBundle/Controller/Admin/AdminDessertsController.php
UTF-8
3,036
2.515625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Alexis * Date: 24/11/2017 * Time: 14:41 */ namespace AppBundle\Controller\Admin; use AppBundle\Entity\Desserts; use AppBundle\Form\DessertsType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Request; class AdminDessertsController extends Controller { /** * @Route("/desserts", name="app.admin.desserts") * */ public function adminAction() { $doctrine = $this->getDoctrine(); $results = $doctrine->getRepository(Desserts::class)->getResults(); return $this->render('admin/admin_desserts.html.twig', ['results'=>$results]); } /** * @Route("/add_desserts", name="app.admin.add_desserts", defaults={"id" = Null}) * @Route("/add_desserts/update/{id}", name="app.admin.update_desserts") */ public function addModifyDesserts(Request $request, $id) { $doctrine = $this->getDoctrine(); $em = $doctrine->getManager(); $rc = $doctrine->getRepository(desserts::class); // objets nécéssaires à la création du form $entity = $entity = $id ? $rc->find($id) : new desserts(); $entityType = DessertsType::class; //création d'un formulaire $form = $this->createForm($entityType, $entity); //récupération de la saisie précédente contenue dans la requête. // Si erreur sur le formulaire, il recharge le contenu des champs. $form->handleRequest($request); // formulaire valide if($form->isSubmitted() && $form->isValid()) { // recupération de l'entité remplie avec la saisie $data = $form->getData(); // exit(dump($data)); // persistance de l'objet en base de données: ca met les requetes à la queue // en attente d'exectution $em->persist($data); // execution des requetes $em->flush(); //message de confirmation $message = $id ? 'Le dessert à été modifié' : 'Le nouveau dessert a été ajouté au catalogue'; // message flash: clé valeur $this->addFlash('notice', $message); return $this->redirectToRoute('app.admin.desserts', []); } return $this->render('admin/add_desserts.html.twig', ['form'=>$form->createView()]); } /** * @Route("/deletedessert/{id}", name="app.admin.delete_desserts") */ public function deleteDesserts($id) { $doctrine = $this->getDoctrine(); $entity = $doctrine->getRepository(Desserts::class)->find($id); $em = $this->getDoctrine()->getManager(); $em->remove($entity); $em->flush(); //message de confirmation $message = 'Le dessert à été supprimé.'; $this->addFlash('notice', $message); //redirection return $this->redirectToRoute('app.admin.desserts'); } }
true
5d095bc1608994dc02b60dd437780472f4139d29
PHP
ahmad-sa3d/json-response-builder
/tests/unit/TestJsonResponseBuilder.php
UTF-8
5,836
2.546875
3
[ "MIT" ]
permissive
<?php /** * Test Cases for JsonResponseBuilder * * @author Ahmed Saad <a7mad.sa3d.2014@gmail.com> * @package Api Json Response Builder * @license MIT * @version 1.0.0 First Version */ use Orchestra\Testbench\TestCase; use Saad\JsonResponseBuilder\JsonResponseBuilder; use Test\Unit\BuilderTestSetup; /** * @coversDefaultClass Saad\JsonResponseBuilder\JsonResponseBuilder */ class TestJsonResponseBuilder extends TestCase { use BuilderTestSetup; /** @test */ public function it_can_add_meta() { $this->builder->addMeta('name', 'Ahmed Saad'); $this->assertArrayHasKey('name', $this->getMeta()); $this->assertEquals('Ahmed Saad', $this->getMeta()['name']); } /** * @test */ public function it_can_merge_meta_with_correct_value() { $this->builder->addMeta('name', 'Ahmed Saad'); $this->builder->mergeMeta([ 'name' => 'Another Ahmed Saad', 'age' => 29 ]); $this->assertEquals('Another Ahmed Saad', $this->getMeta()['name']); $this->assertArrayHasKey('age', $this->getMeta()); } /** @test */ public function it_can_add_data() { $this->builder->addData('name', 'Ahmed Saad'); $this->assertArrayHasKey('name', $this->getData()); $this->assertEquals('Ahmed Saad', $this->getData()['name']); } /** @test */ public function it_can_merge_data_with_correct_value() { $this->builder->addData('name', 'Ahmed Saad'); $this->builder->mergeData([ 'name' => 'Another Ahmed Saad', 'age' => 29 ]); $this->assertEquals('Another Ahmed Saad', $this->getData()['name']); $this->assertArrayHasKey('age', $this->getData()); } /** @test */ public function it_can_merge_data_contains_meta_correctly() { $this->builder->mergeData([ 'name' => 'Another Ahmed Saad', 'age' => 29, 'meta' => [ 'name' => 'meta name', ] ]); $this->assertCount(2, $this->getData()); $this->assertArrayHasKey('name', $this->getMeta()); } /** @test */ public function it_can_add_header() { $this->builder->addHeader('Content-Type', 'application/json'); $this->assertArrayHasKey('Content-Type', $this->getHeaders()); $this->assertEquals('application/json', $this->getHeaders()['Content-Type']); } /** @test */ public function it_can_set_status_code() { $this->builder->setStatusCode(401); $this->assertEquals(401, $this->getStatusCode()); } /** @test */ public function it_can_set_success_status() { $this->builder->success(); $this->assertEquals(true, $this->isSuccess()); } /** @test */ public function it_can_set_error_status() { $this->builder->error(); $this->assertEquals(false, $this->isSuccess()); $this->assertCount(2, $this->getError()); } /** @test */ public function it_can_set_success_status_with_message() { $this->builder->success('Success!'); $this->assertEquals(true, $this->isSuccess()); $this->assertEquals('Success!', $this->getMessage()); } /** @test */ public function it_can_set_error_status_with_message_and_error_code() { $this->builder->error('Fails!', 300); $error = $this->getError(); $this->assertEquals('Fails!', $error['message']); $this->assertEquals('Fails!', $this->getMessage()); $this->assertEquals(300, $error['code']); } /** @test */ public function it_can_get_response_object() { $this->assertEquals('Illuminate\Http\JsonResponse', get_class($this->builder->getResponse())); } /** @test */ public function it_can_get_response_with_setting_status_code() { $this->builder->getResponse(301); $this->assertEquals(301, $this->getStatusCode()); } /** @test */ public function it_can_get_response_with_errors_only_if_exists() { $this->builder->error(); $this->builder->getResponse(); $this->assertArrayHasKey('error', $this->getResponseArray()); } /** @test */ public function it_throws_errors_on_getting_response_with_invalid_status_code() { $this->expectException('InvalidArgumentException'); $this->builder->getResponse(5064); } /** @test */ public function it_can_set_response_message_explicity() { $this->builder->error('error message') ->setMessage('iam a message'); $this->assertEquals('iam a message', $this->getMessage()); } /** @test */ public function it_can_add_keys_to_error_array() { $this->builder->error('error message') ->addError('key', 'val'); $this->assertArrayHasKey('key', $this->getError()); $this->assertEquals('val', $this->getError()['key']); } /** @test */ public function it_through_exception_when_trying_to_add_error_before_calling_error_method() { $this->expectException('BadMethodCallException'); $this->builder->addError('key', 'val'); } /** @test */ public function it_removes_error_array_if_status_become_success_after_error() { $this->builder->error('My Error!', 400) ->success('My Success') ->getResponse(); $this->assertArrayNotHasKey('error', $this->getResponseArray()); } /** @test */ public function it_can_enable_strict_mode() { $this->builder->strictMode(true) ->getResponse(); $this->assertTrue($this->getStrictMode()); } /** @test */ public function it_can_disable_strict_mode() { $this->builder->strictMode(false) ->getResponse(); $this->assertFalse($this->getStrictMode()); } /** @test */ public function it_sets_strict_mode_by_default() { $this->builder->getResponse(); $this->assertTrue($this->getStrictMode()); } /** @test */ public function it_return_meta_and_data_if_are_empty_as_empty_array_on_strict_mode_off() { $this->builder->strictMode(false)->getResponse(); $this->assertEquals([], $this->getMeta()); $this->assertEquals([], $this->getData()); } /** @test */ public function it_can_add_data_contains_meta_and_merge_meta_correctly() { $this->builder->addData('key', [ 'name' => 'Another Ahmed Saad', 'age' => 29, 'meta' => [ 'name' => 'meta name', ] ], true); $this->assertArrayHasKey('key', $this->getData()); $this->assertArrayHasKey('name', $this->getMeta()); } }
true
0d20f7f22f426acbf3140f471a3d86aef9729b75
PHP
smaignan/Prono
/View/Page.php
UTF-8
369
2.9375
3
[]
no_license
<?php /* * fichier : Page.php * version : 1.0 * auteur : Sylvain * date : 11 janv. 08 * * description : * modification : auteur date modification */ abstract class Page { var $s_Contenu = ""; function __construct() { $s_Contenu = "sss"; } public function Affiche() { echo "ddd : ".$s_Contenu."<br>"; } } ?>
true
8b5022be4e76fb81df41e045e87ecfcedbe03383
PHP
alexbelij/yandex-ad-generator
/models/AdTemplateCategory.php
UTF-8
1,244
2.5625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "ad_template_category". * * @property integer $ad_template_id * @property integer $category_id * * @property AdTemplate $adTemplate * @property ExternalCategory $category */ class AdTemplateCategory extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'ad_template_category'; } /** * @inheritdoc */ public function rules() { return [ [['ad_template_id', 'category_id'], 'required'], [['ad_template_id', 'category_id'], 'integer'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'ad_template_id' => 'Ad Template ID', 'category_id' => 'Category ID', ]; } /** * @return \yii\db\ActiveQuery */ public function getAdTemplate() { return $this->hasOne(AdTemplate::className(), ['id' => 'ad_template_id']); } /** * @return \yii\db\ActiveQuery */ public function getCategory() { return $this->hasOne(ExternalCategory::className(), ['id' => 'category_id']); } }
true
b2488430a5a5532cccc94eaa0ae8641307003e93
PHP
filbertkm/WikiClient
/src/WikiClient/MediaWiki/WikiFactory.php
UTF-8
437
2.859375
3
[]
no_license
<?php namespace WikiClient\MediaWiki; use Exception; class WikiFactory { private $wikis; public function __construct( array $wikis ) { $this->wikis = $wikis; } public function newWiki( $siteId ) { if ( !array_key_exists( $siteId, $this->wikis ) ) { throw new Exception( "Site $siteId not found in config." ); } $config = $this->wikis[$siteId]; $wiki = new Wiki( $siteId, $config['api'] ); return $wiki; } }
true
180456abf0075790bd297fff58afdd34bbe80aa2
PHP
gabrielvsf/cursolaravel
/controle-series/app/Services/RemovedorDeAnime.php
UTF-8
551
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Services; use App\Anime; use App\Temporada; use App\Episodio; class RemovedorDeAnime { public function removerAnime(int $animeId):string { $anime=Anime::find($animeId); $nomeAnime = $anime->nome; $anime->temporadas->each(function (Temporada $temporada){ $temporada->episodios()->each(function (Episodio $episodio) { $episodio->delete(); }); $temporada->delete(); }); $anime->delete(); return $nomeAnime; } }
true
7b1e398432c54e6cebbf853cd866d19d2a57bb71
PHP
starme/elasticsearch
/src/Query/Grammars/Warp.php
UTF-8
2,305
2.9375
3
[ "MIT" ]
permissive
<?php namespace Starme\Elasticsearch\Query\Grammars; trait Warp { protected $tablePrefix; /** * Convert an array of column names into a delimited string. * * @param array $columns * @param bool $build_script * @return array */ public function columnize(array $columns, $build_script=true): array { $id = $columns['id'] ?? ""; if ( ! $build_script) { $body['script'] = $this->compileScript($columns); } else{ $body = array_map([$this, 'wrap'], $columns); } return compact('id', 'body'); } /** * Wrap a table in keyword identifiers. * * @param string $table * @return string */ public function wrapTable(string $table): string { return $this->wrap($this->tablePrefix.$table); } /** * Wrap a type in keyword identifiers. * * @param string|null $type * @return string */ public function wrapType(?string $type): ?string { return $this->wrap($type); } /** * Wrap a value in keyword identifiers. * * @param mixed $value * @return mixed */ public function wrap($value, $defaultAlias = '') { if (stripos($value, ' as ') !== false) { return $this->wrapAliasedValue($value); } if ($defaultAlias) { return [$value, $defaultAlias]; } return $value; } /** * Wrap a value that has an alias. * * @param string $value * @return array */ protected function wrapAliasedValue(string $value): array { return preg_split('/\s+as\s+/i', $value); } /** * Get the format for database stored dates. * * @return string */ public function getDateFormat(): string { return 'Y-m-d H:i:s'; } /** * Get the grammar's table prefix. * * @return string */ public function getTablePrefix(): string { return $this->tablePrefix; } /** * Set the grammar's table prefix. * * @param string $prefix * @return self */ public function setTablePrefix(string $prefix) { $this->tablePrefix = $prefix; return $this; } }
true
5ed7637a0242b50aab2f49912f2feca4bcf125a0
PHP
flexiodata/flexio-web-app
/application/services/Vfs.php
UTF-8
14,156
2.71875
3
[ "MIT" ]
permissive
<?php /** * * Copyright (c) 2013, Flex Research LLC. All rights reserved. * * Project: Flex.io App * Author: Benjamin I. Williams * Created: 2017-10-04 * * @package flexio * @subpackage Services */ declare(strict_types=1); namespace Flexio\Services; class Vfs implements \Flexio\IFace\IFileSystem { private $owner_eid = ''; // the user to use when evaluating vfs paths private $process_context_service = null; private $store_service = null; private $process = null; private $root_connection_identifier = null; // if set, this forces the vfs to operate only on one connection type public function __construct(string $owner_eid) { $this->owner_eid = $owner_eid; } public function setProcess(\Flexio\IFace\IProcess $process) : void { $this->process = $process; $this->process_context_service = new \Flexio\Services\ProcessContext($process); } public function setRootConnection($connection_identifier) { $this->root_connection_identifier = $connection_identifier; } public function getOwner() : string { return $this->owner_eid; } //////////////////////////////////////////////////////////// // IFileSystem interface //////////////////////////////////////////////////////////// public function getFlags() : int { return 0; } public function list(string $path = '', array $options = []) : array { $results = []; $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); $service_list = $service->list($rpath); $results = array(); if ($service_list === false) return $results; foreach ($service_list as $entry) { if ($this->root_connection_identifier === null) { $full_path = $connection_identifier . ':/' . ltrim($entry['path'],'/'); } else { $full_path = $entry['path']; if (substr($full_path, 0, 1) !== '/') $full_path = '/' . $full_path; } $item = array( 'id' => $entry['id'] ?? sha1($full_path), 'name' => $entry['name'], 'path' => $entry['path'], 'full_path' => $full_path, 'size' => $entry['size'], 'modified' => $entry['modified'], 'hash' => $entry['hash'] ?? '', // TODO: remove ?? when all services have hash implemented 'type' => $entry['type'] ); if ($this->root_connection_identifier === null) { // $item['connection'] = $connection_identifier; } $results[] = $item; } return $results; } public function getFileInfo(string $path) : array { try { $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->getFileInfo($rpath); } catch(\Exception $e) { throw new \Flexio\Base\Exception(\Flexio\Base\Error::UNAVAILABLE); // use unavailable rather than 'no-service' so path behavior is consistent } } public function exists(string $path) : bool { $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->exists($rpath); } public function createFile(string $path, array $properties = []) : bool { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->createFile($rpath, $properties); } public function createDirectory(string $path, array $properties = []) : bool { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->createDirectory($rpath, $properties); } public function open($path) : \Flexio\IFace\IStream { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->open([ 'path' => $rpath ]); } public function unlink($path) : bool { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->unlink($rpath); } public function read($path, callable $callback) // TODO: add return type { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } if (strlen(trim($path)) == 0) throw new \Flexio\Base\Exception(\Flexio\Base\Error::UNAVAILABLE); $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->read([ 'path' => $rpath ], $callback); } public function write($path, callable $callback) // TODO: add return type { // path can either be an array [ 'path' => value ] or a string containing the path $pathstr = $path; if (is_array($path)) { $pathstr = $path['path'] ?? ''; } if (strlen(trim($pathstr)) == 0) throw new \Flexio\Base\Exception(\Flexio\Base\Error::UNAVAILABLE); $arr = $this->splitPath($pathstr); $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($pathstr, $connection_identifier, $rpath); $arr = [ 'path' => $rpath ]; if (is_array($path)) { unset($path['path']); $arr = array_merge($arr, $path); } return $service->write($arr, $callback); } //////////////////////////////////////////////////////////// // additional functions //////////////////////////////////////////////////////////// public function listWithWildcard(string $path = '', array $options = []) : array { $parts = \Flexio\Base\File::splitPath($path); $lastpart = array_pop($parts); foreach ($parts as $part) { if (strpos($part, '*') !== false) { // only the last part of the path may contain a wildcard throw new \Flexio\Base\Exception(\Flexio\Base\Error::INVALID_SYNTAX, "Invalid parameter 'path'. Only the last part of the path may contain a wildcard"); } } $wildcard = null; if ($lastpart !== null) { if (strpos($lastpart, '*') !== false) $wildcard = $lastpart; else $parts[] = $lastpart; } $path = '/' . implode('/', $parts); $files = $this->list($path); $results = []; foreach ($files as $f) { if ($wildcard !== null) { if (!\Flexio\Base\File::matchPath($f['name'], $wildcard, false)) continue; } $results[] = $f; } return $results; } public function insert(string $path, array $rows) // TODO: add return type { // path can either be an array [ 'path' => value ] or a string containing the path if (is_array($path)) { $path = $path['path'] ?? ''; } $connection_identifier = ''; $rpath = ''; $service = $this->getServiceFromPath($path, $connection_identifier, $rpath); return $service->insert([ 'path' => $rpath ], $rows); } public function getServiceFromPath(string $path, string &$connection_identifier, string &$rpath) // TODO: add return type { if ($this->root_connection_identifier !== null) { $connection_identifier = $this->root_connection_identifier; $rpath = $path; return $this->getService($connection_identifier); } $service_identifier_len = strpos($path, '://'); if ($service_identifier_len !== false) { $service_identifier_len += 3; if (substr($path, 0, 8) == 'context:') $rpath_start = 9; else $rpath_start = 0; // url remote paths include the protocol and the :// } else { $is_url = false; $service_identifier_len = strpos($path, ':'); if ($service_identifier_len !== false) { $rpath_start = $service_identifier_len+1; } } if ($service_identifier_len !== false) { $connection_identifier = substr($path, 0, $service_identifier_len); $rpath = substr($path, $rpath_start); } else { $arr = $this->splitPath($path); $connection_identifier = $arr[0]; $rpath = rtrim(trim($arr[1]), '/'); return $this->getService($connection_identifier); } return $this->getService($connection_identifier); } private $service_map = []; private function getService(string $connection_identifier) { $conn = $this->service_map[$connection_identifier] ?? null; if (isset($conn)) return $conn; if ($connection_identifier == 'context://') { if ($this->process_context_service === null) throw new \Flexio\Base\Exception(\Flexio\Base\Error::NO_SERVICE); $this->service_map[$connection_identifier] = $this->process_context_service; return $this->process_context_service; } if ($connection_identifier == 'http://' || $connection_identifier == 'https://') { $http_service = \Flexio\Services\Http::create(); $this->service_map[$connection_identifier] = $http_service; return $http_service; } if ($connection_identifier == 's3://') { $s3_service = \Flexio\Services\AmazonS3::create(); $this->service_map[$connection_identifier] = $s3_service; return $s3_service; } if ($this->process) { // first, check the process's local connections for a hit $connection_properties = $this->process->getLocalConnection($connection_identifier); if ($connection_properties) { $connection_type = $connection_properties['connection_type']; $connection_info = $connection_properties['connection_info']; $service = \Flexio\Services\Factory::create($connection_type, $connection_info); $this->service_map[$connection_identifier] = $service; return $service; } } $owner_user_eid = $this->getOwner(); // load the connection if (\Flexio\Base\Eid::isValid($connection_identifier) === false) { $eid_from_identifier = \Flexio\Object\Connection::getEidFromName($owner_user_eid, $connection_identifier); $connection_identifier = isset($eid_from_identifier) ? $eid_from_identifier : ''; } $connection = \Flexio\Object\Connection::load($connection_identifier); // check the rights on the connection if ($connection->getStatus() === \Model::STATUS_DELETED) throw new \Flexio\Base\Exception(\Flexio\Base\Error::UNAVAILABLE); if ($connection->allows($owner_user_eid, \Flexio\Api\Action::TYPE_CONNECTION_READ) === false) throw new \Flexio\Base\Exception(\Flexio\Base\Error::INSUFFICIENT_RIGHTS); // get the service and make sure it has the file system interface $service = $connection->getService(); if (!($service instanceof \Flexio\IFace\IFileSystem)) throw new \Flexio\Base\Exception(\Flexio\Base\Error::UNAVAILABLE); $this->service_map[$connection_identifier] = $service; return $service; } private function splitPath(string $path) : array { $path = trim($path); if (strlen($path) == 0) return []; $urlsep_pos = strpos($path, '://'); if ($urlsep_pos !== false) { $protocol = substr($path, 0, $urlsep_pos); if ($protocol == 'context') { // split off the schema portion context://; the path portion will retain the preceding slash return [ substr($path, 0, $urlsep_pos+3), substr($path, 9) ]; } else if ($protocol == 'https' || $protocol == 'http' || $protocol == 's3') { return [ substr($path, 0, $urlsep_pos+3), $path ]; } } $off = ($path[0] == '/' ? 1:0); $pos = strpos($path, '/', $off); if ($pos === false) { return [ substr($path, $off), '/' ]; } else { return [ substr($path, $off, $pos-$off), substr($path, $pos) ]; } } }
true
e9588ba8b4fb6fbaa3594f482dbecee41d8ccc2e
PHP
adgolubchikov/wap-php-math
/nodnok/nodnok.php
UTF-8
665
2.546875
3
[]
no_license
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd"> <html> <head> <meta http-equiv="content-type" content="text/xhtml+xml; charset=utf-8" /> <title>НОД и НОК</title> </head> <body> <p align="center"> <a href="/">На главную</a><br/> <?php $a=(integer)$_GET['a']; $b=(integer)$_GET['b']; echo 'НОК('.$a.','.$b.')='.nok($a,$b).'<br/>НОД('.$a.','.$b.')='.nod($a,$b); function nod($a,$b) { $w; while ($b != 0) { $w = $a % $b; $a = $b; $b = $w; } return $a; } function nok($a,$b) { $nod=nod($a,$b); return ($a * $b) / $nod; } ?> </p> </form> </body> </html>
true
19dab97f58022ed3bbe51fc8356e96053a8b6022
PHP
chrisribal/onix-parser
/src/CodeList/CodeList.php
UTF-8
1,628
3.28125
3
[ "MIT" ]
permissive
<?php namespace Ribal\Onix\CodeList; use Ribal\Onix\Exception\InvalidCodeListCodeException; use Ribal\Onix\Exception\InvalidCodeListLanguageException; class CodeList { /** * The code to be resolved * * @var string */ protected $code = ""; /** * The resolved value * * @var string */ protected $value = ""; /** * Resolves a CodeList value by code and language * * @param string $code * @param string $language * @return CodeList */ public static function resolve(string $code, string $language = 'en') { $codeList = new static(); if (!isset($codeList::$$language) || !is_array($codeList::$$language)) { throw new InvalidCodeListLanguageException(sprintf('Missing language \'%s\' in %s', $language, static::class)); } if (!array_key_exists($code, $codeList::$$language)) { throw new InvalidCodeListCodeException(sprintf('Missing code %s for language %s in %s', $code, $language, static::class)); } $codeList->code = $code; $codeList->value = $codeList::$$language[$code]; return $codeList; } /** * Get Code * * @return string */ public function getCode() { return $this->code; } /** * Get Value * * @return string */ public function getValue() { return $this->value; } /** * Convert the CodeList Object to string * * @return string */ public function __toString() { return $this->value; } }
true
f0c320d175abbde8629a981d58b90dc6f7e56a5e
PHP
oladygin/hellish
/code/hellish/engine/auth.php
UTF-8
4,495
3.046875
3
[]
no_license
<?php class HAuth { var $s_Hash; var $isCookieLogin; var $isAuthUser; var $m_Me; function __construct () { session_name (HApplication::$p_Instance->m_Params['auth']['sessionname']); session_start (); if (isset($_SESSION[HApplication::$p_Instance->m_Params['auth']['cookiename']])) { // кривого пользователя сразу сбросим if (!$this->get_user_by_hash()) $this->break_session(); } } function is_real() { return $this->m_Me && $this->m_Me->is_real(); } function break_session () { setcookie(HApplication::$p_Instance->m_Params['auth']['cookiename'], 0, time()-1, '/', false, 0); unset ($_SESSION[HApplication::$p_Instance->m_Params['auth']['cookiename']]); $this->clear (); session_unset (); } function clear () { $this->m_Me = null; $this->s_Hash = false; $this->isCookieLogin = false; $this->isAuthUser = false; } function install_cookie ($hash) { $this->s_Hash = $hash; $coockietime = 60*60*24*365; setcookie(HApplication::$p_Instance->m_Params['auth']['cookiename'], $this->s_Hash, time()+$coockietime, '/', false, 0); $this->isCookieLogin = true; HApplication::$p_Instance->m_Logger->write(HLOG_INFO, "Install cookie by hash: ".$this->s_Hash); } function create_hash ($value) { $random_compat = new PHP\Random(true); $soul = $random_compat->int(getrandmax()); $hash = md5($value.$soul.time()); return $hash; } function get_user_by_hash ($hash) { $this->m_Me = new HApplication::$p_Instance->m_Params['auth']['usermodel'](); $this->s_Hash = $hash; return $this->m_Me->LoadByHash($hash); } function do_auth () { // Есть ли авторизация по куки? if (isSet ($_COOKIE[HApplication::$p_Instance->m_Params['auth']['cookiename']])) { if ($_COOKIE[HApplication::$p_Instance->m_Params['auth']['cookiename']]) { $this->isCookieLogin = true; HApplication::$p_Instance->m_Logger->write(HLOG_DEBUG, "Try hash: ".$_COOKIE[HApplication::$p_Instance->m_Params['auth']['cookiename']]); if ($this->get_user_by_hash($_COOKIE[HApplication::$p_Instance->m_Params['auth']['cookiename']])) { // Получили пользователя по хэшу $this->isAuthUser = true; HApplication::$p_Instance->m_Logger->write(HLOG_INFO, "Get user by cookie: ".$this->m_Me->GetLogName()); return true; } else { // Это неавторизованный пользователь, но он уже был $ret = HApplication::$p_Instance->m_Params['auth']['allowanonymous']; HApplication::$p_Instance->m_Logger->write(HLOG_INFO, "Anonimous user with cookie, return " . ($ret ? 'True' : 'False')); return ($ret); } } } // Разрешено ли создавать анонимных пользователей? if (!HApplication::$p_Instance->m_Params['auth']['creteanonymous']) { // запращено, не создаем, просто болванка пустая HApplication::$p_Instance->m_Logger->write(HLOG_INFO, "Anonimous user first time, set cookie"); $this->m_Me = new HApplication::$p_Instance->m_Params['auth']['usermodel'](); $this->install_cookie("anonymous"); return (HApplication::$p_Instance->m_Params['auth']['allowanonymous']); } else { // разрешено, создаем в БД (пока не реализованоs) $this->m_Me = new HApplication::$p_Instance->m_Params['auth']['usermodel'](); return true; } } } ?>
true
af8603acff019a7ed6aed5a01b1b14ea3075d061
PHP
kvesskrishna/lightkids
/sendcontact.php
UTF-8
1,235
2.609375
3
[]
no_license
<?php session_start(); if (isset($_POST['send'])) { # code... $to="ambofchrist@gmail.com"; $name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $usermessage=$_POST['message']; $subject="Contact from Lightkids.org Website ContactForm"; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Create email headers $headers .= 'From: '.$email."\r\n". 'Reply-To: '.$email."\r\n" . 'X-Mailer: PHP/' . phpversion(); // Compose a simple HTML email message $message = '<html><body>'; $message .= '<h1 style="color:#f40;">Hi!</h1>'; $message .= '<p style="color:#080;font-size:18px;">There is a contact from visitor of Lightkids.org website. Following are the contact Details</p>'; $message .= '<p style="color:#080;font-size:18px;"> Name: '.$name.'<br> Email: '.$email.'<br> Phone: '.$phone.'<br> Message: '.$usermessage.'<br> </p><br><i>Regards,<br>Webmaster Lightkids.org</i>'; $message .= '</body></html>'; // Sending email if(mail($to, $subject, $message, $headers)){ // echo 'Your mail has been sent successfully.'; $_SESSION['sendcontact']=1; header('Location: ' . $_SERVER['HTTP_REFERER']); } else{ echo 'Unable to send email. Please try again.'; } } ?>
true
f414c515f80cbad8114d64d536078dc92bfefd21
PHP
luismiguens/skaphandrus_v4
/src/Skaphandrus/AppBundle/Entity/Repository/SkIdentificationCriteriaRepository.php
UTF-8
3,647
2.515625
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php namespace Skaphandrus\AppBundle\Entity\Repository; use Doctrine\ORM\EntityRepository; /** * SkIdentificationCriteriaRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class SkIdentificationCriteriaRepository extends EntityRepository { /** * Metodo que com base nas especies enviadas, devolve as os critérios e caracteres que fazem match. */ public function getCriteriasFromSpecies($species_id) { $em = $this->getEntityManager(); $connection = $em->getConnection(); $sql = "SELECT distinct( sk_identification_character.criteria_id ) as criteria_id FROM sk_identification_species_character join sk_identification_character on sk_identification_species_character.character_id = sk_identification_character.id where species_id = " . $species_id; $statement = $connection->prepare($sql); $statement->execute(); $values = $statement->fetchAll(); $result = array(); foreach ($values as $value) { //$result[] = $em->getRepository('SkaphandrusAppBundle:SkIdentificationCriteria')->find($value['criteria_id']); $result[] = $value['criteria_id']; } return $result; } public function findCriteriaJoinAllCharacters($criteria_id) { $query = $this->getEntityManager() ->createQuery( 'SELECT crits, chars FROM SkaphandrusAppBundle:SkIdentificationCriteria crits JOIN crits.characters chars WHERE crits.id = :criteria_id' )->setParameter('criteria_id', $criteria_id); try { return $query->getOneOrNullResult(); } catch (\Doctrine\ORM\NoResultException $e) { return null; } } /** * Metodo que com base nas especies enviadas, devolve as os critérios e caracteres que fazem match. */ public function getCriteriaIDSFromSpeciesIDS($species, $module_id = null) { $em = $this->getEntityManager(); $connection = $em->getConnection(); $sql = "SELECT distinct(criteria_id) FROM sk_identification_criteria_matrix" . ( ($module_id == null) ? "" : "_" . $module_id ) . " where species_id in (" . implode(', ', $species) . ") "; $statement = $connection->prepare($sql); $statement->execute(); $values = $statement->fetchAll(); $result = array(); foreach ($values as $value) { $result[] = $value['criteria_id']; } return $result; } /** * Metodo que com base no modulo, devolve os critérios que fazem match. */ public function getCriteriaIDSFromModule($module) { $em = $this->getEntityManager(); $connection = $em->getConnection(); $sql = "SELECT distinct(criteria_id) FROM sk_identification_criteria_matrix_" . $module->getId() . " where "; foreach ($module->getGroups() as $key => $group_obj) { $sql .= $group_obj->getTaxonName() . "_id = " . $group_obj->getTaxonValue()->getId(); if ($key < count($module->getGroups()) - 1): $sql .= " or "; endif; } $statement = $connection->prepare($sql); $statement->execute(); $values = $statement->fetchAll(); $result = array(); foreach ($values as $value) { $result[] = $value['criteria_id']; } return $result; } }
true
a3a72a52a2b5be8217c30d6180599ce7d51b6545
PHP
ProgrissiveProgramCompany/bookStore
/model/getComments.php
UTF-8
1,766
2.578125
3
[]
no_license
<?php require "connection.php"; $isbn = $_GET['isbn']; $query = "select * from comments where isbn='$isbn'"; $result = $conn->query($query); if($result->num_rows>0){ while($row = $result->fetch_assoc()) { $userCommentId = $row['userid']; $comment = $row['comment']; $sql = "select * from users where id='$userCommentId'"; $result2 = $conn->query($sql); if($result2->num_rows>0){ while($row = $result2->fetch_assoc()) { $pic = "../profiles/".$row['picture']; $userName = $row['userName']; $content = " <div class=\"col-12 \"> <div class=\"panel panel-white post panel-shadow\"> <div class=\"post-heading\"> <div class=\"pull-left image\"> <img src='$pic' class='rounded-circle' style='width: 50px;height: 50px;' alt=\"user profile image\"> </div> <div class=\"pull-left meta\"> <div class=\"title h5\"> <b>'$userName'</b> </div> </div> </div> <div class=\"post-description\"> <p>'$comment'</p> <div class=\"stats\"> </div> </div> </div> </div> <br> "; echo $content; } } } } else{ echo "<center><h4>No Comments for this book</h4></center> "; } ?>
true
f9898d08459a12335696a6a4427050b281b3a72b
PHP
ci5aIo/Qboqx-2.3.8
/mod/tasks/actions/que/pick.php
UTF-8
3,940
2.53125
3
[]
no_license
<?php /** * QuebX pick elements action * * Used by: * : */ /* Pseudocode * Receive element_type. * Receive item_guid * if item_guid is empty * set item_guid to 0 * Receive container_guid * If container_guid is empty * set container_guid to item_guid * Receive selected groups * Determine type of container * If container is a transfer item * Create new receipt item * Create new link between receipt item and selected item * If container is a receipt item * Delete existing link between receipt item and selected item * Create new link between receipt item and selected item */ // Get variables $pick = get_input('pick'); /******************/ $element_type = $pick[element_type]; $item_guid = $pick[item_guid]; if (empty($item_guid)){$item_guid = 0;} $pick_type = $pick[pick_type]; if (empty($pick_type)){$pick_type = 'task';} $group_subtype = $pick[group_subtype]; $access_id = $pick[access_id]; $owner_guid = $pick[owner_guid]; if (empty($owner_guid)){$owner_guid = elgg_get_logged_in_user_guid();} $selected = $pick[selected_tasks]; /******************/ $item = get_entity($item_guid); if ($item_guid != 0) { $item_type = $item->getSubtype(); } $display = '$group_subtype: '.$group_subtype.'<br>'; $display .= '$pick_type: '.$pick_type.'<br>'; $display .= '$item_guid: '.$item_guid.'<br>'; $display .= '$element_type: '.$element_type.'<br>'; Switch ($pick_type) { case 'task': $relationship = 'que'; break; default: $relationship = 'que'; break; } $inverse_relationship=false; $relationships = get_entity_relationships($item_guid, $inverse_relationship); /** * Updates the task associations of a schedule * @param type $item * @param type $selected_tasks * @param type $existing_tasks * @param type $relationship */ function collections_update($item, $selected, $existing, $relationship) { $display .= 'collections_update ...<br>'; $add = array_diff($selected, $existing); $rem = array_diff($existing, $selected); $display .= '$relationship: '.$relationship.'<br>'; $add = array_unique($add); $add = array_values($add); $rem = array_unique($rem); $rem = array_values($rem); $guid_two = $item->getguid(); foreach($add as $i){ $guid_one = $i; if(!check_entity_relationship($guid_one, $relationship, $guid_two)){ add_entity_relationship($guid_one, $relationship, $guid_two); } } foreach($rem as $i){ $guid_one = $i; remove_entity_relationship($guid_one, $relationship, $guid_two); } } if ($element_type == 'maintenance'){ // remove empty elements // $selected_tasks = array_diff($selected_tasks , array("0")); $display .= '$selected: '.$selected[0].'<br>'; $existing = elgg_get_entities_from_relationship(array( 'relationship' => $relationship, 'relationship_guid' => $item_guid, 'inverse_relationship' => true, // 'relationship_join_on' => 'guid', )); if ($existing){ foreach($existing as $i){ $existing[] = $i->getguid(); $display .= '$existing[]: '.$i->getguid().'<br>'; } } // collections_update($item, $selected, $existing, $relationship); $display .= 'collections_update ...<br>'; $add = array_diff($selected, $existing); $rem = array_diff($existing, $selected); $display .= '$relationship: '.$relationship.'<br>'; $add = array_unique($add); $add = array_values($add); $rem = array_unique($rem); $rem = array_values($rem); $guid_two = $item->getguid(); $display .= '$guid_two: '.$guid_two.'<br>'; foreach($add as $i){ $guid_one = $i; $display .= '$guid_one: '.$guid_one.'<br>'; if(!check_entity_relationship($guid_one, $relationship, $guid_two)){ add_entity_relationship($guid_one, $relationship, $guid_two); } } foreach($rem as $i){ $guid_one = $i; remove_entity_relationship($guid_one, $relationship, $guid_two); } } //register_error($display);
true
884d6c9a9ed1a8b4292ee3c77c9f418ef8b0863a
PHP
saad197/PHP-Art-Store
/includes/process-registration.php
UTF-8
2,251
2.625
3
[]
no_license
<?php include "config.inc.php"; $email = $_GET['email']; $password = $_GET['password']; $cpasswoord = $_GET['cpassword']; $country = $_GET['country']; $firstName = $_GET['firstname']; $lastName = $_GET['lastname']; $city = $_GET['city']; $address = $_GET['address']; $postal = $_GET['postal']; $state = $_GET['region']; $phone = $_GET['phone']; try { $conn = new PDO(DBCONNSTRING,DBUSER,DBPASS); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully"; } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); } $hashed_password = sha1($password); try { //login details insert $insertCustomerLogonSql = "INSERT INTO `CustomerLogon` ( `UserName`, `Pass`, `Salt`, `State`, `DateJoined`, `DateLastModified`) VALUES ( '$email', '$hashed_password', 1, 1, NOW(), NOW())"; $customerLogon = $conn->prepare($insertCustomerLogonSql); $conn->exec($insertCustomerLogonSql); //get customer id $getCustIdSql = "SELECT CustomerID, UserName FROM CustomerLogon WHERE UserName = '$email'; "; $getCustId = $conn->prepare($getCustIdSql); $getCustId->execute(); echo '</br>'; foreach ($getCustId as $key => $value) { // echo '</br>'; //echo 'email is' . $value['UserName']; // echo '</br>'; $customerID = $value['CustomerID']; echo $customerID; // echo '</br>'; } //insert to customers $insertCustomerSql = "INSERT INTO `Customers` (`CustomerID`, `FirstName`, `LastName`, `Address`, `City`, `Region`, `Country`, `Postal`, `Phone`, `Email`, `Privacy`) VALUES ($customerID, '$firstName', '$lastName', '$address', '$city', '$state', '$country', '$postal', '$phone', '$email', NULL)"; $customer= $conn->prepare($insertCustomerSql); $conn->exec($insertCustomerSql); echo "New records created successfully"; header('Location: ../registration-complete.php'); } catch(PDOException $e) { echo $insertCustomerLogonSql . "<br>" . $e->getMessage(); echo $insertCustomerLogonSql . "<br>" . $e->getMessage(); echo $getCustIdSql . "<br>" . $e->getMessage(); } ?>
true
84a77ab2e78c4145a0da3196b8290a6804fb8219
PHP
captainhookphp/captainhook
/tests/unit/Hook/Message/Rule/UseImperativeMoodTest.php
UTF-8
1,294
2.59375
3
[ "MIT" ]
permissive
<?php /** * This file is part of CaptainHook * * (c) Sebastian Feldmann <sf@sebastian-feldmann.info> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace CaptainHook\App\Hook\Message\Rule; use SebastianFeldmann\Git\CommitMessage; use PHPUnit\Framework\TestCase; class UseImperativeMoodTest extends TestCase { /** * Tests UseImperativeMood::pass * * @dataProvider passProvider * * @param string $string * @param bool $begin * @param bool $expectedResult */ public function testPass(string $string, bool $begin, bool $expectedResult): void { $msg = new CommitMessage($string); $rule = new UseImperativeMood($begin); $this->assertSame($expectedResult, $rule->pass($msg)); } /** * The testPass data provider * * @return array */ public function passProvider(): array { return [ ['foo bar baz', true, true], ['foo bar baz', false, true], ['fixed soemthing something', false, false], ['fixed soemthing something', true, false], ['soemthing fixed something', false, false], ['soemthing fixed something', true, true], ]; } }
true
7513b5e2aefaaa686bf54cfd8edbf7f39b651ed2
PHP
CrazyCrud/shithouse-poetry-website
/www/php/backend/getTypes.php
UTF-8
1,238
2.640625
3
[]
no_license
<?php // How to use this page: // open it without any info: // // getTypes.php // // required parameters are: // none // // The answer looks as follows: // a json with a successcode and the data about all types: /* { "success":1, "data": [ { "id":"1", "name":"Text", "description":"Ein an eine Wand, T\u00fcr oder auf einen anderen Gegenstand geschriebener Text." } ] } */ // for success codes see ../php/config.php // HEADER header('Content-Type: application/json; charset=utf-8'); error_reporting(0); include_once("../settings/config.php"); include_once("../helpers/dbhelper.php"); // END HEADER // PREPARE RESULT $json = array(); $json["success"]=$CODE_INSUFFICIENT_PARAMETERS; $db = new DBHelper(); if(isset($_GET["authkey"])){ $db->setAuthKey($_GET["authkey"]); } $types = $db->getAllTypes(); if($types == false){ $json["success"]=$CODE_ERROR; if(DBConnection::getInstance()->status == DBConfig::$dbStatus["offline"]){ $json["message"] = "Database error";$json["success"] = $CODE_DB_ERROR; }else{ $json["success"] = $CODE_NOT_FOUND; $json["message"] = "Types not found"; } echo json_encode($json); exit(); } $json["data"] = $types; $json["success"] = $CODE_SUCCESS; echo json_encode($json); ?>
true
174c2b6b9e035de9cb1b32381c7b795ad0e8c963
PHP
yzysun/studay
/rik/day7.php
UTF-8
339
3.375
3
[]
no_license
<?php echo GetUglyNumber_Solution(25); function GetUglyNumber_Solution($index) { $a=$index/2; if($a==intval($a)) { echo $index;die; }else{ $b=$index/3; if($b==intval($b)) { echo $index;die; }else{ $c=$index/5; if($c==intval($c)) { echo $index;die; }else{ echo $index.'不是丑数'; } } } } ?>
true
ca58c3a38993daed2a933c7f7d51d90d1eeb5ca9
PHP
mem-memov/telepanorama
/decorator/src/ArtStudio/MeasuredOriginal.php
UTF-8
803
2.890625
3
[]
no_license
<?php declare(strict_types=1); namespace Telepanorama\ArtStudio; class MeasuredOriginal { private Original $original; private Rectangle $rectangle; public function __construct( Original $original, Rectangle $rectangle ) { $this->original = $original; $this->rectangle = $rectangle; } public function getAbsolutePath(): string { return $this->original->getAbsolutePath(); } public function getWidth(): int { return $this->rectangle->getWidth()->getPixels(); } public function getHeight(): int { return $this->rectangle->getHeight()->getPixels(); } public function toComparableRectangle(): ComparableRectangle { return $this->rectangle->toComparableRectangle(); } }
true
9e556d928a3329f56e7701476c63f0bcac8201c8
PHP
thangpd/strava
/wordpress-helper-plugins/admin/modules/pages/stravaApiSettingPages/stravaChat/StravaChat.php
UTF-8
2,425
2.515625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: tom * Date: 3/1/21 * Time: 10:34 AM */ namespace Elhelper\admin\modules\pages\stravaApiSettingPages\stravaChat; use Elhelper\common\Controller; use Elhelper\common\View; use Elhelper\Elhelper_Plugin; class StravaChat extends Controller { private $strava; public function __construct() { $this->strava = new \Elhelper\model\TechvsiStravaModel(); add_action( 'elhelper_add_submenu', [ $this, 'register_strava_setting_page' ] ); add_action( 'wp_ajax_get_history_message_of_subscriber', [ $this, 'get_history_message_of_subscriber' ] ); add_action( 'wp_ajax_get_list_subscribers', [ $this, 'get_list_subscribers' ] ); add_action( 'wp_ajax_send_strava_message', [ $this, 'send_strava_message' ] ); } function register_strava_setting_page() { add_submenu_page( 'strava-api-setting', 'Strava Chat', 'Strava Chat', 'manage_options', 'strava-chat', [ $this, 'mt_settings_page' ], 10 ); } public function mt_settings_page() { $assets = Elhelper_Plugin::instance()->wpackio_enqueue( 'testapp', 'stravaChat', [ 'css_dep' => [ // 'font-awesome-all', // 'font-awesome', // 'fontawesome-pro-5', ], ] ); $view = new View( $this ); echo $view->render( 'strava-chat.php', [ 'hidden_field_name' => 'test', ] ); } public function send_strava_message() { if ( isset( $_POST['message'] ) && isset( $_POST['user_id'] ) ) { $user_id = $_POST['user_id']; $message = $_POST['message']; $list_mess = $this->strava->sendMessageToListRecipient( $user_id, $message ); wp_die( json_encode( $list_mess ) ); } } public function get_history_message_of_subscriber() { if ( isset( $_GET['user_id'] ) ) { $list_mess = $this->strava->getRecentWithSubMessage( $_GET['user_id'] ); wp_die( json_encode( $list_mess ) ); } } public function get_list_subscribers() { $list_subscribers = $this->strava->getListSubscribers(); $data = []; if ( ! empty( $list_subscribers ) && isset( $list_subscribers['data'] ) ) { if ( $list_subscribers['data']['total'] > 0 ) { foreach ( $list_subscribers['data']['followers'] as $value ) { if ( isset( $value['user_id'] ) ) { $data[ $value['user_id'] ] = $this->strava->getInfoUser( $value['user_id'] ); } } } } else { } $code = 200; echo json_encode( [ 'data' => $data, 'code' => $code ] ); wp_die(); } }
true
1febe1f6baa2f25ea4cd4283f74ddb3d8e60150a
PHP
trueman52/ivs
/app/EditBookingCalculator.php
UTF-8
18,420
2.78125
3
[ "MIT" ]
permissive
<?php namespace App; use App\Enums\DiscountType; use App\Models\ApplicableCoupon; use App\Models\Booking; use App\Models\BookingDiscount; use App\Models\Coupon; use App\Models\GroupedAddOn; use App\Models\Period; use App\Models\Unit; use Illuminate\Support\Collection; use Illuminate\Support\Str; class EditBookingCalculator { use InteractsWithEditedBooking; /** * Sequence of which the discounts are applied in. * * @var array */ protected $discountSequence = []; /** * @var int */ protected $quantity; /** * @var \Illuminate\Database\Eloquent\Collection */ protected $periods; /** * @var \Illuminate\Database\Eloquent\Collection */ protected $groupedAddOns; /** * @var \App\Models\Unit */ protected $unit; /** * @var \App\Models\Coupon */ protected $coupon; /** * THe calculation result. * * @var array */ protected $result = []; /** * The subtotal for the booking. (Discounted periods + add-ons). * * @var float */ protected $subTotal; /** * The un-discounted period total. * * @var float */ protected $periodsTotal = 0; /** * The adhoc items * * @var array */ protected $adhocItems = []; /** * Total amount for adhoc items. * * @var int */ protected $adhocItemsTotal = 0; /** * The discounted period total. * * @var float */ protected $discountedPeriodsTotal; /** * The add-ons total * * @var float */ protected $addOnsTotal = 0; /** * Information for the add-ons that has been added to this booking. * * @var array */ protected $addOnCalculations = []; /** * Information for the periods that was selected for this booking. * * @var array */ protected $periodsCalculation = []; /** * Information for the adhoc items that was added for this booking. * * @var array */ protected $adhocCalculations = []; /** * Applied discounts information. * * @var array */ protected $appliedDiscounts = []; /** * Applied coupon's information. * * @var null */ protected $appliedCoupon = null; /** * @var float */ protected $gst; /** * @var float */ protected $grandTotal = 0; /** * BookingCalculator constructor. * * @param \App\Models\Booking $booking * @param int $quantity - Number of units. * @param \App\Models\Unit $unit - Unit model * @param \Illuminate\Support\Collection $periods - Collection of App\Models\Period * @param \Illuminate\Support\Collection $groupedAddOns - Collection of App\Models\GroupedAddOn * @param \App\Models\ApplicableCoupon $coupon * @param array $adhocItems */ public function __construct(Booking $booking, int $quantity, Unit $unit, Collection $periods, Collection $groupedAddOns, ApplicableCoupon $coupon, array $adhocItems = []) { $this->booking = $booking; $this->quantity = $quantity; $this->unit = $unit; $this->periods = $periods; $this->groupedAddOns = $groupedAddOns; $this->coupon = $coupon; $this->adhocItems = $adhocItems; $this->setDiscountSequence(); } /** * Store information on our calculated grouped add-on. * * @param \App\Models\GroupedAddOn $groupedAddOn * @param int $addOnTotal */ protected function addCalculatedAddOn(GroupedAddOn $groupedAddOn, int $addOnTotal) { $this->addOnCalculations[] = [ 'total' => $addOnTotal, 'quantity' => (int)$groupedAddOn->quantity, 'name' => $groupedAddOn->name, ]; } protected function addCalculatedAdhocItem(array $adhocItem, int $total) { $this->adhocCalculations[] = [ 'item' => $adhocItem, 'total' => $total, ]; } /** * Store information on our calculated period. * * @param \App\Models\Period $period * @param int $periodTotal */ protected function addCalculatedPeriod(Period $period, int $periodTotal) { $this->periodsCalculation[] = [ 'date' => "{$period->fromDate->format('d')} - {$period->toDate->format('d M Y')}", 'quantity' => $this->quantity, 'total' => $periodTotal, ]; } /** * Apply coupon discounts to periods where applicable * * @return void */ public function applyCoupon() { // check if the current coupon we are trying to apply is associated to a booking. // if it is, we will have to calculate the discount based on the the used coupon. if ($this->booking->isUsingCoupon($this->coupon)) { $this->coupon = $this->getUsedCoupon(); } // if this coupon is not the one that's associated to the booking, we will // need to ensure the coupon meets the application criteria. if ($this->coupon instanceof Coupon && !$this->canApplyCoupon()) return; $couponInformation = ['beforeDiscount' => $this->discountedPeriodsTotal]; $this->discountedPeriodsTotal = $this->coupon->apply($this->discountedPeriodsTotal); $couponInformation['afterDiscount'] = $this->discountedPeriodsTotal; $couponInformation['coupon'] = $this->coupon; $this->appliedCoupon = $couponInformation; } /** * Apply discounts to periods where applicable. */ protected function applyDiscounts() { $discounts = $this->booking->bookingDiscounts; $this->discountedPeriodsTotal = $this->periodsTotal; $discountedTotal = $this->periodsTotal; if (!$discounts) return; // Apply discounts based on the order of discount sequence. foreach ($this->discountSequence as $sequence) { // Filter discounts so that we don't have to loop through all of them. $filteredDiscounts = $discounts->where('type', $sequence); $methodName = "apply" . Str::studly($sequence) . "Discount"; // Apply and store discount information. foreach ($filteredDiscounts as $filteredDiscount) { $discountInformation = ['beforeDiscount' => $discountedTotal]; $discountedTotal = $this->$methodName($discountedTotal, $filteredDiscount); $discountInformation['afterDiscount'] = $discountedTotal; if (!$this->discountApplied($discountInformation['beforeDiscount'], $discountInformation['afterDiscount'])) { continue; } $discountInformation['discount'] = $filteredDiscount; $this->appliedDiscounts[] = $discountInformation; } } $this->discountedPeriodsTotal = $discountedTotal; } /** * Apply discount to our total. * * @param float $amount * @param \App\Models\BookingDiscount $discount * * @return float */ protected function applyLimitedTimeDiscount(float $amount, BookingDiscount $discount) { return $discount->applyLimitedTimeDiscount($amount); } /** * Apply periods quantity discount. * * @param float $amount * @param \App\Models\BookingDiscount $discount * * @return float */ protected function applyPeriodDiscount(float $amount, BookingDiscount $discount) { return $discount->applyPeriodDiscount($amount, $this->periods->count()); } /** * Apply unit quantity discount. * * @param float $amount * @param \App\Models\BookingDiscount $discount * * @return float */ protected function applyQuantityDiscount(float $amount, BookingDiscount $discount) { return $discount->applyQuantityDiscount($amount, $this->quantity); } /** * Calculate bookings. */ protected function calculate() { // Load information if they have not been loaded. $this->booking->loadMissing([ 'usedCoupon', 'bookingPeriods', 'bookingDiscounts', 'bookingAddOns.addOn', 'AdhocItems', ]); $this->calculatePeriods(); $this->calculateAddOns(); $this->applyDiscounts(); $this->applyCoupon(); $this->calculateAdhocItems(); $this->calculateSubTotal(); $this->calculateGst(); $this->calculateGrandTotal(); } /** * Calculates the sum of each add-on and adding them up. * * @return void */ protected function calculateAddOns() { $addOnsTotal = 0; $periodCount = $this->periods->count(); if (!$this->groupedAddOns) return; foreach ($this->groupedAddOns as $groupedAddOn) { if ($this->isGroupedAddOnAssociatedToBooking($groupedAddOn)) { // If this grouped add-on was already associated to the booking, then we will // have to use the pricing at the point when the booking was created // for the calculation. $addOnTotal = $groupedAddOn->quantity * $this->getBookingGroupedAddOnPricing($groupedAddOn) * $periodCount; } else { // If it isn't we will use the grouped add-on's latest pricing. $addOnTotal = $groupedAddOn->quantity * $groupedAddOn->costPerUnit * $periodCount; } $addOnsTotal += $addOnTotal; $this->addCalculatedAddOn($groupedAddOn, $addOnTotal); } $this->addOnsTotal = $addOnsTotal; } public function calculateAdhocItems() { foreach ($this->adhocItems as $adhocItem) { if ($this->isAdhocItemAssociatedToBooking($adhocItem)) { // If this adhoc item was already associated to the booking, then we will // have to use the pricing at the point when the booking was created // for the calculation. $total = $this->getBookingAdhocPricing($adhocItem) * $adhocItem['quantity']; } else { // If it isn't we will use the period's latest pricing. $total = $adhocItem['amount'] * $adhocItem['quantity']; } $this->adhocItemsTotal += $total; $this->addCalculatedAdhocItem($adhocItem, $total); } } /** * Calculated grand total by adding subtotal, gst, and security deposits. * * @return void */ protected function calculateGrandTotal() { $this->grandTotal = $this->subTotal + $this->gst + $this->unit->securityDeposit; } /** * Calculate gst based on subtotal * * @return void */ protected function calculateGst() { // Since we are already calculating the subtotal in cents, when calculating // the gst, we should get rid of the remaining decimal places. $this->gst = (int)round($this->subTotal * AppSetting::get('gst') / 100); } /** * Calculates the sum of each period and adding them up. * * @return void */ protected function calculatePeriods() { foreach ($this->periods as $period) { if ($this->isPeriodAssociatedToBooking($period)) { // If this period was already associated to the booking, then we will // have to use the pricing at the point when the booking was created // for the calculation. $total = $this->getBookingPeriodPricing($period) * $this->quantity; } else { // If it isn't we will use the period's latest pricing. $total = $period->pivot->unit_price * $this->quantity; } $this->periodsTotal += $total; $this->addCalculatedPeriod($period, $total); } } /** * Calculates booking's subtotal. */ public function calculateSubTotal() { $this->subTotal = $this->discountedPeriodsTotal + $this->adhocItemsTotal + $this->addOnsTotal; } /** * Checks if the coupon supplied can be used. * * @return bool */ protected function canApplyCoupon() { if (!$this->coupon->exists) { return false; } if (!$this->isCouponUsableBySpace()) return false; if (!$this->isCouponUsableByCustomer()) return false; return true; } /** * Checks if discount was successfully applied. * True if discount applied. * * @param $before * @param $after * * @return bool */ protected function discountApplied($before, $after) { return $before != $after; } /** * @return array */ public function getAddOnCalculations() { return $this->addOnCalculations; } /** * @return float */ public function getAddOnsTotal() { return $this->addOnsTotal; } /** * @return array */ protected function getAdhocItemCalculations() { return $this->adhocCalculations; } /** * @return mixed */ public function getAdhocItemsTotal() { return $this->adhocItemsTotal; } /** * @return array */ public function getAppliedCoupon() { return $this->appliedCoupon; } /** * @return array */ public function getAppliedDiscounts() { return $this->appliedDiscounts; } /** * Get the pricing that was used at the point when the booking was created. * * @param array $item * * @return int */ protected function getBookingAdhocPricing(array $item) { $item = $this->getBookingAdhocItem($item); return $item->amount; } /** * Get the pricing that was used at the point when the booking was created. * * @param \App\Models\GroupedAddOn $groupedAddOn * * @return int */ public function getBookingGroupedAddOnPricing(GroupedAddOn $groupedAddOn) { $addOn = $this->getBookingAddOn($groupedAddOn); return $addOn->purchasedAt; } /** * Get the pricing that was used at the point when the booking was created. * * @param \App\Models\Period $period * * @return int */ public function getBookingPeriodPricing(Period $period) { $bookingPeriod = $this->getBookingPeriod($period); return $bookingPeriod->purchasedAt; } /** * Perform calculation and return the results. * * @return array */ public function getCalculations() { $this->calculate(); return [ 'addOns' => [ 'calculations' => $this->getAddOnCalculations(), 'total' => $this->getAddOnsTotal(), ], 'periods' => [ 'calculations' => $this->getPeriodsCalculation(), 'total' => $this->getPeriodsTotal(), ], 'appliedCoupon' => $this->getAppliedCoupon(), 'appliedDiscounts' => $this->getAppliedDiscounts(), 'adhocItems' => [ 'calculations' => $this->getAdhocItemCalculations(), 'total' => $this->getAdhocItemsTotal(), ], 'discountedPeriodsTotal' => $this->getDiscountedPeriodsTotal(), 'gst' => [ 'amount' => $this->getGst(), 'percentage' => AppSetting::get('gst'), ], 'securityDeposit' => $this->getSecurityDeposit(), 'subTotal' => $this->getSubTotal(), 'grandTotal' => $this->getGrandTotal(), ]; } /** * @return float */ public function getDiscountedPeriodsTotal() { return $this->discountedPeriodsTotal; } /** * @return float */ public function getGrandTotal() { return $this->grandTotal; } /** * @return float */ public function getGst() { return $this->gst; } /** * Get unit's periods. * * @param array $periodIds * * @return \Illuminate\Database\Eloquent\Collection */ protected function getPeriods(array $periodIds) { return $this->unit->periods()->wherePivotIn('period_id', $periodIds)->get(); } /** * @return array */ public function getPeriodsCalculation() { return $this->periodsCalculation; } /** * @return float */ public function getPeriodsTotal() { return $this->periodsTotal; } /** * Get unit's security deposit. * * @return mixed */ public function getSecurityDeposit() { return $this->unit->securityDeposit; } /** * @return float */ public function getSubTotal() { return $this->subTotal; } /** * Get unit details * * @param int $id * * @return \App\Models\Unit */ protected function getUnit(int $id) { return Unit::find($id); } /** * Get the used coupon that was used for the booking. * * @return \App\Models\UsedCoupon */ protected function getUsedCoupon() { return $this->booking->usedCoupon; } /** * Set order in which discounts are applied. */ public function setDiscountSequence() { $this->discountSequence = [ (string)DiscountType::LIMITED_TIME(), (string)DiscountType::PERIOD(), (string)DiscountType::QUANTITY(), ]; } }
true
256625e2a9cbfb859f456e9381ebfdf74604622f
PHP
soon14/Hitrip
/core/function/identitycard.func.php
UTF-8
2,290
2.578125
3
[]
no_license
<?php /** * @author Fm453(方少) * @DACMS https://api.hiluker.com * @site https://www.hiluker.com * @url http://s.we7.cc/index.php?c=home&a=author&do=index&uid=662 * @email fm453@lukegzs.com * @QQ 393213759 * @wechat 393213759 */ /* * @remark:身份证合法性校验 */ defined('IN_IA') or exit('Access Denied'); //返回身份证校验结果 function fmFunc_idcard_validation_filter($id_card){ if(strlen($id_card)==18){ return fmFunc_idcard_checksum18($id_card); }elseif((strlen($id_card)==15)){ $id_card=fmFunc_idcard_15to18($id_card); return fmFunc_idcard_checksum18($id_card); }else{ return false; } } //给身份证号加空格隔断、加掩码 function fmFunc_idcard_mask($id_card){ if(!$id_card) { return; } $str = substr($id_card, 0, 2) . '**' . substr($id_card, 5,2).'********'.substr($id_card, 14); $card =''; for($i=0; $i<5; $i++){ $card = $card. substr($id_card,4*$i,4). ' '; } return $card; } // 计算身份证校验码,根据国家标准GB 11643-1999 function fmFunc_idcard_verify_number($idcard_base){ if(strlen($idcard_base)!=17){ return false; } //加权因子 $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2); //校验码对应值 $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2'); $checksum=0; for($i=0;$i<strlen($idcard_base);$i++){ $checksum += substr($idcard_base,$i,1) * $factor[$i]; } $mod=$checksum % 11; $verify_number=$verify_number_list[$mod]; return $verify_number; } // 将15位身份证升级到18位 function fmFunc_idcard_15to18($idcard){ if(strlen($idcard)!=15){ return false; }else{ // 如果身份证顺序码是996 997 998 999,这些是为百岁以上老人的特殊编码 if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){ $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9); }else{ $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9); } } $idcard=$idcard.fmFunc_idcard_verify_number($idcard); return $idcard; } // 18位身份证校验码有效性检查 function fmFunc_idcard_checksum18($idcard){ if(strlen($idcard)!=18){ return false; } $idcard_base=substr($idcard,0,17); if(fmFunc_idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){ return false; }else{ return true; } }
true
68b65fc1ce83af84705ce9f5b021f7817e9f3eb0
PHP
Joshuavtk/gastenboek
/index.php
UTF-8
3,157
2.859375
3
[]
no_license
<?php $dbc = new PDO('mysql:host=localhost;dbname=22288_gastenboek', 'root', ''); ?> <!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>Gastenboek</title> </head> <body> <form method="post" action="index.php"> <label for="gastboek-naam">Uw naam</label> <input type="text" name="gastboek_name" id="gastboek-naam"><br> <label for="gastboek-body">Uw bericht</label> <textarea name="gastboek_body" id="gastboek-body"></textarea><br> <p>Geweigerde woorden: shit, fuck, poep, kut, knakworst, dumbass, donald trump</p> <input type="submit" name="gastboek_submit" value="SEND"> </form> <?php if (isset($_POST['gastboek_submit'])) { if (strlen($_POST['gastboek_name']) < 50) { $name = $_POST['gastboek_name']; } else { die("generic error message 1"); } if (strlen($_POST['gastboek_body']) < 500) { $body = $_POST['gastboek_body']; $bad_words = ['shit', 'fuck', 'poep', 'kut', 'knakworst', 'dumbass', 'donald trump']; foreach ($bad_words as $bad_word) { if (preg_match('%' . $bad_word . '%', $body)) { $body = preg_replace('%' . $bad_word . '%', '*****' , $body); } } } else { die("generic error message 2"); } $stmt = $dbc->prepare("INSERT INTO berichten VALUES (0,?,?,0)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $body); $stmt->execute() or die('Error querying after PDO'); } if (isset($_POST['gastenboek_set_safe'])) { $id = $_POST['bericht_id']; $stmt = $dbc->prepare("UPDATE berichten SET is_safe=1 WHERE id=$id"); $stmt->execute() or die('Error querying after PDO'); } if (isset($_POST['gastenboek_delete'])) { $id = $_POST['bericht_id']; $stmt = $dbc->prepare("DELETE FROM berichten WHERE id=$id"); $stmt->execute() or die('Error querying after PDO'); } ?> <h1>De berichten van andere mensen</h1> <?php $stmt = $dbc->prepare("SELECT * FROM berichten WHERE is_safe = 1"); $stmt->execute(); while ($row = $stmt->fetch()) { echo "<h3>Naam " . $row['name'] . "</h3>"; echo "Bericht: " . $row['body']; echo "<br>"; } ?> <h1>Onveilige berichten</h1> <?php $stmt = $dbc->prepare("SELECT * FROM berichten WHERE is_safe = 0"); $stmt->execute(); while ($row = $stmt->fetch()) { echo "<h3>Naam " . $row['name'] . "</h3>"; echo "<p>Bericht: " . $row['body'] . "</p>"; echo "<form method='post' action='" . $_SERVER['PHP_SELF'] . "' >"; echo "<input type='hidden' value='" . $row['id'] ."' name='bericht_id'>"; echo "<input type='submit' value='Zet bericht als veilig' name='gastenboek_set_safe' >"; echo "<input type='submit' value='Verwijder bericht' name='gastenboek_delete' >"; echo "</form>"; echo "<br>"; } ?> <?php $dbc = null; $stmt = null; ?> </body> </html>
true
53748b8b8f822d35510013ee6fdec202e16bdf52
PHP
saintmylife/coldiac-admin
/app/Modules/Hero/Domain/HeroFilter.php
UTF-8
816
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Modules\Hero\Domain; use App\Modules\Base\BaseDto; use App\Modules\Base\Domain\BaseFilter; use Illuminate\Validation\Rule; /** * Hero filter */ class HeroFilter extends BaseFilter { public function forUpdate(BaseDto $data): bool { $this->messages = []; $this->setBasicRule(); return $this->basic($data); } public function forUpdateActive(BaseDto $data): bool { $this->messages = []; $this->rules['active'] = 'required|boolean|numeric'; return $this->basic($data); } protected function setBasicRule() { $this->rules = [ 'image' => 'required|mimes:jpeg,bmp,png|max:10240', 'url' => 'nullable|active_url', 'active' => 'nullable|boolean|numeric', ]; } }
true
43ae8d12860d3c9a82ea64dc0902433b91ebcde2
PHP
luispabon/favicon-finder
/src/Exception/NoHostUrlException.php
UTF-8
338
2.5625
3
[ "Apache-2.0" ]
permissive
<?php declare(strict_types=1); namespace FaviconFinder\Exception; use Throwable; /** * @codeCoverageIgnore */ class NoHostUrlException extends UrlException { public function __construct(string $url, Throwable $previous = null) { parent::__construct(sprintf('No host found at url `%s`', $url), 0, $previous); } }
true
9aa037197b2cca70c7e44ecc0e0e126adec7f771
PHP
Ahmetburhan/nurhanhome
/wp-content/themes/dt-the7/inc/extensions/core-functions.php
UTF-8
30,352
2.78125
3
[ "LicenseRef-scancode-generic-exception", "LGPL-2.1-or-later", "LicenseRef-scancode-warranty-disclaimer", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-other-copyleft", "LicenseRef-scancode-proprietary-license", "GPL-2.0-or-later", "MIT" ]
permissive
<?php /** * Core functions. * * @since presscore 0.1 */ // File Security Check if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! function_exists( 'the7_aq_resize' ) ) { /** * This is just a tiny wrapper function for the class above so that there is no * need to change any code in your own WP themes. Usage is still the same :) */ function the7_aq_resize( $url, $img_width, $img_height, $width = null, $height = null, $crop = null, $single = true, $upscale = false ) { $aq_resize = The7_Aq_Resize::getInstance(); return $aq_resize->process( $url, $img_width, $img_height, $width, $height, $crop, $single, $upscale ); } } /** * Constrain dimensions helper. * * @param $w0 int * @param $h0 int * @param $w1 int * @param $h1 int * @param $change boolena * * @return array */ function dt_constrain_dim( $w0, $h0, &$w1, &$h1, $change = false ) { $prop_sizes = wp_constrain_dimensions( $w0, $h0, $w1, $h1 ); if ( $change ) { $w1 = $prop_sizes[0]; $h1 = $prop_sizes[1]; } return array( $w1, $h1 ); } /** * Resize image to speciffic dimetions. * * Magick - do not touch! * * Evaluate new width and height. * $img - image meta array ($img[0] - image url, $img[1] - width, $img[2] - height). * $opts - options array, supports w, h, zc, a, q. * * @param array $img * @param * @return array */ function dt_get_resized_img( $img, $opts, $resize = true, $is_retina = false ) { $opts = apply_filters( 'dt_get_resized_img-options', $opts, $img ); if ( !is_array( $img ) || !$img || (!$img[1] && !$img[2]) ) { return false; } if ( !is_array( $opts ) || !$opts ) { if ( !isset( $img[3] ) ) { $img[3] = image_hwstring( $img[1], $img[2] ); } return $img; } $defaults = array( 'w' => 0, 'h' => 0, 'zc' => 1, 'z' => 1, 'hd_ratio' => 2, 'hd_convert' => true ); $opts = wp_parse_args( $opts, $defaults ); $w = absint( $opts['w'] ); $h = absint( $opts['h'] ); // Return original image if there is no proper dimensions. if ( !$w && !$h ) { if ( !isset( $img[3] ) ) { $img[3] = image_hwstring( $img[1], $img[2] ); } return $img; } // If zoomcropping off and image smaller then required square if ( 0 == $opts['zc'] && ( $img[1] <= $w && $img[2] <= $h ) ) { return array( $img[0], $img[1], $img[2], image_hwstring( $img[1], $img[2] ) ); } elseif ( 3 == $opts['zc'] || empty ( $w ) || empty ( $h ) ) { if ( 0 == $opts['z'] ) { dt_constrain_dim( $img[1], $img[2], $w, $h, true ); } else { $p = absint( $img[1] ) / absint( $img[2] ); $hx = absint( floor( $w / $p ) ); $wx = absint( floor( $h * $p ) ); if ( empty( $w ) ) { $w = $wx; } else if ( empty( $h ) ) { $h = $hx; } else { if ( $hx < $h && $wx >= $w ) { $h = $hx; } elseif ( $wx < $w && $hx >= $h ) { $w = $wx; } } } if ( $img[1] == $w && $img[2] == $h ) { return array( $img[0], $img[1], $img[2], image_hwstring( $img[1], $img[2] ) ); } } $img_h = $h; $img_w = $w; if ( $opts['hd_convert'] && $is_retina ) { $img_h = round( $img_h * $opts['hd_ratio'] ); $img_w = round( $img_w * $opts['hd_ratio'] ); } if ( 1 == $opts['zc'] ) { if ( $img[1] >= $img_w && $img[2] >= $img_h ) { // do nothing } else if ( $img[1] <= $img[2] && $img_w >= $img_h ) { // img=portrait; c=landscape $cw_new = $img[1]; $k = $cw_new/$img_w; $ch_new = $k * $img_h; } else if ( $img[1] >= $img[2] && $img_w <= $img_h ) { // img=landscape; c=portrait $ch_new = $img[2]; $k = $ch_new/$img_h; $cw_new = $k * $img_w; } else { $kh = $img_h/$img[2]; $kw = $img_w/$img[1]; $kres = max( $kh, $kw ); $ch_new = $img_h/$kres; $cw_new = $img_w/$kres; } if ( isset($ch_new, $cw_new) ) { $img_h = absint(floor($ch_new)); $img_w = absint(floor($cw_new)); } } if ( $resize ) { $img_width = $img_height = null; if ( ! empty( $opts['speed_resize'] ) ) { $img_width = $img[1]; $img_height = $img[2]; } $file_url = the7_aq_resize( $img[0], $img_width, $img_height, $img_w, $img_h, true, true, false ); } if ( empty( $file_url ) ) { $file_url = $img[0]; } return array( $file_url, $img_w, $img_h, image_hwstring( $img_w, $img_h ) ); } /** * DT master get image function. * * @param $opts array * * @return string */ function dt_get_thumb_img( $opts = array() ) { global $post; $default_image = presscore_get_default_image(); $defaults = array( 'wrap' => '<a %HREF% %CLASS% %TITLE% %CUSTOM%><img %SRC% %IMG_CLASS% %SIZE% %ALT% %IMG_TITLE% /></a>', 'class' => '', 'alt' => '', 'title' => '', 'custom' => '', 'img_class' => '', 'img_title' => '', 'img_description' => '', 'img_caption' => '', 'href' => '', 'img_meta' => array(), 'img_id' => 0, 'options' => array(), 'default_img' => $default_image, 'prop' => false, 'lazy_loading' => false, 'lazy_class' => 'lazy-load', 'lazy_bg_class' => 'layzr-bg', 'echo' => true, ); $opts = wp_parse_args( $opts, $defaults ); $opts = apply_filters('dt_get_thumb_img-args', $opts); $original_image = null; if ( $opts['img_meta'] ) { $original_image = $opts['img_meta']; } elseif ( $opts['img_id'] ) { $original_image = wp_get_attachment_image_src( $opts['img_id'], 'full' ); } if ( !$original_image ) { $original_image = $opts['default_img']; } // proportion if ( $original_image && !empty($opts['prop']) && ( empty($opts['options']['h']) || empty($opts['options']['w']) ) ) { $_prop = $opts['prop']; $_img_meta = $original_image; if ( $_prop > 1 ) { $h = (int) floor((int) $_img_meta[1] / $_prop); $w = (int) floor($_prop * $h ); } else if ( $_prop < 1 ) { $w = (int) floor($_prop * $_img_meta[2]); $h = (int) floor($w / $_prop ); } else { $w = $h = min($_img_meta[1], $_img_meta[2]); } if ( !empty($opts['options']['w']) && $w ) { $__prop = $h / $w; $w = intval($opts['options']['w']); $h = intval(floor($__prop * $w)); } else if ( !empty($opts['options']['h']) && $h ) { $__prop = $w / $h; $h = intval($opts['options']['h']); $w = intval(floor($__prop * $h)); } $opts['options']['w'] = $w; $opts['options']['h'] = $h; } $src = ''; $hd_src = ''; $resized_image = $resized_image_hd = array(); if ( $opts['options'] ) { $resized_image = dt_get_resized_img( $original_image, $opts['options'], true, false ); $resized_image_hd = dt_get_resized_img( $original_image, $opts['options'], true, true ); $hd_src = $resized_image_hd[0]; $src = $resized_image[0]; if ( $resized_image_hd[0] === $resized_image[0] ) { $resized_image_hd = array(); } } else { $resized_image = $original_image; $src = $resized_image[0]; } if ( $img_id = absint( $opts['img_id'] ) ) { if ( '' === $opts['alt'] ) { $opts['alt'] = get_post_meta( $img_id, '_wp_attachment_image_alt', true ); } if ( '' === $opts['img_title'] ) { $opts['img_title'] = get_the_title( $img_id ); } } $href = $opts['href']; if ( !$href ) { $href = $original_image[0]; } $_width = $resized_image[1]; $_height = $resized_image[2]; if ( empty($resized_image[3]) || !is_string($resized_image[3]) ) { $size = image_hwstring( $_width, $_height ); } else { $size = $resized_image[3]; } $lazy_loading_src = "data:image/svg+xml,%3Csvg%20xmlns%3D&#39;http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg&#39;%20viewBox%3D&#39;0%200%20{$_width}%20{$_height}&#39;%2F%3E"; $lazy_loading = ! empty( $opts['lazy_loading'] ); $srcset_tpl = '%s %dw'; if ( $lazy_loading ) { $src = str_replace( array(' '), array('%20'), $src ); $hd_src = str_replace( array(' '), array('%20'), $hd_src ); $esc_src = esc_attr( $src ); $src_att = sprintf( $srcset_tpl, $esc_src, $resized_image[1] ); if ( $resized_image_hd ) { $src_att .= ', ' . sprintf( $srcset_tpl, esc_attr( $hd_src ), $resized_image_hd[1] ); } $src_att = 'src="' . $lazy_loading_src . '" data-src="' . $esc_src . '" data-srcset="' . $src_att . '"'; $opts['img_class'] .= ' ' . $opts['lazy_class']; $opts['class'] .= ' ' . $opts['lazy_bg_class']; } else { $src_att = sprintf( $srcset_tpl, $src, $resized_image[1] ); if ( $resized_image_hd ) { $src_att .= ', ' . sprintf( $srcset_tpl, $hd_src, $resized_image_hd[1] ); } $src_sizes = $resized_image[1] . 'px'; $src_att = 'src="' . esc_attr( $src ) . '" srcset="' . esc_attr( $src_att ) . '" sizes="' . esc_attr( $src_sizes ) . '"'; } $class = empty( $opts['class'] ) ? '' : 'class="' . esc_attr( trim($opts['class']) ) . '"'; $title = empty( $opts['title'] ) ? '' : 'title="' . esc_attr( trim($opts['title']) ) . '"'; $img_title = empty( $opts['img_title'] ) ? '' : 'title="' . esc_attr( trim($opts['img_title']) ) . '"'; $img_class = empty( $opts['img_class'] ) ? '' : 'class="' . esc_attr( trim($opts['img_class']) ) . '"'; $output = str_replace( array( '%HREF%', '%CLASS%', '%TITLE%', '%CUSTOM%', '%SRC%', '%IMG_CLASS%', '%SIZE%', '%ALT%', '%IMG_TITLE%', '%RAW_TITLE%', '%RAW_ALT%', '%RAW_IMG_TITLE%', '%RAW_IMG_DESCRIPTION%', '%RAW_IMG_CAPTION%' ), array( 'href="' . esc_url( $href ) . '"', $class, $title, strip_tags( $opts['custom'] ), $src_att, $img_class, $size, 'alt="' . esc_attr( $opts['alt'] ) . '"', $img_title, esc_attr( $opts['title'] ), esc_attr( $opts['alt'] ), esc_attr( $opts['img_title'] ), esc_attr( $opts['img_description'] ), esc_attr( $opts['img_caption'] ) ), $opts['wrap'] ); $output = apply_filters( 'dt_get_thumb_img-output', $output, $opts ); if ( $opts['echo'] ) { echo $output; return ''; } return $output; } /** * Load presscore template. * * @param $slug string * @param $name string */ function dt_get_template_part( $slug = '', $name = '' ) { if ( empty( $slug ) ) { return; } $dir_base = '/templates/'; get_template_part( $dir_base . $slug, $name ); } /** * Description here. * * @param $src string * * @return string * * @since presscore 0.1 */ function dt_get_of_uploaded_image( $src ) { if ( ! $src ) { return ''; } $uri = $src; if ( ! parse_url( $src, PHP_URL_SCHEME ) ) { if ( dt_maybe_uploaded_image_url( $src ) ) { $uri = site_url( $src ); } else { $uri = PRESSCORE_PRESET_BASE_URI . $src; } } return $uri; } function dt_maybe_uploaded_image_url( $url ) { $uploads = wp_upload_dir(); $baseurl = str_replace( site_url(), '', $uploads['baseurl'] ); $pattern = '/' . trailingslashit( basename( WP_CONTENT_URL ) ); return ( strpos( $url, $baseurl ) !== false || strpos( $url, $pattern ) !== false ); } /** * Parse str to array with src, width and height * expample: image.jpg?w=25&h=45 * * @param $str string * * @return array * * @since presscore 0.1 */ function dt_parse_of_uploaded_image_src ( $str ) { if ( empty( $str ) ) { return array(); } $res_arr = array(); $str_arr = explode( '?', $str ); $res_arr[0] = dt_get_of_uploaded_image( current( $str_arr ) ); // if no additional arguments specified if ( ! isset( $str_arr[1] ) ) { return array(); } $args_arr = array(); wp_parse_str( $str_arr[1], $args_arr ); if ( isset( $args_arr['w'] ) && isset( $args_arr['h'] ) ) { $res_arr[1] = intval( $args_arr['w'] ); $res_arr[2] = intval( $args_arr['h'] ); } else { return array(); } return $res_arr; } /** * Return prepeared logo attributes array or null. * * @param $logo array array( 'href', 'id' ) * @param $type string (normal/retina) * * @return mixed * * @since presscore 0.1 */ function dt_get_uploaded_logo( $logo, $type = 'normal' ) { if( empty( $logo ) || ! is_array( $logo ) ) { return null; } $res_arr = null; if ( next( $logo ) ) { $logo_src = wp_get_attachment_image_src( current( $logo ), 'full' ); } else { reset( $logo ); $logo_src = dt_parse_of_uploaded_image_src( current( $logo ) ); } if ( ! empty( $logo_src ) ) { if ( 'retina' === $type ) { $w = $logo_src[1]/2; $h = $logo_src[2]/2; } else { $w = $logo_src[1]; $h = $logo_src[2]; } $res_arr = array( 0 => $logo_src[0], 1 => $logo_src[1], 2 => $logo_src[2], 'src' => $logo_src[0], 'width' => $w, 'height' => $h, 'size' => image_hwstring( $w, $h ) ); } return $res_arr; } // TODO: refactor /** * Description here. * * @since presscore 0.1 */ function dt_get_google_fonts( $font = '', $effect = '' ) { if ( ! $font ) { return; } ?> <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=<?php echo str_replace( ' ', '+', $font ); ?>"> <?php } /** * Description here. * * @since presscore 0.1 */ function dt_make_web_font_uri( $font ) { if ( !$font ) { return false; } return '//fonts.googleapis.com/css?family=' . str_replace( ' ', '+', $font ); } /** * Create html tag. * * @return object. * * @since presscore 0.1 */ function dt_create_tag( $type, $options ) { switch( $type ) { case 'checkbox': return new DT_Mcheckbox( $options ); case 'radio': return new DT_Mradio( $options ); case 'select': return new DT_Mselect( $options ); case 'button': return new DT_Mbutton( $options ); case 'text': return new DT_Mtext( $options ); case 'textarea': return new DT_Mtextarea( $options ); case 'link': return new DT_Mlink( $options ); } } function the7_get_image_mime( $image ) { $ext = explode( '.', $image ); if ( count( $ext ) <= 1 ) { return ''; } $ext = end( $ext ); switch ( $ext ) { case 'png': return image_type_to_mime_type( IMAGETYPE_PNG ); case 'gif': return image_type_to_mime_type( IMAGETYPE_GIF ); case 'jpg': case 'jpeg': return image_type_to_mime_type( IMAGETYPE_JPEG ); case 'ico': return 'image/x-icon'; default: return ''; } } /** * Return current paged/page query var or 1 if it's empty. * * @since 7.1.1 * * @return int */ function the7_get_paged_var() { $pg = get_query_var( 'page' ); if ( ! $pg ) { $pg = get_query_var( 'paged' ); $pg = $pg ? $pg : 1; } /** * Filter the returned paged var. * * @since 7.1.1 * * @see the7_get_paged_var() * * @param int Paged var. */ return apply_filters( 'the7_get_paged_var', absint( $pg ) ); } /** * Get page template name. * * Return template name based on current post ID or empty string if fail's. * * @return string. */ function dt_get_template_name( $post_id = 0, $force_in_loop = false ) { global $post; // work in admin if ( is_admin() && !$force_in_loop ) { if ( isset($_GET['post']) ) { $post_id = $_GET['post']; } elseif( isset($_POST['post_ID']) ) { $post_id = $_POST['post_ID']; } } // work in the loop if ( !$post_id && isset($post->ID) ) { $post_id = $post->ID; } return get_post_meta( absint($post_id), '_wp_page_template', true ); } /** * Get theme metaboxes ids list. * * Loock global $wp_meta_boxes for metaboxes with theme related id prefix (by default 'dt_page_box'). * * @param $opts array. array('id', 'page'). * @return array. */ function dt_admin_get_metabox_list( $opts = array() ) { global $wp_meta_boxes; $defaults = array( 'id' => 'dt_page_box', 'page' => 'page' ); $opts = wp_parse_args( $opts, $defaults ); $meta_boxes = array(); foreach( array('side', 'normal') as $context ) { foreach( array('high', 'sorted', 'core', 'default', 'low') as $priority ) { if( isset($wp_meta_boxes[$opts['page']][$context][$priority]) ) { foreach ( (array) $wp_meta_boxes[$opts['page']][$context][$priority] as $id=>$box ) { if( false !== strpos( $id, $opts['id']) ) { $meta_boxes[] = $id; } } } } } return $meta_boxes; } /** * Prepare data for categorizer. * Returns array or false. * * @return mixed */ function dt_prepare_categorizer_data( array $opts ) { $defaults = array( 'taxonomy' => null, 'post_type' => null, 'all_btn' => true, 'other_btn' => true, 'select' => 'all', 'terms' => array(), 'post_ids' => array(), ); $opts = wp_parse_args( $opts, $defaults ); if( !($opts['taxonomy'] && $opts['post_type'] && is_array($opts['terms'])) ) { return false; } if ( !empty($opts['post_ids']) && 'all' != $opts['select'] ) { $opts['post_ids'] = array_map( 'intval', array_values($opts['post_ids']) ); $query_args = array( 'posts_per_page' => -1, 'post_status' => 'publish', 'post_type' => $opts['post_type'], 'suppress_filters' => false, ); if ( 'except' == $opts['select'] ) { $query_args['post__not_in'] = $opts['post_ids']; } if ( 'only' == $opts['select'] ) { $query_args['post__in'] = $opts['post_ids']; } // check if posts exists $check_posts = new WP_Query( $query_args ); if ( ! $check_posts->have_posts() ) { return false; } $opts['post_ids'] = wp_list_pluck( $check_posts->posts, 'ID' ); $posts_terms = wp_get_object_terms( $opts['post_ids'], $opts['taxonomy'], array( 'fields' => 'all_with_object_id' ) ); if( is_wp_error($posts_terms) ) { return false; } $opts['terms'] = wp_list_pluck( $posts_terms, 'term_id' ); $opts['select'] = 'only'; } $args = array( 'type' => $opts['post_type'], 'hide_empty' => true, 'hierarchical' => false, 'orderby' => 'slug', 'order' => 'ASC', 'taxonomy' => $opts['taxonomy'], 'pad_counts' => false, 'include' => array(), ); if ( isset( $opts['terms']['child_of'] ) ) { $args['child_of'] = $opts['terms']['child_of']; $args['hide_empty'] = 0; unset( $opts['terms']['child_of'] ); } if ( ! empty( $opts['terms'] ) ) { $terms_arr = array_map( 'intval', array_values( $opts['terms'] ) ); if ( 'except' == $opts['select'] ) { $args['exclude'] = $terms_arr; } if ( 'only' == $opts['select'] ) { $args['include'] = $terms_arr; } } /** * Filter get_categories() args. * * @since 6.8.0 * * @param array $args get_categories() args. */ $terms = get_categories( apply_filters( 'dt_prepare_categorizer_data_categories_args', $args ) ); return array( 'terms' => $terms, 'all_count' => false, 'other_count' => false, ); } /** * Get symplyfied post mime type. * * @param $post_id int * * @return string Mime type */ function dt_get_short_post_myme_type( $post_id = '' ) { $mime_type = get_post_mime_type( $post_id ); if ( $mime_type ) { $mime_type = current(explode('/', $mime_type)); } return $mime_type; } /** * Returns oembed generated html based on $src or false. * * @param $src string * @param $width mixed * @param $height mixed * * @return mixed. */ function dt_get_embed( $src, $width = '', $height = '' ) { $the7_embed = new The7_Embed( $src ); $the7_embed->set_width( $width ); $the7_embed->set_height( $height ); return $the7_embed->get_html(); } /** * Inner left join filter for query. * * @param $parts array * * @return array */ function dt_core_join_left_filter( $parts ) { if( isset($parts['join']) && !empty($parts['join']) ) { $parts['join'] = str_replace( 'INNER', 'LEFT', $parts['join']); } return $parts; } /** * Order sanitize filter. * * @param $order string * * @return string */ function dt_sanitize_order( $order = '' ) { return in_array($order, array('ASC', 'asc')) ? 'ASC' : 'DESC'; } add_filter( 'dt_sanitize_order', 'dt_sanitize_order', 15 ); /** * Orderby sanitize filter. * * @param $orderby string * * @return string */ function dt_sanitize_orderby( $orderby = '' ) { $orderby_values = array( 'none', 'ID', 'author', 'title', 'name', 'date', 'modified', 'parent', 'rand', 'comment_count', 'menu_order', 'meta_value', 'meta_value_num', 'post__in', ); return in_array($orderby, $orderby_values) ? $orderby : 'date'; } add_filter( 'dt_sanitize_orderby', 'dt_sanitize_orderby', 15 ); /** * Posts per page sanitize. * * @param $ppp mixed (string/integer) * * @return int */ function dt_sanitize_posts_per_page( $ppp = '', $max = -1 ) { $ppp = intval($ppp); return $ppp <= 0 || ($max > 0 && $ppp >= $max) ? -1 : $ppp; } add_filter('dt_sanitize_posts_per_page', 'dt_sanitize_posts_per_page', 15, 2); /** * Flag sanitize. * * @param $flag string * * @return boolean */ function dt_sanitize_flag( $flag = '' ) { return in_array($flag, array('1', 'true', 'y', 'on', 'enabled')); } add_filter( 'dt_sanitize_flag', 'dt_sanitize_flag', 15 ); /** * Get attachment data by id. * Source http://wordpress.org/ideas/topic/functions-to-get-an-attachments-caption-title-alt-description * * Return attachment meta array if $attachment_id is valid, other way return false. * * @param $attachment_id int * * @return mixed */ function dt_get_attachment( $attachment_id ) { $attachment = get_post( $attachment_id ); if ( !$attachment || is_wp_error($attachment) ) { return false; } return array( 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ), 'caption' => $attachment->post_excerpt, 'description' => $attachment->post_content, 'href' => get_permalink( $attachment->ID ), 'src' => $attachment->guid, 'title' => $attachment->post_title ); } /** * Check if current page is login page. * * @return boolean */ function dt_is_login_page() { return in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ); } /** * Get current admin page name. * * @return string */ function dt_get_current_page_name() { if ( isset($GLOBALS['pagenow']) && is_admin() ) { return $GLOBALS['pagenow']; } else { return false; } } /** * Count words based on wp_trim_words() function. * * @param $text string * @param $num_words int * * @return int */ function dt_count_words( $text, $num_words = 55 ) { $text = wp_strip_all_tags( $text ); /* translators: If your word count is based on single characters (East Asian characters), enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */ if ( 'characters' == _x( 'words', 'word count: words or characters?', 'the7mk2' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) { $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' ); preg_match_all( '/./u', $text, $words_array ); $words_array = array_slice( $words_array[0], 0, null ); } else { $words_array = preg_split( "/[\n\r\t ]+/", $text, -1, PREG_SPLIT_NO_EMPTY ); } return count( $words_array ); } /** * Simple function to print from the filter array. * * @see http://stackoverflow.com/questions/5224209/wordpress-how-do-i-get-all-the-registered-functions-for-the-content-filter */ function dt_print_filters_for( $hook = '' ) { global $wp_filter; if( empty( $hook ) || !isset( $wp_filter[$hook] ) ) { return; } print '<pre>'; print_r( $wp_filter[$hook] ); print '</pre>'; } /** * Get next post url. * * @param int $max_page Optional. Max page. * * @return string */ function dt_get_next_posts_url( $max_page = 0 ) { global $paged, $wp_query; if ( ! $paged = (int) get_query_var( 'page' ) ) { $paged = (int) get_query_var( 'paged' ); } if ( ! $max_page ) { $max_page = $wp_query->max_num_pages; } if ( ! $paged ) { $paged = 1; } $nextpage = (int) $paged + 1; if ( ! $max_page || $max_page >= $nextpage ) { return get_pagenum_link( $max_page ); } return ''; } function dt_is_woocommerce_enabled() { return class_exists( 'Woocommerce' ); } function dt_the7_core_is_enabled() { return function_exists( 'The7PT' ); } function dt_is_legacy_mode() { return Presscore_Modules_Legacy::is_legacy_mode_active(); } /** * @todo: Remove in 5.7.0 * * @deprecated * @return bool */ function dt_is_plugins_silenced() { return false; } function dt_make_image_src_ssl_friendly( $src ) { $ssl_friendly_src = (string) $src; if ( is_ssl() ) { $ssl_friendly_src = str_replace('http:', 'https:', $ssl_friendly_src); } return $ssl_friendly_src; } function dt_array_push_after( $src, $in, $pos ) { if ( is_int( $pos ) ) { $R = array_merge( array_slice( $src, 0, $pos + 1 ), $in, array_slice( $src, $pos+1 ) ); } else { foreach( $src as $k => $v ) { if ( is_int( $k ) ) { $R[] = $v; } else { $R[ $k ] = $v; } if ( $k === $pos ) { $R = array_merge( $R, $in ); } } } return $R; } function dt_plugin_dir_relative_path( $file ) { $regexp = array( '/\\\/', '/\/\//' ); $plugin_path = preg_replace( $regexp, '/', plugin_dir_path( $file ) ); $template_path = preg_replace( $regexp, '/', get_template_directory() ); $stylesheet_path = preg_replace( $regexp, '/', get_stylesheet_directory() ); return str_replace( array( $stylesheet_path, $template_path ), '', $plugin_path ); } function presscore_get_post_type_edit_link( $post_type, $text = null ) { $link = ''; if ( post_type_exists( $post_type ) ) { $link = '<a href="' . esc_url( add_query_arg( 'post_type', $post_type, get_admin_url() . 'edit.php' ) ) . '" target="_blank">' . ( $text ? $text : _x( 'Edit post type', 'backend', 'the7mk2' ) ) . '</a>'; } return $link; } if ( ! function_exists( 'presscore_config' ) ) : /** * @return Presscore_Config */ function presscore_config() { return Presscore_Config::get_instance(); } endif; if ( ! function_exists( 'presscore_get_template_part' ) ) : function presscore_get_template_part( $interface, $slug, $name = null, $args = array() ) { return presscore_template_manager()->get_template_part( $interface, $slug, $name, $args ); } endif; if ( ! function_exists( 'presscore_template_manager' ) ) : function presscore_template_manager() { static $instance = null; if ( null === $instance ) { $instance = new The7_Template_Manager(); } return $instance; } endif; if ( ! function_exists( 'presscore_query' ) ) : function presscore_query() { static $instance = null; if ( null === $instance ) { $instance = new The7_Query(); } return $instance; } endif; if ( ! function_exists( 'presscore_load_template' ) ) : function presscore_load_template( $_template_file, $args = array(), $require_once = true ) { return presscore_template_manager()->load_template( $_template_file, $args, $require_once ); } endif; function presscore_split_classes( $class ) { $classes = array(); if ( $class ) { if ( ! is_array( $class ) ) { $class = preg_split( '#\s+#', $class ); } $classes = array_map( 'esc_attr', $class ); } return $classes; } function presscore_sanitize_classes( $classes ) { $classes = array_map( 'esc_attr', $classes ); $classes = array_filter( $classes ); $classes = array_unique( $classes ); return $classes; } function presscore_theme_is_activated() { return ( 'yes' === get_site_option( 'the7_registered' ) ); } function presscore_activate_theme() { update_site_option( 'the7_registered', 'yes' ); do_action( 'the7_after_theme_activation' ); } function presscore_deactivate_theme() { delete_site_option( 'the7_registered' ); do_action( 'the7_after_theme_deactivation' ); } function presscore_delete_purchase_code() { delete_site_option( 'the7_purchase_code' ); } function presscore_get_purchase_code() { return get_site_option( 'the7_purchase_code' ); } function presscore_get_censored_purchase_code() { $code = presscore_get_purchase_code(); $starred_part = substr( $code, 4, -4 ); if ( $starred_part ) { $code = str_replace( $starred_part, str_repeat( '*', strlen( $starred_part ) ), $code ); } return $code; } /** * Wrapper for set_time_limit to see if it is enabled. * * @since 6.4.0 * @param int $limit Time limit. */ function the7_set_time_limit( $limit = 0 ) { if ( function_exists( 'set_time_limit' ) && false === strpos( ini_get( 'disable_functions' ), 'set_time_limit' ) && ! ini_get( 'safe_mode' ) ) { @set_time_limit( $limit ); // @codingStandardsIgnoreLine } } if ( ! function_exists( 'the7_get_theme_version' ) ): /** * Returns parent theme version. * * @TODO: Remove in 6.1.0 * * @deprecated * * @return false|string */ function the7_get_theme_version() { return THE7_VERSION; } endif; /** * Add a submenu page after specified submenu page. * * This function takes a capability which will be used to determine whether * or not a page is included in the menu. * * The function which is hooked in to handle the output of the page must check * that the user has the required capability as well. * * @since 7.0.0 * * @global array $submenu * @global array $menu * @global array $_wp_real_parent_file * @global bool $_wp_submenu_nopriv * @global array $_registered_pages * @global array $_parent_pages * * @param string $parent_slug The slug name for the parent menu (or the file name of a standard * WordPress admin page). * @param string $page_title The text to be displayed in the title tags of the page when the menu * is selected. * @param string $menu_title The text to be used for the menu. * @param string $capability The capability required for this menu to be displayed to the user. * @param string $menu_slug The slug name to refer to this menu by. Should be unique for this menu * and only include lowercase alphanumeric, dashes, and underscores characters * to be compatible with sanitize_key(). * @param callable $function The function to be called to output the content for this page. * @param string $insert_after Insert after menu item with that slug. * @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required. */ function the7_add_submenu_page_after( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function = '', $insert_after = '' ) { $hook = add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function ); if ( $hook && $insert_after ) { global $submenu; $menu_slug = plugin_basename( $menu_slug ); $new_submenu = array(); foreach ( $submenu[ $parent_slug ] as $i => $item ) { if ( $item[2] === $menu_slug ) { continue; } isset( $new_submenu[ $i ] ) ? $new_submenu[] = $item : $new_submenu[ $i ] = $item; if ( $item[2] === $insert_after ) { $new_submenu[] = array( $menu_title, $capability, $menu_slug, $page_title ); } } $submenu[ $parent_slug ] = $new_submenu; } return $hook; }
true
9166adf67bf6e7e36b7d36f189ed30406c3bae73
PHP
slualexvas/beejee-test-task
/app/core/Route.php
UTF-8
766
2.734375
3
[]
no_license
<?php class Route { static function start() { $controller_name = 'task'; $action_name = 'index'; if (!empty($_GET['c'])) $controller_name = $_GET['c']; if (!empty($_GET['a'])) $action_name = $_GET['a']; $controller_name = 'Controller_'.$controller_name; $controller_file = 'app/controllers/'.$controller_name.'.php'; if (file_exists($controller_file)) { include_once $controller_file; } else { throw new Exception('Controller not found!'); } $controller = new $controller_name; $action_name = 'action_'.$action_name; if(method_exists($controller_name, $action_name)) { $controller->$action_name(); } else { throw new Exception('Action not found!'); } } } ?>
true
3dc098b216669128b167e1d590f8852237792e87
PHP
DerManoMann/acache
/tests/Radebatz/ACache/Tests/NamespaceCacheTest.php
UTF-8
3,671
2.6875
3
[ "MIT" ]
permissive
<?php /* * This file is part of the ACache library. * * (c) Martin Rademacher <mano@radebatz.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Radebatz\ACache\Tests; use Radebatz\ACache\CacheInterface; use Radebatz\ACache\ArrayCache; use Radebatz\ACache\NamespaceCache; /** * NamespaceCache tests. * * @author Martin Rademacher <mano@radebatz.net> */ class NamespaceCacheTest extends CacheTest { /** * Provide cache instances for testing. */ public function cacheProvider() { return [ [new ArrayCache()], [new NamespaceCache(new ArrayCache(), 'other')], ]; } /** * Test namespace. * * @dataProvider cacheProvider */ public function testNamespace(CacheInterface $cache) { $this->doTestNamespace($cache); $this->doTestNamespace(new NamespaceCache($cache, 'super')); } /** * Do namespace tests. */ protected function doTestNamespace(CacheInterface $decoratedCache) { // ensure we are clean $decoratedCache->flush(); if ($decoratedCache instanceof NamespaceCache) { $decoratedCache->getCache()->flush(); } $cache = new NamespaceCache($decoratedCache, 'foo'); $this->assertFalse($cache->contains('yin')); $this->assertNull($cache->fetch('yin')); $this->assertTrue($cache->save('yin', 'yang')); $this->assertTrue($cache->contains('yin')); $this->assertEquals('yang', $cache->fetch('yin')); // check decorated cache to make sure there is a namespace in the name... $this->assertFalse($decoratedCache->contains('yin')); $this->assertTrue($cache->delete('yin')); $this->assertFalse($cache->contains('yin')); $this->assertNull($cache->fetch('yin')); $stats = $decoratedCache->getStats(); $this->assertEquals(0, $stats[CacheInterface::STATS_SIZE]); $this->assertTrue($cache->save('foo', 'bar')); $stats = $decoratedCache->getStats(); $this->assertEquals(1, $stats[CacheInterface::STATS_SIZE]); $cache->flush(); if ($stats = $decoratedCache->getStats()) { $this->assertFalse($cache->contains('foo')); $this->assertEquals(0, $stats[CacheInterface::STATS_SIZE]); } } /** * Test empty namespace. * * @dataProvider cacheProvider */ public function testEmptyNamespace(CacheInterface $cache) { // regular $this->doTestEmptyNamespace($cache); $this->doTestEmptyNamespace(new NamespaceCache($cache, 'super')); } /** * Do empty namespace tests. */ protected function doTestEmptyNamespace(CacheInterface $decoratedCache) { // ensure we are clean $decoratedCache->flush(); if ($decoratedCache instanceof NamespaceCache) { $decoratedCache->getCache()->flush(); } $cache = new NamespaceCache($decoratedCache); $this->assertFalse($cache->contains('yin')); $this->assertNull($cache->fetch('yin')); $this->assertTrue($cache->save('yin', 'yang')); $this->assertTrue($cache->contains('yin')); $this->assertEquals('yang', $cache->fetch('yin')); // check decorated cache as that should be the same $this->assertTrue($decoratedCache->contains('yin')); $cache->flush(); if ($stats = $decoratedCache->getStats()) { $this->assertFalse($cache->contains('foo')); $this->assertEquals(0, $stats[CacheInterface::STATS_SIZE]); } } }
true
dd2f8ad22157d7a60eeb46a2962cf39298daed5c
PHP
schummel/yii2-core
/helpers/ArrayHelper.php
UTF-8
4,333
2.921875
3
[]
no_license
<?php namespace yii\helpers; use Yii; use yii\base\Arrayable; use yii\helpers\BaseArrayHelper; class ArrayHelper extends BaseArrayHelper { /** * конвертим массив в postgres jsonb строку * * @param array $value * @return string */ public static function postgresStyleJsonEncode($value) { settype($value, 'array'); array_walk($value, function(&$item, $key) { $item = sprintf('"%s": "%s"', $key, $item); }); return '{' . implode(', ', $value) . '}'; } /** * конвертим массив в строку дял бд * для конвертации массива в postgres * * @param array $set * @return string */ public static function toPostgresArray($set) { settype($set, 'array'); // can be called with a scalar or array $result = array(); foreach ($set as $t) { $t = str_replace('"', '\\"', $t); // escape double quote if (! is_numeric($t)) // quote only non-numeric values $t = '"' . $t . '"'; $result[] = $t; } return '{' . implode(",", $result) . '}'; // format } /** * конвертим стркоу в массив php * для конвертации данных из postgres * * @param string $string - строка из постгреса {"a","b"} * @return array */ public static function toPhpArray($string) { $result = []; $items = (str_getcsv(trim($string, '[2:2]={}'))); if(! $items){ return $result; } foreach ($items as $key => $string){ $result[] = trim($string, '{\"}'); } return $result; } /** * @inheritdoc */ public static function toArray($object, $properties = [], $recursive = true, $expands = []) { if (is_array($object)) { if ($recursive) { foreach ($object as $key => $value) { if (is_array($value) || is_object($value)) { if(is_int($key)){ $expand = $expands; }elseif (isset ($expands[$key])) { $expand = $expands[$key]; } else { $expand = []; } $object[$key] = static::toArray($value, $properties, true, $expand); } } } return $object; } elseif (is_object($object)) { if (!empty($properties)) { $className = get_class($object); if (!empty($properties[$className])) { $result = []; foreach ($properties[$className] as $key => $name) { if (is_int($key)) { $result[$name] = $object->$name; } else { $result[$key] = static::getValue($object, $name); } } return $recursive ? static::toArray($result, $properties) : $result; } } if ($object instanceof Arrayable) { $result = $object->toArray([], $expands, $recursive); } else { $result = []; foreach ($object as $key => $value) { $result[$key] = $value; } } return $recursive ? static::toArray($result, [], true, $expands) : $result; } else { return [$object]; } } /** * Возвращает массив элементов имеющих пустые значения * * @param array $array * @return array */ public static function getEmptyValues($array) { if(! is_array($array)){ return []; } return array_filter($array , function($v){ if(is_array($v)){ return self::getEmptyValues($v); } if(! $v){ return true; } return false; }); } }
true
70a3db40965a94d75d2b721ba3d59574f941183e
PHP
carlosblinf/gestioner-api
/app/Persona.php
UTF-8
1,071
2.578125
3
[ "MIT" ]
permissive
<?php namespace App; use App\Activity; use App\Structure; use App\Department; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Persona extends Model { use SoftDeletes; protected $dates = ['delete_at']; const PERSONA_MEMBER = 'true'; const PERSONA_NO_MEMBER = 'false'; protected $fillable = [ 'name', 'lastname','ci', 'address', 'gender', 'phone', 'celphone', 'email', 'civil_status', 'date_birth', 'ocupations', 'professions', 'desease', 'celula', 'member', 'department_id', ]; public function setEmailAttribute($valor){ $this->attributes['email'] = strtolower($valor); } public function isMember(){ return $this->member == Persona::PERSONA_MEMBER; } public function departments(){ return $this->belongsTo(Department::class); } public function activities(){ return $this->belongsToMany(Activity::class); } public function structures(){ return $this->belongsToMany(Structure::class); } }
true
6c8b1621329bc51f602615e1e62c353d0c2066c2
PHP
dbetm/cursoPHP
/Examples/ficha.php
UTF-8
391
2.734375
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Ficha</title> </head> <body> <h1>Ficha con datos</h1> <?php echo "Su nombre es: ".$_POST['txtname']; echo "<br />"; echo "Su apellido es: ".$_POST['txtlastname']."."; echo "<br />"; echo "Su contraseña tiene: ".strlen($_POST['txtpass'])." caracteres."; ?> </body> </html>
true
966b9aa69fcb3067649df499699089d515e68c58
PHP
brngylni/phplearn
/file_operations/ftruncate.php
UTF-8
732
3.390625
3
[]
no_license
<!doctype html> <html lang="tr-TR"> <head> <meta http-equiv="Content-Type" content="text/html" charset="utf-8"> <meta http-equiv="Content-Language" content="tr"> <meta charset="utf-8"> <title></title> </head> <body> <?php /* fwrite() : It is using to delete the content that coming after the specified character in a specified file.It can also return the result as a boolean value. */ $file = "folder/file.txt"; $fileOpen = fopen($file, "a"); $totalCharNum = 0; ftruncate($fileOpen, 0); // Removed whole file content. fclose($fileOpen); $fileOpen = fopen($file, "r"); while(!feof($fileOpen)){ $chars = fgetc($fileOpen); $totalCharNum++; } echo $totalCharNum . " characters remained."; ?> </body> </html>
true
cc89fe21f84ecabf21298f032bf7ad913662c7d3
PHP
russpos/google-drive-utils
/phplib/Auth/Loader.php
UTF-8
5,417
2.921875
3
[]
no_license
<?php namespace Russpos\GoogleDriveUtils\Auth; use Russpos\GoogleDriveUtils\Util; class Loader { private $client_data; private $scope; private $with_redirect = false; private $redirect_params; private $token_store = null; private $loader; const RESPONSE_TYPE_TOKEN = "token"; const RESPONSE_TYPE_CODE = "code"; /** * __construct * Creates a new Auth/Loader * @param ClientData $client_data ClientData object of the application you are loading authorization for * @param TokenStorageInterface $token_store Cache where this token should be stored. * Check here first, and also store it here if its not present. * @param Scope $scope The scope you are attempting to load authorization for * @access public */ public function __construct(ClientData $client_data, TokenStorageInterface $token_store, Scope $scope) { $this->token_store = $token_store; $this->scope = $scope; $this->client_data = $client_data; } /** * enableRedirect * Sets flag so that we load auth via a redirect mechanism * @access public * @return void */ public function enableRedirect() { $this->with_redirect = true; } /** * getAuthURL * Gets the auth URL for the given redirect * @access private * @return string URL as a string to send user to authorize this application */ private function getAuthURL() : string { $payload = [ "client_id" => $this->client_data->getClientId(), "scope" => $this->scope->toString(), ]; if ($this->with_redirect) { $redirect = $this->client_data->getRedirectUri(1); $payload['response_type'] = self::RESPONSE_TYPE_TOKEN; } else { $redirect = $this->client_data->getRedirectUri(0); $payload['response_type'] = self::RESPONSE_TYPE_CODE; } $payload["redirect_uri"] = (empty($this->redirect_params)) ? $redirect : $redirect.'?'.http_build_query($this->redirect_params); return $this->client_data->getAuthURI(). '?'. http_build_query($payload); } /** * getTokenWithInterface * Returns a Token object, with user authorization happening through the provided interface * @param UserInterface $ui The user interface through which the authorization takes place * @param boolean $allow_retry Attempt to retry authorization if token cannot be refreshed * @access public * @return Token Token data - either from the cache or fetched from the server */ public function getTokenWithInterface(UserInterface $ui, bool $allow_retry = true) : Token { try { $token = $this->token_store->loadToken($this); } catch (NoTokenStoredException $e) { $code = $ui->triggerUserApplicationAuthorizationFromUrl($this->getAuthURL()); $token = $this->exchangeCodeForToken($code); } try { $token->ensureFresh(); } catch (CannotRefreshTokenException $e) { if ($allow_retry) { return $this->getTokenWithInterface($ui, false); } throw $e; } $this->token_store->storeToken($token); return $token; } public function refreshToken(Token $auth_token) : Token { $url = $this->getTokenUrl(); $payload = $this->getTokenRefreshPayloadForToken($auth_token); $request = Util\Request::post($url, $payload); $response = $request->exec(); $token_data_as_array = $response->getJSONBody(); $new_token = new Token($this, $token_data_as_array); $this->token_store->storeToken($new_token); return $new_token; } private function exchangeCodeForToken(AccessCode $code) : Token { $url = $this->getTokenUrl(); $payload = $this->getTokenPayloadForAccessCode($code); $request = Util\Request::post($url, $payload); $response = $request->exec(); $token_data_as_array = $response->getJSONBody(); return new Token($this, $token_data_as_array); } private function getTokenUrl() : string { return $this->client_data->getTokenURI(); } private function getTokenPayloadForAccessCode(AccessCode $code) : array { $payload = [ "code" => $code->toString(), "client_id" => $this->client_data->getClientId(), "client_secret" => $this->client_data->getClientSecret(), "scope" => $this->scope->toString(), "grant_type" => "authorization_code", ]; if ($this->with_redirect) { $payload["redirect_uri"] = $this->client_data->getRedirectUri(1); } else { $payload["redirect_uri"] = $this->client_data->getRedirectUri(0); } return $payload; } private function getTokenRefreshPayloadForToken(Token $token) : array { $refresh = $token->getRefreshToken(); if (empty($refresh)) { throw new CannotRefreshTokenException(); } return [ "refresh_token" => $token->getRefreshToken(), "client_id" => $this->client_data->getClientId(), "client_secret" => $this->client_data->getClientSecret(), "grant_type" => "refresh_token", ]; } }
true
bcbbcd78eeaf60aacee4de2ec2230ce9b13244d0
PHP
abivia/hydration
/test/objects/Synthetic.php
UTF-8
1,583
2.8125
3
[ "MIT" ]
permissive
<?php /** @noinspection ALL */ namespace Abivia\Hydration\Test\Objects; use Abivia\Hydration\Hydratable; use Abivia\Hydration\HydrationException; use Abivia\Hydration\Hydrator; use Abivia\Hydration\Property; use JsonSerializable; use ReflectionException; class Synthetic implements Hydratable, JsonSerializable { public array $a1 = []; private static Hydrator $hydrator; /** @noinspection PhpUnused */ public function getSynth(Property $property) { $source = explode('.', $property->source()); return $this->a1[$source[1]]; } /** * @param mixed $config * @param array $options * @return bool * @throws HydrationException * @throws ReflectionException */ public function hydrate($config, $options = []): bool { self::$hydrator = Hydrator::make() ->addProperties( ['synthetic.one', 'synthetic.two'], [ 'getter' => 'getSynth', 'setter' => 'setSynth', ] ) ->bind(self::class, 0); self::$hydrator->hydrate($this, $config); return true; } /** * @throws ReflectionException * @throws HydrationException */ public function jsonSerialize() { return self::$hydrator->encode($this); } /** @noinspection PhpUnused */ public function setSynth($value, Property $property): bool { $source = explode('.', $property->source()); $this->a1[$source[1]] = $value; return true; } }
true
7cf2f40a7430944d6698e2846efad49fb0e36974
PHP
christian-kramer/OverTheWire-Wargames
/Natas/natas17.php
UTF-8
1,461
3.03125
3
[]
no_license
<?php function get($url) { $username = "natas17"; $password = "8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw"; $string = base64_encode("$username:$password"); $options = [ 'http' => [ 'header' => "Content-Type: application/x-www-form-urlencoded\r\n" . "authorization: Basic $string", 'method' => 'GET' ] ]; $context = stream_context_create($options); $raw_response = file_get_contents($url, false, $context); return $raw_response; } $c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $library = ''; for ($i = 0; $i < strlen($c); $i++) { $character = $c[$i]; $query = urlencode("natas18\" AND IF(password LIKE BINARY \"%$character%\", sleep(5), null) #"); $start = time(); $r = get("http://natas17.natas.labs.overthewire.org/index.php?username=$query"); $end = time(); if ($end - $start > 4) { $library .= $character; } } var_dump($library); $password = ''; for ($i = 0; $i < 32; $i++) { for ($j = 0; $j < strlen($library); $j++) { $character = $library[$j]; $query = urlencode("natas18\" AND IF(password LIKE BINARY \"$password$character%\", sleep(5), null) #"); $start = time(); $r = get("http://natas17.natas.labs.overthewire.org/index.php?username=$query"); $end = time(); if ($end - $start > 4) { $password .= $character; echo "$password\n"; } } }
true
efdf1ee141858bc66b2d6999cc7542a7cf3197a3
PHP
josendulip/outroQuarto
/app/Models/Role.php
UTF-8
966
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use App\Traits\HasPermissions; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Role extends Model { use HasFactory, HasPermissions; public function permissions() { return $this->belongsToMany(Permission::class, 'roles_permissions'); } public function hasPermissionTo(...$permissions) { //role->hasPermissionTo ('edit-user', 'edit-issue') return $this->permissions()->whereIn('slug', $permissions)->count(); } //Este funcao serviu para colocar no Model do registar ao inves de fazer la. public function scopeDeveloper($query) { return $query->where('slug', 'developer'); } public function scopeAdmin($query) { return $query->where('slug', 'admin'); } public function scopeVendor($query) { return $query->where('slug', 'vendor'); } }
true
e7fecae68ce36cd12c1ad8515bf439432ea3037b
PHP
steverobinett/php-data-stack
/application/util/formattingUtils.php
UTF-8
400
3.359375
3
[]
no_license
<?php // expect 2 dim array and retunr as a formatted table function buildHTMLTable($dataSet){ $tblHTML = "<table class='cleanTbl'>"; foreach ($dataSet as $row) { $tblHTML = $tblHTML."<tr class='cleanTbl'>"; foreach($row as $col){ $tblHTML = $tblHTML."<td class='cleanTbl'>$col</td>"; } $tblHTML = $tblHTML."</tr>"; } $tblHTML = $tblHTML."</table>"; return $tblHTML; }
true
cfaaee2146c2cbb08927f9f9173ea38e1e455c3f
PHP
ex3mlyfab/applicant
/app/Models/WardModel.php
UTF-8
784
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; class WardModel extends Model { protected $guarded = []; public function beds(): HasMany { return $this->hasMany(Bed::class); } public function floor(): BelongsTo { return $this->belongsTo(Floor::class); } public function getBedStatusAttribute() { return $this->beds->filter(function($item){ return $item['status'] == 'occupied'; })->count(); } public function getUnoccupiedBedAttribute() { return $this->beds->filter(function($item){ return $item['status'] != 'occupied'; }); } }
true
cb0e67e4e9fc327c5e37e7c2288a6b4b62fb2c41
PHP
corporate-ngp/beeryde
/modules/Api/Models/Rating.php
UTF-8
997
2.609375
3
[ "MIT" ]
permissive
<?php /** * To present Rating Model with associated authentication * * @author Nilesh G. Pangul <nileshgpangul@gmail.com> * @package Api */ namespace Modules\Api\Models; use Modules\Api\Models\BaseModel; class Rating extends BaseModel { public $timestamps = false; /** * The database collection used by the model. * * @var string */ protected $collection = 'ratings'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = array('group_code', 'ratings_by', 'ratings_to', 'ratings'); /** * used to join with Modules\Admin\Models\User * * @return user */ public function givenByUser() { return $this->belongsTo('\Modules\Api\Models\User', 'ratings_by'); } /** * used to join with Modules\Admin\Models\User * * @return user */ public function givenToUser() { return $this->belongsTo('\Modules\Api\Models\User', 'ratings_to'); } }
true
b5e5a8e26c3106c3d6c222fa94a929f59588cd2f
PHP
mxs-dev/JournalBackend
/public/migrations/m180405_101046_add_academic_year_table.php
UTF-8
1,048
2.515625
3
[]
no_license
<?php use yii\db\Expression; use yii\db\Schema; use yii\db\Migration; class m180405_101046_add_academic_year_table extends Migration { public static $tableName = 'academic_year'; public function safeUp() { $this->createTable(static::$tableName, [ 'id' => $this->primaryKey()->unsigned(), 'title' => $this->string('10'), 'startDate' => $this->date(), 'endDate' => $this->date(), 'createdAt' => $this->dateTime()->defaultExpression('NOW()'), 'updatedAt' => $this->dateTime()->defaultExpression('NOW()'), 'createdBy' => $this->integer(11)->unsigned(), 'updatedBy' => $this->integer(11)->unsigned() ]); $this->createIndex( 'idx-academic_year', static::$tableName, ['title', 'startDate', 'endDate'] ); } public function safeDown() { $this->dropIndex('idx-academic_year', static::$tableName); $this->dropTable(static::$tableName); } }
true
e669d8197400d4b81ce366057dc306d99af7e091
PHP
Gimalca/zebra_ml
/module/Application/src/Application/Model/Dao/UserDao.php
UTF-8
3,935
2.546875
3
[]
no_license
<?php namespace Application\Model\Dao; use Zend\Db\Sql\Sql; use Zend\Db\TableGateway\TableGateway; use Application\Model\Entity\User; use Application\Model\Entity\BankTransmitter; use Application\Model\Entity\State; use Application\Model\Entity\PaymentMethod; use Application\Model\Entity\ShippingMethod; use Application\Model\Entity\ShippingCourierService; use Application\Model\Dao\BankTransmitterDao; use Application\Model\Dao\StateDao; use Application\Model\Dao\PaymentMethodDao; use Application\Model\Dao\ShippingMethodDao; use Application\Model\Dao\ShippingCourierServiceDao; /** * */ class UserDao { protected $tableGateway; public $user_id; public function __construct(TableGateway $tablegateway) { $this->tableGateway = $tablegateway; } public function saveUser($data) { return $this->tableGateway->insert($data); } public function guardarUser($data) { $idData = $data['user_id']; $id = (int) $idData; if ($id == 0) { $this->tableGateway->insert($data); } else { if ($this->obtenerPorId($id)) { return $this->tableGateway->update($data, array('user_id' => $id)); } else { throw new \Exception('El Formulario no Existe'); } } } public function obtenerPorId($id) { $user_id = (int) $id; $rowset = $this->tableGateway->select(array('user_id' => $user_id)); $row = $rowset->current(); if (!$row) { throw new \Exception("El Usuario no Existe"); } return $row; } public function getAll() { $query = $this->tableGateway->getSql()->select(); $query->order("user_id DESC"); //echo $query->getSqlString();die; $resultSet = $this->tableGateway->selectWith($query); //var_dump($resultSet);die; return $resultSet; } public function saveUser(User $data) { if ($productId == 0) { // insert Product Table $sProduct = $this->tableGateway->insert($data_product); if ($sProduct) { $productId = $this->tableGateway->getLastInsertValue(); // Insert Product Description $sDescription = $this->saveProductDescription($productId, $data_product_description); // Insert Images $sImage = $this->saveProductImage($productId, $data_product_image); // insert Url Alias $sUrlAlias = $this->saveUrlAlias($productId, $data_product_urlAlias); // insert Categories $sUrlAlias = $this->saveProductCategories($productId, $data_product_categories); return $productId; } else { throw new \Exception('Form id does not exist'); } } else { if ($this->getById($productId)) { $data_product['date_modified'] = date("Y-m-d H:i:s"); //print_r($data_product);die; $this->tableGateway->update($data_product, array( 'product_id' => $productId, )); // update Product Description $sDescription = $this->saveProductDescription($productId, $data_product_description, 1); // update Images ( AJAX ) //$sImage = $this->saveProductImage($productId, $data_product_image); // update Url Alias $sUrlAlias = $this->saveUrlAlias($productId, $data_product_urlAlias, 1); // update Categories $sUrlAlias = $this->saveProductCategories($productId, $data_product_categories, 1); return $productId; } else { throw new \Exception('Form id does not exist'); } } } }
true
875a2ae8821fdaa06c04266e9efa8ea987bf33dc
PHP
dede-amdp/polibook
/php/search.php
UTF-8
6,274
2.75
3
[]
no_license
<?php //<!-- FUNZIONE CHE GENERA UN ARRAY CONTENETE TUTTE LE INFO RICERCATE--> echo json_encode(getRisultati()); function getRisultati() { require_once '../php/dbh.inc.php'; $conn= open_conn(); if($conn){ //prende i dati inseriti in input alla richiesta $inputs = json_decode(file_get_contents('php://input'), true); $anno = mysqli_real_escape_string($conn, $inputs['anno']); $dipartimento = mysqli_real_escape_string($conn, $inputs['dipartimento']); $docente = mysqli_real_escape_string($conn, $inputs['docente']); $attDid = mysqli_real_escape_string($conn, $inputs['attDid']); $cdl = mysqli_real_escape_string($conn, $inputs['cdl']); //dichiaro una variabile di tipo array che conterrà tutti i cdl e gli esami $risultati = array(); //verifico che almeno uno dei valori sia stato inserito per effettuare la ricerca if (isset($anno) || isset($dipartimento) || isset($docente) || isset($attDid) || isset($cdl)){ $tabellone = 'SELECT cdl.id as id_cdl, id_corso, attivita_didattica.id, ordinamento, docente.id as id_docente, facolta.id as id_facolta, cfu, docente.nome as nome_docente, docente.cognome as cognome_docente, facolta.nome as nome_facolta, attivita_didattica.nome as nome_attdid, cdl.nome as nome_cdl FROM attdid_cdl JOIN attivita_didattica JOIN esame JOIN facolta JOIN cdl JOIN docente ON attivita_didattica.id = attdid_cdl.id_attdid AND attivita_didattica.ordinamento = attdid_cdl.ord_attdid AND attdid_cdl.id_cdl = cdl.id AND cdl.id_facolta = facolta.id AND esame.id_attdid = attivita_didattica.id AND esame.ord_attdid = attivita_didattica.ordinamento AND esame.id_docente = docente.id '; $query_ord = 'LOWER(ordinamento) = LOWER(?)'; $query_dip = 'LOWER(facolta.nome) = LOWER(?)'; $query_doc = 'LOWER(CONCAT(docente.nome, docente.cognome)) = LOWER(?) OR LOWER(CONCAT(docente.cognome, docente.nome)) = LOWER(?)'; $query_attdid = 'LOWER(attivita_didattica.nome) = LOWER(?)'; $query_cdl = 'LOWER(cdl.nome) = LOWER(?)'; $query = ''; $vals = array(); //costruisco la query a seconda dei dati che mi servono if ($anno != ''){ $semiquery = '('.$tabellone.' WHERE '.$query_ord.') ordinamento'; if(strlen($query) <= 0){ $query = 'SELECT DISTINCT ordinamento.* FROM '.$semiquery; }else{ $query .= ' NATURAL JOIN '.$semiquery; // se ho già una parte di query (ovvero l'utente ha inserito più di un dato) allora fai l'intersezione tra i risultati } array_push($vals, $anno); } if ($dipartimento != ''){ $semiquery = '('.$tabellone.' WHERE '.$query_dip.') dipartimento'; if(strlen($query) <= 0){ $query = 'SELECT DISTINCT dipartimento.* FROM '.$semiquery; }else{ $query .= ' NATURAL JOIN '.$semiquery; } array_push($vals, $dipartimento); } if ($docente != ''){ $semiquery = '('.$tabellone.' WHERE '.$query_doc.') prof'; if(strlen($query) <= 0){ $query = 'SELECT DISTINCT prof.* FROM '.$semiquery; }else{ $query .= ' NATURAL JOIN '.$semiquery; } array_push($vals, $docente, $docente); } if ($attDid != ''){ $semiquery = '('.$tabellone.' WHERE '.$query_attdid.') attdid'; if(strlen($query) <= 0){ $query = 'SELECT DISTINCT attdid.* FROM '.$semiquery; }else{ $query .= ' NATURAL JOIN '.$semiquery; } array_push($vals, $attDid); } if ($cdl != ''){ $semiquery = '('.$tabellone.' WHERE '.$query_cdl.') corsodl'; if(strlen($query) <= 0){ $query = 'SELECT DISTINCT corsodl.* FROM '.$semiquery; }else{ $query .= ' NATURAL JOIN '.$semiquery; } array_push($vals, $cdl); } // eseguo la query $risultati = fetch_DB($conn, $query, ...$vals); $data = array(); while($risultati && $row = mysqli_fetch_assoc($risultati)){ array_push($data, $row); } if (isset($cdl) || isset($dipartimento)){ // cerca solo i cdl e aggiungili in coda $query = 'SELECT facolta.nome as nome_facolta, cdl.nome as nome_cdl, facolta.id as id_facolta, cdl.id as id_cdl FROM cdl JOIN facolta ON id_facolta = facolta.id WHERE LOWER(cdl.nome)=LOWER(?) OR LOWER(facolta.nome) = LOWER(?);'; $risultati = fetch_DB($conn, $query, $cdl, $dipartimento); while($risultati && $row = mysqli_fetch_assoc($risultati)){ array_push($data, $row); } } $conn -> close(); return $data; }else{ return null; } } }//fine funzione ?>
true
00e710a8fe06ff2211125877950133496e0477f3
PHP
krystiangonczi/whereiscash
/src/Controller/Controller.php
UTF-8
2,409
2.78125
3
[]
no_license
<?php namespace d0niek\Whereiscash\Controller; use d0niek\Whereiscash\Core\DependenceInjectionInterface; use d0niek\Whereiscash\Http\Response\HtmlResponse; use d0niek\Whereiscash\Http\Response\RedirectResponse; use d0niek\Whereiscash\Http\ResponseInterface; use d0niek\Whereiscash\Model\Route; use Ds\Map; /** * @author Damian Glinkowski <damianglinkowski@gmail.com> */ abstract class Controller { /** * @var \d0niek\Whereiscash\Http\RequestInterface */ protected $request; /** * @var \d0niek\Whereiscash\Http\SessionInterface */ protected $session; /** * @var \d0niek\Whereiscash\Model\Route */ protected $route; /** * @var \d0niek\Whereiscash\Core\DependenceInjectionInterface */ private $di; /** * @var string */ private $viewPath; /** * Controller constructor. * * @param \d0niek\Whereiscash\Core\DependenceInjectionInterface $di * @param \d0niek\Whereiscash\Model\Route $route * @param string $viewPath */ public function __construct( DependenceInjectionInterface $di, Route $route, string $viewPath ) { $this->di = $di; $this->route = $route; $this->viewPath = $viewPath; $this->request = $this->di->get('request'); $this->session = $this->di->get('session'); } /** * @return \d0niek\Whereiscash\Http\ResponseInterface */ abstract public function execute(): ResponseInterface; /** * @param string $template * @param \Ds\Map $parameters * * @return \d0niek\Whereiscash\Http\Response\HtmlResponse */ protected function render(string $template, Map $parameters = null): HtmlResponse { if ($parameters === null) { $parameters = new Map(); } $parameters->put('user', $this->di->get('user')); return new HtmlResponse($this->viewPath, $template, $parameters, $this->session); } /** * @param string $redirectUrl * * @return \d0niek\Whereiscash\Http\Response\RedirectResponse */ protected function redirect(string $redirectUrl): RedirectResponse { return new RedirectResponse($redirectUrl); } /** * @param string $serviceName * * @return mixed */ protected function get(string $serviceName) { return $this->di->get($serviceName); } }
true
73012f438578b6b125d8787367a4cea3796cae7f
PHP
kx13vip/Yshop
/code/140-142/14001.php
UTF-8
1,264
2.9375
3
[]
no_license
<?php header("content-type:text/html;charset=utf-8"); /** * 最后一个月,2016.9.9号前弄完商城项目;PHP入门就算结束!Come On Go! * @authors Your Name (you@example.org) * @date 2016-08-11 08:45:54 * @version $Id$ */ //=========================140-文件操作案例之导入csv文件======================= /*** 批量处理文件内容 把小于10字节的文件,和含有fuck的文件删除掉 思路: 循环文件名 判断大小 filesize 如果<10,删. 如果不小于,读内容,判断是否有f**k单词, 如果有, 用unlink来删除.rmdir删除目录; ***/ $arr = array('a.txt' , 'b.txt' , 'c.txt' , 'd.txt'); foreach ($arr as $v){ $file = './140article/'.$v; //判断大小 if ((filesize($file)) < 10) { unlink($file); echo $file,'有小于10字节的被删除了<br />'; continue; } $cont = file_get_contents($file); if (stripos($cont,'fuck')!==false) {//如果不写!==false,会出错吗? unlink($file); echo $file,'有不文明用语被删除了'; } } /** 如果这个目录有很多文件 想把一个目录下的文件 都打印出来 a.txt b.txt j.exe japan.avi aa.bmp **/ // 匹配文件,把txt后缀的文件找出来,返回数组 //print_r(glob('./article/*.txt')); ?>
true
48760568d1b8a7f2ea133def5a27dd0155f8e1ce
PHP
SequentSoft/ThreadFlow
/src/Contracts/Session/SessionStoreInterface.php
UTF-8
336
2.546875
3
[ "MIT" ]
permissive
<?php namespace SequentSoft\ThreadFlow\Contracts\Session; use SequentSoft\ThreadFlow\Contracts\Chat\MessageContextInterface; interface SessionStoreInterface { public function load(MessageContextInterface $context): SessionInterface; public function save(MessageContextInterface $context, SessionInterface $session): void; }
true
7352b3a930d1355da4008cb5fb19406874271952
PHP
Alexxosipov/courseplatform
/app/Models/Course.php
UTF-8
2,017
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; /** * App\Models\Course * * @property int $id * @property int|null $team_id * @property int $type_id * @property string|null $name * @property string|null $description * @property string|null $uri * @property int $is_active * @property \Illuminate\Support\Carbon|null $created_at * @property \Illuminate\Support\Carbon|null $updated_at * @property-read \Illuminate\Database\Eloquent\Collection|\App\Models\CourseCategory[] $categories * @property-read int|null $categories_count * @property-read \App\Models\Team|null $team * @method static \Illuminate\Database\Eloquent\Builder|Course newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|Course newQuery() * @method static \Illuminate\Database\Eloquent\Builder|Course query() * @method static \Illuminate\Database\Eloquent\Builder|Course whereCreatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereDescription($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereId($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereIsActive($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereName($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereTeamId($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereTypeId($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereUpdatedAt($value) * @method static \Illuminate\Database\Eloquent\Builder|Course whereUri($value) * @mixin \Eloquent */ class Course extends Model { use HasFactory; protected $fillable = [ 'name', 'description', 'uri', 'is_active', ]; public function team() { return $this->belongsTo(Team::class); } public function categories() { return $this->belongsToMany(CourseCategory::class); } }
true
b723e049ecb093ae04237d0e817103e5702bf483
PHP
bigroski/bigroski
/classes/site_config.php
UTF-8
4,470
2.78125
3
[]
no_license
<?php class Site_Config{ public static function fileCreate(){ $fp = fopen('../globalinc/g_db_config.php','w'); $string = '<?php $config[host]="'.$_POST[host].'"; $config[username]="'.$_POST[username].'"; $config[password]="'.$_POST[password].'"; $config[database]="'.$_POST[database].'"; ?>'; $fw = fwrite($fp,$string); fclose($fp); //self::importDb($_POST[database]); } /* * Creates A g_db_config.ini file */ public function importDb($db){ // mysql db_name < backup-file.sql //echo "c:/wamp/mysql/bin/mysql --host=$_POST[host] --user=$_POST[username] --password=$_POST[password] $db < ../globalinc/datab.sql"; $mysqlImportFilename ='../globalinc/datab.sql'; //passthru("mysql --host=$_POST[host] --user=$_POST[username] --password=$_POST[password] $db < ../globalinc/datab.sql", $r); echo $command='mysql -h' .$_POST[host] .' -u' .$_POST[username] .' -p' .$_POST[password] .' ' .$db .' < ' .$mysqlImportFilename; exec($command,$output=array(),$worked); var_dump($worked); switch($worked){ case 0: echo 'Import file <b>' .$mysqlImportFilename .'</b> successfully imported to database <b>' .$mysqlDatabaseName .'</b>'; break; case 1: echo 'There was an error during import. Please make sure the import file is saved in the same folder as this script and check your values:<br/><br/><table><tr><td>MySQL Database Name:</td><td><b>' .$db .'</b></td></tr><tr><td>MySQL User Name:</td><td><b>' .$_POST[username] .'</b></td></tr><tr><td>MySQL Password:</td><td><b>NOTSHOWN</b></td></tr><tr><td>MySQL Host Name:</td><td><b>' .$_POST[host] .'</b></td></tr><tr><td>MySQL Import Filename:</td><td><b>' .$mysqlImportFilename .'</b></td></tr></table>'; break; } } public static function create_db_config(){ global $obj; if(isset($_POST['btn_create_db'])&&$_POST['btn_create_db']!=""){ //echo 'Creating Database'; if(empty($_POST['host'])||empty($_POST['username'])){ Page_finder::set_message("Unable To perform Request. Please Refill Form",'error.png'); $url = 'index.php'; Page_finder::redirect_static($url); }else{ self::fileCreate(); $url = 'index.php'; Page_finder::redirect_static($url); } }else{ echo '<body style="background:black;float:left; width:100%;height:100%; "> '.Page_finder::get_message().' <form action="" method="post" style="margin:0 auto; width:50%;"> <h1 style="color:red">Shouldn\'t you Set up your database first.</h1> <table> <tr> <td colspan=""><h2 style="color:red;">Enter Database Credentials</h2></td> </tr> <tr> <td style="color:white;">Enter Hostname</td> <td><input type="text" name="host" /></td> </tr> <tr> <td style="color:white;">Enter Username</td> <td><input ttype="text" name="username" /></td> </tr> <tr> <td style="color:white;">Enter Password</td> <td><input type="text" name="password" /></td> </tr> <tr> <td style="color:white;">Enter Database Name</td> <td><input type="text" name="database" /></td> </tr> <tr> <td></td> <td><input type="submit" name="btn_create_db" value="Create Database"></td> </tr> </table> </form> </body>'; self::stop(); } } /* * Stop Execution */ public static function stop(){ die(); } }
true
8d5715056db788c3e9b84e3cab79509b9caf69f4
PHP
concretecms-community-store/community_store
/src/CommunityStore/Group/Group.php
UTF-8
2,134
2.640625
3
[ "MIT" ]
permissive
<?php namespace Concrete\Package\CommunityStore\Src\CommunityStore\Group; use Doctrine\ORM\Mapping as ORM; use Concrete\Core\Support\Facade\DatabaseORM as dbORM; use Doctrine\Common\Collections\ArrayCollection; /** * @ORM\Entity * @ORM\Table(name="CommunityStoreGroups") */ class Group { /** * @ORM\Id @ORM\Column(type="integer") * @ORM\GeneratedValue */ protected $gID; /** * @ORM\Column(type="string") */ protected $groupName; private function setGroupName($groupName) { $this->groupName = $groupName; } public function getGroupName() { return $this->groupName; } public function getID() { return $this->gID; } public function getGroupID() { return $this->gID; } /** * @ORM\OneToMany(targetEntity="Concrete\Package\CommunityStore\Src\CommunityStore\Product\ProductGroup", mappedBy="group",cascade={"persist"})) * @ORM\OrderBy({"sortOrder" = "ASC"}) */ protected $products; public function getProducts() { return $this->products; } public function __construct() { $this->products = new ArrayCollection(); } public static function getByID($gID) { $em = dbORM::entityManager(); return $em->find(get_called_class(), $gID); } public static function getByName($gName) { $em = dbORM::entityManager(); return $em->getRepository(get_class())->findOneBy(['groupName' => $gName]); } public static function add($groupName) { $productGroup = new self(); $productGroup->setGroupName($groupName); $productGroup->save(); return $productGroup; } public function update($groupName) { $this->setGroupName($groupName); $this->save(); return $this; } public function save() { $em = dbORM::entityManager(); $em->persist($this); $em->flush(); } public function delete() { $em = dbORM::entityManager(); $em->remove($this); $em->flush(); } }
true
870d7602164d1840cd842314b2e11d267e0766bc
PHP
joshthackeray/getaddress-api
/src/Data/Suggestion.php
UTF-8
1,057
3.171875
3
[]
no_license
<?php namespace JoshThackeray\GetAddress\Data; use JoshThackeray\GetAddress\Data\Contracts\SuggestionInterface; class Suggestion implements SuggestionInterface { protected string $address; protected string $url; protected string $id; /** * Constructs the Suggestion object from an AutoComplete response. * * @param $response */ public function __construct($response) { $this->address = $response['address']; $this->url = $response['url']; $this->id = $response['id']; } /** * Returns the address line of this suggestion. * * @return string */ public function address(): string { return $this->address; } /** * Returns the URL to retrieve this address. * * @return string */ public function url(): string { return $this->url; } /** * Returns the URL to ID of this address. * * @return string */ public function id(): string { return $this->id; } }
true
cedec923f93f11ac3849e2689743eed20bca00d3
PHP
miroslavvlajnic/currency-trader-api
/app/routes.php
UTF-8
1,298
2.75
3
[]
no_license
<?php $router = new Core\Router; /** * Route pattern (first argument) must begin with a forward slash (/) and * must not have one at the end... * dynamic arguments are denoted with a colon sign (:) * e.g. '/user/:id' * * examples of valid routes: '/user', '/user/:id', '/user/:id/posts' * examples of invalid routes: 'user', '/user/', 'user/:id', '/user/:id/posts/' * * second argument must be an associative array with * two keys: 'controller' and 'action' * * they determine what method on which controller will be invoked * when the incoming request matches the route in question */ $router->post('/calculate', ['controller' => 'App\Controller\OrderController', 'action' => 'calculate']); $router->get('/currencies', ['controller' => 'App\Controller\CurrenciesController', 'action' => 'getAllCurrencies']); $router->get('/currencies/codes', ['controller' => 'App\Controller\CurrenciesController', 'action' => 'getCurrencyCodes']); $router->post('/order', ['controller' => 'App\Controller\OrderController', 'action' => 'store']); $router->post('/refresh-rates', ['controller' => 'App\Controller\CurrenciesController', 'action' => 'refreshRates']); $router->get('/last-entry', ['controller' => 'App\Controller\OrderController', 'action' => 'getLastEntry']); return $router;
true
d4ed3504d591784bd7720946e316a113b39beb67
PHP
FiPie/photoUploadGallery
/controllers/loginHandler.php
UTF-8
1,939
2.890625
3
[]
no_license
<?php session_start(); // Here we check if the user is logged in and if so she/he will be redirected back to index if ((isset($_SESSION['logged']) == TRUE) && ($_SESSION['logged'] == TRUE)) { $message = "You are already logged as : <b>$userName</b>! Logout before account switch."; $_SESSION["promptMessage"] = $message; $_SESSION["msg_type"] = "info"; header('Location: ../index.php'); exit(); } // We check if the userID and password admited by the user are correct IT IS HARDCODED here for the sake of simplicity of this project but normaly we would store it in dataBase if (isset($_POST['userName'], $_POST['userPswd'])) { $userName = test_input(filter_input(INPUT_POST, "userName", FILTER_SANITIZE_SPECIAL_CHARS)); $userPswd = test_input(filter_input(INPUT_POST, "userPswd", FILTER_SANITIZE_SPECIAL_CHARS)); if ($userName == 'admin' && $userPswd == 'password') { $_SESSION["logged"] = TRUE; $_SESSION["userName"] = $userName; $_SESSION["isAdmin"] = $isAdmin; $message = "You have successfully logged in as : <b>$userName</b>"; $_SESSION["promptMessage"] = $message; $_SESSION["msg_type"] = "success"; header('Location: ../index.php'); exit(); } else { $message = "Wrong User ID or associated password incorrect, for : <b>$userName</b>"; $_SESSION["promptMessage"] = $message; $_SESSION["msg_type"] = "danger"; header('Location: ../views/loginForm.php'); exit(); } } else { $message = "You have to fill userID and password fields in order to log in. <b>Don't mess around with this code:)</b>"; $_SESSION["promptMessage"] = $message; $_SESSION["msg_type"] = "danger"; header('Location: ../views/loginForm.php'); exit(); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
true
60f307728af825261b61cd247f30c09d2edb5003
PHP
thaislsilveira/php_fatec_inicio
/Lista-3/exercicio04.php
UTF-8
309
3.390625
3
[]
no_license
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Aplicaçoes em php</title> </head> <body> <?php $ano = 2000; //Formato AAAA; if((($ano%4==0)||($ano%400==0))&&($ano%100!=0)){ echo "Bissexto!"; }else{ echo "Ano não Bissexto!!"; } ?> </body> </html>
true
4487950d024eaa21a8187e37ddcaffc4437d1fca
PHP
HaoPai/L_NET
/patent/patent.php
UTF-8
2,197
2.65625
3
[]
no_license
<?php $dbc = mysql_connect("localhost:3310","root","hunan2010"); mysql_select_db("patent",$dbc); mysql_query('SET NAMES UTF8'); date_default_timezone_set("Asia/Shanghai"); $stock_code = ""; $ap_company = ""; $patent_title = ""; $patent_abstract = ""; $query = "select stock_code ,ap_company , patent_title, patent_abstract from patent order by stock_code limit 1 "; $result = mysql_query($query,$dbc); if($row = mysql_fetch_array($result)){ $stock_code = $row['stock_code']; $ap_company = $row['ap_company']; $patent_title = $row['patent_title']; $patent_abstract = $row['patent_abstract']; } ?> <html> <head> <title>专利操作</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style> table { font-size:16px; width : 900px; margin: auto;padding:30px; border: 2px solid #000; text-align:left; } button { width:150px; height: 40px; text-aign:center; line-height:40px; border:none; border-radius: 10px;color:#fff;cursor:pointer;margin:20px; } #green { background:green;} #red {background:red;} </style> </head> <body> <table> <thead></thead> <tbody> <tr> <td>股票代码:</td><td><?php echo $stock_code; ?></td> </tr> <tr> <td>申请公司:</td><td><?php echo $ap_company; ?></td> </tr> <tr> <td>专利标题:</td><td><?php echo $patent_title; ?></td> </tr> <tr> <td>摘要:</td><td><?php echo $patent_abstract; ?></td> </tr> <tr> <td></td><td></td> </tr> <tr> <td><button id = "green">绿色专利</button></td><td><button id = "red">非绿色专利</button></td> </tr> </tbody> </table> </body> </html>
true
c865c49fdb9758631d117d9600e6dda3b5a1d16f
PHP
rajabbilly/DHAMIS-API
/src/app/models/staffQualification.php
UTF-8
862
2.9375
3
[]
no_license
<?php /** * Created by Rajab E. Billy * Date: 8/15/2019 * Time: 10:39 AM */ class staffQualification { //Class properties protected $conn = NULL; private $table_name = "[dbo].[concept]"; public function __construct($db) { $this->conn = $db; } //Get all staff qualifications from DHAMIS public function getStaffQualifications() { //Query statement $query = "SELECT [concept_name] AS [qualification] FROM [dbo].[concept] WHERE (([concept].[concept_ID_parent]) In (880,881,885,1494,1495,1498,1623,1624)) ORDER BY [concept_ID_parent], [sort_weight];"; //Prepare the query statement $stmt = $this->conn->prepare($query); //Execute query statement $stmt->execute(); return $stmt; } }
true
f933b142ebc2f5ff0c70370041797a1d5b0c09b2
PHP
AndreeaStefanovici/PiX
/php/upload.php
UTF-8
3,909
2.703125
3
[]
no_license
<?php include('server.php'); if(isset($_SESSION['username'])) { // Initialize message variable $msg = ""; //apasare buton click if (isset($_POST['upload'])) { $allowed = array('jpeg','png' ,'jpg'); $filename = $_FILES['image']['name'][0]; $ext = pathinfo($filename, PATHINFO_EXTENSION); if(!in_array($ext, $allowed) ) { array_push($errors, "File extension is not allowed!"); //echo"NUUUUU"; } else{ $imagesCount = count($_FILES['image']['name']); //preluare titlu , descriere, tag $image_text = mysqli_real_escape_string($db, $_POST['image_text']); $image_title = mysqli_real_escape_string($db, $_POST['image_title']); $image_tags = mysqli_real_escape_string($db, $_POST['image_tags']); $usr = $_SESSION['username']; $resultt = mysqli_query($db, "SELECT userID from users where username = '$usr'"); $galleryID = mysqli_fetch_array($resultt); $galleryID = $galleryID['userID']; //echo $galleryID['userID']; for($i = 0; $i < $imagesCount; $i++){ // nume imagine $image = $_FILES['image']['name'][$i]; // fisierul imaginilor $target = "imagini_upload/".basename($image); //image size, dimensions $width = getimagesize($_FILES['image']['tmp_name'][$i])[0]; $height = getimagesize($_FILES['image']['tmp_name'][$i])[1]; $size = round(filesize($_FILES['image']['tmp_name'][$i])/1024, 1); $sql = "INSERT INTO images (image, image_text , image_title, image_tags, galleryID, image_size, image_width, image_height) VALUES ('$image', '$image_text', '$image_title', '$image_tags', '$galleryID', '$size', '$width', '$height')"; // upload success/fail mysqli_query($db, $sql); if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $target)) { $msg = "Image uploaded successfully"; }else{ $msg = "Failed to upload image"; } } } } echo ' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="css/upload.css"> <link rel="icon" href="imagini/logo.jpg"> <title>PiX</title> </head> <body> <header> //spatiul de deasupra meniului <div class="space"></div> <div class="menu"> <ul class="clearfix"> <li><a href="login.php"> LogOut</a><br></li> <li> Upload<br></li> <li><a href="index.php"> Home</a><br></li> <li><a href="gallery.php"> Gallery</a><br></li> </ul> </div> </header> <div class = "body_wrapper"> <div class = "little_icon_container"> <div class = "little_icon"> <img class = "icon" src="imagini/upload.png" alt="logo"> </div> </div> <p> Select a file to upload :</p> <div class = "formUpload"> <form method="POST" action="upload.php" enctype="multipart/form-data"> <input type="hidden" name="size" value="1000000"> <label class="label_upload"> <input type="file" name="image[]" multiple /> Choose File </label> <div> <br> <label for="descriere"> Description:</label> <textarea rows="4" id="descriere" name="image_text" placeholder="Say something about this image..."></textarea> <label for="titlu"> Title:</label> <textarea rows="1" cols="50" id="titlu" name="image_title" placeholder="Add title..."></textarea> <label for="tags"> Tags:</label> <textarea rows="2" cols="50" id="tags" name="image_tags" placeholder="Add tags..."></textarea> <br> </div>'; //erori include('errors.php'); echo'<div> <button class = "dropbtn" name="upload">Submit</button> </div> </form> </div> </div> </body> </html>'; } ?>
true