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
922c5935892f2846b82d6ccdab9edbe2510e1f44
PHP
jsreese92/tutorScheduler
/toOpenShift/tutor/tutor_hours.php
UTF-8
2,741
3.015625
3
[]
no_license
<?php /* WRITTEN BY: Eric Jones LAST EDITED: 12/8/2013 This page simply displays the hours currently given by the database. It prints the current schedule and open hours in hidden tables and the javascript will be used to fill out the display for the user. No user interaction can be done here. */ include "./../common/session_validator.php"; $con = getDatabaseConnection(); $employee_info = mysqli_fetch_array(mysqli_query($con, "SELECT * FROM `employeeInfo` WHERE `PID` = '".mysqli_real_escape_string($con, $_SESSION['pid'])."'")); if($employee_info[3] == 'admin') { echo "<script type = 'text/javascript'>location.href='http://$_SERVER[HTTP_HOST]/common/onyen_validator.php'</script>"; exit(); } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>View Schedule</title> <link rel="stylesheet" type="text/css" href="./../common/stylesheet.css"> <script type="text/javascript" src="./../common/jquery-1.10.2.min.js"></script> <script type="text/javascript" src="tutor_hours.js"></script> </head> <body> <?php //the go back/logout bar echo "<div><strong class='login'>Currently logged in as " . $employee_info[1] . " " . $employee_info[2] . ". <button type='button' onclick='logout()'>Log Out</button></strong>" . "<button onclick='goBack()'>Back to Tutor Overview Page</button></div>"; ?> <div id="view_schedule_div"> </div> <!--Insert table from actual hours table--> <table id="tutor_schedule_result" hidden> <tbody> <?php if(!$result = mysqli_query($con, "SELECT * FROM `actSchedule` WHERE `PID` = ".$employee_info[0])){ echo "Error "; echo mysqli_error($con); } //populate the table with the values from the database while($row = mysqli_fetch_array($result)) { echo "<tr class='".$row[1]."'>"; echo "<td>".$row[1]."</td>"; for($i=7; $i<24; $i++) { if($i < 10) { echo "<td class='".$row[1]."0".($i)."'>".$row[$i+2]."</td>"; }else echo "<td class='".$row[1].($i)."'>".$row[$i+2]."</td>"; } echo "</tr>\n"; } ?> </tbody> </table> <!--Insert table from open hours database--> <table id="hours_database_result" hidden> <tbody> <?php function numToClass($val) { if($val==1) { return 'open'; }else return 'closed'; } if(!$result = mysqli_query($con, "SELECT * FROM `openHours`")){ echo "Error "; echo mysqli_error($con); } //populate the table with the values from the database while($row = mysqli_fetch_array($result)) { echo "<tr class='".$row[0]."'>"; for($i=1; $i<18; $i++) { if($i < 4) { echo "<td class='0".($i+6)."'>".numToClass($row[$i])."</td>"; }else echo "<td class='".($i+6)."'>".numToClass($row[$i])."</td>"; } echo "</tr>\n"; } ?> </body> </html>
true
0057ea1b24a2fcbf79428046d231a921b13e6c62
PHP
steveharwell1/remindMe
/utils/error_msg.php
UTF-8
193
2.5625
3
[ "MIT" ]
permissive
<?php function log_error($message) { session_start(); if(!isset($_SESSION['errors'])){ $_SESSION['errors'] = array(); } array_push($_SESSION['errors'], $message); }
true
e4e6de92355796d732ccb2e334bd8a47caf58441
PHP
alex-kusakin/quote-csv
/Test/Unit/Model/Csv/DataProvider/QuoteTest.php
UTF-8
1,897
2.5625
3
[]
no_license
<?php /** * @author Alex Kusakin */ namespace AlexKusakin\QuoteCsv\Test\Unit\Model\Csv\DataProvider; class QuoteTest extends \PHPUnit\Framework\TestCase { /** * @var array */ protected $mockItemsArray = [ ['skuA', 'Test A', 3, 12.6], ['skuB', 'Test B', 1, 13.25], ['skuC', 'Test C', 5, 20] ]; /** * Test getHeaders method */ public function testGetHeaders() { // prepare mocks $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); // execute logic $dataProvider = new \AlexKusakin\QuoteCsv\Model\Csv\DataProvider\Quote($quoteMock); $result = $dataProvider->getHeaders(); // verify results $this->assertEquals(['SKU', 'Name', 'Quantity', 'Total Price'], $result); } /** * Test getData method */ public function testGetData() { // prepare mocks $mockItems = []; foreach ($this->mockItemsArray as $row) { $itemMock = $this->createPartialMock(\Magento\Quote\Model\Quote\Item::class, []); $itemMock->setData([ \Magento\Quote\Model\Quote\Item::KEY_SKU => $row[0], \Magento\Quote\Model\Quote\Item::KEY_NAME => $row[1], \Magento\Quote\Model\Quote\Item::KEY_QTY => $row[2], 'row_total_incl_tax' => $row[3], ]); $mockItems[] = $itemMock; } $quoteMock = $this->createMock(\Magento\Quote\Model\Quote::class); $quoteMock->expects($this->any()) ->method('getAllVisibleItems') ->willReturn($mockItems); // execute logic $dataProvider = new \AlexKusakin\QuoteCsv\Model\Csv\DataProvider\Quote($quoteMock); $result = $dataProvider->getData(); // verify results $this->assertEquals($this->mockItemsArray, $result); } }
true
212efb7458442a7d58f2856c6dc145a89b1c07e2
PHP
DenisGorbachev/OldRoboticks
/client/lib/command/base/RealmCommand.class.php
UTF-8
1,841
2.71875
3
[]
no_license
<?php require_once dirname(__FILE__).'/UserInterfaceCommand.class.php'; abstract class RealmCommand extends UserInterfaceCommand { public $realmId; public function getOptionConfigs() { return array( 'realm_id' => array( 'short_name' => '-m', 'long_name' => '--realm-id', 'description' => 'ID of playable realm (example: 6)', 'action' => 'StoreInt', 'default' => $this->getRealmId() ) ); } public function setRealmId($realmId) { $this->realmId = $realmId; $this->setVariable('realm_id', $realmId); } public function getRealmId() { if (empty($this->realmId)) { $this->realmId = $this->getVariable('realm_id'); } return $this->realmId; } public function getLogFilenames() { $logFilenames = parent::getLogFilenames(); $realmId = $this->getRealmId(); if ($realmId) { $logFilenames[] = $this->getBaseLogDirname().'/realm/'.$realmId; } return $logFilenames; } public function preExecute($options, $arguments) { parent::preExecute($options, $arguments); if ($this->getOption('realm_id') === null) { throw new RoboticksCacheException('No realm selected. '.PHP_EOL.'See a list of available realms using `rk realm:ls`, select a realm using `rk realm:select ID`. '.PHP_EOL.'Alternatively, you can select a realm for a specific command by adding `--realm-id|-m ID`.'); } } public function request($controller, $parameters = array(), $method = 'GET', $options = array()) { $parameters['realm_id'] = $this->getOption('realm_id'); return parent::request($controller, $parameters, $method, $options); } }
true
ee0fa6b76c192960e54342d6f12e7f0173e34c73
PHP
tpmanc/backup-backend
/app/Models/DatabaseBackups.php
UTF-8
611
2.671875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; /** * Class DatabaseBackups * @package App\Models * @property int $id * @property int $database_id * @property string $name * @property string $path * @property-read Database $database */ class DatabaseBackups extends Model { use HasFactory; protected $table = 'database_backups'; protected $fillable = [ 'database_id', 'name', 'path', ]; public function database() { return $this->belongsTo(Database::class); } }
true
08c14c4fd0d2ffb5bbe2909bbae165f0bb10dc97
PHP
alexboo/Core-Engine
/library/Core/View/Helper/BookNavigation.php
UTF-8
3,501
2.546875
3
[]
no_license
<?php class Core_View_Helper_BookNavigation { public function bookNavigation($section = null, $content = null) { $session = new Core_Session(); if ( isset($session->book) ) { $modelBook = new Model_Books_Book(); $sections = $modelBook->getMenu($session->book); $view = new Core_View(); $navigations = array(); foreach ( $sections as $i => $_section ) { if ( ($_section['type'] == 'section' && $_section['id'] == $section) || ($_section['type'] == 'content' && $_section['id'] == $content) ) { if ( isset($sections[$i-1]) ) { if ( $sections[$i-1]['type'] == 'section' ) $navigations[1] = array('title' => 'Предыдущий раздел', 'url' => $view->url(array('controller' => 'index', 'action' => 'section', 'book' => $session->book, 'section' => $sections[$i-1]['id']))); else $navigations[1] = array('title' => 'Предыдущий раздел', 'url' => $view->url(array('controller' => 'index', 'action' => 'content', 'book' => $session->book, 'id' => $sections[$i-1]['id']))); } else $navigations[1] = array('title' => 'Предыдущий раздел'); if ( $_section['type'] == 'section' && ( !empty($section) && !empty($content) ) ) $navigations[3] = array('title' => 'К оглавлению', 'url' => $view->url(array('controller' => 'index', 'action' => 'section', 'book' => $session->book, 'section' => $_section['id']))); if ( isset($sections[$i+1]) ) { if ( $sections[$i+1]['type'] == 'section' ) $navigations[5] = array('title' => 'Следующий раздел', 'url' => $view->url(array('controller' => 'index', 'action' => 'section', 'book' => $session->book, 'section' => $sections[$i+1]['id']))); else $navigations[5] = array('title' => 'Следующий раздел', 'url' => $view->url(array('controller' => 'index', 'action' => 'content', 'book' => $session->book, 'id' => $sections[$i+1]['id']))); } else $navigations[5] = array('title' => 'Предыдущий раздел'); break; } } if ( null !== $content && null !== $section ) { $modelBooksContent = new Model_Books_Content(); $prev = $modelBooksContent->getPrevious($content); if ( isset($prev['id']) ) $navigations[2] = array('title' => 'Предыдущая страница', 'url' => $view->url(array('controller' => 'index', 'action' => 'content', 'book' => $session->book, 'section' => $prev['section'], 'id' => $prev['id']))); else $navigations[2] = array('title' => 'Предыдущая страница'); $next = $modelBooksContent->getNext($content); if ( isset($next['id']) ) $navigations[4] = array('title' => 'Следующая страница', 'url' => $view->url(array('controller' => 'index', 'action' => 'content', 'book' => $session->book, 'section' => $next['section'], 'id' => $next['id']))); else $navigations[4] = array('title' => 'Следующая страница'); } $urls = array(); for ( $i = 1; $i<=5; $i++ ) { if ( isset($navigations[$i]) ) { if ( isset($navigations[$i]['url']) ) $urls[] = "<a href=\"" . $navigations[$i]['url'] . "\">" . $navigations[$i]['title'] . "</a>"; else $urls[] = $navigations[$i]['title']; } } return '<div class="navigation">' . implode($urls, ' | ') . '</div>'; } } }
true
e2749772963c6a829cbe080882d5dc59b6ffdc3d
PHP
imanuelnickles/gigsitfrontend
/database/migrations/2016_06_13_150709_create_sell_table.php
UTF-8
1,104
2.5625
3
[]
no_license
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateSellTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sell', function (Blueprint $table) { $table->increments('sellID'); $table->integer('userID')->unsigned(); $table->integer('songID')->unsigned(); $table->integer('paymentID')->unsigned(); $table->integer('discount')->unsigned(); //Foreign Key $table->foreign('userID')->references('userID')->on('user')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('songID')->references('songID')->on('song')->onDelete('cascade')->onUpdate('cascade'); $table->foreign('paymentID')->references('paymentID')->on('payment')->onDelete('cascade')->onUpdate('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('sell'); } }
true
8d3f12c491ac718220a244c5899474f4e631a396
PHP
sfadless/payment
/src/Transaction/Arguments/CheckTransactionArguments.php
UTF-8
813
2.84375
3
[]
no_license
<?php namespace Sfadless\Payment\Transaction\Arguments; /** * CheckTransactionArguments * * @author Pavel Golikov <pgolikov327@gmail.com> */ class CheckTransactionArguments { /** * @var string */ private $transactionId; /** * @var array */ private $options; /** * CheckTransactionArguments constructor. * @param $transactionId string * @param array $options */ public function __construct($transactionId, array $options = []) { $this->transactionId = $transactionId; $this->options = $options; } /** * @return string */ public function getTransactionId() { return $this->transactionId; } /** * @return array */ public function getOptions() { return $this->options; } }
true
070dfea38c2c771cd8e7f5efaf06c0bdf8be641e
PHP
lednhatkhanh/lamp-final-project
/register.php
UTF-8
2,948
2.625
3
[]
no_license
<?php require 'connect.php'; session_start(); if(isset($_SESSION['user_name'])) { header('Location: main.php'); } if(isset($_POST['username']) && isset($_POST['password']) && isset($_POST['passwordConfirm'])){ $username = $_POST['username']; $password = $_POST['password']; $passwordConfirm = $_POST['passwordConfirm']; if($password != $passwordConfirm) { $fmsg ="Password does not match!"; } else { $query = "INSERT INTO `thanhvien` (username, password) VALUES ('$username', md5('$password'))"; $result = mysqli_query($connection, $query); if($result) { $smsg = "User Created Successfully."; header("Location: http://localhost/lamp/login.php"); exit(); } else{ $fmsg ="User Registration Failed"; } } } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Register</title> <link rel="import" href="./components/importStyles.html"> </head> <body> <link rel="import" id="header" href="./components/header.html"> <script> var getImport = document.querySelector('#header'); var getContent = getImport.import.querySelector('#content'); document.body.appendChild(document.importNode(getContent, true)); </script> <div id="wrapper" class="container-fluid"> <div class="row"> <div class="col-md-8 offset-md-2"> <div class="card card-block"> <h3>Register</h3> <hr /> <form id="registerForm" method="post"> <?php if(isset($smsg)){ ?><div class="alert alert-success" role="alert"> <?php echo $smsg; ?> </div><?php } ?> <?php if(isset($fmsg)){ ?><div class="alert alert-danger" role="alert"> <?php echo $fmsg; ?> </div><?php } ?> <div class="form-group"> <label for="username">Username*</label> <input id="username" name="username" type="text" class="form-control" placeholder="Enter your username" required /> </div> <div class="form-group"> <label for="password">Password*</label> <input id="password" name="password" type="password" class="form-control" placeholder="Enter your password" required /> </div> <div class="form-group"> <label for="passwordConfirm">Password Confirm*</label> <input id="passwordConfirm" name="passwordConfirm" type="password" class="form-control" placeholder="Reenter your password" required /> </div> <button type="submit" class="btn btn-primary">Register</button> <a href="login.php" class="btn btn-secondary">Login</a> </form> </div> </div> </div> </div> <link rel="import" href="./components/imports.html"> <script type="text/javascript" src="./register.js"> </script> </body> </html>
true
5b504539d154598722e2cf358e322314daac14ce
PHP
theallmightyjohnmanning/secc
/app/commands/LACE.php
UTF-8
2,389
2.9375
3
[]
no_license
<?php /** * */ namespace SECC\Commands; use SECC\App; class LACE { private static $commands = []; public static function initialize($argc = null, $argv = null) { self::setValidCommands(); if($argc == 1) { self::header(); for($i = 0; $i < count(self::$commands); $i++) { echo "\n"; Shell::write(self::$commands[$i]." \n", "light_green"); $command = "SECC\\Commands\\".self::$commands[$i]; if(class_exists($command)) { $command = new $command; $command->help(); } } } if(isset($argv[1])) { if(!in_array($argv[1], self::$commands)) { Shell::write('You need to enter a valid LACE command!', 'red'); } else { $command = "SECC\\Commands\\".$argv[1]; $command = new $command; if($argc > 2) { $methods = []; for($i = 0; $i < $argc - 2; $i++) { $methods[] = $argv[$i + 2]; $params = []; if(strpos($methods[$i], ':')) { $argument = $methods[$i]; $argument = explode(':', $argument); $method = $argument[0]; unset($argument[0]); $params = $argument; if(count($params) > 0) { if(method_exists($command, $method)) { call_user_func_array([$command, $method], $params); } else { Shell::write('That isn\'t a valid LACE command', 'red'); } } } else { $command->{$methods[$i]}(); } } } else { $command->help(); } } } } public static function setValidCommands() { $commands = scandir('app/commands'); for($i = 0; $i < count($commands); $i++) { if($commands[$i] != '.' && $commands[$i] != '..' && $commands[$i] != 'LACE.php' && $commands[$i] != 'Shell.php') { $commands[$i] = explode('.', $commands[$i]); self::$commands[] = $commands[$i][0]; } } } public static function header() { $header = App::service('View')->make('templates.code.header'); $colors = [ "dark_grey", "red", "light_red", "yellow", "blue", "green", "light_green", "brown", "light_blue", "cyan", "purple", "light_purple", "white" ]; Shell::write($header."\n", $colors[rand(0, 12)]); } }
true
939a0d174ae9cadc432a71672669f819e2574789
PHP
zinovyev/servelat
/app/Components/ProcessManager/ProcessInterface.php
UTF-8
1,497
3.078125
3
[ "MIT" ]
permissive
<?php namespace Servelat\Components\ProcessManager; use Servelat\Components\TaskManager\TaskInterface; /** * Interface ProcessInterface. * Base process interface. * * @author Ivan Zinovyev <vanyazin@gmail.com> */ interface ProcessInterface { /** * @param \Servelat\Components\TaskManager\TaskInterface $task */ public function __construct(TaskInterface $task); /** * Get list of streams (stdin, stdout, stderr). * Every stream must be a resource of type "stream". * * @return array */ public function getStreams(); /** * Set exit code. * 0 - for success, any other code - for failure. * * @param int $exitCode * @return $this */ public function setExitCode($exitCode); /** * Get exit code. * 0 - for success, any other code - for failure. * * @return int */ public function getExitCode(); /** * Add new line from stdout/stderr. * * @param $line * @return $this */ public function addOutputLine($line); /** * Get array of process output. * * @return array */ public function getOutputLines(); /** * Get the caused task item. * * @return TaskInterface */ public function getTask(); /** * Is process closed. * * @return bool */ public function isClosed(); /** * Return process resource. * * @return $this */ public function close(); }
true
814599bbfbf285b4b0e52401d904067ef2c2fb17
PHP
yuaccp2/oso_extend
/classes/categories.php
UTF-8
2,495
2.703125
3
[]
no_license
<?php /** * 分类的树型类 * @author espow team nathan 2011-8-24 * @package * @licese http://www.oscommerce.com * @version 1.1 * @copyright (c) 2003 osCommerce */ Class categories extends tree{ public function categories($all_access = false){ global $customer_group_id; if(empty($customer_group_id)){ $customer_group_id = 'G'; } if($all_access){ $query = tep_db_query("select c.categories_id, c.parent_id from " . TABLE_CATEGORIES .' c order by c.parent_id,c.category_toptab'); }else{ $query = tep_db_query("select c.categories_id, c.parent_id from " . TABLE_CATEGORIES .' c where products_group_access like "%'.$customer_group_id.'%" order by category_toptab,categories_id,parent_id '); } while($row = tep_db_fetch_array($query)){ //设置树型结构数据 $this->set_node($row['categories_id'], $row['parent_id'], $row['categories_id']); } } /** * 返回所有N级子类分类ID * @authoer nathan * @access public * @param $id int 分类ID * @return Array */ public function get_subcategories($id){ $arr = $this->get_childs($id); $arr[] = $id; return $arr; } /** * 返回上级分类ID * @authoer nathan * @access public * @param $id int 分类ID * @return int */ public function get_parent_id($id){ return $this->get_parent($id); } /** * * @authoer nathan * @access public * @param * @return */ public function get_topcategories_id($id){ $_top_ids = $this->get_parents($id); if(empty($_top_ids)) return 0; reset($_top_ids); return current($_top_ids); } /** * 获取目录名称 * @authoer nathan * @access public * @param $id int 目录ID * @return String */ function get_name($id){ global $customer_group_id, $languages_id; if(empty($customer_group_id)){ $customer_group_id = 'G'; } $query = tep_db_query("select categories_name from " . TABLE_CATEGORIES_DESCRIPTION .' left join '.TABLE_CATEGORIES.' using (categories_id) where products_group_access like "%'.$customer_group_id.'%" and categories_id ="'. (int)$id.'" and language_id="'. $languages_id.'"'); $info = tep_db_fetch_array($query); return $info ? $info['categories_name'] : null; } /** * * @authoer nathan * @access public * @param * @return */ function get_parent_all($id){ $result = array(); while($_cid = $this->get_parent($id)){ $result[] = $_cid; $id = $_cid; } return $result; } } ?>
true
d171699f3ae06a0184c3428c63ab461e03567403
PHP
octalmage/wib
/php-7.3.0/ext/imap/tests/imap_include.inc
UTF-8
5,460
2.734375
3
[ "MIT", "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "TCL", "ISC", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "blessing" ]
permissive
<?php // Change these to make tests run successfully $server = '{127.0.0.1/norsh}'; $default_mailbox = $server . "INBOX"; $domain = "something.com"; $admin_user = "webmaster"; // a user with admin access $username = "$admin_user@$domain"; $password = 'p4ssw0rd'; $users = array("webmaster", "info", "admin", "foo"); // tests require 4 valid userids $mailbox_prefix = "phpttest"; // name used for test mailbox // record test start time (used by displayOverviewFields()) $start_time = time(); // list of fields to expect $mandatory_overview_fields = array( 'size', 'uid', 'msgno', 'recent', 'flagged', 'answered', 'deleted', 'seen', 'draft', 'udate', ); /** * Display all fields in an element from an imap_fetch_overview() response * * Special handling for 'udate', which will vary run-to-run; assumes an IMAP * server with its clock synced to the current system, which is consistent with * setup instructions in ext/imap/tests/README * * @param array resp element from the return value of imap_fetch_overview() */ function displayOverviewFields($resp, $fields=null) { global $mandatory_overview_fields; global $start_time; foreach ($fields ? $fields : $mandatory_overview_fields as $mf) { $z = $resp->$mf; if ($mf == 'udate') { if (($z >= $start_time) && ($z <= time())) { echo "$mf is OK\n"; } else { echo "$mf is BAD ($z)\n"; } } else { echo "$mf is $z\n"; } } } /** * Create a test mailbox and populate with msgs * * @param string mailbox_suffix Suffix used to uniquely identify mailboxes * @param int message_count number of test msgs to be written to new mailbox * * @return IMAP stream to new mailbox on success; FALSE on failure */ function setup_test_mailbox($mailbox_suffix, $message_count, &$new_mailbox = null, $msg_type = "simple"){ global $server, $default_mailbox, $username, $password; // open a stream to default mailbox $imap_stream = imap_open($default_mailbox, $username, $password); if ($imap_stream === false) { echo "Cannot connect to IMAP server $server: " . imap_last_error() . "\n"; return false; } echo "Create a temporary mailbox and add " . $message_count . " msgs\n"; $new_mailbox = create_mailbox($imap_stream, $mailbox_suffix, $message_count, $msg_type); if ($new_mailbox === false) { echo "Cant create a temporary mailbox: " . imap_last_error(). "\n"; return false; } echo ".. mailbox '$new_mailbox' created\n"; // reopen stream to new mailbox if (imap_reopen($imap_stream, $new_mailbox) === false) { echo "cant re-open '$new_mailbox' mailbox: " . imap_last_error() . "\n"; return false; } return $imap_stream; } /** * Create mailbox and fill with generic emails * * @param resource $imap_stream * @param string $mailbox */ function create_mailbox($imap_stream, $mailbox_suffix, $message_count, $msg_type= "simple"){ global $default_mailbox, $mailbox_prefix; $mailbox = $default_mailbox . "." . $mailbox_prefix . $mailbox_suffix; $mailboxes = imap_getmailboxes($imap_stream, $mailbox, '*'); // check mailbox does not already exist if ($mailboxes) { foreach($mailboxes as $value) { if ($value->name == $mailbox) { exit ("TEST FAILED : Mailbox '$mailbox' already exists\n"); } } } if (imap_createmailbox($imap_stream, $mailbox) === false) { return false; } // Add number of test msgs requested if ($message_count > 0) { populate_mailbox($imap_stream, $mailbox, $message_count, $msg_type); } return $mailbox; } /** * Populate a mailbox with generic emails * * @param resource $imap_stream * @param string $mailbox */ function populate_mailbox($imap_stream, $mailbox, $message_count, $msg_type = "simple"){ global $users, $domain; for($i = 1; $i <= $message_count; $i++) { if ($msg_type == "simple") { $msg = "From: foo@anywhere.com\r\n" . "To: $users[0]@$domain\r\n" . "Subject: test$i\r\n" . "\r\n" . "$i: this is a test message, please ignore\r\n"; } else { $envelope["from"]= "foo@anywhere.com"; $envelope["to"] = "$users[0]@$domain"; $envelope["subject"] = "Test msg $i"; $part1["type"] = TYPEMULTIPART; $part1["subtype"] = "mixed"; $part2["type"] = TYPETEXT; $part2["subtype"] = "plain"; $part2["description"] = "imap_mail_compose() function"; $part2["contents.data"] = "message 1:xxxxxxxxxxxxxxxxxxxxxxxxxx"; $part3["type"] = TYPETEXT; $part3["subtype"] = "plain"; $part3["description"] = "Example"; $part3["contents.data"] = "message 2:yyyyyyyyyyyyyyyyyyyyyyyyyy"; $part4["type"] = TYPETEXT; $part4["subtype"] = "plain"; $part4["description"] = "Return Values"; $part4["contents.data"] = "message 3:zzzzzzzzzzzzzzzzzzzzzzzzzz"; $body[1] = $part1; $body[2] = $part2; $body[3] = $part3; $body[4] = $part4; $msg = imap_mail_compose($envelope, $body); } imap_append($imap_stream, $mailbox, $msg); } } /** * Get the mailbox name from a mailbox decription, i.e strip off server details. * * @param string mailbox complete mailbox name * @return mailbox name */ function get_mailbox_name($mailbox){ if (preg_match('/\{.*?\}(.*)/', $mailbox, $match) != 1) { echo "Unrecpognized mailbox name\n"; return false; } return $match[1]; } ?>
true
0862fedf74ec642a5deba1ed2a48c143cbf6e010
PHP
2gmurillo/ventus
/tests/Feature/Home/FilterTest.php
UTF-8
1,966
2.515625
3
[]
no_license
<?php namespace Tests\Feature\Home; use App\Models\Product; use App\Models\User; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Str; use Tests\TestCase; class FilterTest extends TestCase { use RefreshDatabase; /** @test * @dataProvider searchItemsProvider * @param string $field * @param string $value */ public function itCanFilterProductsInHome(string $field, string $value) { //Arrange $user = User::factory()->create(); Product::factory()->count(15)->create(); $product = Product::factory()->create([ 'name' => 'Nombre del producto', ]); $filters[$field] = $value; //Act $response = $this->actingAs($user) ->get(route('home', $filters)); $responseProducts = $response->getOriginalContent()['products']; //Assert $this->assertTrue($responseProducts->contains($product)); } /** @test * @dataProvider notValidSearchDataProvider * @param string $field * @param null $value */ public function itFailsWhenFilterProductsInHomeWithNotValidData(string $field, $value = null) { //Arrange $user = User::factory()->create(); Product::factory()->count(15)->create(); $data[$field] = $value; //Act $response = $this->actingAs($user) ->get(route('home', $data)); //Assert $response->assertRedirect(); $response->assertSessionHasErrors($field); } /** * @return array */ public function notValidSearchDataProvider(): array { return [ 'Test name is too long' => ['search', Str::random(81)], ]; } /** * @return array|string[] */ public function searchItemsProvider(): array { return [ 'it can search products by name' => ['search', 'Nombre del producto'], ]; } }
true
f4ba6f6d42224b216919b6a4b35ed68f39c92edf
PHP
mhoss3in/php.local
/oop/classes/htmlExport.php
UTF-8
196
2.53125
3
[]
no_license
<?php require_once __DIR__ .DIRECTORY_SEPARATOR."../interfaces/canExport.php"; class htmlExport implements canExport{ public function export() { echo "data format : html"; } }
true
af6506e59684504416d0dfa31424943a8e6b3341
PHP
sqj-modules/Digiccy
/Support/Contracts/Market/Repository.php
UTF-8
1,123
2.8125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: sunqingjiang * Date: 2018/11/8 * Time: 11:21 AM */ namespace SQJ\Modules\Digiccy\Support\Contracts\Market; use Illuminate\Contracts\Events\Dispatcher; class Repository { private $market; private $events; public function __construct(Market $market) { $this->market = $market; } /** * Set the event dispatcher instance. * * @param \Illuminate\Contracts\Events\Dispatcher $events * @return void */ public function setEventDispatcher(Dispatcher $events) { $this->events = $events; } /** * 获取市场中所有的交易币 * * @return mixed */ public function queryAllCurrencies() { return $this->market->queryAllCurrencies(); } public function queryAllSymbols() { return $this->market->queryAllSymbols(); } /** * 获取指定交易对的聚合行情 * @param $symbol * @return mixed */ public function queryMergedTicker($symbol) { return $this->market->queryMergedTicker($symbol); } }
true
4db8874b15085218bf6cfc0092d9e2541a2e2be3
PHP
aedart/athenaeum
/packages/Http/Clients/src/Requests/Builders/Concerns/Cookies.php
UTF-8
3,593
3
3
[ "BSD-3-Clause" ]
permissive
<?php namespace Aedart\Http\Clients\Requests\Builders\Concerns; use Aedart\Contracts\Http\Clients\Requests\Builder; use Aedart\Contracts\Http\Cookies\Cookie; use Aedart\Http\Clients\Exceptions\InvalidCookieFormat; use Aedart\Http\Cookies\SetCookie; use Throwable; /** * Concerns Cookies * * @see Builder * @see Builder::withCookie * @see Builder::withCookies * @see Builder::withoutCookie * @see Builder::hasCookie * @see Builder::getCookie * @see Builder::getCookies * @see Builder::addCookie * @see Builder::makeCookie * * @author Alin Eugen Deac <aedart@gmail.com> * @package Aedart\Http\Clients\Requests\Builders\Concerns */ trait Cookies { /** * Cookies * * @var Cookie[] Key = cookie name, value = cookie instance */ protected array $cookies = []; /** * @inheritdoc * * @throws Throwable */ public function withCookie(Cookie|array|callable $cookie): static { if (is_array($cookie)) { $cookie = $this->makeCookie($cookie); } if (is_callable($cookie)) { $cookie = $this->resolveCallbackCookie($cookie); } if (!($cookie instanceof Cookie)) { throw new InvalidCookieFormat('Argument must be a Cookie instance, array, or callback'); } // Add to list of cookies $this->cookies[$cookie->getName()] = $cookie; return $this; } /** * @inheritdoc * * @throws Throwable */ public function withCookies(array $cookies = []): static { foreach ($cookies as $cookie) { $this->withCookie($cookie); } return $this; } /** * @inheritdoc */ public function withoutCookie(string $name): static { unset($this->cookies[$name]); return $this; } /** * @inheritdoc */ public function hasCookie(string $name): bool { return isset($this->cookies[$name]); } /** * @inheritdoc */ public function getCookie(string $name): ?Cookie { if ($this->hasCookie($name)) { return $this->cookies[$name]; } return null; } /** * @inheritdoc */ public function getCookies(): array { return array_values($this->cookies); } /** * @inheritdoc * * @throws Throwable */ public function addCookie(string $name, string|null $value = null): static { return $this->withCookie([ 'name' => $name, 'value' => $value ]); } /** * @inheritdoc * * @throws Throwable */ public function makeCookie(array $data = []): Cookie { // NOTE: The SetCookie inherits from Cookie. While this // shouldn't be used for requests, it might be useful // for responses, should such be required, e.g. // response formatting, ...etc. return new SetCookie($data); } /***************************************************************** * Internals ****************************************************************/ /** * Resolves a cookie from given callback * * @param callable $callback New {@see Cookie} instance is given as callback argument * * @return Cookie * * @throws Throwable */ protected function resolveCallbackCookie(callable $callback): Cookie { // Create cookie $cookie = $this->makeCookie(); // Invoke the callback $callback($cookie); // Finally, return cookie return $cookie; } }
true
2711b2ed30a21ee9cc68b761455dcc04d7469c57
PHP
ameliendrez/Empleados-Empresa
/Resolucion/clases/Designer.php
UTF-8
346
3.171875
3
[]
no_license
<?php class Designer extends Employee{ function __construct() { parent::__construct(); } public function getSpecility() { return $this->speciality; } public function setSpeciality($typeDesign) { $this->speciality = $typeDesign; } } ?>
true
435e406de68531bbc4f22f92c2637e08601ae83f
PHP
stof/aws
/src/Service/CodeDeploy/src/ValueObject/ErrorInformation.php
UTF-8
1,179
3.140625
3
[ "MIT" ]
permissive
<?php namespace AsyncAws\CodeDeploy\ValueObject; use AsyncAws\CodeDeploy\Enum\ErrorCode; /** * Information about any error associated with this deployment. */ final class ErrorInformation { /** * For more information, see Error Codes for CodeDeploy in the CodeDeploy User Guide. * * @see https://docs.aws.amazon.com/codedeploy/latest/userguide/error-codes.html * @see https://docs.aws.amazon.com/codedeploy/latest/userguide */ private $code; /** * An accompanying error message. */ private $message; /** * @param array{ * code?: null|ErrorCode::*, * message?: null|string, * } $input */ public function __construct(array $input) { $this->code = $input['code'] ?? null; $this->message = $input['message'] ?? null; } public static function create($input): self { return $input instanceof self ? $input : new self($input); } /** * @return ErrorCode::*|null */ public function getCode(): ?string { return $this->code; } public function getMessage(): ?string { return $this->message; } }
true
e5f6a5fd2def831c70ff371ce92dadaddb67299d
PHP
Ibrahim-Elsanhouri/PHPMVC
/src/Http/Request.php
UTF-8
211
2.640625
3
[]
no_license
<?php namespace Src\Http; class Request{ public function method(){ return strtolower($_SERVER['REQUEST_METHOD']); } public function path(){ return $_SERVER['REQUEST_URI']; } }
true
8ee710e483b8abb898619a844022a6d184c52cfc
PHP
therakib7/mombo-wp
/inc/frontend/schema.php
UTF-8
19,150
2.859375
3
[]
no_license
<?php /** * Theme Helpers * * @package Mombo * @since 1.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; } if(! class_exists( 'Mombo_Helpers' ) ) { /** * The Mombo Helpers */ class Mombo_Helpers { public function __construct() { //Print Theme Colors $this->mombo_color(); //Print Heading Colors //$this->mombo_main_headings_color(); //Header Color Background and styles //$this->mombo_backgound_image_cover_bg(); //Spacing Elements //$this->mombo_spaing_elements( ); } /** * Hexa to RGBA Convector * * @package Mombo * @since 1.0 */ private function mombo_hex_2_rgba($color, $opacity = false) { $default = 'rgb(0,0,0)'; //Return default if no color provided if(empty($color)) return $default; //Sanitize $color if "#" is provided if ($color[0] == '#' ) { $color = substr( $color, 1 ); } //Check if color has 6 or 3 characters and get values if (strlen($color) == 6) { $hex = array( $color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5] ); } elseif ( strlen( $color ) == 3 ) { $hex = array( $color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2] ); } else { return $default; } //Convert hexadec to rgb $rgb = array_map('hexdec', $hex); //Check if opacity is set(rgba or rgb) if($opacity){ if(abs($opacity) > 1) $opacity = 1.0; $output = 'rgba('.implode(",",$rgb).','.$opacity.')'; } else { $output = 'rgb('.implode(",",$rgb).')'; } //Return rgb(a) color string return $output; } /** * Theme Colors * * @package Mombo * @since 1.0 */ public function mombo_color() { // $theme_primary_rgba = $this->mombo_hex_2_rgba($theme_color_primary, 0.8); $theme_color_primary = mombo_get_options(array('theme_color_primary', '#03c')); $theme_color_primary_hover = mombo_get_options(array('theme_color_primary_hover', '#002080')); $theme_color_primary_light = mombo_get_options(array('theme_color_primary_light', 'rgba(0, 51, 204, 0.1)')); $theme_color_secondary = mombo_get_options(array('theme_color_secondary', '#15db95')); $theme_color_secondary_hover = mombo_get_options(array('theme_color_secondary_hover', '#0e9566')); $theme_color_secondary_light = mombo_get_options(array('theme_color_secondary_light', 'rgba(21, 219, 149, 0.1)')); ?> a { color: <?php echo esc_attr($theme_color_primary); ?>; } a:hover { color: <?php echo esc_attr($theme_color_primary_hover); ?>; } .theme-color { color: <?php echo esc_attr($theme_color_primary); ?> !important; } .theme-bg { background: <?php echo esc_attr($theme_color_primary); ?> !important; } .theme-bg-alt { background: <?php echo esc_attr($theme_color_primary_light); ?> !important; } .m-btn-theme { background: <?php echo esc_attr($theme_color_primary); ?> !important; } .theme2nd-color { color: <?php echo esc_attr($theme_color_secondary); ?> !important; } .theme2nd-bg { background: <?php echo esc_attr($theme_color_secondary); ?> !important; } .theme2nd-bg-alt { background: <?php echo esc_attr($theme_color_secondary_light); ?> !important; } .m-btn-theme2nd { background: <?php echo esc_attr($theme_color_secondary); ?> !important; } .pagination .page-item.active .page-link, .pagination .page-item .page-link:hover { background: <?php echo esc_attr($theme_color_primary); ?> !important; border-color: <?php echo esc_attr($theme_color_primary); ?> !important; } .post .nav span.dark-color a:hover { color: <?php echo esc_attr($theme_color_primary); ?> !important; } .comment-reply .m-btn:hover, .woocommerce-pagination ul li a:hover, .wp-block-tag-cloud a:hover { background: <?php echo esc_attr($theme_color_primary); ?> !important; } .comment-reply .m-btn{ border-color: <?php echo esc_attr($theme_color_primary); ?> !important; } .top-button { background: <?php echo esc_attr($theme_color_primary); ?> !important; } .top-button:hover { background: <?php echo esc_attr($theme_color_primary_hover); ?> !important; color: #fff; } @media (min-width: 992px) { .main-menu ul.menu ul.sub-menu { border-color: <?php echo esc_attr($theme_color_primary); ?> !important; } } @media (max-width: 992px) { .main-menu ul.menu > li:hover > a, .main-menu ul li a:hover { color: <?php echo esc_attr($theme_color_primary); ?> !important; } } .user-registration-form-login.login input[type=submit], .post-page-numbers.current span , .post-password-form [type=submit], .form-submit input, .woocommerce-product-search button, .woocommerce-pagination ul li span , .wp-block-button__link, .wp-block-search__button, .woocommerce button.button, .woocommerce-form-login__submit, .single_add_to_cart_button, .widget_price_filter .price_slider_wrapper .ui-widget-content, .product .onsale, .button.alt, .actions button, .woocommerce a.button { background-color: <?php echo esc_attr($theme_color_primary); ?> !important; color: #fff !important; } .main-menu .tc-menu-close, .tc-toggle-menu i, .main-menu ul.menu ul.sub-menu { background-color: #fff; } /* ==== Background hover ==== */ .post-password-form [type=submit]:hover, .form-submit input:hover, .widget_price_filter .price_slider_wrapper button:hover, .woocommerce-product-search button:hover, .woocommerce a.button:hover { background: #002080 !important; } /* ==== Widget Hover ==== */ .widget_recent_comments ul a:hover, .widget_recent_entries ul li a:hover, .widget_layered_nav ul li a:hover, .widget_product_categories ul li a:hover, .widget_nav_menu ul li a:hover, .widget_pages ul li a:hover, .widget_archive ul li a:hover, .widget_meta ul li a:hover, .widget_categories ul li a:hover { color: <?php echo esc_attr($theme_color_primary); ?> !important; } .widget_calendar tr td:hover, .widget_calendar tr td:hover a, .tagcloud a:hover { background: <?php echo esc_attr($theme_color_primary); ?>; color: #fff !important; } /* ==== Color hover ==== */ .main-menu ul.menu ul.sub-menu li a:hover, .fixed-header .main-menu ul.menu > li:hover > a, .woocommerce-MyAccount-navigation ul li a:hover, .menu-color-dark ul.menu > li:hover > a, .menu-color-dark ul.menu > li:hover > i, table th a:hover, table td a:hover, .wp-block-latest-comments__comment-meta a:hover, .wp-block-latest-posts.wp-block-latest-posts__list li a:hover, .wp-block-archives.wp-block-archives-list li a:hover, .wp-block-rss .wp-block-rss__item-title a:hover { color: <?php echo esc_attr($theme_color_primary); ?> !important; } .wp-block-tag-cloud a:hover, .comment-reply .m-btn:hover, .widget_price_filter .price_slider_wrapper button:hover, .woocommerce-pagination ul li a:hover { color: #fff !important; } /* ==== Color ==== */ .woocommerce-MyAccount-navigation ul li.is-active a, .menu-color-dark ul li.menu-item-object-page.current_page_item a, .comment-reply .m-btn, .fixed-header ul li.current_page_item a, .menu-item-object-page.current-menu-ancestor > a, .menu-item-object-page.current-menu-ancestor > a, .main-menu ul li ul li.menu-item-object-page.current_page_item > a { color: <?php echo esc_attr($theme_color_primary); ?> !important; } .wp-block-button__link, .wp-block-search__button, .woocommerce button.button, .woocommerce-form-login__submit, .button.alt, .actions button, .woocommerce a.button, .white-color, .blog-grid-overlay h5, .post-page-numbers.current span, .woocommerce-pagination ul li span, .main-menu ul > li > a, .widget_price_filter .price_slider_wrapper button, .product .added_to_cart, .woocommerce-product-search button { color: #fff !important; } .price-table-03 .pt-head .price, .wp-block-tag-cloud a, .main-menu ul.sub-menu .fa-angle-right, .main-menu .tc-menu-close, .menu-color-dark ul.menu > li.menu-item > a, .menu-color-dark ul.menu > li > i, .header-nav.header-white.fixed-header .main-menu ul .fa-angle-down, .tc-toggle-menu i, .woocommerce-EditAccountForm.edit-account fieldset legend, .wp-block-latest-posts.wp-block-latest-posts__list + p, .wp-block-latest-posts.wp-block-latest-posts__list li a, .gallery-size-thumbnail + p, .wp-block-search + p, .wp-block-tag-cloud + p, .comment-body .comment-reply-link, .comment-body .comment-metadata .c-name a, table td a, table th, table th a, .woocommerce-cart-form__contents td a, .woocommerce-cart-form__contents th, .widget_recently_viewed_products li a, .woocommerce-pagination ul li a, .woocommerce-tabs ul.tabs li a, .woocommerce-result-count, .textwidget strong, .widget_rss ul .rsswidget, .widget_rss .h5 a, .wp-block-calendar table th, .widget_calendar thead tr th, .tagcloud a, .widget .h5, h5, .card-body strong, .entry-content strong { color: #171347 !important; } /* ==== Theme Bg Color Primary Hover, Active, Focus, After, Before ==== */ .video-btn.theme:after, #loading, .herbyCookieConsent .herbyBtn, .navbar-toggler, .owl-dots .owl-dot.active, .portfolio-filter-01 .filter li:after, .tab-style-1 .nav-item a:after, .price-table-01 .pt-head:after, .tab-style-4 .nav .nav-item a:after, .custom-control-input:checked ~ .custom-control-label:before, .tab-style-5 .nav-tabs .nav-item > a.active, .pagination .page-item.active .page-link, .video-btn.theme, .m-btn.m-btn-theme, .theme-bg, .theme-after:after, .theme-before:before, .social-icon.theme a, .social-icon.theme2nd a:hover, .m-btn.m-btn-theme-light.active, .m-btn.m-btn-theme-light:focus, .m-btn.m-btn-theme-light:hover, .theme-hover-bg:hover, .portfolio-box-02 .portfolio-desc .pb-tag a:hover, .tag-cloud a:hover, .pagination .page-item .page-link:hover, .m-btn.m-btn-t-theme.active, .m-btn.m-btn-t-theme:focus, .m-btn.m-btn-t-theme:hover { background-color: <?php echo esc_attr($theme_color_primary); ?> !important; } /* ==== Theme Color Primary ==== */ .m-btn.m-btn-theme-light, .m-btn.m-btn-t-theme, .m-link-theme, .m-btn.m-link.theme, .video-btn.white span, .theme-color, .header-white .main-navbar .navbar-nav > li > a.active, .header-dark .main-navbar .navbar-nav > li > a.active, .header-white .main-navbar .navbar-nav > li:hover > a, .header-dark .main-navbar .navbar-nav > li:hover > a, .px-dropdown .px-dropdown-menu > li:hover > a, .px-mega .mm-title, .px-mega .mm-link li:hover > a, .mm-in .mm-dorp-in > li > a:hover, .mm-in .px-mega-menu .mm-title, .mm-in .px-mega-menu .mm-link > li > a:hover, .portfolio-filter-01 .filter li:hover, .portfolio-filter-01 .filter li.active, .portfolio-box-02 .gallery-link:hover, .portfolio-box-02 .portfolio-desc .pb-tag a, .tab-style-1 .nav-item a.active, .tab-style-2 .nav .nav-item a.active, .tab-style-2 .nav .nav-item a.active, .tab-style-4 .nav .nav-item .icon, .accordion-03 .acco-group .acco-heading span, .accordion-04 .acco-group .acco-heading span, .accordion-05 .acco-group.acco-active .acco-heading, .accordion-06 .acco-group.acco-active .acco-heading, .list-type-01.theme li i, .list-type-02.theme li i { color: <?php echo esc_attr($theme_color_primary); ?> !important; } /* ==== Theme Color Primary Border ==== */ .techcandle-mega-menu, .m-btn.m-btn-t-theme, .px-dropdown .px-dropdown-menu, .px-mega .px-mega-menu, .owl-dots .owl-dot, .accordion-05 .acco-group .acco-des, .comment-respond-form .form-control:focus, .list-type-05 li:after, .m-btn.m-btn-t-gray:focus, .m-btn.m-btn-t-gray:hover, .border-color-theme, .card-frame:hover, .accordion-06 .acco-group.acco-active .acco-heading:after, .tag-cloud a:hover, .pagination .page-item .page-link:hover .pagination .page-item.active .page-link, .custom-control-input:checked ~ .custom-control-label:before { border-color: <?php echo esc_attr($theme_color_primary); ?> !important; } /* ==== Theme Color Secondary Bg Hover, Active, Focus, After, Before ==== */ .m-btn.m-btn-theme2nd-light.active, .m-btn.m-btn-theme2nd-light:focus, .m-btn.m-btn-theme2nd-light:hover, .m-btn.m-btn-t-theme2nd.active, .m-btn.m-btn-t-theme2nd:focus, .m-btn.m-btn-t-theme2nd:hover, .theme2nd-bg, .theme2nd-after:after, .theme2nd-before:before, .social-icon.theme a:hover, .social-icon.theme2nd a, .counter-col-02 .cc-icon:after, .tab-style-2 .nav .nav-item a:after, .tab-style-3 .nav a:after, .price-table .pt-head .msg, .price-table-01 .pt-head .msg, .price-table-01.active .pt-head:after, .blog-grid .b-meta .meta, .list-type-03 li i, .m-btn.m-btn-theme2nd { background-color: <?php echo esc_attr($theme_color_secondary); ?> !important; } /* ==== Theme Color Secondary ==== */ .m-btn.m-btn-theme2nd-light, .m-btn.m-btn-t-theme2nd, .m-link-theme2nd, .m-btn.m-link.theme2nd, .theme2nd-color, .tab-style-3 .nav a.active, .list-type-02 li i { color: <?php echo esc_attr($theme_color_secondary); ?> !important; } /* ==== Theme Border Color Secondary ==== */ .m-btn.m-btn-t-theme2nd, .list-type-04 li:after, .border-color-theme2nd { border-color: <?php echo esc_attr($theme_color_secondary); ?> !important; } /* ==== Theme Color Secondary Hover, Focus, Active ==== */ .m-btn.m-btn-theme2nd.active, .m-btn.m-btn-theme2nd:focus, .m-btn.m-btn-theme2nd:hover { background: <?php echo esc_attr($theme_color_secondary_hover); ?> !important; } /* ==== Theme Color Secondary Light ==== */ .theme2nd-bg-alt { background-color: <?php echo esc_attr($theme_color_secondary_light); ?> !important; } /* ==== Theme Color Primary Light ==== */ .theme-bg-alt { background-color: <?php echo esc_attr($theme_color_primary_light); ?> !important; } /* ==== Theme Color Primary Hover, Focus, Active ==== */ .m-btn.m-btn-theme.active, .m-btn.m-btn-theme:focus, .m-btn.m-btn-theme:hover { background: <?php echo esc_attr($theme_color_primary_hover); ?> !important; } <?php } // end mombo_color function /** * Title Color * * @package Mombo * @since 1.0 */ public function mombo_main_headings_color() { } /** * Theme Background Colors * * @package Mombo * @since 1.0 */ public function mombo_backgound_image_cover_bg() { ?> <?php } /** * Theme Spacing Element * * @package Mombo * @since 1.0 */ public function mombo_spaing_elements() { // Return CSS /* if ( ! empty( $css ) ) { echo wp_strip_all_tags( $css ); } */ } } } new Mombo_Helpers;
true
cd559205de9325534e86e18c2bfb1e58d6ba5ce5
PHP
hellangel28/moephp4-collection
/tests/MoePHP4/Collections/ReferencedCollectionTest.php
UTF-8
35,801
3.046875
3
[]
no_license
<?php namespace tests\MoePHP4\Collection; use MoePHP4\Collections\Collection; use MoePHP4\Collections\Exception\CollectionException; use MoePHP4\Collections\ReferencedCollection; use PHPUnit\Framework\TestCase; /** * Class ReferencedCollectionTest * @package tests\MoePHP4\Collections */ class ReferencedCollectionTest extends TestCase { /** * @throws CollectionException */ public function testStaticUnwrap() { $arr = [1, 2, 3]; $collection = new ReferencedCollection($arr); $unwrapped = &ReferencedCollection::unwrap($collection); $this->assertSame(count($arr), count($unwrapped)); } /** * @throws CollectionException */ public function testStaticUnwrap_notArrayOrCollection() { $this->expectException(CollectionException::class); $this->expectExceptionMessage('Can only unwrap collections and arrays'); $wrapped = "test"; $unwrapped = ReferencedCollection::unwrap($wrapped); $this->assertSame($unwrapped, $wrapped); } /** * */ public function testStaticUnwrap_isReference() { $arr = [1, 2, 3]; $collection = new ReferencedCollection($arr); $unwrapped = ReferencedCollection::unwrap($collection); $this->assertSame(3, count($unwrapped)); unset($arr[0]); $unwrapped = ReferencedCollection::unwrap($collection); $this->assertSame(2, count($unwrapped)); } /** * */ public function testStaticUnwrap_array() { $arr = [1, 2, 3]; $unwrapped = ReferencedCollection::unwrap($arr); $this->assertSame(3, count($unwrapped)); } // non-static methods /** * */ public function testConstruct_Reference() { $arr = [1, 2, 3]; $collection = new ReferencedCollection($arr); unset($arr[0]); $this->assertSame(2, $collection->count()); } /** * */ public function testCreateWithoutReference() { $array = [1, 2, 3]; $withoutRef = new Collection($array); unset($array[0]); $this->assertSame(3, $withoutRef->count()); } /** * */ public function testAccumulate() { $array = [1, 2, 3, 4, 5]; $collection = new ReferencedCollection($array); $result = $collection->accumulate(function ($acc, $current) { return $acc + $current; }); $this->assertSame(15.0, $result); } public function testAverage() { $collection = new Collection([1, 1, 1, 1, 1, 5, 5, 5, 5, 5]); $this->assertSame(3.0, $collection->average()); } /** * */ public function testChunk() { $array = [1, 2, 3, 4, 5, 6, 7]; $collection = new ReferencedCollection($array); $chunks = $collection->chunk(2); $this->assertSame(4, $chunks->count()); $this->assertSame(2, $chunks[0]->count()); $this->assertSame(2, $chunks[1]->count()); $this->assertSame(2, $chunks[2]->count()); $this->assertSame(1, $chunks[3]->count()); $this->assertFalse(array_key_exists(4, $chunks->getArrayReference())); } /** * */ public function testClear() { $array = [1, 2, 3, 4, 5]; $collection = new ReferencedCollection($array); $collection->clear(); $this->assertSame(0, count($array)); } /** * */ public function testConcat() { $a = [1, 2, 3]; $b = [4, 5, 6]; $collection = new ReferencedCollection($a); $collection->concat($b); $this->assertSame(3, $collection->count()); $this->assertSame(4, $collection->get(0)); $this->assertSame(5, $collection->get(1)); $this->assertSame(6, $collection->get(2)); } /** * */ public function testConcat_noOverwriteKeys() { $a = [1, 2, 3]; $b = [4, 5, 6]; $collection = new ReferencedCollection($a); $collection->concat($b, false); $this->assertSame(3, $collection->count()); $this->assertSame(1, $collection->get(0)); $this->assertSame(2, $collection->get(1)); $this->assertSame(3, $collection->get(2)); } /** * */ public function testConcatCollection() { $a = [1, 2, 3]; $b = [4, 5, 6]; $collection = new ReferencedCollection($a); $collection->concatCollection(new ReferencedCollection($b)); $this->assertSame(3, $collection->count()); $this->assertSame(4, $collection->get(0)); $this->assertSame(5, $collection->get(1)); $this->assertSame(6, $collection->get(2)); } /** * */ public function testConcatCollection_noOverwriteKeys() { $a = [1, 2, 3]; $b = [4, 5, 6]; $collection = new ReferencedCollection($a); $collection->concatCollection(new ReferencedCollection($b), false); $this->assertSame(3, $collection->count()); $this->assertSame(1, $collection->get(0)); $this->assertSame(2, $collection->get(1)); $this->assertSame(3, $collection->get(2)); } /** * */ public function testContains() { $collection = new Collection(["test", "another"]); $this->assertTrue($collection->contains('test')); $this->assertTrue($collection->contains('another')); } /** * */ public function testCopy() { $array = [1, 2, 3, 4]; $collection = new ReferencedCollection($array); $copy = $collection->copy(); unset($array[0]); $this->assertSame(3, $collection->count()); $this->assertSame(4, $copy->count()); } /** * */ public function testCount() { $array = [1, 2, 3]; $test = new ReferencedCollection($array); $this->assertSame(3, $test->count()); $array = [1, 2, 3, 4, 5]; $test = new ReferencedCollection($array); $this->assertSame(5, $test->count()); } /** * */ public function testExtract() { $collection = new Collection([ "a" => "one", "b" => "two", "c" => "three", ]); $only = $collection->extract(['a', 'b']); $this->assertSame(2, $only->count()); $this->assertSame('one', $only->get("a")); $this->assertSame('two', $only->get("b")); $this->assertFalse($only->keyExists("c")); $this->assertTrue($collection->keyExists("c")); $this->assertFalse($collection->keyExists("a")); $this->assertFalse($collection->keyExists("b")); $this->assertSame(1, $collection->count()); } /** * */ public function testFilter() { $array = [1, 2, 3, 4, 5]; $test = new ReferencedCollection($array); $test->filter(function (int $value) { return $value > 3; }); $this->assertSame(2, $test->count()); } /** * */ public function testFind() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->find(function ($value) { return ($value == 'abc'); }); $this->assertSame($result, 'abc'); } /** * */ public function testFind_notFound() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->find(function ($value) { return ($value == 'defg'); }); $this->assertFalse($result); } public function testFindClosest() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->findClosest(null, 'abc'); $this->assertSame('abc', $result[0]['entry']); $this->assertSame('bla', $result[1]['entry']); $this->assertSame('test', $result[2]['entry']); } public function testFindClosestOne() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->findClosestOne(null, 'abc'); $this->assertSame('abc', $result); } public function testFindClosestOne_emptyList() { $array = []; $collection = new ReferencedCollection($array); $result = $collection->findClosestOne(null, 'abc'); $this->assertSame(null, $result); } /** * */ public function testFindIndex() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->findIndex(function ($value) { return ($value == 'abc'); }); $this->assertSame(1, $result); } /** * */ public function testFindIndex_notFound() { $array = ['test', 'abc', 'bla']; $collection = new ReferencedCollection($array); $result = $collection->findIndex(function ($value) { return ($value == 'defg'); }); $this->assertFalse($result); } /** * */ public function testFirst() { $array = [1, 2, 3]; $collection = new ReferencedCollection($array); $this->assertSame(1, current($array)); $this->assertSame(1, $collection->first()); next($array); $this->assertSame(2, current($array)); $this->assertSame(1, $collection->first()); $this->assertSame(2, current($array)); } /** * */ public function testFlatten() { $collection = new Collection([ 'test' => 'value', 'another' => [ 'subtest' => 'subvalue', 'subsubarr' => [ 1, 2, 3 ] ] ]); /* expected result: array(3) { 'test' => string(5) "value" 'subtest' => string(8) "subvalue" 'subsubarr' => array(3) { [0] => int(1) [1] => int(2) [2] => int(3) } } */ $collection->flatten(1); $arr = $collection->getArray(); $this->assertSame(3, count($arr)); $this->assertSame('value', $arr['test']); $this->assertSame([1, 2, 3], $arr['subsubarr']); $this->assertSame('subvalue', $arr['subtest']); } /** * */ public function testFlip() { $collection = new Collection(["A", "B", 'C', 'D', 'F']); $collection->flip(); $arr = $collection->getArray(); reset($arr); $this->assertSame(0, current($arr)); next($arr); $this->assertSame(1, current($arr)); next($arr); $this->assertSame(2, current($arr)); next($arr); $this->assertSame(3, current($arr)); next($arr); $this->assertSame(4, current($arr)); next($arr); } /** * */ public function testGet() { $collection = new Collection(['test', 'abc']); $keys = $collection->getKeys(); $this->assertSame(2, $keys->count()); $this->assertSame($keys->get(0), 0); $this->assertSame($keys->get(1), 1); } /** * */ public function testGetIfExists() { $collection = new Collection(['exists' => true]); $this->assertSame(true, $collection->getIfExists("exists")); $this->assertSame(null, $collection->getIfExists("doesNotExist")); $this->assertSame("something", $collection->getIfExists("doesNotExist", "something")); } /** * */ public function testGetKeys() { $collection = new Collection(['test', 'abc']); $keys = $collection->getKeys()->getArray(); $this->assertSame(2, count($keys)); $this->assertSame($keys[0], 0); $this->assertSame($keys[1], 1); } /** * */ public function testGetValues() { $collection = new Collection(['test', 'abc']); $keys = $collection->getValues()->getArray(); $this->assertSame(2, count($keys)); $this->assertSame($keys[0], 'test'); $this->assertSame($keys[1], 'abc'); } /** * */ public function testIndexOf() { $collection = new Collection(['test', 'abc']); $index = $collection->indexOf('abc'); $this->assertSame(1, $index); } /** * */ public function testInsert() { $collection = new Collection(['test']); $collection->insert("abc", "test"); $this->assertSame('test', $collection->get("abc")); } /** * */ public function testIsEmpty_notEmpty() { $collection = new Collection([1, 2, 3]); $this->assertFalse($collection->isEmpty()); } /** * */ public function testIsEmpty_isEmpty() { $collection = new Collection([]); $this->assertTrue($collection->isEmpty()); } /** * */ public function testJoin() { $collection = new Collection(['abc', 'defg', 'abc']); $result = $collection->join(); $this->assertSame("abc,defg,abc", $result); } /** * */ public function testJoin_withCustomSeparator() { $collection = new Collection(['abc', 'defg', 'abc']); $result = $collection->join("SEPARATOR"); $this->assertSame("abcSEPARATORdefgSEPARATORabc", $result); } /** * */ public function testLast() { $array = [1, 2, 3]; $collection = new ReferencedCollection($array); $this->assertSame(1, current($array)); $this->assertSame(3, $collection->last()); next($array); $this->assertSame(2, current($array)); $this->assertSame(3, $collection->last()); $this->assertSame(2, current($array)); } /** * */ public function testLastIndexOf() { $collection = new Collection(['abc', 'defg', 'abc', 'defg']); $result = $collection->lastIndexOf('abc'); $this->assertSame(2, $result); $result = $collection->lastIndexOf('defg'); $this->assertSame(3, $result); } /** * */ public function testKeyExists() { $collection = new Collection(['test' => 'bla']); $this->assertTrue($collection->keyExists('test')); } /** * */ public function testKeyExists_doesNotExist() { $collection = new Collection(['test' => 'bla']); $this->assertFalse($collection->keyExists('undefined')); } /** * */ public function testMap() { $collection = new Collection([ [2, 2], [3, 3] ]); $collection->map(function ($value) { $result = 0; foreach ($value as $item) { $result += $item; } return $result; }); $this->assertSame(4, $collection->get(0)); $this->assertSame(6, $collection->get(1)); } /** * */ public function testMin() { $array = [5, 10, 15]; $collection = new ReferencedCollection($array); $min = $collection->min(); $this->assertSame(5.0, $min); } /** * */ public function testMinSub() { $array = [ ['test' => 50], ['test' => 15], ['nope' => 1], ['test' => 33] ]; $collection = new ReferencedCollection($array); $min = $collection->minSub('test'); $this->assertSame(15.0, $min); $min = $collection->minSub('nope'); $this->assertSame(1.0, $min); } /** * */ public function testMinCustom() { $array = [ ['test' => 50], ['test' => 15], ['nope' => 1], ['test' => 33] ]; $collection = new ReferencedCollection($array); $min = $collection->minCustom(function ($value) { return current($value); }); $this->assertSame(1.0, $min); } /** * */ public function testMinCustom_withFalseReturn() { $array = [ ['test' => 50], ['test' => 15], ['nope' => false], ['test' => 33] ]; $collection = new ReferencedCollection($array); $min = $collection->minCustom(function ($value) { return current($value); }); $this->assertSame(15.0, $min); } /** * */ public function testMax() { $array = [5, 10, 15]; $collection = new ReferencedCollection($array); $max = $collection->max(); $this->assertSame(15.0, $max); } /** * */ public function testMaxChild() { $array = [ ['test' => 50], ['test' => 15], ['nope' => 111], ['test' => 33] ]; $collection = new ReferencedCollection($array); $max = $collection->maxChild('test'); $this->assertSame(50.0, $max); $max = $collection->maxChild('nope'); $this->assertSame(111.0, $max); } /** * */ public function testMaxCustom() { $array = [ ['test' => 50], ['test' => 15], ['nope' => 100], ['test' => 33] ]; $collection = new ReferencedCollection($array); $max = $collection->maxCustom(function ($value) { return current($value); }); $this->assertSame(100.0, $max); } /** * */ public function testMaxCustom_withFalseReturn() { $array = [ ['test' => 50], ['test' => 15], ['nope' => false], ['test' => 33] ]; $collection = new ReferencedCollection($array); $max = $collection->maxCustom(function ($value) { return current($value); }); $this->assertSame(50.0, $max); } /** * */ public function testNth() { $array = [1, 2, 3, 4, 5, 6, 7, 8]; $collection = new ReferencedCollection($array); $nth = $collection->nth(2); $this->assertSame(4, $nth->count()); $this->assertSame(1, $nth[0]); $this->assertSame(3, $nth[1]); $this->assertSame(5, $nth[2]); $this->assertSame(7, $nth[3]); } /** * */ public function testOnly() { $collection = new Collection([ "a" => "one", "b" => "two", "c" => "three", ]); $only = $collection->only(['a', 'b']); $this->assertSame(2, $only->count()); $this->assertSame('one', $only->get("a")); $this->assertSame('two', $only->get("b")); $this->assertFalse($only->keyExists("c")); } /** * */ public function testPop() { $array = [1, 2, 3]; $collection = new ReferencedCollection($array); $this->assertSame(3, $collection->pop()); $this->assertSame(2, $collection->count()); $this->assertSame(2, $collection->pop()); $this->assertSame(1, $collection->count()); $this->assertSame(1, $collection->pop()); $this->assertSame(null, $collection->pop()); $this->assertSame(0, $collection->count()); } /** * */ public function testPull() { $array = ['test' => 1, 'another' => 2]; $collection = new ReferencedCollection($array); $entry = $collection->pull("test"); $this->assertSame(1, $entry); $this->assertSame(1, count($array)); } /** * */ public function testPush() { $collection = new Collection([1, 2]); $this->assertSame(2, $collection->count()); $collection->push("SomeTest"); $this->assertTrue($collection->keyExists(2)); $this->assertSame('SomeTest', $collection->get(2)); } /** * */ public function testPushOnTop() { $collection = new Collection([1, 2, 3]); $collection->pushOnTop('test'); $this->assertSame("test", $collection->get(0)); $this->assertSame(1, $collection->get(1)); $this->assertSame(2, $collection->get(2)); $this->assertSame(3, $collection->get(3)); } public function testRemove() { $collection = new Collection([1, 2]); $collection->remove(0); $this->assertSame(1, $collection->count()); $this->assertSame(2, $collection[1]); } public function testRemoveItem() { $testA = new \stdClass(); $testB = new \stdClass(); $collection = new Collection([$testA, $testB]); $collection->removeItem($testA); $this->assertSame(1, $collection->count()); $this->assertSame($testB, $collection[1]); } /** * */ public function testReverse() { $collection = new Collection([1, 2, 3, 4, 5]); $collection->reverse(); $arr = $collection->getArray(); $this->assertSame(5, current($arr)); next($arr); $this->assertSame(4, current($arr)); next($arr); $this->assertSame(3, current($arr)); next($arr); $this->assertSame(2, current($arr)); next($arr); $this->assertSame(1, current($arr)); next($arr); } /** * */ public function testSelect_noParameters() { $collection = new Collection(range(1, 20)); $selection = $collection->select(); $this->assertSame(20, count($selection)); } /** * */ public function testSelect_onlyLimit() { $collection = new Collection(range(1, 20)); $selection = $collection->select(5); $this->assertSame(5, count($selection)); $this->assertSame(1, $selection[0]); $this->assertSame(5, $selection[4]); } /** * */ public function testSelect_onlyOffset() { $collection = new Collection(range(1, 20)); $selection = $collection->select(null, 15); $this->assertSame(5, count($selection)); $this->assertSame(16, $selection[0]); $this->assertSame(20, $selection[4]); } /** * */ public function testSelect_limitAndOffset() { $collection = new Collection(range(1, 20)); $selection = $collection->select(5, 5); $this->assertSame(5, count($selection)); $this->assertSame(6, $selection[0]); $this->assertSame(10, $selection[4]); } /** * */ public function testSelect_noParameters_collectionIntact() { $collection = new Collection(range(1, 20)); $collection->select(); $this->assertSame(20, $collection->count()); } /** * */ public function testShift() { $collection = new Collection([1, 2, 3]); $this->assertSame(1, $collection->shift()); $this->assertSame(2, $collection->shift()); $this->assertSame(3, $collection->shift()); $this->assertSame(null, $collection->shift()); $this->assertSame(0, $collection->count()); } /** * */ public function testSplit() { $collection = new Collection([1, 2, 3, 4, 5]); $result = $collection->split(function ($value) { return $value % 2 == 0; }); $this->assertSame(2, $result[0]->count()); $this->assertSame(3, $result[1]->count()); $this->assertSame(2, $result[0]->get(1)); $this->assertSame(4, $result[0]->get(3)); $this->assertSame(1, $result[1]->get(0)); $this->assertSame(3, $result[1]->get(2)); $this->assertSame(5, $result[1]->get(4)); } /** * */ public function testSortAlphabetically() { $collection = new Collection(['abc', 'some', 'another']); $collection->sortAlphabetically(); self::assertSame('abc', $collection->get(0)); self::assertSame('another', $collection->get(1)); self::assertSame('some', $collection->get(2)); } /** * */ public function testSortAlphabeticallyKeepKeys() { $collection = new Collection(['abc', 'some', 'another']); $collection->sortAlphabeticallyKeepKeys(); self::assertSame('abc', $collection->get(0)); self::assertSame('another', $collection->get(2)); self::assertSame('some', $collection->get(1)); } /** * */ public function testSortAlphabeticallyDec() { $collection = new Collection(['abc', 'some', 'another']); $collection->sortAlphabeticallyDesc(); self::assertSame('some', $collection->get(0)); self::assertSame('another', $collection->get(1)); self::assertSame('abc', $collection->get(2)); } /** * */ public function testSortAlphabeticallyDescKeepKeys() { $collection = new Collection(['abc', 'some', 'another']); $collection->sortAlphabeticallyDescKeepKeys(); self::assertSame('some', $collection->get(1)); self::assertSame('another', $collection->get(2)); self::assertSame('abc', $collection->get(0)); } /** * */ public function testSortCustom() { $collection = new Collection(['555', '666', '777']); $collection->sortCustom(function ($a, $b) { if ($a == "777") { return -1; } elseif ($b == "777") { return 1; } return 0; }); self::assertSame('777', $collection->get(0)); self::assertSame('555', $collection->get(1)); self::assertSame('666', $collection->get(2)); } /** * */ public function testSortCustomKeepKeys() { $collection = new Collection(['555', '666', '777']); $collection->sortCustomKeepKeys(function ($a, $b) { if ($a == "777") { return -1; } elseif ($b == "777") { return 1; } return 0; }); self::assertSame('777', $collection->get(2)); self::assertSame('555', $collection->get(0)); self::assertSame('666', $collection->get(1)); } /** * */ public function testSortKeysAlphabetical() { $collection = new Collection(['b' => 1, 'a' => 2, 'c' => 3]); $collection->sortKeysAlphabetical(); $this->assertSame(2, reset($collection->getArrayReference())); $this->assertSame(1, next($collection->getArrayReference())); $this->assertSame(3, next($collection->getArrayReference())); } /** * */ public function testSortKeysAlphabeticalDesc() { $collection = new Collection(['b' => 1, 'a' => 2, 'c' => 3]); $collection->sortKeysAlphabeticalDesc(); $this->assertSame(3, reset($collection->getArrayReference())); $this->assertSame(1, next($collection->getArrayReference())); $this->assertSame(2, next($collection->getArrayReference())); } /** * */ public function testSortKeysNumerical() { $collection = new Collection(['2' => "a", '1' => "b", '3' => "c"]); $collection->sortKeysNumerical(); $this->assertSame("b", reset($collection->getArrayReference())); $this->assertSame("a", next($collection->getArrayReference())); $this->assertSame("c", next($collection->getArrayReference())); } /** * */ public function testSortKeysNumericalDesc() { $collection = new Collection(['2' => "a", '1' => "b", '3' => "c"]); $collection->sortKeysNumericalDesc(); $this->assertSame("c", reset($collection->getArrayReference())); $this->assertSame("a", next($collection->getArrayReference())); $this->assertSame("b", next($collection->getArrayReference())); } /** * */ public function testSortKeysCustom() { $collection = new Collection(['2' => "a", '1' => "b", '3' => "c"]); $collection->sortKeysCustom(function ($a, $b) { if ($a == "2") { return -1; } elseif ($a == "1") { return 1; } return 0; }); $this->assertSame("a", reset($collection->getArrayReference())); $this->assertSame("c", next($collection->getArrayReference())); $this->assertSame("b", next($collection->getArrayReference())); } /** * */ public function testSortNumerical() { $collection = new Collection(['123', '3', '444', '15394']); $collection->sortNumerical(); self::assertSame('3', $collection->get(0)); self::assertSame('123', $collection->get(1)); self::assertSame('444', $collection->get(2)); self::assertSame('15394', $collection->get(3)); } /** * */ public function testSortNumericalKeepKeys() { $collection = new Collection(['123', '3', '444', '15394']); $collection->sortNumericalKeepKeys(); self::assertSame('3', $collection->get(1)); self::assertSame('123', $collection->get(0)); self::assertSame('444', $collection->get(2)); self::assertSame('15394', $collection->get(3)); } /** * */ public function testSortNumericallyDesc() { $collection = new Collection(['123', '3', '444', '15394']); $collection->sortNumericalDesc(); self::assertSame('15394', $collection->get(0)); self::assertSame('444', $collection->get(1)); self::assertSame('123', $collection->get(2)); self::assertSame('3', $collection->get(3)); } /** * */ public function testSortNumericallyDescKeepKeys() { $collection = new Collection(['123', '3', '444', '15394']); $collection->sortNumericalDescKeepKeys(); self::assertSame('15394', $collection->get(3)); self::assertSame('444', $collection->get(2)); self::assertSame('123', $collection->get(0)); self::assertSame('3', $collection->get(1)); } /** * */ public function testSum() { $collection = new Collection([1, 2, 3, 4, 5]); $sum = $collection->sum(); $this->assertSame(15.0, $sum); $collection = new Collection([1, 2, 3, 4, 5, 14.5]); $sum = $collection->sum(); $this->assertSame(29.5, $sum); } /** * */ public function testSumInt() { $collection = new Collection([1, 2, 3, 4, 5]); $sum = $collection->sumInt(); $this->assertSame(15, $sum); $collection = new Collection([1, 2, 3, 4, 5, 14.5]); $sum = $collection->sumInt(); $this->assertSame(29, $sum); } /** * */ public function testTestAny() { $collection = new Collection([1, 2, 3, 4, 5]); $result = $collection->testAny(function ($value) { return ($value == 3); }); $this->assertTrue($result); } /** * */ public function testTestAny_fail() { $collection = new Collection([1, 2, 3, 4, 5]); $result = $collection->testAny(function ($value) { return ($value == 15); }); $this->assertFalse($result); } /** * */ public function testTestAll() { $collection = new Collection([1, 2, 3, 4, 5]); $result = $collection->testAll(function () { return true; }); $this->assertTrue($result); } /** * */ public function testTestAll_fail() { $collection = new Collection([1, 2, 3, 4, 5]); $result = $collection->testAll(function ($value) { return ($value != 3); }); $this->assertFalse($result); } /** * */ public function testUnique() { $collection = new Collection([1, 1, 1, 1, 1, 2, 2, 2, 3]); $result = $collection->unique(); $this->assertSame(3, $result->count()); } /** * */ public function testUniqueByKey() { $collection = new Collection([ [ 'test' => 'abc' ], [ 'test' => 'abc' ], [ 'test' => 'abc' ], [ 'test' => 'abc' ], [ 'test' => 'defg' ] ]); $result = $collection->uniqueByKey('test'); $this->assertSame(2, $result->count()); $this->assertSame("abc", $result[0]); $this->assertSame("defg", $result[4]); } /** * */ public function testUnshift() { $collection = new Collection([1, 2, 3]); $collection->unshift('test'); $this->assertSame("test", $collection->get(0)); $this->assertSame(1, $collection->get(1)); $this->assertSame(2, $collection->get(2)); $this->assertSame(3, $collection->get(3)); } /** * */ public function testValueExists_fail() { $collection = new Collection(["test", "another"]); $this->assertFalse($collection->contains('undefined')); } /** * */ public function testArrayAccess_exists() { $array = ['key' => 'test']; $collection = new ReferencedCollection($array); $this->assertTrue(isset($collection['key'])); $this->assertFalse(isset($collection['undefined'])); } /** * */ public function testArrayAccess_get() { $array = ['key' => 'test']; $collection = new ReferencedCollection($array); $this->assertSame('test', $collection['key']); } /** * */ public function testArrayAccess_set() { $array = ['key' => 'test']; $collection = new ReferencedCollection($array); $this->assertSame('test', $array['key']); $collection['key'] = 'test2'; $this->assertSame('test2', $array['key']); } /** * */ public function testArrayAccess_unset() { $array = ['key' => 'test']; $collection = new ReferencedCollection($array); unset($collection['key']); $this->assertSame(0, count($array)); } /** * */ public function testCountable_count() { $collection = new Collection([1, 2, 3, 4, 5]); $this->assertSame(5, count($collection)); } /** * */ public function testIterator_foreach() { $array = ['key' => 'test', 'key2' => 'test2']; $collection = new ReferencedCollection($array); $count = 0; foreach ($collection as $key => $value) { switch ($count) { case 0: $this->assertSame("key", $key); $this->assertSame("test", $value); break; case 1: $this->assertSame("key2", $key); $this->assertSame("test2", $value); break; default: $this->fail("Should not have happened"); } ++$count; } $this->assertSame(2, $count); } }
true
cdcde51e78fe63f6823edeff6893e773385e5993
PHP
ilan84levi/playlist-site-sample
/phpPages/BLL.php
UTF-8
3,261
2.6875
3
[]
no_license
<?php require_once 'DAL.php'; require_once 'playList.php'; require_once 'category.php'; function register($firstName, $lastName, $userName, $password) { $userName = addslashes($userName); $password = addslashes($password); $password = crypt($password, "my site"); // Salt the password. $password = sha1($password); $sql = "INSERT INTO users_details (firstName,lastName,userName,password)" . " VALUES('$firstName', '$lastName','$userName','$password')"; insert($sql); } function getPlayList($userName) { $sql = "SELECT categoryName, name, Description, videoLink,videolist.id as id,category.categoryID as categoryID, videolist.userName AS userName FROM videolist JOIN category ON category.categoryID = videolist.categoryID JOIN users_details ON users_details.userName = videolist.userName WHERE users_details.userName ='$userName'"; $playLists = select($sql); $playListByUser = array(); foreach ($playLists as $p) { $playListByUser[] = new playList($p->categoryName, $p->name, $p->Description, $p->videoLink, $p->id, $p->categoryID, $p->userName); } return $playListByUser; } function is_user_exist($userName, $password) { $userName = addslashes($userName); $password = addslashes($password); $password = crypt($password, "my site"); // Salt the password. $password = sha1($password); $sql = "select count(*) as total_rows from users_details where userName = '$userName' and password = '$password'"; $count = get_object($sql)->total_rows; // echo $count; return $count > 0; } //insert data function addVideo($category, $name, $Description, $videoLink, $userName) { $name = addslashes($name); $Description = addslashes($Description); $videoLink = addslashes($videoLink); $sql = "INSERT INTO videolist(categoryID,name,Description,videoLink,userName) VALUES('$category','$name','$Description','$videoLink', '$userName')"; insert($sql); } function getCatergories() { $sql = "SELECT categoryID, categoryName FROM `category`"; $categories = select($sql); foreach ($categories as $c) { $categoryArr[] = new category($c->categoryID, $c->categoryName); } return $categoryArr; } function deleteVideo($id) { $sql = "DELETE FROM videolist WHERE id = '$id'"; delete($sql); } //update data function updateVideo($name, $description, $videoLink, $catagory, $id) { $name = addslashes($name); $description = addslashes($description); $videoLink = addslashes($videoLink); $sql = "update videolist SET name = '$name', description = '$description' , videoLink = '$videoLink' , categoryID = '$catagory' where id = '$id'"; update($sql); } //serch function serchSql($userName, $serchValue) { $userName = addslashes($userName); $serchValue = addslashes($serchValue); $sql = "SELECT categoryName, name, Description, videoLink,videolist.id as id,category.categoryID as categoryID, videolist.userName FROM videolist JOIN category ON category.categoryID = videolist.categoryID WHERE videolist.userName ='$userName' and (categoryName LIKE '%$serchValue%' OR name LIKE '%$serchValue%' OR Description LIKE '%$serchValue%') "; $playLists = select($sql); return $playLists; }
true
376cfd6d5cbb1b66166cccde3d3ba4493ac33226
PHP
tim-moody/experiments
/cmd-serv/prototype1/client-service.php
UTF-8
760
3.1875
3
[]
no_license
<?php /* * xsce-cmdsrv client * Connects DEALER socket to ipc:///run/cmdsrv_sock * Sends command, expects response back */ ?> <html> <body> <h1>Hello world!</h1> <p>This is being served from xsce-cmdsrv using PHP.</p> <?php // Socket to talk to server $command = $_GET['command']; echo "Command: $command <BR>"; $context = new ZMQContext(); $requester = new ZMQSocket($context, ZMQ::SOCKET_DEALER); $requester->connect("ipc:///run/cmdsrv_sock"); $requester->send($command); $reply = $requester->recv(); echo "message: <BR>$reply"; echo "<BR>"; echo strToHex($reply); function strToHex($string){ $hex=''; for ($i=0; $i < strlen($string); $i++){ $hex .= " " . dechex(ord($string[$i])); } return $hex; } ?> </body> </html>
true
db3e034d6ea03017d55b55e3db1131c32e5506e9
PHP
PauloRenato21/Paulo-phpMailer
/enviaEmail.php
UTF-8
1,453
2.671875
3
[]
no_license
<?php include_once "phpmailer/src/PHPMailer.php"; include_once "phpmailer/src/SMTP.php"; include_once "phpmailer/src/Exception.php"; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; use PHPMailer\PHPMailer\Exception; $nome = $_POST['nome']; $sobrenome = $_POST['sobrenome']; $email = $_POST['email']; $mensagem = $_POST['mensagem']; $mail = new PHPMailer(true); try{ $mail->SMTPDebug = SMTP::DEBUG_SERVER; $mail->CharSet = 'UTF-8'; $mail->isSMTP(); $mail->Host = 'smtp.gmail.com'; $mail->SMTPAuth = true; $mail->Username = ""; $mail->Password = ''; $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; $mail->Port = 587; // $mail->SMTPOptions = array( // 'ssl' => array( // 'verify_peer' => false, // 'verify_peer_name' => false, // 'allow_self_signed' => true // ) // ); $mail->setFrom($mail->Username, "$nome"); $mail->addAddress(''); $conteudo = " Você recebeu uma mensagem de $nome $sobrenome ($email): <br> <br> Mensagem:<br> $mensagem "; $mail->isHTML(true); $mail->Subject = 'Teste de EmailMailer'; $mail->Body = $conteudo; // $mail->AltBody = ; if($mail->send()){ echo "Email Enviado com Sucesso!!"; } else{ echo "Email não enviado"; } } catch (Exception $e) { echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}"; } ?>
true
cf5b2122a9b666acb2f72a6621a5b2ec4a4cb979
PHP
mattiellojr/MVC-CRUD-mySQLi-social-network-app
/functions.php
UTF-8
5,216
2.71875
3
[]
no_license
<?php session_start(); $link = mysqli_connect("shareddb1a.hosting.stackcp.net", "twitter-340109", "fjwqi43r%&/WEF", "twitter-340109"); if(mysqli_connect_error()){ print_r(mysqli_connect_error()); exit(); } if ($_GET['function'] == "logout") { session_unset(); } function time_since($since) { $chunks = array( array(60 * 60 * 24 * 365 , 'year'), array(60 * 60 * 24 * 30 , 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24 , 'day'), array(60 * 60 , 'hour'), array(60 , 'min'), array(1 , 'sec') ); for ($i = 0, $j = count($chunks); $i < $j; $i++) { $seconds = $chunks[$i][0]; $name = $chunks[$i][1]; if (($count = floor($since / $seconds)) != 0) { break; } } $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; return $print; } function displayTweets($type){ global $link; if($type == 'public') { $whereClause = ""; } else if ($type == 'isFollowing') { $query = "SELECT * FROM isFollowing WHERE follower = ".mysqli_real_escape_string($link, $_SESSION['id']); $result = mysqli_query($link, $query); $whereClause = ""; while ($row = mysqli_fetch_assoc($result)) { if ($whereClause == "") $whereClause = "WHERE"; else $whereClause.= " OR"; $whereClause.= " userid = ".$row['isFollowing']; } } else if ($type == 'mytweets') { $whereClause = "WHERE userid= ".mysqli_real_escape_string($link, $_SESSION['id']); } else if ($type == 'search') { echo '<p>Showing search results for "'.mysqli_real_escape_string($link, $_GET['q']).'":</p>'; $whereClause = "WHERE tweet LIKE '%".mysqli_real_escape_string($link, $_GET['q'])."%'"; } else if (is_numeric($type)) { $userQuery = "SELECT * FROM users WHERE id = '".mysqli_real_escape_string($link, $type)."' LIMIT 1"; $userQueryResult = mysqli_query($link, $userQuery); $user = mysqli_fetch_assoc($userQueryResult); echo "<h2>".mysqli_real_escape_string($link, $user['email'])."'s Tweets</h2>"; $whereClause = "WHERE userid= ".mysqli_real_escape_string($link, $type); } $query = "SELECT * FROM tweets ".$whereClause." ORDER BY `datetime` DESC LIMIT 100"; $result = mysqli_query($link, $query); if (mysqli_num_rows($result) == 0) { echo "There are no tweets to display."; } else { while ($row = mysqli_fetch_assoc($result)) { $userQuery = "SELECT * FROM users WHERE id = '".mysqli_real_escape_string($link, $row['userid'])."' LIMIT 1"; $userQueryResult = mysqli_query($link, $userQuery); $user = mysqli_fetch_assoc($userQueryResult); echo "<div class='tweet'><p><span class='userTweet'><a href='?page=publicprofiles&userid=".$user['id']."' style='text-decoration: none'>".$user['email']."</a></span> <span class='time'>".time_since(time() - strtotime($row['datetime']))." ago</span>:</p>"; echo "<p>".$row['tweet']."</p>"; echo "<p class='followBtn'><a class='toggleFollow' data-userId='".$row['userid']."'>"; $isFollowingQuery = "SELECT * FROM isFollowing WHERE follower = ".mysqli_real_escape_string($link, $_SESSION['id'])." AND isFollowing = ".mysqli_real_escape_string($link, $row['userid'])." LIMIT 1"; $isFollowingQueryResult = mysqli_query($link, $isFollowingQuery); if (mysqli_num_rows($isFollowingQueryResult) > 0) { echo "Unfollow"; } else { echo "Follow"; } echo "</a></p></div>"; } } } function displaySearch() { echo '<form class="form-inline"> <input type="hidden" name="page" value="search"> <input type="text" name="q" class="form-control mb-2 mr-sm-2 mb-sm-0 form-control-sm" style="border: 1px solid gray; id="search" placeholder="Search"> <button type="submit" class="btn btn-primary btn-sm" style="cursor: pointer;">Search Tweets</button> </form>'; } function displayTweetBox() { if ($_SESSION[id] > 0){ echo '<div id="tweetSuccess" class="alert alert-success collapse">Your tweet was posted successfully.</div> <div id="tweetFail" class="alert alert-danger collapse"></div> <div class="form"> <textarea class="form-control mb-2 mr-sm-2 mb-sm-0 form-control-sm" rows="3" style="border: 1px solid gray;" id="tweetContent" placeholder="What\'s on your mind?"></textarea> <div style="margin-bottom: 10px;"></div> <div class="text-right"> <button class="btn btn-primary btn-sm" id="postTweetBtn" style="cursor: pointer;">Tweet</button> </div> </div>'; } } function displayUsers() { global $link; $query = "SELECT * FROM users LIMIT 100"; $result = mysqli_query($link, $query); while ($row = mysqli_fetch_assoc($result)) { echo "<p><a href='?page=publicprofiles&userid=".$row['id']."' style='text-decoration: none'><b>".$row['email']."</b></a></p>"; } } ?>
true
6b9ad4b9b666db6ae27efd1053402ab2c59bad47
PHP
cristianJourdan/PHP-ADVANCED
/2-Loops/taak02/loops-for.php
UTF-8
183
2.78125
3
[]
no_license
<?php for ($leeftijd =0; $leeftijd <= 17; $leeftijd++){ echo "Ik ben $leeftijd jaar, dus ik mag nog niet stemmen <br>"; } echo "Ik ben $leeftijd jaar, dus ik mag stemmen <br>"; ?>
true
59593834b06ab1d9c784da82ab6f7c0bfbbe483e
PHP
hmazter/advent-of-code-solutions
/2016/day16/functions.php
UTF-8
1,266
3.453125
3
[]
no_license
<?php declare(strict_types = 1); /** * Pass a string trough dragon curve calculation * * @param string $input * @return string */ function dragonCurve(string $input): string { $b = $input; $b = strrev($b); $length = strlen($b); for ($i = 0; $i < $length; $i++) { $b[$i] = $b[$i] === '1' ? '0' : '1'; } return $input . '0' . $b; } /** * Get data generated by dragon curve of a specific length * * @param string $initial initial data * @param int $length the desired length * @return string */ function getData(string $initial, int $length): string { $data = $initial; while (strlen($data) < $length) { $data = dragonCurve($data); } return substr($data, 0, $length); } /** * Calculate checksum of a data string * * @param string $data * @return string */ function calculateChecksum(string $data): string { $checksum = ''; while (strlen($checksum) % 2 === 0) { $checksum = ''; $length = strlen($data); for ($i = 0; $i < $length - 1; $i += 2) { if ($data[$i] === $data[$i + 1]) { $checksum .= '1'; } else { $checksum .= '0'; } } $data = $checksum; } return $checksum; }
true
59006ca6a8a42846ab4d3322af427c93c70e94d5
PHP
fm-ph/quark-server
/tests/GeocoderTest.php
UTF-8
1,863
2.75
3
[ "MIT" ]
permissive
<?php /** * GeocoderTest. */ namespace Quark\Utils; use PHPUnit\Framework\TestCase; /** * GeocoderTest class. * * @coversDefaultClass \Quark\Utils\Geocoder * @todo Add missing WAN tests. */ class GeocoderTest extends TestCase { static $lanIP = '127.0.0.1'; static $wanIP = '138.197.194.7'; static $badIP = '0.0.0.0.0'; /** * @covers ::__construct */ public function testGeocoderLAN() { $geocoder = new Geocoder(self::$lanIP); $this->assertInstanceOf(Geocoder::class, $geocoder); return $geocoder; } /** * @covers ::_construct */ public function testGeocoderWAN() { $geocoder = new Geocoder(self::$wanIP); $this->assertInstanceOf(Geocoder::class, $geocoder); return $geocoder; } /** * @depends testGeocoderLAN * @covers ::getGeocode */ public function testGeocodeLAN(Geocoder $geocoder) { $geocode = $geocoder->getGeocode(); $this->assertInstanceOf(\Geocoder\Model\AddressCollection::class, $geocode); } /** * @depends testGeocoderLAN * @covers ::getLocale */ public function testLocaleLAN(Geocoder $geocoder) { $locale = $geocoder->getLocale(); $this->assertEquals(locale(), $locale); } /** * @depends testGeocoderLAN * @covers ::getCountry */ public function testCountryLAN(Geocoder $geocoder) { $country = $geocoder->getCountry(); $this->assertEquals('localhost', $country); } /** * @depends testGeocoderWAN * @covers ::getCountry */ public function testLocaleWAN(Geocoder $geocoder) { $locale = $geocoder->getLocale(); $this->assertEquals('en', $locale); } /** * @depends testGeocoderWAN * @covers ::getCountry */ public function testCountryWAN(Geocoder $geocoder) { $country = $geocoder->getCountry(); $this->assertEquals('united states', $country); } }
true
987e64090881782c15b16d3643692b89bc685cc6
PHP
hungdaycb00/PHP-Learning
/Session3/snippet2.php
UTF-8
248
3.25
3
[]
no_license
<?php $x = 1; $y = 2; echo $x.'<=>' .y,' Returns ', $x <=> $y; //return -1 echo '</br>'; $x = 10; $y = 10; echo $x. '<=>' .$y, ' Returns ', $x <=>$y; //return 0 echo '</br>'; $x = 10; $y = 5; echo $x. '<=>' .$y, ' Returns ', $x <=>$y; //return 1 ?>
true
6e2afe1a6be889fbfe2a0ccd91e443f6af58349d
PHP
mdjaman/BaconUser
/src/BaconUser/InputFilter/RegistrationFilter.php
UTF-8
2,819
2.546875
3
[ "BSD-2-Clause" ]
permissive
<?php /** * BaconUser * * @link http://github.com/Bacon/BaconUser For the canonical source repository * @copyright 2013 Ben Scholzen 'DASPRiD' * @license http://opensource.org/licenses/BSD-2-Clause Simplified BSD License */ namespace BaconUser\InputFilter; use BaconUser\Options\UserOptionsInterface; use Zend\InputFilter\InputFilter; use Zend\Validator\ValidatorInterface; /** * Input filter for the {@see RegistrationForm}. */ class RegistrationFilter extends InputFilter { /** * @param ValidatorInterface $emailUniqueValidator * @param ValidatorInterface $usernameUniqueValidator * @param UserOptionsInterface $options */ public function __construct( ValidatorInterface $emailUniqueValidator, ValidatorInterface $usernameUniqueValidator, UserOptionsInterface $options ) { if ($options->getEnableUsername()) { $this->add(array( 'name' => 'username', 'required' => true, 'filters' => array(array('name' => 'StringTrim')), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'min' => 3, 'max' => 255, ), ), $usernameUniqueValidator, ), )); } $this->add(array( 'name' => 'email', 'required' => true, 'filters' => array(array('name' => 'StringTrim')), 'validators' => array( array( 'name' => 'EmailAddress' ), $emailUniqueValidator, ), )); $this->add(array( 'name' => 'password', 'required' => true, 'filters' => array(array('name' => 'StringTrim')), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'min' => 6, ), ), ), )); $this->add(array( 'name' => 'password_verification', 'required' => true, 'filters' => array(array('name' => 'StringTrim')), 'validators' => array( array( 'name' => 'StringLength', 'options' => array( 'min' => 6, ), ), array( 'name' => 'Identical', 'options' => array( 'token' => 'password', ), ), ), )); } }
true
a4236c3c16bed033505eff00da7ebce071bcfaa0
PHP
chuck-cp/choujiang
/common/tools/Redis.php
UTF-8
1,007
2.59375
3
[]
no_license
<?php namespace common\tools; use Yii; class Redis { protected static $instance = null; public function __construct() { if (!extension_loaded('redis')) { throw new \BadFunctionCallException('not support: redis'); } $redisConfig = Yii::$app->redis; self::$instance = new \Redis(); self::$instance->connect($redisConfig->hostname,$redisConfig->port); if(isset($redisConfig->password)){ self::$instance->auth($redisConfig->password); } } private function __clone(){} public static function getInstance($db=0) { if (!is_object(self::$instance)) { new self(); } self::$instance->select($db); return self::$instance; } public static function createTask($key,$value) { $value['time'] = time(); $value['token'] = System::generatePublicToken($value['time']); return self::getInstance(1)->rpush($key,json_encode($value)); } }
true
f80bc0eb96fd85d2f47860fe2a279a59309001b1
PHP
hostnet/type-inference-tool
/src/Analyzer/DynamicMethod/Tracer/Parser/Record/AbstractRecord.php
UTF-8
1,075
2.84375
3
[ "MIT" ]
permissive
<?php /** * @copyright 2017-2018 Hostnet B.V. */ declare(strict_types=1); namespace Hostnet\Component\TypeInference\Analyzer\DynamicMethod\Tracer\Parser\Record; /** * Representation of a trace record. */ abstract class AbstractRecord { /** * Unique number in a trace mapped to a function. * * @var int */ private $number; /** * @var string */ private $function_declaration_file; /** * @param int $number */ public function __construct(int $number) { $this->number = $number; } /** * @return int */ public function getNumber(): int { return $this->number; } /** * @return string|null */ public function getFunctionDeclarationFile(): ?string { return $this->function_declaration_file; } /** * @param string $function_declaration_file */ public function setFunctionDeclarationFile(string $function_declaration_file) { $this->function_declaration_file = $function_declaration_file; } }
true
5ead9a0bd6532e8047b5712cfe48f8028b6302bb
PHP
sadafm/ecarrefour
/multebox/models/search/Queue.php
UTF-8
1,936
2.625
3
[]
no_license
<?php namespace multebox\models\search; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use multebox\models\Queue as QueueModel; use multebox\models\QueueUsers as QueueUsersModel; /** * Queue represents the model behind the search form about multebox\models\Queue`. */ class Queue extends QueueModel { public function rules() { return [ [['id', 'queue_supervisor_user_id','department_id'], 'integer'], [['queue_title', 'active'], 'safe'], ]; } public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } public function search($params) { $query = QueueModel::find()->orderBy('queue_title'); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'department_id' => $this->department_id, 'queue_supervisor_user_id' => $this->queue_supervisor_user_id, ]); $query->andFilterWhere(['like', 'queue_title', $this->queue_title]) ->andFilterWhere(['like', 'active', $this->active]); return $dataProvider; } public function searchQueueUser($params, $entity_id) { $query = QueueUsersModel::find ()->where ( [ 'queue_id' => $entity_id ] ); $dataProvider = new ActiveDataProvider ( [ 'query' => $query ] ); if (! ($this->load ( $params ) && $this->validate ())) { return $dataProvider; } return $dataProvider; } public static function getQueueUsers($entity_id) { $dataProvider = QueueUsersModel::find ()->where ( [ 'queue_id' => $entity_id ] )->asArray()->all(); return $dataProvider; } }
true
b27b81ecc994ffc5f6e1fd8680f14ac87642d4e1
PHP
pfazzi/patrickfazzi.it
/rich_domain_model/rich/Customer.php
UTF-8
1,877
3.09375
3
[]
no_license
<?php declare(strict_types=1); namespace App; class Customer { /** @var int */ private $id; /** @var string */ private $firstName; /** @var string */ private $lastName; /** @var string */ private $address; /** @var string */ private $phone; /** @var string */ private $email; public function __construct( int $id, string $firstName, string $lastName, PostalAddress $address, Telephone $phone, ?EmailAddress $email ) { $this->id = $id; $this->firstName = $firstName; $this->lastName = $lastName; $this->address = $address; $this->phone = $phone; $this->email = $email; } public function changePersonalName(string $firstName, string $lastName): void { $this->firstName = $firstName; $this->lastName = $lastName; } public function changeEmail(EmailAddress $newEmailAddress): void { $this->email = $newEmailAddress; } public function relocateTo(PostalAddress $newPostalAddress): void { $this->address = $newPostalAddress; } public function changeTelephone(Telephone $newTelephone): void { $this->phone = $newTelephone; } public function disconnectTelephone(): void { $this->phone = null; } public function getId(): int { return $this->id; } public function getFirstName(): string { return $this->firstName; } public function getLastName(): string { return $this->lastName; } public function getAddress(): PostalAddress { return $this->address; } public function getPhone(): ?Telephone { return $this->phone; } public function getEmail(): ?EmailAddress { return $this->email; } }
true
d27afd359add1e3091014644a904777d6d29f883
PHP
KNIGHTTH0R/travelgo
/admin/edit-document.php
UTF-8
3,766
2.640625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php include("inc/validasi-login.php"); include("inc/anti-injection.php"); include("inc/connection.php"); $error = ""; error_reporting(0); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Kristal Tour Admin :: Add New Document</title> </head> <?php if(isset($_POST['submit'])) { $id = antiinjection($_GET['id']); $heading = antiinjection($_POST['heading']); $short_desc = antiinjection($_POST['short-desc']); $content = ($_POST['content']); $note = ($_POST['note']); $post_date = date("y-m-d"); $post_time = date("H:i:s"); $error = ""; if(empty($heading)){ $error = "<div class='alert alert-danger'>Document name is empty !</div>"; } elseif(empty($content)){ $error = "<div class='alert alert-danger'>Content is empty !</div>"; } else{ $sql = mysql_query("update d_information set heading='$heading', short_description='$short_desc', content='$content', note='$note' where id_dinformation='$id'") or die (mysql_error()); $error = "<div class='alert alert-success'>Document Has Been Changed. <a href='list-dInformation.php'>Click Here </a> For View List Document Informations</div>"; } } ?> <?php $id = antiinjection($_GET['id']); $sql = mysql_query("select * from d_information where id_dinformation='$id'"); $doc=mysql_fetch_array($sql); ?> <body> <!-- Header --> <div class="row"> <?php include("inc/header.php"); ?> </div> <!-- Header --> <!-- Content --> <div class="row"> <!-- Nav-Bar --> <div class="col-md-2"> <?php include("inc/nav-bar.php"); ?> </div> <!-- Nav-Bar --> <!-- Content --> <div class="col-md-6"> <div class="container"> <div class="jumbotron"> <form action="<?php echo $_SERVER['PHP_SELF']."?id=".$doc['id_dinformation']; ?>" method="post" class="form" role="form" enctype="multipart/form-data"> <div class="row"> <div class="col-xs-6"> <legend>Edit Document</legend> <?php echo $error; ?> <lebel>Document Name</lebel> <input class="form-control" name="heading" placeholder="Heading" type="text" required value="<?php echo $doc['heading']; ?>"/> <lebel>Short Description</lebel> <input class="form-control" name="short-desc" placeholder="Short Description" type="text" value="<?php echo $doc['short_description']; ?>"/> <lebel>Description</lebel> <textarea name="content" class="form-control" reqiured><?php echo $doc['content']; ?></textarea> <lebel>Note</lebel> <textarea name="note" class="form-control"><?php echo $doc['note']; ?></textarea> </div> </div> <br /> <input class="btn btn-success" type="submit" name="submit" value="Save" /> <input class="btn btn-success" type="button" name="cancel" value="Back" onclick="window.location='list-dInformation.php'" /> </form> </div> </div> </div> <!-- Content --> </div> <!-- Content --> <!-- Footer --> <div class="row"> <?php include("inc/footer.php"); ?> </div> <!-- Footer --> </div> </body> </html>
true
366dba0fe6e814dd172aa95c13eba2d31bb401a9
PHP
Nahuusi-Investments-Ltd/mma
/application/models/Data_model.php
UTF-8
1,124
2.546875
3
[]
no_license
<?php class Data_model extends CI_Model { function __construct(){ parent::__construct(); } function get_data_raw_query($query){ return $this->db->query($query); } function get_table_data($table){ return $this->db->get($table); } function get_uuid(){ return $this->db->query('SELECT UUID() AS uuid')->row()->uuid; } function insert_table_data($table, $data){ return $this->db->insert($table, $data); } function get_table_data_where($table, $where){ return $this->db->get_where($table, $where); } function save_table_data($table, $data, $where){ return $this->db->update($table, $data, $where); } function delete_table_data($table, $where){ return $this->db->delete($table, $where); } function get_unique_id(){ $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; return substr(str_shuffle($permitted_chars), 0, 10); } function get_password(){ $permitted_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwzyz'; return substr(str_shuffle($permitted_chars), 0, 16); } } ?>
true
0cbde66e0001b88c6145326ac54b8d68b33dde8f
PHP
bearer1024/feedReaderPHP
/app/Controllers/feedController.php
UTF-8
20,307
2.8125
3
[]
no_license
<?php /** * Controller to handle every feed actions. */ class FreshRSS_feed_Controller extends Minz_ActionController { /** * This action is called before every other action in that class. It is * the common boiler plate for every action. It is triggered by the * underlying framework. */ public function firstAction() { if (!FreshRSS_Auth::hasAccess()) { // Token is useful in the case that anonymous refresh is forbidden // and CRON task cannot be used with php command so the user can // set a CRON task to refresh his feeds by using token inside url $token = FreshRSS_Context::$user_conf->token; $token_param = Minz_Request::param('token', ''); $token_is_ok = ($token != '' && $token == $token_param); $action = Minz_Request::actionName(); $allow_anonymous_refresh = FreshRSS_Context::$system_conf->allow_anonymous_refresh; if ($action !== 'actualize' || !($allow_anonymous_refresh || $token_is_ok)) { Minz_Error::error(403); } } } public static function addFeed($url, $title = '', $cat_id = 0, $new_cat_name = '', $http_auth = '') { FreshRSS_UserDAO::touch(); @set_time_limit(300); $catDAO = new FreshRSS_CategoryDAO(); $cat = null; if ($cat_id > 0) { $cat = $catDAO->searchById($cat_id); } if ($cat == null && $new_cat_name != '') { $cat = $catDAO->addCategory(array('name' => $new_cat_name)); } if ($cat == null) { $catDAO->checkDefault(); } $cat_id = $cat == null ? FreshRSS_CategoryDAO::defaultCategoryId : $cat->id(); $feed = new FreshRSS_Feed($url); //Throws FreshRSS_BadUrl_Exception $feed->_httpAuth($http_auth); $feed->load(true); //Throws FreshRSS_Feed_Exception, Minz_FileNotExistException $feed->_category($cat_id); $feedDAO = FreshRSS_Factory::createFeedDao(); if ($feedDAO->searchByUrl($feed->url())) { throw new FreshRSS_AlreadySubscribed_Exception($url, $feed->name()); } // Call the extension hook $feed = Minz_ExtensionManager::callHook('feed_before_insert', $feed); if ($feed === null) { throw new FreshRSS_FeedNotAdded_Exception($url, $feed->name()); } $values = array( 'url' => $feed->url(), 'category' => $feed->category(), 'name' => $title != '' ? $title : $feed->name(), 'website' => $feed->website(), 'description' => $feed->description(), 'lastUpdate' => time(), 'httpAuth' => $feed->httpAuth(), ); $id = $feedDAO->addFeed($values); if (!$id) { // There was an error in database... we cannot say what here. throw new FreshRSS_FeedNotAdded_Exception($url, $feed->name()); } $feed->_id($id); // Ok, feed has been added in database. Now we have to refresh entries. self::actualizeFeed($id, $url, false, null, true); return $feed; } /** * This action subscribes to a feed. * * It can be reached by both GET and POST requests. * * GET request displays a form to add and configure a feed. * Request parameter is: * - url_rss (default: false) * * POST request adds a feed in database. * Parameters are: * - url_rss (default: false) * - category (default: false) * - new_category (required if category == 'nc') * - http_user (default: false) * - http_pass (default: false) * It tries to get website information from RSS feed. * If no category is given, feed is added to the default one. * * If url_rss is false, nothing happened. */ public function addAction() { $url = Minz_Request::param('url_rss'); if ($url === false) { // No url, do nothing Minz_Request::forward(array( 'c' => 'subscription', 'a' => 'index' ), true); } $feedDAO = FreshRSS_Factory::createFeedDao(); $url_redirect = array( 'c' => 'subscription', 'a' => 'index', 'params' => array(), ); $limits = FreshRSS_Context::$system_conf->limits; $this->view->feeds = $feedDAO->listFeeds(); if (count($this->view->feeds) >= $limits['max_feeds']) { Minz_Request::bad(_t('feedback.sub.feed.over_max', $limits['max_feeds']), $url_redirect); } if (Minz_Request::isPost()) { $cat = Minz_Request::param('category'); $new_cat_name = ''; if ($cat === 'nc') { // User want to create a new category, new_category parameter // must exist $new_cat = Minz_Request::param('new_category'); $new_cat_name = isset($new_cat['name']) ? $new_cat['name'] : ''; } // HTTP information are useful if feed is protected behind a // HTTP authentication $user = trim(Minz_Request::param('http_user', '')); $pass = Minz_Request::param('http_pass', ''); $http_auth = ''; if ($user != '' && $pass != '') { //TODO: Sanitize $http_auth = $user . ':' . $pass; } try { $feed = self::addFeed($url, '', $cat, $new_cat_name, $http_auth); } catch (FreshRSS_BadUrl_Exception $e) { // Given url was not a valid url! Minz_Log::warning($e->getMessage()); Minz_Request::bad(_t('feedback.sub.feed.invalid_url', $url), $url_redirect); } catch (FreshRSS_Feed_Exception $e) { // Something went bad (timeout, server not found, etc.) Minz_Log::warning($e->getMessage()); Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect); } catch (Minz_FileNotExistException $e) { // Cache directory doesn't exist! Minz_Log::error($e->getMessage()); Minz_Request::bad(_t('feedback.sub.feed.internal_problem', _url('index', 'logs')), $url_redirect); } catch (FreshRSS_AlreadySubscribed_Exception $e) { Minz_Request::bad(_t('feedback.sub.feed.already_subscribed', $e->feedName()), $url_redirect); } catch (FreshRSS_FeedNotAdded_Exception $e) { Minz_Request::bad(_t('feedback.sub.feed.not_added', $e->feedName()), $url_redirect); } // Entries are in DB, we redirect to feed configuration page. $url_redirect['params']['id'] = $feed->id(); Minz_Request::good(_t('feedback.sub.feed.added', $feed->name()), $url_redirect); } else { // GET request: we must ask confirmation to user before adding feed. Minz_View::prependTitle(_t('sub.feed.title_add') . ' · '); $this->catDAO = new FreshRSS_CategoryDAO(); $this->view->categories = $this->catDAO->listCategories(false); $this->view->feed = new FreshRSS_Feed($url); try { // We try to get more information about the feed. $this->view->feed->load(true); $this->view->load_ok = true; } catch (Exception $e) { $this->view->load_ok = false; } $feed = $feedDAO->searchByUrl($this->view->feed->url()); if ($feed) { // Already subscribe so we redirect to the feed configuration page. $url_redirect['params']['id'] = $feed->id(); Minz_Request::good(_t('feedback.sub.feed.already_subscribed', $feed->name()), $url_redirect); } } } /** * This action remove entries from a given feed. * * It should be reached by a POST action. * * Parameter is: * - id (default: false) */ public function truncateAction() { $id = Minz_Request::param('id'); $url_redirect = array( 'c' => 'subscription', 'a' => 'index', 'params' => array('id' => $id) ); if (!Minz_Request::isPost()) { Minz_Request::forward($url_redirect, true); } $feedDAO = FreshRSS_Factory::createFeedDao(); $n = $feedDAO->truncate($id); invalidateHttpCache(); if ($n === false) { Minz_Request::bad(_t('feedback.sub.feed.error'), $url_redirect); } else { Minz_Request::good(_t('feedback.sub.feed.n_entries_deleted', $n), $url_redirect); } } public static function actualizeFeed($feed_id, $feed_url, $force, $simplePiePush = null, $isNewFeed = false) { @set_time_limit(300); $feedDAO = FreshRSS_Factory::createFeedDao(); $entryDAO = FreshRSS_Factory::createEntryDao(); // Create a list of feeds to actualize. // If feed_id is set and valid, corresponding feed is added to the list but // alone in order to automatize further process. $feeds = array(); if ($feed_id > 0 || $feed_url) { $feed = $feed_id > 0 ? $feedDAO->searchById($feed_id) : $feedDAO->searchByUrl($feed_url); if ($feed) { $feeds[] = $feed; } } else { $feeds = $feedDAO->listFeedsOrderUpdate(-1); } // Calculate date of oldest entries we accept in DB. $nb_month_old = max(FreshRSS_Context::$user_conf->old_entries, 1); $date_min = time() - (3600 * 24 * 30 * $nb_month_old); // PubSubHubbub support $pubsubhubbubEnabledGeneral = FreshRSS_Context::$system_conf->pubsubhubbub_enabled; $pshbMinAge = time() - (3600 * 24); //TODO: Make a configuration. $updated_feeds = 0; $is_read = FreshRSS_Context::$user_conf->mark_when['reception'] ? 1 : 0; foreach ($feeds as $feed) { $url = $feed->url(); //For detection of HTTP 301 $pubSubHubbubEnabled = $pubsubhubbubEnabledGeneral && $feed->pubSubHubbubEnabled(); if ((!$simplePiePush) && (!$feed_id) && $pubSubHubbubEnabled && ($feed->lastUpdate() > $pshbMinAge)) { //$text = 'Skip pull of feed using PubSubHubbub: ' . $url; //Minz_Log::debug($text); //file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND); continue; //When PubSubHubbub is used, do not pull refresh so often } $mtime = 0; $ttl = $feed->ttl(); if ($ttl == -1) { continue; //Feed refresh is disabled } if ((!$simplePiePush) && (!$feed_id) && ($feed->lastUpdate() + 10 >= time() - ($ttl == -2 ? FreshRSS_Context::$user_conf->ttl_default : $ttl))) { //Too early to refresh from source, but check whether the feed was updated by another user $mtime = $feed->cacheModifiedTime(); if ($feed->lastUpdate() + 10 >= $mtime) { continue; //Nothing newer from other users } //Minz_Log::debug($feed->url() . ' was updated at ' . date('c', $mtime) . ' by another user'); //Will take advantage of the newer cache } if (!$feed->lock()) { Minz_Log::notice('Feed already being actualized: ' . $feed->url()); continue; } try { if ($simplePiePush) { $feed->loadEntries($simplePiePush); //Used by PubSubHubbub } else { $feed->load(false, $isNewFeed); } } catch (FreshRSS_Feed_Exception $e) { Minz_Log::warning($e->getMessage()); $feedDAO->updateLastUpdate($feed->id(), true); $feed->unlock(); continue; } $feed_history = $feed->keepHistory(); if ($isNewFeed) { $feed_history = -1; //∞ } elseif ($feed_history == -2) { // TODO: -2 must be a constant! // -2 means we take the default value from configuration $feed_history = FreshRSS_Context::$user_conf->keep_history_default; } // We want chronological order and SimplePie uses reverse order. $entries = array_reverse($feed->entries()); if (count($entries) > 0) { $newGuids = array(); foreach ($entries as $entry) { $newGuids[] = safe_ascii($entry->guid()); } // For this feed, check existing GUIDs already in database. $existingHashForGuids = $entryDAO->listHashForFeedGuids($feed->id(), $newGuids); unset($newGuids); $oldGuids = array(); // Add entries in database if possible. foreach ($entries as $entry) { $entry_date = $entry->date(true); if (isset($existingHashForGuids[$entry->guid()])) { $existingHash = $existingHashForGuids[$entry->guid()]; if (strcasecmp($existingHash, $entry->hash()) === 0 || trim($existingHash, '0') == '') { //This entry already exists and is unchanged. TODO: Remove the test with the zero'ed hash in FreshRSS v1.3 $oldGuids[] = $entry->guid(); } else { //This entry already exists but has been updated //Minz_Log::debug('Entry with GUID `' . $entry->guid() . '` updated in feed ' . $feed->id() . //', old hash ' . $existingHash . ', new hash ' . $entry->hash()); //TODO: Make an updated/is_read policy by feed, in addition to the global one. $entry->_isRead(FreshRSS_Context::$user_conf->mark_updated_article_unread ? false : null); //Change is_read according to policy. if (!$entryDAO->inTransaction()) { $entryDAO->beginTransaction(); } $entryDAO->updateEntry($entry->toArray()); } } elseif ($feed_history == 0 && $entry_date < $date_min) { // This entry should not be added considering configuration and date. $oldGuids[] = $entry->guid(); } else { if ($isNewFeed) { $id = min(time(), $entry_date) . uSecString(); } elseif ($entry_date < $date_min) { $id = min(time(), $entry_date) . uSecString(); $entry->_isRead(true); //Old article that was not in database. Probably an error, so mark as read } else { $id = uTimeString(); $entry->_isRead($is_read); } $entry->_id($id); $entry = Minz_ExtensionManager::callHook('entry_before_insert', $entry); if ($entry === null) { // An extension has returned a null value, there is nothing to insert. continue; } if ($pubSubHubbubEnabled && !$simplePiePush) { //We use push, but have discovered an article by pull! $text = 'An article was discovered by pull although we use PubSubHubbub!: Feed ' . $url . ' GUID ' . $entry->guid(); file_put_contents(USERS_PATH . '/_/log_pshb.txt', date('c') . "\t" . $text . "\n", FILE_APPEND); Minz_Log::warning($text); $pubSubHubbubEnabled = false; $feed->pubSubHubbubError(true); } if (!$entryDAO->inTransaction()) { $entryDAO->beginTransaction(); } $entryDAO->addEntry($entry->toArray()); } } $entryDAO->updateLastSeen($feed->id(), $oldGuids, $mtime); } if ($feed_history >= 0 && rand(0, 30) === 1) { // TODO: move this function in web cron when available (see entry::purge) // Remove old entries once in 30. if (!$entryDAO->inTransaction()) { $entryDAO->beginTransaction(); } $nb = $feedDAO->cleanOldEntries($feed->id(), $date_min, max($feed_history, count($entries) + 10)); if ($nb > 0) { Minz_Log::debug($nb . ' old entries cleaned in feed [' . $feed->url() . ']'); } } $feedDAO->updateLastUpdate($feed->id(), false, $entryDAO->inTransaction(), $mtime); if ($entryDAO->inTransaction()) { $entryDAO->commit(); } if ($feed->hubUrl() && $feed->selfUrl()) { //selfUrl has priority for PubSubHubbub if ($feed->selfUrl() !== $url) { //https://code.google.com/p/pubsubhubbub/wiki/MovingFeedsOrChangingHubs $selfUrl = checkUrl($feed->selfUrl()); if ($selfUrl) { Minz_Log::debug('PubSubHubbub unsubscribe ' . $feed->url()); if (!$feed->pubSubHubbubSubscribe(false)) { //Unsubscribe Minz_Log::warning('Error while PubSubHubbub unsubscribing from ' . $feed->url()); } $feed->_url($selfUrl, false); Minz_Log::notice('Feed ' . $url . ' canonical address moved to ' . $feed->url()); $feedDAO->updateFeed($feed->id(), array('url' => $feed->url())); } } } elseif ($feed->url() !== $url) { // HTTP 301 Moved Permanently Minz_Log::notice('Feed ' . $url . ' moved permanently to ' . $feed->url()); $feedDAO->updateFeed($feed->id(), array('url' => $feed->url())); } $feed->faviconPrepare(); if ($pubsubhubbubEnabledGeneral && $feed->pubSubHubbubPrepare()) { Minz_Log::notice('PubSubHubbub subscribe ' . $feed->url()); if (!$feed->pubSubHubbubSubscribe(true)) { //Subscribe Minz_Log::warning('Error while PubSubHubbub subscribing to ' . $feed->url()); } } $feed->unlock(); $updated_feeds++; unset($feed); // No more than 10 feeds unless $force is true to avoid overloading // the server. if ($updated_feeds >= 10 && !$force) { break; } } return array($updated_feeds, reset($feeds)); } /** * This action actualizes entries from one or several feeds. * * Parameters are: * - id (default: false): Feed ID * - url (default: false): Feed URL * - force (default: false) * If id and url are not specified, all the feeds are actualized. But if force is * false, process stops at 10 feeds to avoid time execution problem. */ public function actualizeAction() { Minz_Session::_param('actualize_feeds', false); $id = Minz_Request::param('id'); $url = Minz_Request::param('url'); $force = Minz_Request::param('force'); list($updated_feeds, $feed) = self::actualizeFeed($id, $url, $force); if (Minz_Request::param('ajax')) { // Most of the time, ajax request is for only one feed. But since // there are several parallel requests, we should return that there // are several updated feeds. $notif = array( 'type' => 'good', 'content' => _t('feedback.sub.feed.actualizeds') ); Minz_Session::_param('notification', $notif); // No layout in ajax request. $this->view->_useLayout(false); } else { // Redirect to the main page with correct notification. if ($updated_feeds === 1) { Minz_Request::good(_t('feedback.sub.feed.actualized', $feed->name()), array( 'params' => array('get' => 'f_' . $feed->id()) )); } elseif ($updated_feeds > 1) { Minz_Request::good(_t('feedback.sub.feed.n_actualized', $updated_feeds), array()); } else { Minz_Request::good(_t('feedback.sub.feed.no_refresh'), array()); } } return $updated_feeds; } public static function renameFeed($feed_id, $feed_name) { if ($feed_id <= 0 || $feed_name == '') { return false; } FreshRSS_UserDAO::touch(); $feedDAO = FreshRSS_Factory::createFeedDao(); return $feedDAO->updateFeed($feed_id, array('name' => $feed_name)); } public static function moveFeed($feed_id, $cat_id, $new_cat_name = '') { if ($feed_id <= 0 || ($cat_id <= 0 && $new_cat_name == '')) { return false; } FreshRSS_UserDAO::touch(); $catDAO = new FreshRSS_CategoryDAO(); if ($cat_id > 0) { $cat = $catDAO->searchById($cat_id); $cat_id = $cat == null ? 0 : $cat->id(); } if ($cat_id <= 1 && $new_cat_name != '') { $cat_id = $catDAO->addCategory(array('name' => $new_cat_name)); } if ($cat_id <= 1) { $catDAO->checkDefault(); $cat_id = FreshRSS_CategoryDAO::defaultCategoryId; } $feedDAO = FreshRSS_Factory::createFeedDao(); return $feedDAO->updateFeed($feed_id, array('category' => $cat_id)); } /** * This action changes the category of a feed. * * This page must be reached by a POST request. * * Parameters are: * - f_id (default: false) * - c_id (default: false) * If c_id is false, default category is used. * * @todo should handle order of the feed inside the category. */ public function moveAction() { if (!Minz_Request::isPost()) { Minz_Request::forward(array('c' => 'subscription'), true); } $feed_id = Minz_Request::param('f_id'); $cat_id = Minz_Request::param('c_id'); if (self::moveFeed($feed_id, $cat_id)) { // TODO: return something useful } else { Minz_Log::warning('Cannot move feed `' . $feed_id . '` ' . 'in the category `' . $cat_id . '`'); Minz_Error::error(404); } } public static function deleteFeed($feed_id) { FreshRSS_UserDAO::touch(); $feedDAO = FreshRSS_Factory::createFeedDao(); if ($feedDAO->deleteFeed($feed_id)) { // TODO: Delete old favicon // Remove related queries FreshRSS_Context::$user_conf->queries = remove_query_by_get( 'f_' . $feed_id, FreshRSS_Context::$user_conf->queries); FreshRSS_Context::$user_conf->save(); return true; } return false; } /** * This action deletes a feed. * * This page must be reached by a POST request. * If there are related queries, they are deleted too. * * Parameters are: * - id (default: false) * - r (default: false) * r permits to redirect to a given page at the end of this action. * * @todo handle "r" redirection in Minz_Request::forward()? */ public function deleteAction() { $redirect_url = Minz_Request::param('r', false, true); if (!$redirect_url) { $redirect_url = array('c' => 'subscription', 'a' => 'index'); } if (!Minz_Request::isPost()) { Minz_Request::forward($redirect_url, true); } $id = Minz_Request::param('id'); if (self::deleteFeed($id)) { Minz_Request::good(_t('feedback.sub.feed.deleted'), $redirect_url); } else { Minz_Request::bad(_t('feedback.sub.feed.error'), $redirect_url); } } }
true
3005ea4876769ce84ba024071871291228a19b1e
PHP
gsbombon/proyectoWeb
/php/horario.php
UTF-8
1,738
2.96875
3
[]
no_license
<!doctype html> <html> <head> <meta charset="utf-8"> <title>Documento sin título</title> </head> <body> <?php $m[1] ="leng"; $m[2] ="matematicas"; $m[3] ="sociales"; $m[4] ="naturales"; $m[5] ="artiscitica"; $m[6] ="fisica"; $m[7] ="quimica"; $m[8] ="filosofia"; $m[9]="ciudadani"; $m[10] ="educa"; $v =[0,6,6,4,4,2,4,4,4,2,4,4]; print_r($v); $v2 =6; $v3 =4; $v4 = 4; $v5 = 2; $v6 =4; $v7 =4; $v8 =2; $v9 =4; $v10 =4; echo(""); echo "<br>"; generarhorario($v,0,$m); echo(""); echo "<br>"; generarhorario($v,1,$m); echo(""); echo "<br>"; generarhorario($v,5,$m); echo(""); echo "<br>"; generarhorario($v,3,$m); echo(""); echo "<br>"; function generarhorario($v,$k,$m){ for($j=0;$j<5;$j++){ for($i=0;$i<8;$i++){ if($i%2==0){ $v[$k]=$v[$k]-2; $k= $k+1; }; if($k==10){ $k=0; } if($v[$k]==0){ $k=$k+1; } $matriz[$i][$j] = $m[$k]." "; } } for($i=0;$i<8;$i++){ for($j=0;$j<8; $j++){ echo $matriz[$i][$j]; } echo '<br>'; } } echo "hola"; ?> <script> function enviarSelect(e){ var val = $(e).find('option:selected').val(); $.post( "horario.php", { nombre: val}, function(e){ //ver que devuelve php alert(e); }); }</script> <form id="nivel" name="nivel" method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>" > <select name="aa" onchange="enviarSelect(this)" > <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="5">4</option> </select> <?php $curs=$_POST["aa"]; echo $curs; ?> </form> </body> </html>
true
3c592c84178c883a0bc0af472505449babea2aa7
PHP
dimayaschhuk/a_b_z
/database/seeds/PeopleTableSeeder.php
UTF-8
4,871
2.875
3
[]
no_license
<?php use Illuminate\Database\Seeder; use App\People; class PeopleTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $array[0]=['name'=>'економічного','name_boss'=>'Юрій','patronymic'=>'Миколайвич','surname'=>'Станкевич','position'=>'економіст']; $array[1]=['name'=>'юридичного','name_boss'=>'Сергій','patronymic'=>'Терешкович','surname'=>'Гуменюк','position'=>'юрист']; $array[2]=['name'=>'ІТ','name_boss'=>'Віталій','patronymic'=>'Федоровис','surname'=>'Іванов','position'=>'програміст']; $array[3]=['name'=>'фінансого','name_boss'=>'Андрій','patronymic'=>'Миколайович','surname'=>'Правдивий','position'=>'фінансист']; $array[4]=['name'=>'статистичного','name_boss'=>'Олександра','patronymic'=>'Михайловна','surname'=>'Голівець','position'=>'статист']; function generateText($length = 8){ $chars = 'qazxswedcvfrtgbnhyujmkiol'; $numChars = strlen($chars); $string = ''; for ($i = 0; $i < $length; $i++) { $string .= substr($chars, rand(1, $numChars) - 1, 1); } return $string; } function generateNumber($length = 8){ $chars = '1234567890'; $numChars = strlen($chars); $string = ''; for ($i = 0; $i < $length; $i++) { $string .= substr($chars, rand(1, $numChars) - 1, 1); } return $string; } $a=People::create( [ 'name'=>'Василь', 'patronymic'=>'Михайлович', 'surname'=>'Вакуленко', 'id_boss'=>0, 'name_boss'=>'Бог', 'position'=>'Власник фірми', 'salary'=>999999, ] ); $b=People::create( [ 'name'=>'Віталій', 'patronymic'=>'Євгенович', 'surname'=>'Прохоренко', 'id_boss'=>$a->id, 'name_boss'=>$a->name.' '.$a->patronymic, 'position'=>'Головний директор', 'salary'=>150000, ] ); foreach ($array as $item){ $c=People::create( [ 'name'=>$item['name_boss'], 'patronymic'=>$item['patronymic'], 'surname'=>$item['surname'], 'id_boss'=>$b->id, 'name_boss'=>$b->name.' '.$b->patronymic, 'position'=>'Директор '.$item['name'].' відділу', 'salary'=>100000, ] ); for($q=0;$q<10;$q++){ $d=People::create( [ 'name'=> ucfirst(generateText(5)), 'patronymic'=>ucfirst(generateText(5)), 'surname'=>ucfirst(generateText(5)), 'id_boss'=>$c->id, 'name_boss'=>$c->name." ".$c->patronymic, 'position'=>'керівник цеху № '.generateNumber(4), 'salary'=>generateNumber(5), ] ); for($z=0;$z<10;$z++){ $e=People::create( [ 'name'=> ucfirst(generateText(5)), 'patronymic'=>ucfirst(generateText(5)), 'surname'=>ucfirst(generateText(5)), 'id_boss'=>$d->id, 'name_boss'=>$d->name." ".$d->patronymic, 'position'=>'керівник бригад № '.generateNumber(4), 'salary'=>generateNumber(4), ] ); for($r=0;$r<100;$r++){ $f=People::create( [ 'name'=> ucfirst(generateText(5)), 'patronymic'=>ucfirst(generateText(5)), 'surname'=>ucfirst(generateText(5)), 'id_boss'=>$e->id, 'name_boss'=>$e->name." ".$e->patronymic, 'position'=>$item['position'], 'salary'=>generateNumber(3), ] ); } } } } } }
true
ce77021656424f9847c00356ad3a63a89850613f
PHP
jguittard/tripsorter
/lib/Trip.php
UTF-8
2,323
3.46875
3
[ "BSD-2-Clause" ]
permissive
<?php /** * Class Trip * * @author Julien Guittard <julien@youzend.com> * @link http://github.com/jguittard/tripsorter for the canonical source repository * @copyright Copyright (c) 2014 Julien Guittard */ class Trip { /** * Array of boarding cards * * @var array */ protected $cards; /** * Start point of the trip * * @var string */ protected $departure; /** * End point of the trip * * @var string */ protected $arrival; /** * Get cards * * @return array */ public function getCards() { return $this->cards; } /** * Get departure * * @return string */ public function getDeparture() { return $this->departure; } /** * Get arrival * * @return string */ public function getArrival() { return $this->arrival; } /** * Constructor * * @param array $cards */ public function __construct($cards) { $this->cards = $cards; } /** * Initialize the data to be ready to use * * @return void */ public function setup() { $origins = array(); $destinations = array(); foreach ($this->cards as $card) { $origins[] = $card->getOrigin(); $destinations[] = $card->getDestination(); } foreach ($this->cards as $card) { if ($card->isDeparture($destinations)) { $this->departure = $card->getOrigin(); } if ($card->isArrival($origins)) { $this->arrival = $card->getDestination(); } } $this->sort(); } /** * Sort the boarding cards * * @return void */ protected function sort() { $stop = $this->departure; $cards = $this->cards; $this->cards = array(); while ($stop != $this->arrival) { foreach ($cards as $index => $card) { if ($card->getOrigin() == $stop) { $this->cards[] = $card; $stop = $card->getDestination(); unset($cards[$index]); } } } } }
true
95f520e2b2012160b7b2f9cfbae41404e2239c5f
PHP
zecawithdawn/DEP_Test
/DEP_server/test.php
UTF-8
1,193
2.5625
3
[]
no_license
<?php error_reporting(E_ALL); ini_set("display_errors", 1); $host = 'localhost'; $user = 'root'; $pw = 'root'; $db = 'depression'; $port = 3306; $mysqli = new mysqli($host,$user,$pw,$db,$port); $mysqli->set_charset("utf8"); if ( !$mysqli ) { die("error"); }; $json_data = json_decode(file_get_contents('php://input')); $result_id = $json_data -> ID; $result_score = $json_data -> score; $result_set = $json_data -> queset; $result_max = $json_data -> maxscore; $sql_set = "SELECT queset FROM testset WHERE testname = '".$result_set."'"; $result1 = $mysqli->query($sql_set); if(strlen($result1) == 0){ $sql_new_max = "INSERT INTO `depression`.`testset` (`queset`, `testmax`) VALUES ('".$result_set."', '".$result_max."')"; $result3 = $mysqli->query($sql_new_max); } $sql_upload="INSERT INTO `depression`.`results` (`time`, `ID`, `score`,`queset`) VALUES ('".date("Y-m-d")."', '".$result_id."', '".$result_score."', '".$result_set."')"; $result2 = $mysqli->query($sql_upload); if (!$result2) { die("error"); } mysqli_close($mysqli); ?>
true
01f306a4df72a4d725b093f76675237780448100
PHP
Emilyhyn/blackcat
/app/Http/Controllers/ProfileController.php
UTF-8
1,208
2.640625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: emily * Date: 28/04/2016 * Time: 2:42 PM */ namespace Blackcat\Http\Controllers; use Blackcat\Models\User; use Illuminate\Http\Request; use Auth; class ProfileController extends Controller{ public function getProfile( $username){ // dd($username); //Step 2 $user = User::where('username',$username)->first(); if(!$user){ abort(404); } return view('profile.index') ->with('user',$user); } public function getEdit(){ return view('profile.edit'); } public function postEdit(Request $request){ $this->validate($request, [ 'first_name'=>'alpha|max:50', 'last_name'=>'alpha|max:50', 'location'=> 'max:20' ]); Auth::user()->update([ 'first_name'=> $request->input('first_name'), 'last_name'=>$request->input('last_name'), 'location'=>$request->input('location'), ]); return redirect() ->route('profile.edit') ->with('info','Your profile has been updated.'); } }
true
5c2d71e720f046b4051a0dfbbfe9ae6725b87a2d
PHP
SpoonX/SxBootstrap
/src/SxBootstrap/View/Helper/Bootstrap/ButtonGroup.php
UTF-8
2,150
2.625
3
[ "BSD-2-Clause" ]
permissive
<?php namespace SxBootstrap\View\Helper\Bootstrap; use SxCore\Html\HtmlElement; use SxBootstrap\View\Helper\Bootstrap\Button as SxButton; class ButtonGroup extends AbstractElementHelper { /** * Contains all buttons in array or Zend\Form\Element\Button * * @param array $buttons */ protected $buttons = array(); /** * Render buttonGroup * * @return string */ public function render() { foreach ($this->buttons as $button) { $this->getElement()->appendContent($this->renderButton($button)); } return $this->getElement()->render(); } /** * @param SxButton|string $button * * @return string */ protected function renderButton($button) { if ($button instanceOf SxButton) { return $button->render(); } return $this->getView()->plugin('sxb_button')->__invoke($button)->render(); } /** * Add button * * @param mixed $button */ public function addButton($button) { $this->buttons[] = $button; } /** * Make button group element and add buttons * * @param array $buttons * * @return \SxBootstrap\View\Helper\Bootstrap\ButtonGroup */ public function __invoke(array $buttons = array()) { $this->setElement(new HtmlElement); $this->buttons = array(); $this->addClass('btn-group'); foreach ($buttons as $button) { $this->addButton($button); } return clone $this; } /** * Add checkbox data to group */ public function checkbox() { $this->getElement()->addAttribute('data-toggle', 'buttons-checkbox'); return $this; } /** * Add radio data to group */ public function radio() { $this->getElement()->addAttribute('data-toggle', 'buttons-radio'); return $this; } /** * Add vertical class to group */ public function vertical() { $this->getElement()->addClass('btn-group-vertical'); return $this; } }
true
f04955f29bca6fcc77e925861e3623e627e3f318
PHP
EMegamanu/boutiqueculturelle
/connexion.php
UTF-8
2,836
2.828125
3
[]
no_license
<?php /* Inclusion script connexion base de données. */ require_once('inc/db.inc.php'); if(!empty($_POST)) { $success = false; if(!empty($_POST['email']) && !empty($_POST['motDePasse'])) { $email = $_POST['email']; $motDePasse = $_POST['motDePasse']; $requete = 'SELECT * FROM Utilisateur ' . 'WHERE courriel = :email AND motDePasse = :motDePasse'; $results = $db->prepare($requete); $results->bindValue(':email', $email); $results->bindValue(':motDePasse', $motDePasse); $results->execute(); $count = $results->rowCount(); $results->setFetchMode(PDO::FETCH_OBJ); if($count == 1) { session_start(); $utilisateur = $results->fetch(); $success = true; $_SESSION['utilisateur'] = array(); $_SESSION['utilisateur']['id'] = $utilisateur->id; $_SESSION['utilisateur']['nom'] = $utilisateur->nom; $_SESSION['utilisateur']['prenom'] = $utilisateur->prenom; $_SESSION['utilisateur']['courriel'] = $utilisateur->courriel; $_SESSION['utilisateur']['admin'] = (bool) $utilisateur->admin; header("location: ./"); } } /* Inclusion de l'en-tête. */ include_once('inc/header.inc.php'); ?> <section id="section-connexion"> <?php if(!$success) { ?> <article> <p class="result fail">Erreur : vos identifiants ne sont pas reconnus.</p> </article> <?php } } else { /* Inclusion de l'en-tête. */ include_once('inc/header.inc.php'); ?> <section id="section-connexion"> <form method="post" action="connexion.php"> <h2> <span class="title"> <span class="fa fa-sign-in"></span> Connexion </span> </h2> <fieldset> <legend>Identification</legend> <div> <label for="email">Courriel</label> : <input type="text" name="email" id="email" /> </div> <div> <label for="mot-de-passe">Mot de passe</label> : <input type="password" name="motDePasse" id="mot-de-passe" /> </div> <div class="groupe-boutons"> <button type="reset"><span class="fa fa-hand-o-left"></span> Annuler</button> <button type="submit"><span class="fa fa-check"></span> Envoyer</button> </div> </fieldset> </form> <?php } ?> </section> <?php /* Inclusion de l'en-tête. */ include_once('inc/footer.inc.php'); ?>
true
fe848a2d0d5b04707acb988f2b9db1a307f33ea6
PHP
maxito123/PHP
/processform.php
UTF-8
412
2.625
3
[]
no_license
<?php if(isset($_POST['submit'])){ $firstName = $_POST['first_name']; $lastName = $_POST['last_name']; $email = $_POST['email']; $gender= $_POST['gender']; $message = $_POST['message']; $file = fopen("$firstName.txt" , "a"); fwrite($file, $firstName); fwrite($file, $lastName); fwrite($file, $email); fwrite($file, $gender); fwrite($file, $message); }
true
c31565e756bd36b884794231fb1c89cc94cafd5f
PHP
MiSTOMEDIA/framework
/packages/core/view.php
UTF-8
823
2.921875
3
[]
no_license
<?php namespace Core { class View { /** * The view instance * @var Gears */ protected $view; /** * Assign a new instance of Gears to the view property */ public function __construct() { $this->view = new \Core\Libraries\Gears; } /** * Render a view via the Gears template engine * @param string $view * @param array $data * @return Gears */ public function render ($view, $data = array()) { list ($path, $view) = explode ('::', $view); $path = PACKAGES_PATH.str_replace ('.', DS, strtolower ($path)).DS; $view = ! strstr ($view, '.tpl') ? $view.'.tpl' : $view; $this->view->setPath ($path); if (count ($data)) { $this->view->bind ($data); } return $this->view->display ($view); } } }
true
02cdb7ec31b00ecbd80ada67cf5078225be5cad2
PHP
richjenks/wp-splitester
/src/Metaboxes/Variants.php
UTF-8
1,395
2.65625
3
[]
no_license
<?php namespace RichJenks\Splitester\Metaboxes; /** * Displays custom fields for test variations */ class Variants { public function __construct() { // Container $cmb = new_cmb2_box( array( 'id' => 'splitester_variants', 'title' => __( 'Variants', 'splitester' ), 'object_types' => array( 'splitester' ), // Post type 'context' => 'normal', 'priority' => 'high', ) ); // Group for fields, one per variation $group_field_id = $cmb->add_field( array( 'id' => 'splitester_variants', 'type' => 'group', 'options' => array( 'group_title' => __( 'Variant {#}', 'cmb' ), // since version 1.1.4, {#} gets replaced by row number 'add_button' => __( 'Add Variant', 'cmb' ), 'remove_button' => __( 'Remove Variant', 'cmb' ), ), ) ); // Fields to be grouped $cmb->add_group_field( $group_field_id, array( 'name' => 'Variant Name', 'id' => 'splitester_variant_name', 'type' => 'text', 'attributes' => array( 'required' => 'true', 'placeholder' => 'Variant Name', ), ) ); $cmb->add_group_field( $group_field_id, array( 'name' => 'Content', 'id' => 'splitester_variant_content', 'type' => 'wysiwyg', 'attributes' => array( 'required' => 'true', 'placeholder' => 'Variant Content', ), ) ); } }
true
b56554ec3978fa0228d9e6ffd1c6e08d50ff70f4
PHP
jatin0777/jatin-github
/plugin/wp-content/plugins/polylang/include/links-abstract-domain.php
UTF-8
2,248
2.78125
3
[ "GPL-2.0-or-later", "GPL-1.0-or-later", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-proprietary-license", "GPL-3.0-only", "LicenseRef-scancode-public-domain", "GPL-3.0-or-later" ]
permissive
<?php /** * Links model for use when using one domain or subdomain per language * * @since 2.0 */ abstract class PLL_Links_Abstract_Domain extends PLL_Links_Permalinks { /** * Constructor * * @since 2.0 * * @param object $model PLL_Model instance. */ public function __construct( &$model ) { parent::__construct( $model ); // Avoid cross domain requests ( mainly for custom fonts ). add_filter( 'content_url', array( $this, 'site_url' ) ); add_filter( 'theme_root_uri', array( $this, 'site_url' ) ); // The above filter is not sufficient with WPMU Domain Mapping. add_filter( 'plugins_url', array( $this, 'site_url' ) ); add_filter( 'rest_url', array( $this, 'site_url' ) ); add_filter( 'upload_dir', array( $this, 'upload_dir' ) ); } /** * Returns the language based on language code in url * links_model interface * * @since 1.2 * @since 2.0 add $url argument * * @param string $url optional, defaults to current url * @return string language slug */ public function get_language_from_url( $url = '' ) { if ( empty( $url ) ) { $url = pll_get_requested_url(); } $host = wp_parse_url( $url, PHP_URL_HOST ); return ( $lang = array_search( $host, $this->get_hosts() ) ) ? $lang : ''; } /** * Sets the home urls * * @since 2.2 * * @param object $language */ protected function set_home_url( $language ) { $home_url = $this->home_url( $language ); $language->set_home_url( $home_url, $home_url ); // Search url and home url are the same } /** * Returns the current site url * * @since 1.8 * * @param string $url * @return string */ public function site_url( $url ) { $lang = $this->get_language_from_url(); $lang = $this->model->get_language( $lang ); return $this->add_language_to_link( $url, $lang ); } /** * Fix the domain for upload directory * * @since 2.0.6 * * @param array $uploads * @return array */ public function upload_dir( $uploads ) { $lang = $this->get_language_from_url(); $lang = $this->model->get_language( $lang ); $uploads['url'] = $this->add_language_to_link( $uploads['url'], $lang ); $uploads['baseurl'] = $this->add_language_to_link( $uploads['baseurl'], $lang ); return $uploads; } }
true
dcfc01bd21acd91091844f0f7564cb8530c278ae
PHP
zxf5115/SystemCMS_Green
/Application/Admin/Plugin/FormatPlugin.class.php
UTF-8
7,540
2.953125
3
[]
no_license
<?php /** * --------------------------------------------------------------------------------- * @filename * @chinese: 后台数据格式化插件类 * @english: FormatPlugin.class.php * * @version: 1.0 * @desc : 操作后台数据格式化 * * @author : Zhang XiaoFei (1326336909@qq.com) * @date : 2015-12-11 16:11:01 */ class FormatPlugin { /** * -------------------------------------------------------------------------------------- * 根据条件格式化数据 * * @param String $data 格式化前数据 * @param String $type 使用格式化类型 * @param String $format 格式化数据样式 * @param String $field 格式化数据字段 * * @return String $data 格式化后数据 */ public function getFormatDataInfo($data, $type = 'date', $format = '', $condition = '', $field = '') { if(!isset($data)) { return ''; } if('date' === $type) { empty($format) && $format = 'Y-m-d H:i:s'; # 格式化时间样式 $data = $this->setDateTimeFormat($data, $format); } else if('size' === $type) { empty($format) && $format = '80'; # 格式化内容数据长度 $data = $this->setDataSizeFormat($data, $format); } else if('status' === $type) { empty($format) && $format = array(0=>'禁用',1=>'启用'); # 格式化内容数据状态 $data = $this->setDataStatusFormat($data, $format); } else if('pay' === $type) { # 格式化内容数据支付方式 $data = $this->setDataPayFormat($data); } else if('model' === $type) { # 格式化内容数据模型名称 $data = $this->setDataModelNameFormat($data); } else if('utf8' === $type) { empty($format) && $format = 'UTF-8'; # 格式化内容数据编号对应文字内容 $data = $this->setDataTransFormat($data, $format); } else if('field' === $type) { empty($format) && $format = 'Member'; empty($condition) && $format = 'id'; empty($field) && $field = 'id'; # 格式化内容数据编号对应文字内容 $data = $this->setDataDataFieldFormat($data, $format, $condition, $field); } else if('function' === $type) { # 调用方法格式化内容数据 $data = $format($data); } else { # TODO: 暂时没有想到还需要什么,将来改进 } return $data; } # + ---------------------------------------------------------------------------------------------- # + 内部操作逻辑 /** * -------------------------------------------------------------------------------------- * 根据条件格式化时间数据 * * @param String $data 需要格式化的数据 * @param String $style 格式化样式 * * @return String 格式化后数据 */ private function setDateTimeFormat($data, $style) { if(isset($data)) { return date($style, $data); } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化内容长度数据 * * @param String $data 需要格式化的数据 * @param String $size 格式化样式 * * @return String 格式化后数据 */ private function setDataSizeFormat($data, $size) { if(isset($data)) { if($size < strlen($data)) { return msubstr($data, 0, $size); } else { return $data; } } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化内容编码格式数据 * * @param String $data 需要格式化的数据 * @param String $format 格式化样式 * * @return String 格式化后数据 */ private function setDataTransFormat($data, $format) { if(isset($data)) { return mb_convert_encoding($data, $format); } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化内容长度数据 * * @param String $data 需要格式化的数据 * @param Array $style 样式数组 array(0=>'禁用',1=>'启用',...) * * @return String 格式化后数据 */ private function setDataStatusFormat($data, $style) { if(isset($data)) { switch($data) { case 0: return $style[0]; break; case 1: return $style[1]; break; case 2: return $style[2]; break; case 3: return $style[3]; break; case 4: return $style[4]; break; case 5: return $style[5]; break; case 6: return $style[6]; break; case 7: return $style[7]; break; case 8: return $style[8]; break; default: return $style[9]; break; } } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化支付方式数据 * * @param String $data 需要格式化的数据 * * @return String 格式化后数据 */ private function setDataPayFormat($data) { if(isset($data)) { switch($data) { case 'ALIPAY': return '支付宝'; break; case 'WXPAY': return '微信'; break; default: return '其他'; break; } } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化模块名称数据 * * @param String $data 需要格式化的数据 * * @return String 格式化后数据 */ private function setDataModelNameFormat($data) { if(isset($data)) { switch($data) { case 'home': return '首页'; break; case 'figure': return '大师'; break; case 'question': return '问答'; break; case 'course': return '课程'; break; case 'commodity': return '商品'; break; case 'find': return '发现'; break; case 'pay': return '支付'; break; case 'my': return '我的'; break; case 'advertisement': return '广告'; break; case 'welcome': return '启动页'; break; case 'evaluate': return '评价'; break; case 'backstage': return '运营后台'; break; default: return '未知'; break; } } } /** * -------------------------------------------------------------------------------------- * 根据条件格式化数据编号数据 * * @param String $data 需要格式化的数据 * @param String $function 方法名称 * * @return String 格式化后数据 */ private function setDataDataFieldFormat($data, $model, $condition, $field) { if(isset($data)) { if(empty($data)) { return '无'; } $where[$condition] = $data; return D($model)->getWithWhereTableOneFieldInfo($where, $field); } } }
true
e17d659af3d7ab983ac90fa8e2856f7b94ab6665
PHP
open-orchestra/open-orchestra-cms-bundle
/ApiBundle/Transformer/ContentAttributeTransformer.php
UTF-8
1,270
2.515625
3
[ "Apache-2.0" ]
permissive
<?php namespace OpenOrchestra\ApiBundle\Transformer; use OpenOrchestra\BaseApi\Exceptions\TransformerParameterTypeException; use OpenOrchestra\BaseApi\Facade\FacadeInterface; use OpenOrchestra\BaseApi\Transformer\AbstractTransformer; use OpenOrchestra\ModelInterface\Model\ContentAttributeInterface; /** * Class ContentAttributeTransformer */ class ContentAttributeTransformer extends AbstractTransformer { /** * @param ContentAttributeInterface $contentAttribute * @param array $params * * @return FacadeInterface * * @throws TransformerParameterTypeException */ public function transform($contentAttribute, array $params = array()) { if (!$contentAttribute instanceof ContentAttributeInterface) { throw new TransformerParameterTypeException(); } $facade = $this->newFacade(); $facade->name = $contentAttribute->getName(); $facade->value = $contentAttribute->getValue(); $facade->stringValue = $contentAttribute->getStringValue(); $facade->type = $contentAttribute->getType(); return $facade; } /** * @return string */ public function getName() { return 'content_attribute'; } }
true
8133fd6e1c1533d5c3a125f347aa4fc71024d0c8
PHP
yiqiniu/logger-viewer
/src/library/Logger.php
UTF-8
3,221
2.734375
3
[]
no_license
<?php namespace yiqiniu\logger\library; use think\App; use think\Exception; use yiqiniu\logger\library\contract\YqnLoggerInterface; class Logger implements YqnLoggerInterface { private static $_config = []; //public function protected $namespace = ''; /** * @var App */ protected $app; // 保存 /** * @var * */ protected $handler = null; protected static $_instance = null; /** * Procdata constructor. * @param mixed ...$args */ private function __construct() { } public static function getInstance(...$args) { // 获取调用者,产生一个单列调用值 if (empty(self::$_instance)) { self::$_instance = new static(); } if (method_exists(self::$_instance, '_initilize')) { call_user_func_array([self::$_instance, '_initilize'], $args); } return self::$_instance; } public function _initilize(App $app) { $this->app = $app; $this->getDriver(); } /** * 获取驱动实例 * @param string $name * @return mixed * @throws Exception */ protected function getDriver() { if ($this->handler === null) { $name = $this->getConfig('default', 'file'); $class = '\\yiqiniu\\logger\\library\\drives\\' . ucfirst($name); if (!class_exists($class)) { throw new Exception($class . 'file not found'); } $handler = new $class($this->app); if ($handler->initOption($this->getConfig($name)) === false) { throw new Exception('初始化驱动失败'); } $this->handler = $handler; return $handler; } return $this->handler; } /** * 获取日志配置 * @access public * @param null|string $name 名称 * @param mixed $default 默认值 * @return mixed */ public function getConfig(string $name = null, $default = '') { if (!empty(self::$_config)) { $config = self::$_config; } else { $config = Base::getConfig($this->app, false); } if (!is_null($name)) { return $config[$name] ?? $default; } return $config; } /** * 初始驱动 * @param array $option * @return bool */ public function initOption(array $option): bool { return true; } public function write(string $content): bool { return $this->handler->write($content); } public function treelist(): array { return $this->handler->treelist(); } public function filelist(string $fileID = ''): array { return $this->handler->filelist($fileID); } public function read(string $fileID): string { return $this->handler->read($fileID); } public function delete(string $fileID): bool { return $this->handler->delete($fileID); } public function page(string $fileID, $page, int $page_size): string { return $this->handler->page($fileID, $page, $page_size); } }
true
e4d4309ba4ff7f4919caaa6e271a09f555785039
PHP
chcantre/artandcraft
/code/SendEmails.php
UTF-8
1,446
2.921875
3
[]
no_license
<?php $headers = "From: chcantre@gmail.com\r\nReply-to: chcantre@gmail.com"; $addresses = "EmailList.txt"; $handle = fopen($addresses, 'r'); while (($line = fgets($handle)) !== false) { echo $line . "\n"; $parts = preg_split('/\|/', $line); $email = $parts[0]; $fname = $parts[2]; $hsname = $parts[3]; $lname = $parts[4]; $street = $parts[5]; $city = $parts[6]; $state = $parts[7]; $zip = $parts[8]; $phone = $parts[9]; $text = getEmailText($fname, $hsname, $lname, $street, $city, $state, $zip, $phone) echo $text; mail($email, "SHS Class of '66 Reunion", $text, $headers); } return; function getEmailText($fname, $hsname, $lname, $street, $city, $state, $zip, $phone) { $text = <<<TEXT Hello, $fname, Charles Cantrell here. I am sending emails to all of the SHS Class of '66 classmates where I have emails. I hope this finds you well. The 50th Year Reunion is planned for August 6th, at the Southern Dunes Golf Club at 8220 South Tibbs Avenue. Hope you will save the date for that. In the meantime, I would like to verify the information that I have in my database. The name I have is: $fname $lname Could you please confirm that I have the spelling correct. Also, the address I have for you is: $street $city, $state $zip The phone is: $phone I would appreciate it if you would email me back to confirm all this information. Thanks for your help, and I am looking forward to seeing you at the reunion. Charles Cantrell TEXT; return $text; } ?>
true
ca090eb4debc0efba14c2453ce5f6217a28c8270
PHP
sebastiancorrales/nutrir
/models/Departamento.class.php
UTF-8
489
2.859375
3
[]
no_license
<?php include_once 'core\BaseModel.php'; class Departamento extends BaseModel { private $nombre; public function __construct() { parent::__construct(); } /** * Get the value of nombre */ public function getNombre() { return $this->nombre; } /** * Set the value of nombre * * @return self */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } }
true
dc8490306ed3a2db6a9b261ae0e04a9381ae85a6
PHP
Thebys/ih-theme-test
/templates/shortcode-page-button.php
UTF-8
1,805
2.703125
3
[]
no_license
<?php /** * Template for the Page Button shortcode. * * Template is ready to be used with or without Elementor. Thanks to the add_render_attribute() method this element * can be edited live with Elementor (the changes are visible right away and one can change the button text right * in the page itself without interacting with the user interface on the left). * * This template is called from shortcodes/page-button.php */ /** @var array $atts array of shortcode arguments */ $link_url = $atts['link']['url']; $new_tab = $atts['link']['is_external']; $nofollow = $atts['link']['nofollow']; $modal = $atts['modal']; $text = $atts['text']; $anec = $atts['anec']; $anea = $atts['anea']; $classes = ['page-button-new']; if(!empty($atts['size'])) array_push($classes, $atts['size']); if(!empty($atts['text_color'])) array_push($classes, $atts['text_color']); if(!empty($atts['style'])) $classes = array_merge($classes, $atts['style']); /** @var IH_Widget_PageButton $el */ $el = $atts['elementor_widget']; if($el) $el->add_render_attribute( 'text', [ 'class' => $classes, 'href' => $link_url, 'target' => $new_tab ? '_blank' : '_self', 'rel' => $nofollow ? 'nofollow' : '', 'data-toggle' => $modal ? 'modal' : '', 'anec' => $anec, 'anea' => $anea ] ) ?> <a <?= $el ? $el->get_render_attribute_string( 'text' ) : '' ?> <?= !$el ? 'class="'.join(' ', $classes) . '"' : '' ?> <?= !$el ? 'href="' . $link_url . '"' : '' ?> <?= !$el ? 'target="' . ($new_tab ? '_blank' : '_self') : '' ?> <?= !$el ? 'rel="' . ($nofollow ? 'nofollow' : '') : '' ?> <?= !$el ? 'anec="' . ($anec ? $anec : '') : '' ?> <?= !$el ? 'anea="' . ($anea ? $anea : '') : '' ?> <?= !$el ? 'data-toggle="' . ($modal ? 'modal' : '') : '' ?> > <?= $text ?> </a>
true
89645bac62cd67723e9a5ff833f54875e8d44078
PHP
EricHindle/lms
/lms_php/struct/game/game-functions.php
UTF-8
11,266
2.546875
3
[]
no_license
<?php /* * HINDLEWARE * Copyright (C) 2020 Eric Hindle. All rights reserved. */ $myPath = '../../'; require_once $myPath . 'includes/db_connect.php'; require_once $myPath . 'struct/picks/pick-functions.php'; require_once $myPath . 'struct/email/email-functions.php'; date_default_timezone_set('Europe/London'); function add_player_to_game($gameid, $playerid) { global $mypdo; $sqljoingame = "INSERT INTO lms_game_player (lms_game_id, lms_player_id, lms_game_player_status) VALUES (:gameid, :playerid, 1)"; $stmtjoingame = $mypdo->prepare($sqljoingame); $stmtjoingame->bindParam(":gameid", $gameid, PDO::PARAM_INT); $stmtjoingame->bindParam(":playerid", $playerid, PDO::PARAM_INT); $stmtjoingame->execute(); $joincount = $stmtjoingame->rowCount(); $joinok = false; if ($joincount > 0) { $joinok = true; $gamesql = "SELECT lms_game_id, lms_game_total_players, lms_game_still_active FROM lms_game WHERE lms_game_id = :id"; $gamequery = $mypdo->prepare($gamesql); $gamequery->execute(array( ':id' => $gameid )); $gamecount = $gamequery->rowCount(); if ($gamecount > 0) { $gamefetch = $gamequery->fetch(PDO::FETCH_ASSOC); $total = $gamefetch['lms_game_total_players'] + 1; $active = $gamefetch['lms_game_still_active'] + 1; $upsql = "UPDATE lms_game SET lms_game_total_players = :total, lms_game_still_active = :active WHERE lms_game_id = :id"; $upquery = $mypdo->prepare($upsql); $upquery->bindParam(':id', $gameid, PDO::PARAM_INT); $upquery->bindParam(':total', $total, PDO::PARAM_INT); $upquery->bindParam(':active', $active, PDO::PARAM_INT); $upquery->execute(); $teamsql = "SELECT lms_team_id, lms_team_name FROM lms_team t JOIN lms_league_team lt on t.lms_team_id = lt.lms_league_team_team_id WHERE t.lms_team_active = 1 and lt.lms_league_team_league_id IN (SELECT lms_game_league_league_id from lms_game_league where lms_game_league_game_id = :gameid) ORDER BY lms_team_name ASC"; $teamquery = $mypdo->prepare($teamsql); $teamquery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $teamquery->execute(); $teamfetch = $teamquery->fetchAll(PDO::FETCH_ASSOC); foreach ($teamfetch as $rs) { insert_available_team($playerid, $gameid, $rs['lms_team_id']); } } } return $joinok; } function remove_player_from_game($gameid, $playerid) { global $mypdo; $leaveok = false; $sqlleavegame = "UPDATE lms_game_player SET lms_game_player_status = 3 WHERE lms_game_id = :gameid and lms_player_id = :playerid"; $stmtleavegame = $mypdo->prepare($sqlleavegame); $stmtleavegame->bindParam(":gameid", $gameid, PDO::PARAM_INT); $stmtleavegame->bindParam(":playerid", $playerid, PDO::PARAM_INT); $stmtleavegame->execute(); $leavecount = $stmtleavegame->rowCount(); if ($leavecount > 0) { $leaveok = true; $gamesql = "SELECT lms_game_id, lms_game_total_players, lms_game_still_active FROM lms_game WHERE lms_game_id = :id"; $gamequery = $mypdo->prepare($gamesql); $gamequery->execute(array( ':id' => $gameid )); $gamecount = $gamequery->rowCount(); if ($gamecount > 0) { $gamefetch = $gamequery->fetch(PDO::FETCH_ASSOC); $active = $gamefetch['lms_game_still_active'] - 1; $upsql = "UPDATE lms_game SET lms_game_still_active = :active WHERE lms_game_id = :id"; $upquery = $mypdo->prepare($upsql); $upquery->bindParam(':id', $gameid, PDO::PARAM_INT); $upquery->bindParam(':active', $active, PDO::PARAM_INT); $upquery->execute(); } } return $leaveok; } function generate_game_code() { $allchars = "abcdefghjkmnpqrstuvwxyz23456789"; $randstr = str_shuffle($allchars); $gamecode = ""; $gamecount = - 1; do { for ($i = 1; $i < 7; $i ++) { $gamecode .= substr($randstr, 0, 1); $randstr = str_shuffle($randstr); } $gamequery = find_game_by_code($gamecode); $gamecount = $gamequery->rowCount(); } while ($gamecount != 0); return $gamecode; } function find_game_by_code($gamecode) { global $mypdo; $gamesql = "SELECT lms_game_id, lms_game_name, lms_game_manager, lms_game_status, lms_player_screen_name, lms_game_start_wkno FROM v_lms_game WHERE lms_game_code = :id"; $gamequery = $mypdo->prepare($gamesql); $gamequery->execute(array( ':id' => $gamecode )); return $gamequery; } function get_player_games() { global $mypdo; $player = $_SESSION['user_id']; $gamesql = "SELECT * FROM v_lms_player_games WHERE lms_player_id = :player ORDER BY lms_game_player_status, lms_game_name ASC"; $gamequery = $mypdo->prepare($gamesql); $gamequery->bindParam(':player', $player, PDO::PARAM_INT); $gamequery->execute(); $gamelist = $gamequery->fetchAll(PDO::FETCH_ASSOC); return $gamelist; } function set_game_player_out($gameid, $playerid) { global $mypdo; $upsql = "UPDATE lms_game_player SET lms_game_player_status = 2 WHERE lms_game_id = :gameid and lms_player_id = :playerid"; $upquery = $mypdo->prepare($upsql); $upquery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $upquery->bindParam(':playerid', $playerid, PDO::PARAM_INT); $upquery->execute(); $upCount = $upquery->rowCount(); if ($upCount > 0) { $game = get_game($gameid); $stillActive = max(0, $game['lms_game_still_active'] - 1); $updgamesql = "UPDATE lms_game SET lms_game_still_active = :stillactive WHERE lms_game_id = :gameid"; $updgamequery = $mypdo->prepare($updgamesql); $updgamequery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $updgamequery->bindParam(':stillactive', $stillActive, PDO::PARAM_INT); $updgamequery->execute(); $upCount = $updgamequery->rowCount(); } } function get_active_games() { global $mypdo; $gamesql = "SELECT * FROM lms_game WHERE lms_game_status = 2"; $gamequery = $mypdo->prepare($gamesql); $gamequery->execute(); $gamefetch = $gamequery->fetchAll(PDO::FETCH_ASSOC); return $gamefetch; } function set_game_complete($gameid) { global $mypdo; $updgamesql = "UPDATE lms_game SET lms_game_status = 3 WHERE lms_game_id = :gameid"; $updgamequery = $mypdo->prepare($updgamesql); $updgamequery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $updgamequery->execute(); $upCount = $updgamequery->rowCount(); return $upCount; } function set_game_week_count($gameid, $newweekcount) { global $mypdo; $updgamesql = "UPDATE lms_game SET lms_game_week_count = :weekcount WHERE lms_game_id = :gameid"; $updgamequery = $mypdo->prepare($updgamesql); $updgamequery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $updgamequery->bindParam(':weekcount', $newweekcount, PDO::PARAM_INT); $updgamequery->execute(); $upCount = $updgamequery->rowCount(); return $upCount; } function get_still_active_game_players($gameid) { global $mypdo; $gamesql = "SELECT * FROM v_lms_player_games WHERE lms_game_id = :gameid and lms_game_player_status = 1 "; $gamequery = $mypdo->prepare($gamesql); $gamequery->bindParam(':gameid', $gameid, PDO::PARAM_INT); $gamequery->execute(); $gamelist = $gamequery->fetchAll(PDO::FETCH_ASSOC); return $gamelist; } function activateGames($nextgameweek, $calid) { global $mypdo; $updgamesql = "UPDATE lms_game SET lms_game_status = 2, lms_game_week_count = 1 WHERE lms_game_start_wkno = :weekno AND lms_game_calendar = :cal"; $updgamequery = $mypdo->prepare($updgamesql); $updgamequery->bindParam(':weekno', $nextgameweek); $updgamequery->bindParam(':cal', $calid, PDO::PARAM_INT); $updgamequery->execute(); $upCount = $updgamequery->rowCount(); return $upCount; } function sendcancelemailsforgame($gameid) { $gamelist = get_still_active_game_players($gameid); foreach ($gamelist as $player) { $playerid = $player['lms_player_id']; sendemailusingtemplate('cancel', $playerid, $gameid, 0, '', true); } } function check_game_exists($gameid) { global $mypdo; $gamesql = "SELECT * FROM lms_game WHERE lms_game_id = :gameid LIMIT 1"; $gamequery = $mypdo->prepare($gamesql); $gamequery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $gamequery->execute(); return $gamequery->rowCount(); } function set_game_cancelled($gameid) { $upsql = "UPDATE lms_game SET lms_game_status = 4 WHERE lms_game_id = :id"; $upquery = $mypdo->prepare($upsql); $upquery->bindParam(':id', $gameid, PDO::PARAM_INT); $upquery->execute(); return $upquery->rowCount(); } function remove_available_picks($gameid) { global $mypdo; $delsql = "DELETE FROM lms_available_picks WHERE lms_available_picks_game = :gameid"; $delquery = $mypdo->prepare($delsql); $delquery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $delquery->execute(); return $delquery->rowCount(); } function remove_game_league($gameid) { global $mypdo; $delsql = "DELETE FROM lms_game_league WHERE lms_game_league_game_id = :gameid"; $delquery = $mypdo->prepare($delsql); $delquery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $delquery->execute(); return $delquery->rowCount(); } function remove_game_player($gameid) { global $mypdo; $delsql = "DELETE FROM lms_game_player WHERE lms_game_id = :gameid"; $delquery = $mypdo->prepare($delsql); $delquery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $delquery->execute(); return $delquery->rowCount(); } function remove_pick($gameid) { global $mypdo; $delsql = "DELETE FROM lms_pick WHERE lms_pick_game_id = :gameid"; $delquery = $mypdo->prepare($delsql); $delquery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $delquery->execute(); return $delquery->rowCount(); } function remove_game($gameid) { global $mypdo; $delsql = "DELETE FROM lms_game WHERE lms_game_id = :gameid"; $delquery = $mypdo->prepare($delsql); $delquery->bindParam(":gameid", $gameid, PDO::PARAM_INT); $delquery->execute(); return $delquery->rowCount(); } function insert_game_league($gameid, $leagueId) { global $mypdo; $sqladdgameleague = "INSERT INTO lms_game_league (lms_game_league_game_id, lms_game_league_league_id) VALUES (:gameid, :leagueid)"; $stmtaddgameleague = $mypdo->prepare($sqladdgameleague); $stmtaddgameleague->bindParam(':gameid', $gameid, PDO::PARAM_INT); $stmtaddgameleague->bindParam(':leagueid', $leagueId, PDO::PARAM_INT); $stmtaddgameleague->execute(); return $stmtaddgameleague->rowCount(); } ?>
true
fc84ea8b90669f04d99d4cbc780cc7ac373922e9
PHP
namncn/rtcore
/woocommerce/single-product/product-thumbnails.php
UTF-8
1,842
2.53125
3
[]
no_license
<?php /** * Single Product Thumbnails * * This template can be overridden by copying it to yourtheme/woocommerce/single-product/product-thumbnails.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you * (the theme developer) will need to copy the new files to your theme to * maintain compatibility. We try to do this as little as possible, but it does * happen. When this occurs the version of the template file will be bumped and * the readme will list any important changes. * * @see https://docs.woocommerce.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates * @version 3.0.2 */ if ( ! defined( 'ABSPATH' ) ) { exit; } global $post, $product; $attachment_ids = $product->get_gallery_image_ids(); ?> <ul class="list-unstyled"> <?php if ( $attachment_ids && has_post_thumbnail() ) { foreach ( $attachment_ids as $attachment_id ) { $full_size_image = wp_get_attachment_image_src( $attachment_id, 'full' ); $attributes = array( 'class' => 'cloudzoom-gallery', 'data-cloudzoom' => "useZoom:'.cloudzoom', image:'$full_size_image[0]'", ); if ( has_post_thumbnail() ) { $html = '<li class="woocommerce-product-gallery__image">'; $html .= '<img class="cloudzoom-gallery" src="' . get_the_post_thumbnail_url( $post->ID, 'full' ) . '" data-cloudzoom="useZoom:\'.cloudzoom\', image:\'' . get_the_post_thumbnail_url( $post->ID, 'full' ) . '\'">'; $html .= '</li>'; } $html .= '<li class="woocommerce-product-gallery__image">'; $html .= '<img class="cloudzoom-gallery" src="' . $full_size_image[0] . '" data-cloudzoom="useZoom:\'.cloudzoom\', image:\'' . $full_size_image[0] . '\'">'; $html .= '</li>'; echo apply_filters( 'woocommerce_single_product_image_thumbnail_html', $html, $attachment_id ); } } ?> </ul>
true
40158acf6835eddc0702a96351db5c485c6b0489
PHP
jfsfranco/Tv
/app/Modules/DataProcessor/Infrastructure/Exception/ErrorReadingFileException.php
UTF-8
345
2.71875
3
[]
no_license
<?php namespace App\DataProcessor\Infrastructure\Exception; use RuntimeException; use App\DataProcessor\Application\Exception\ErrorReadingFileException as ErrorReadingFileExceptionInterface; class ErrorReadingFileException extends RuntimeException implements ErrorReadingFileExceptionInterface { const MESSAGE = "File can not be read"; }
true
15e8c77ef4319c0ccc9f89c1c2f1b2f6bf730b67
PHP
adbhas/collect
/kugou.php
UTF-8
822
2.59375
3
[]
no_license
<?php /** * 获取列表 * @param string $keyword 关键字 * @param integer $page 当前页 * @param integer $pagesize 每页获取数量 * @return array */ function getList($keyword, $page = 1, $pagesize = 10){ $url = "https://songsearch.kugou.com/song_search_v2?&keyword={$keyword}&page={$page}&pagesize={$pagesize}"; $resp = json_decode(file_get_contents($url), true); return $resp; } /** * 获取音乐地址 * @param string $hash 音乐hash码 * @return array */ function getMusic($hash){ $url = "http://m.kugou.com/app/i/getSongInfo.php?hash={$hash}&cmd=playInfo"; $resp = json_decode(file_get_contents($url), true); return $resp; } $data = getList("默")["data"]["lists"];//获取搜索列表 $url = getMusic($data[0]["FileHash"])["url"]; echo $url;
true
a4492c51c392e27a7e37cf3221598ada8f52f4fc
PHP
egorsmkv/laravel-api-example
/app/Data/Transformers/Api/ArticleTransformer.php
UTF-8
342
2.53125
3
[]
no_license
<?php namespace App\Data\Transformers\Api; use App\Data\Models\Article; use League\Fractal\TransformerAbstract; class ArticleTransformer extends TransformerAbstract { /** * @param Article $item * @return array<string, mixed> */ public function transform(Article $item) { return $item->toArray(); } }
true
73d66bf8f6bece24ddb026f20d033068c2d409fa
PHP
phpcr/phpcr-shell
/src/PHPCR/Shell/Console/Command/Phpcr/VersionCheckinCommand.php
UTF-8
3,117
2.609375
3
[ "MIT" ]
permissive
<?php /* * This file is part of the PHPCR Shell package * * (c) Daniel Leech <daniel@dantleech.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * */ namespace PHPCR\Shell\Console\Command\Phpcr; use PHPCR\RepositoryInterface; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class VersionCheckinCommand extends BasePhpcrCommand { protected function configure() { $this->setName('version:checkin'); $this->setDescription('Checkin (commit) a node version'); $this->addArgument('path', InputArgument::REQUIRED, 'Absolute path to node'); $this->setHelp( <<<'HERE' Creates for the versionable node at <info>path</info> a new version with a system generated version name and returns that version (which will be the new base version of this node). Sets the <property>jcr:checkedOut</property> property to false thus putting the node into the checked-in state. This means that the node and its connected non-versionable subgraph become read-only. A node's connected non-versionable subgraph is the set of non-versionable descendant nodes reachable from that node through child links without encountering any versionable nodes. In other words, the read-only status flows down from the checked-in node along every child link until either a versionable node is encountered or an item with no children is encountered. In a system that supports only simple versioning the connected non-versionable subgraph will be equivalent to the whole subgraph, since simple-versionable nodes cannot have simple-versionable descendants. Read-only status means that an item cannot be altered by the client using standard API methods (addNode, setProperty, etc.). The only exceptions to this rule are the restore(), restoreByLabel(), merge() and Node::update() operations; these do not respect read-only status due to check-in. Note that remove of a read-only node is possible, as long as its parent is not read-only (since removal is an alteration of the parent node). If this node is already checked-in, this method has no effect but returns the current base version of this node. If checkin succeeds, the change to the <property>jcr:isCheckedOut</property> property is dispatched immediately. HERE ); $this->requiresDescriptor(RepositoryInterface::OPTION_VERSIONING_SUPPORTED, true); } public function execute(InputInterface $input, OutputInterface $output) { $session = $this->get('phpcr.session'); $nodeHelper = $this->get('helper.node'); $path = $input->getArgument('path'); $workspace = $session->getWorkspace(); $versionManager = $workspace->getVersionManager(); $node = $session->getNodeByPathOrIdentifier($path); $nodeHelper->assertNodeIsVersionable($node); $version = $versionManager->checkin($node->getPath()); $output->writeln('Version: '.$version->getName()); return 0; } }
true
189ea695da3294efb6630b0daffe8c7c9c12709c
PHP
qeyser/SSSUIBLOG
/Core/Extend/Library/ORG/Util/Sssuizip.class.php
UTF-8
1,951
2.890625
3
[]
no_license
<?php class Sssuizip{ public function __construct(){ } public function Jieya($savename='',$extractpath=''){ $extractpath= empty($extractpath) ? './'.date('YmdHis') : $extractpath; if (!file_exists($extractpath)){ if (!mkdir($extractpath)){ return '文件夹创建失败,请先手动创建存放目录!'; } } if (!file_exists($savename)){ return '要解压缩的文件不存在!'; } $zip = new ZipArchive; if ($zip->open($savename) === TRUE) { $zip->extractTo($extractpath); $zip->close(); return true; } else { return 'zip文件不存在或者目标不是zip文件'; } } protected function scandir($path){ $tree=array(); foreach(glob($path.'/*') as $v){ if(is_dir($v)){ $tree=array_merge($tree,Sssuizip::scandir($v)); }else{ $tree[]=$v; } } return $tree; } public function Yasuo($file='',$savename=''){ if (is_array($file)){ $filearr=$file; }elseif (is_dir($file)){ $filearr=Sssuizip::scandir($file); }elseif(is_file($file)){ $filearr=array($file); }else{ return '第一个参数不合法,正确情况下应该是一个文件,一个文件夹,一个一维文件数组的任意一种!'; } $savename= empty($savename) ? './'.date('YmdHis').'zip' : $savename; $tmp=pathinfo($savename); if (!file_exists($tmp['dirname'])){ if (!mkdir($tmp['dirname'])){ return '文件夹创建失败,请先手动创建存放目录!'; } } Sssuizip::tozip($filearr,$savename); return true; } /** * 压缩文件(zip格式) */ protected function tozip($filearr,$savename){ $zip=new ZipArchive(); $zip->open($savename,ZipArchive::CREATE); for ($i=0;$i<count($filearr);$i++){ $tmp=pathinfo($filearr[$i]); $zip->addFile($filearr[$i],$tmp['basename']); //true || false } $zip->close(); } } ?>
true
ea5b211870ec25faeabb82d1e37fc158e46084a5
PHP
igor-zac/boutique
/catalogue.php
UTF-8
1,278
2.796875
3
[]
no_license
<?php include("functions.php"); session_start(); $articles_choisis_catalogue =[]; //Si nous avons un panier en cours et qu'on ne vient pas de valider le passage de la commande, // on récupère la liste des articles sélectionnés if(isset($_SESSION['panier']) AND !isset($_GET['empty_choice'])){ $articles_choisis = unserialize($_SESSION['panier']); foreach($articles_choisis as $article){ $articles_choisis_catalogue[] = $article['nom']; } } ?> <!doctype html> <html lang="fr"> <head> <meta charset="utf-8"> <title>Titre de la page</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="styles.css"> </head> <body> <?php include("entete.php"); ?> < <form action="panier.php" method="GET" class="block"> <?php //appel de la fonction afficherCatalogue de functions.php pour afficher l'ensemble des articles dispo afficherCatalogue($articles_choisis_catalogue); ?> <div class="bouton"> <button type="submit" name="add" class="btn btn-primary">Ajouter au panier</button> </div> </form> </body> </html>
true
dba1b32695a82ac4812c5495eaffd226ecb6cc9f
PHP
alexkovalevv/sociallocker-cloud
/common/modules/lockers/models/lockers/Lockers.php
UTF-8
1,362
2.78125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\modules\lockers\models\lockers; use common\modules\lockers\models\visability\LockersVisability; use Yii; use yii\db\ActiveRecord; use yii\behaviors\TimestampBehavior; /** * This is the model class for table "lockers". * * @property string $id * @property string $user_id * @property string $title * @property string $header * @property string $message * @property string $options * @property string $type * @property integer $status * @property integer $created_at * @property integer $updated_at */ class Lockers extends ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%widgets}}'; } public function behaviors() { return [ TimestampBehavior::className(), ]; } /** * @inheritdoc */ public function rules() { return [ [['title', 'options'], 'required'], [['title', 'options', 'status'], 'string'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'title' => 'Название замка', 'type' => 'Тип', 'status' => 'Статус', 'created_at' => 'Создан', 'updated_at' => 'Обновлен', ]; } public function getLockersVisability() { return $this->hasOne(LockersVisability::className(), ['locker_id' => 'id']); } }
true
66dac84bafbc85ae0c0af9e3b34d450c8d335873
PHP
mynicky/phpstudy
/Data Structures & Algorithms/demo.php
UTF-8
1,139
3.40625
3
[]
no_license
<?php require_once 'Algorithm/Engine/SortEngine.php'; use Algorithm\Engine\SortEngine; $array = array(0, 3, 2, 4, 1); $array = '873457560132413678310967823129605'; // $array = array('c', 'b', 'd', 'a'); // $array = 'cbda'; echo '======== Bubble sort ========<br />'; echo 'Ascending<br />'; echo '<pre>'; $sortedArray = SortEngine::bubble($array); print_r($sortedArray); echo '</pre>'; echo 'Descending<br />'; echo '<pre>'; $sortedArray = SortEngine::bubble($array, false); print_r($sortedArray); echo '</pre><br />'; echo '======== Selection sort ========<br />'; echo 'Ascending<br />'; echo '<pre>'; $sortedArray = SortEngine::selection($array); print_r($sortedArray); echo '</pre>'; echo 'Descending<br />'; echo '<pre>'; $sortedArray = SortEngine::selection($array, false); print_r($sortedArray); echo '</pre><br />'; echo '======== Insertion sort ========<br />'; echo 'Ascending<br />'; echo '<pre>'; $sortedArray = SortEngine::insertion($array); print_r($sortedArray); echo '</pre>'; echo 'Descending<br />'; echo '<pre>'; $sortedArray = SortEngine::insertion($array, false); print_r($sortedArray); echo '</pre><br />';
true
16845786d5a6871a2d4eae018f1c2aa230a54e83
PHP
k-bigboss99/PHP-MySQL
/本書範例程式/samples/ch08/error1.php
UTF-8
179
2.6875
3
[]
no_license
<?php function F1(array $a) { } try { F1(1); }catch (Exception $e) // failed to catch it { echo $e->getMessage(); } ?>
true
5c92a30e7208b34154e152d730b525505a99bef5
PHP
Maximnnn/map
/app/Controllers/Api/Login.php
UTF-8
561
2.6875
3
[]
no_license
<?php namespace App\Controllers\Api; use App\Controllers\Controller; use App\Core\Request; use App\Models\User; class Login extends Controller { public function __invoke(Request $request) { $user = User::query() ->where('email', $request->get('email')) ->where('password', sha1($request->get('password'))) ->first(); if ($user) { $request->login($user); return $this->json($user); } else { $this->jsonError('wrong password or email'); } } }
true
91cffb9e4db2fc17a5cdf537badc9c75bc71e8cf
PHP
jiokeokwuosa/hotel-system
/checkout.php
UTF-8
2,417
2.546875
3
[]
no_license
<?php require_once'header1.php'; if($_SESSION['access_level'] !=1 and $_SESSION['access_level'] !=3){ header('Location:login.php'); } ?> <form action="transact.php" method="post"> <div class="row"> <h3 class="center color">Check Out</h3> <?php if(isset($_SESSION['c'])){ $error=$_SESSION['c']; echo("<div class='alert alert-success center' role='alert'> <strong>Congratulations!</strong> <br/>Checkout Successful </div>"); unset($_SESSION['c']); }elseif(isset($_SESSION['b'])){ echo("<div class='alert alert-danger center' role='alert'> <strong>Oops!</strong> <br/>Error Checking Out </div>"); unset($_SESSION['b']); } ?> </div> </form> <div class="row"> <div class="col-md-12"> <?php $db=new Database('localhost','christ4life','','hotel'); $db->connect(); $result=$db->select('checkin',array('checkout_status'=>'false'),array('id'=>'desc')); $numrow=$db->numRow(); if($numrow==0){ echo("<h6 class=title>No Existing Record</h6>"); } else{ ?> <table class="table table-striped table-hover"> <thead style="background-color: #000033; color: white;"> <tr> <th>Customer Name</th> <th>Room Name</th> <th>Checkin Date</th> <th>Checkout</th> </tr> </thead> <tbody> <?php while($row=mysqli_fetch_assoc($result)){ extract($row); ?> <tr> <td><?php echo ucwords(strtolower($last_name.' '.$first_name));?></td> <td><?php echo ucwords(strtolower($db->getRoomName($room_id)));?></td> <td> <?php echo date('d-m-y',strtotime($date_created));?></td> <td><?php echo"<a onclick='return checkOut();' href=transact.php?key=$room_id&action=checkOutRoom>";?><i class="fa fa-sign-out" style="color: red;"></i></a> </td> </tr> <?php } ?> </tbody> <tfoot style="background-color: #000033; color: white; text-align: center;"> <tr> <td colspan="4">We have <?php echo $numrow;?> Record(s)</td> </tr> </tfoot> </table> <?php } ?> </div> </div> <?php require_once'footer.php'; ?>
true
4e4d7c9e05ce25df616784744bd0453431eb56c0
PHP
animais-de-rua/animais-de-rua
/app/Helpers/EnumHelper.php
UTF-8
700
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Helpers; use Config; class EnumHelper { public static function get($name) { return Config::get("enums.$name"); } public static function values($name, $join = null) { $data = array_values(self::get($name)); return $join ? join($join, $data) : $data; } public static function keys($name, $join = null) { $data = array_keys(self::get($name)); return $join ? join($join, $data) : $data; } public static function translate($name) { $enum = []; foreach (self::get($name) as $key => $value) { $enum[$key] = ucfirst(__($value)); } return $enum; } }
true
afbe93a308ca146310f784c674a55b63f9c01ea3
PHP
lowtone/lowtone
/util/buildables/buildable.class.php
UTF-8
547
2.59375
3
[]
no_license
<?php namespace lowtone\buildables; use lowtone\util\options\Options; /** * @author Paul van der Meijs <code@lowtone.nl> * @copyright Copyright (c) 2011-2012, Paul van der Meijs * @license http://wordpress.lowtone.nl/license/ * @version 1.0 * @package wordpress\libs\lowtone\buildables */ abstract class Buildable implements interfaces\Buildable { protected $itsBuildOptions; public function __construct() { $this->itsBuildOptions = new Options(); } public function updateBuildOptions(array $options) { $this->itsBuildOptions->updateOptions($options); } }
true
6186a10f353bab24bafa11d0448129b111e3ae60
PHP
Yongsanzip/figleaf
/database/migrations/relation/2019_09_23_065103_add_look_books_to_look_book_images_table.php
UTF-8
817
2.5625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddLookBooksToLookBookImagesTable extends Migration { /** * 룩북 이미지 테이블과 룩북 테이블의 관계 형성 * * @return void */ public function up() { Schema::table('look_book_images', function (Blueprint $table) { $table->foreign('look_book_id')->references('id')->on('look_books')->onUpdate('cascade')->onDelete('cascade'); }); } /** * 관계 삭제 * * @return void */ public function down() { Schema::table('look_book_images', function (Blueprint $table) { $table->dropForeign('look_book_images_look_book_id_foreign'); }); } }
true
0b347d393115b17722b40cb48448823f4c45f35c
PHP
defadels/pertemuanTerakhir-master
/pertemuanTerakhir-master/admin/tambahmenu.php
UTF-8
1,597
2.8125
3
[]
no_license
<h2>Tambah Menu</h2> <hr> <form method="POST" enctype="multipart/form-data"> <div class="form-group"> <label>Nama Menu</label> <input type="text" name="nama_menu" class="form-control"> </div> <div class="form-group"> <label>Harga Menu</label> <input type="number" name="harga_menu" class="form-control"> </div> <div class="form-group"> <label>Deskripsi</label> <textarea name="deskripsi_menu" rows="4" class="form-control"></textarea> </div> <div class="form-group"> <label>Gambar</label> <input type="file" name="gambar" class="form-group"> </div> <button class="btn btn-success" name="tambah">Tambah</button> </form> <!-- syntax php untuk menmbah menu --> <?php // ambil data dari form simpan ke variabel if (isset($_POST['tambah'])) { $nama_menu = $_POST['nama_menu']; $harga_menu = $_POST['harga_menu']; $deskripsi_menu = $_POST['deskripsi_menu']; // untuk menyimpan gambar $foto = $_FILES['gambar']['name']; $lokasi = $_FILES['gambar']['tmp_name']; move_uploaded_file($lokasi, "../foto_menu/".$foto); // syntax untuk mengupload ke database $sql = $koneksi->query("INSERT INTO menu (nama_menu, harga_menu, deskripsi_menu, foto_menu) VALUES ('$nama_menu','$harga_menu', '$deskripsi_menu', '$foto')"); if ($sql) { //jika berhasil echo "<script> alert('Menu berhasil di tambah'); document.location.href='index.php?halaman=menu'; </script>"; }else{ //jika gagal echo "<script> alert('Menu gagal di tambah'); document.location.href='index.php?halaman=menu'; </script>"; } } ?>
true
aa4bc127685808ce9869acc7cd7273bf9c6cc530
PHP
paul-gilliard/Service_stockage
/miniprojet-l3-2020-paul-gilliard-dev/src/Entity/mkdir.php
UTF-8
217
2.640625
3
[]
no_license
<?php namespace App\Entity; class mkdir { protected $nameDir; public function getnameDir(): ?string { return $this->nameDir; } public function setnameDir(string $nameDir): void { $this->nameDir = $nameDir; } }
true
9f05bd611f0ae839b51c7b83c32364024c2bb209
PHP
nicolasros/saferpay-paypage-sdk-php
/src/Common/Fields/BillingAddress.php
UTF-8
6,596
2.6875
3
[]
no_license
<?php namespace Worldline\Saferpay\Common\Fields; use Symfony\Component\Serializer\Annotation\Groups; /** * Class BillingAddress * @package Worldline\Saferpay\Common\Fields */ class BillingAddress { /** * @Groups("RequestParams") * @var null|string */ private $FirstName; /** * @Groups("RequestParams") * @var null|string */ private $LastName; /** * @Groups("RequestParams") * @var null|string */ private $DateOfBirth; /** * @Groups("RequestParams") * @var null|string */ private $Company; /** * @Groups("RequestParams") * @var null|string */ private $Gender; /** * @Groups("RequestParams") * @var null|string */ private $LegalForm; /** * @Groups("RequestParams") * @var null|string */ private $Street; /** * @Groups("RequestParams") * @var null|string */ private $Street2; /** * @Groups("RequestParams") * @var null|string */ private $Zip; /** * @Groups("RequestParams") * @var null|string */ private $City; /** * @Groups("RequestParams") * @var null|string */ private $CountrySubdivisionCode; /** * @Groups("RequestParams") * @var null|string */ private $CountryCode; /** * @Groups("RequestParams") * @var null|string */ private $Phone; /** * @Groups("RequestParams") * @var null|string */ private $Email; /** * @return string|null */ public function getFirstName(): ?string { return $this->FirstName; } /** * @param string|null $FirstName * @return $this */ public function setFirstName(?string $FirstName): self { $this->FirstName = $FirstName; return $this; } /** * @return string|null */ public function getLastName(): ?string { return $this->LastName; } /** * @param string|null $LastName * @return $this */ public function setLastName(?string $LastName): self { $this->LastName = $LastName; return $this; } /** * @return string|null */ public function getDateOfBirth(): ?string { return $this->DateOfBirth; } /** * @param string|null $DateOfBirth * @return $this */ public function setDateOfBirth(?string $DateOfBirth): self { $this->DateOfBirth = $DateOfBirth; return $this; } /** * @return string|null */ public function getCompany(): ?string { return $this->Company; } /** * @param string|null $Company * @return $this */ public function setCompany(?string $Company): self { $this->Company = $Company; return $this; } /** * @return string|null */ public function getGender(): ?string { return $this->Gender; } /** * @param string|null $Gender * @return $this */ public function setGender(?string $Gender): self { $this->Gender = $Gender; return $this; } /** * @return string|null */ public function getLegalForm(): ?string { return $this->LegalForm; } /** * @param string|null $LegalForm * @return $this */ public function setLegalForm(?string $LegalForm): self { $this->LegalForm = $LegalForm; return $this; } /** * @return string|null */ public function getStreet(): ?string { return $this->Street; } /** * @param string|null $Street * @return $this */ public function setStreet(?string $Street): self { $this->Street = $Street; return $this; } /** * @return string|null */ public function getStreet2(): ?string { return $this->Street2; } /** * @param string|null $Street2 * @return $this */ public function setStreet2(?string $Street2): self { $this->Street2 = $Street2; return $this; } /** * @return string|null */ public function getZip(): ?string { return $this->Zip; } /** * @param string|null $Zip * @return $this */ public function setZip(?string $Zip): self { $this->Zip = $Zip; return $this; } /** * @return string|null */ public function getCity(): ?string { return $this->City; } /** * @param string|null $City * @return $this */ public function setCity(?string $City): self { $this->City = $City; return $this; } /** * @return string|null */ public function getCountrySubdivisionCode(): ?string { return $this->CountrySubdivisionCode; } /** * @param string|null $CountrySubdivisionCode * @return $this */ public function setCountrySubdivisionCode(?string $CountrySubdivisionCode): self { $this->CountrySubdivisionCode = $CountrySubdivisionCode; return $this; } /** * @return string|null */ public function getCountryCode(): ?string { return $this->CountryCode; } /** * @param string|null $CountryCode * @return $this */ public function setCountryCode(?string $CountryCode): self { $this->CountryCode = $CountryCode; return $this; } /** * @return string|null */ public function getPhone(): ?string { return $this->Phone; } /** * @param string|null $Phone * @return $this */ public function setPhone(?string $Phone): self { $this->Phone = $Phone; return $this; } /** * @return string|null */ public function getEmail(): ?string { return $this->Email; } /** * @param string|null $Email * @return $this */ public function setEmail(?string $Email): self { $this->Email = $Email; return $this; } }
true
827acaed5a740f472926b5556eb5f9bddf29899d
PHP
epfl-dojo/PHP-CRUD
/delete.php
UTF-8
359
2.71875
3
[]
no_license
<?php $id = $_GET['id']; try { $dbh = new PDO('mysql:host=localhost;dbname=DojoCRUD', "root", "password"); if (isset($id)) { $dbh->exec("DELETE FROM Article WHERE id = $id;"); } else { echo "No id was found !"; } $dbh = null; } catch (PDOException $e) { print "Error!: " . $e->getMessage() . "<br/>"; die(); } ?>
true
33554d73995230047e464e8bcdef190dd82a51ce
PHP
Bassil-ali/Design-patterns-php
/Behavioral/Visitor/Covid19Traveler.php
UTF-8
1,094
3.125
3
[ "MIT" ]
permissive
<?php namespace Behavioral\Visitor; class Covid19Traveler implements VisitorInterface { private $traveler; private $pcr; private $covidPass; public function __construct(Traveler $traveler, bool $pcr, bool $covidPass) { $this->traveler = $traveler; $this->pcr = $pcr; $this->covidPass = $covidPass; } public function visitCairo(Cairo $cairo) { if ($this->pcr) { $this->traveler->visitCairo($cairo); } } public function visitLondon(London $landon) { if ($this->covidPass) { $this->traveler->visitLondon($landon); } } public function visitSydney(Sydney $sydney) { if ($this->covidPass) { $this->traveler->visitSydney($sydney); } } public function visitBali(Bali $bali) { if ($this->pcr && $this->covidPass) { $this->traveler->visitBali($bali); } } /** * @return Traveler */ public function getTraveler(): Traveler { return $this->traveler; } }
true
7622e5da35c58f2b101333abce063cebaec742b6
PHP
dknow2003/duck_project
/app/Http/Requests/ServerRequest.php
UTF-8
1,495
2.78125
3
[]
no_license
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class ServerRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $rule = [ 'name' => ['required', 'unique:servers,name'], 'start_from' => ['required', 'date_format:Y-m-d'], 'host.*' => 'required', 'port.*' => 'required', 'database.*' => 'required', 'username.*' => 'required', // 从 Password 改为 pwd, Laravel 过滤了 session 旧值中的 password。 'pwd.*' => 'required', ]; if ($server = $this->route('server')) { array_pop($rule['name']); array_push($rule['name'], 'unique:servers,name,' . $server->id); } return $rule; } /** * Get custom attributes for validator errors. * * @return array */ public function attributes() { return [ 'name' => '服务器名称', 'start_from' => '开服时间', 'host.*' => '主机', 'port.*' => '端口', 'database.*' => '数据库', 'username.*' => '用户名', 'pwd.*' => '密码', ]; } }
true
8eb39bb38c51145f829a3c091bc3b45abe712874
PHP
Gaonuk/SplinterApp
/Sites/consultas/consultas_impar/consulta_dinero_hoteles.php
UTF-8
792
2.734375
3
[]
no_license
<?php include('../templates/header.html'); ?> <body> <?php #Llama a conexión, crea el objeto PDO y obtiene la variable $db require("../config/conexion.php"); $F1 = $_POST["F1"]; $F2 = $_POST["F2"]; $query = "SELECT usuarios.uid, SUM(destinos.precio) FROM usuarios, tickets, destinos WHERE usuarios.uid = tickets.uid AND tickets.did = destinos.did AND tickets.fechacompra >= '$F1' AND tickets.fechacompra <= '$F2' GROUP BY usuarios.uid;"; $result = $db_impar -> prepare($query); $result -> execute(); $usuario = $result -> fetchAll(); ?> <table> <tr> <th>User ID</th> <th>Total Gastado</th> </tr> <?php foreach ($usuario as $u) { echo "<tr> <td>$u[0]</td> <td>$u[1]</td> </tr>"; } ?> </table> <?php include('../templates/footer.html'); ?>
true
021da61ef70dfa40077c0cdf943bc13262d2f642
PHP
ebr00ks/pimcore
/pimcore/models/Tool/TmpStore.php
UTF-8
3,888
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Pimcore * * 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://www.pimcore.org/license * * @category Pimcore * @package Tool * @copyright Copyright (c) 2009-2014 pimcore GmbH (http://www.pimcore.org) * @license http://www.pimcore.org/license New BSD License */ namespace Pimcore\Model\Tool; use Pimcore\Model; class TmpStore extends Model\AbstractModel { /** * @var string */ public $id; /** * @var string */ public $tag; /** * @var string */ public $data; /** * @var int */ public $date; /** * @var int */ public $expiryDate; /** * @var bool */ public $serialized = false; /** * @var Lock */ protected static $instance; /** * @return Lock */ protected static function getInstance () { if(!self::$instance) { self::$instance = new self(); } return self::$instance; } /** * @param $id * @param $data * @param null $tag * @param null $lifetime * @return mixed */ public static function add ($id, $data, $tag = null, $lifetime = null) { $instance = self::getInstance(); if(!$lifetime) { $lifetime = 86400; } return $instance->getResource()->add($id, $data, $tag, $lifetime); } /** * @param $id * @return mixed */ public static function delete($id) { $instance = self::getInstance(); return $instance->getResource()->delete($id); } /** * @param $id * @return null|TmpStore */ public static function get($id) { $item = new self; if($item->getById($id)) { if($item->getExpiryDate() < time()) { self::delete($id); } else { return $item; } } return null; } /** * */ public static function cleanup() { $instance = self::getInstance(); $instance->getResource()->cleanup(); } /** * @return string */ public function getId() { return $this->id; } /** * @param string $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getTag() { return $this->tag; } /** * @param string $tag */ public function setTag($tag) { $this->tag = $tag; } /** * @return string */ public function getData() { return $this->data; } /** * @param string $data */ public function setData($data) { $this->data = $data; } /** * @return int */ public function getDate() { return $this->date; } /** * @param int $date */ public function setDate($date) { $this->date = $date; } /** * @return boolean */ public function isSerialized() { return $this->serialized; } /** * @param boolean $serialized */ public function setSerialized($serialized) { $this->serialized = $serialized; } /** * @return int */ public function getExpiryDate() { return $this->expiryDate; } /** * @param int $expiryDate */ public function setExpiryDate($expiryDate) { $this->expiryDate = $expiryDate; } }
true
1ac3d9ea223ee6dab552d6f85547a6e7ad428362
PHP
mtulian/egfinal
/system/utils/Mailer.php
UTF-8
1,529
2.8125
3
[]
no_license
<?php require_once $_SERVER["DOCUMENT_ROOT"].'/system/lib/phpmailer/class.phpmailer.php'; require_once $_SERVER["DOCUMENT_ROOT"].'/system/lib/phpmailer/class.smtp.php'; class Mailer{ private $mailer; function __construct(){ $mail = new PHPMailer(); // create a new object $mail->IsSMTP(); // enable SMTP $mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only $mail->SMTPAuth = true; // authentication enabled $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail $mail->Host = "smtp.gmail.com"; $mail->Port = 465; // or 587 $mail->IsHTML(true); $mail->CharSet = 'UTF-8'; $mail->Username = "portal.comunicaciones.noreply@gmail.com"; $mail->Password = "sabor123"; $this->mailer = $mail; } function setFrom($from){ $this->mailer->SetFrom($from); } function setAddress($address, $name = ''){ $this->mailer->addAddress($address, $name); } function setBody($body){ $this->mailer->Body = $body; } function setSubject($subject){ $this->mailer->Subject = $subject; } function sendEmail(){ if ($this->mailer->send()){ return true; } else { print_r('Mailer Error: ' . $this->mailer->ErrorInfo); return false; } } } ?>
true
117e2749c560ea3d8e500e67ff50434362ddc749
PHP
OlegPoljakov/Simple_PHP_Shop
/addreview.php
UTF-8
522
2.546875
3
[]
no_license
<?php include_once 'config/init.php'; $consumer = new Consumer; $toy_id = $_POST['toyid']; echo "hello!"; if (isset($_POST)){ echo "fff"; $data=array(); $data['toyid']=$_POST['toyid']; $data['review']=$_POST['review']; $data['consumername']=$_POST['consumername']; $data['numofstars']=$_POST['numofstars']; if($consumer->add($toy_id, $data)){ redirect('item.php?id='. $toy_id, 'Your review has been sent', 'success'); } else{ redirect('item.php?id='. $toy_id, 'Something went wrong', 'error'); } } ?>
true
b7f01fda9c76f41d24b9c728dbf7e0ec01971e88
PHP
Finnology/oro-platform
/src/Oro/Bundle/EmailBundle/Mailer/Checker/SystemConfigConnectionChecker.php
UTF-8
1,299
2.609375
3
[ "MIT" ]
permissive
<?php namespace Oro\Bundle\EmailBundle\Mailer\Checker; use Oro\Bundle\EmailBundle\Mailer\Transport\SystemConfigTransportRealDsnProvider; use Symfony\Component\Mailer\Transport\Dsn; /** * Checks connection for "oro://system-config" DSN. */ class SystemConfigConnectionChecker implements ConnectionCheckerInterface { private ConnectionCheckerInterface $connectionCheckers; private SystemConfigTransportRealDsnProvider $systemConfigTransportRealDsnProvider; public function __construct( ConnectionCheckerInterface $connectionCheckers, SystemConfigTransportRealDsnProvider $systemConfigTransportRealDsnProvider ) { $this->connectionCheckers = $connectionCheckers; $this->systemConfigTransportRealDsnProvider = $systemConfigTransportRealDsnProvider; } /** * Checks that dsn is "oro://system-config". */ public function supports(Dsn $dsn): bool { return $dsn->getScheme() === 'oro' && $dsn->getHost() === 'system-config'; } /** * {@inheritdoc} */ public function checkConnection(Dsn $dsn, string &$error = null): bool { $realDsn = $this->systemConfigTransportRealDsnProvider->getRealDsn($dsn); return $this->connectionCheckers->checkConnection($realDsn, $error); } }
true
9387e4db8eeccf4a8bf9f4a0fd7a93ba0cb2b751
PHP
micki10/CompraVendi.it
/CompraVendi.it/php/login_request.php
UTF-8
1,343
2.765625
3
[]
no_license
<?php $username = $_POST['username']; $password = $_POST['password']; $errorMessage = login($username, $password); if($errorMessage === null) header('location: ../index.php?login=true'); else header('location: ../pages/login.php?errorMessage=' . $errorMessage ); function login($username, $password){ if ($username != null && $password != null){ $userId = authenticate($username, $password); if ($userId != -1 ){ session_start(); $_SESSION['username'] = $username; return null; } } else return 'You should insert something'; return 'Username and password not valid.'; } function authenticate ($username, $password){ require "dbConfig.php"; $conn = new mysqli($dbHostname, $dbUsername, $dbPassword, $dbName); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $username = $conn->real_escape_string($username); $password = $conn->real_escape_string($password); $sql = "select * from user where username='" . $username . "' AND password='" . $password . "'"; $result = $conn->query($sql); $numRow = mysqli_num_rows($result); if ($numRow != 1) return -1; $conn->close(); $userRow = $result->fetch_assoc(); $conn->close(); return $userRow['username']; } ?>
true
b139907138dc4918fdbd0182202f1470d3baa27d
PHP
gmesnard/ffeeeedd
/tag.php
UTF-8
4,373
2.609375
3
[ "MIT", "CC-BY-3.0" ]
permissive
<?php /** * Page d’archive d’un mot-clé * @author Gaël Poupard * @link www.ffoodd.fr * * En savoir plus : http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage ffeeeedd * @since ffeeeedd 1.0 * * @note Si la balise <p> de la description vous gêne, ajoutez ce code dans votre functions.php : * @note remove_filter( 'term_description', 'wpautop' ); * @see http://wpchannel.com/supprimer-balise-p-category_description-wordpress/ * @author Aurélien denis * * @note La description et la liste des sous-catégories sont utiles au référencement. * @note Elles ajoutent un caractère unique à la page afin d’éviter les contenus dupliqués. * @see « Optimiser son référencement WordPress » * @see https://twitter.com/seomixfr * @author Daniel Roch */ $paged = get_query_var( 'paged' ); $tags = array(); get_header(); ?> <?php if ( have_posts() ) { ?> <h2> <?php _e( 'Tag :', 'ffeeeedd' ); ?> <?php echo single_tag_title( '', false ); ?> <?php if ( is_paged() ) { echo ' / Page ' . $paged; } ?> </h2> <?php if ( ! is_paged() ) { echo tag_description(); } ?> <ol> <?php while ( have_posts() ) { the_post(); // On récupère les mots-clés de l’article $ffeeeedd__tags = get_the_tags( $post->ID ); if ( $ffeeeedd__tags ) { foreach ( $ffeeeedd__tags as $ffeeeedd__tag ) { // Et on les ajoute un par un au tableau $tags $tags[$posttag->term_id] = $ffeeeedd__tag->name; } } ?> <li <?php post_class( 'mb2' ); ?>> <article itemscope itemtype="http://schema.org/Article"> <h3 itemprop="name"> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" rel="bookmark" itemprop="url" tabindex="-1"><?php the_title(); ?></a> </h3> <p class="print-hidden" itemprop="UserComments"><?php comments_number( '0', '1', '% ' ); ?></p> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" tabindex="-1" aria-hidden="true"> <?php the_post_thumbnail( 'thumbnail', array( 'itemprop' => 'image', 'alt' => __( 'Permalink to the post', 'ffeeeedd' ) ) ); ?> </a> <?php } ?> <time datetime="<?php the_time( 'Y-m-d' ); ?>" itemprop="datePublished"><?php the_time( __( 'j F Y', 'ffeeeedd' ) ); ?></time> <?php $excerpt = get_the_excerpt() ?> <p itemprop="description"><?php echo $excerpt ?></p> <footer> <p><?php _e( 'Entry written by', 'ffeeeedd' ); ?> <strong itemprop="author" class="vcard author"> <a class="fn" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ) ?>"><?php the_author_meta( 'display_name' ); ?></a> </strong>. <?php _e( 'Last modified on', 'ffeeeedd' ); ?> <time class="updated" datetime="<?php the_modified_date( 'Y-m-d' ); ?>" itemprop="dateModified"><?php the_modified_date(); ?></time>. <?php $cats = get_the_category_list( ( ', ' ) ); // Si l’article est catégorisé, on affiche le lien vers chaque catégorie. if ( $cats ) { ?> <br /><?php _e( 'Categories:', 'ffeeeedd' ); ?> <span itemprop="keywords"><?php echo $cats; ?></span> <?php } ?>. </p> </footer> </article> </li> <?php } // On soustrait le mot-clé actuel au tableaux des mots-clés récupérés : $tag__actuel = array( single_tag_title( '', false ) ); $tags = array_diff( $tags, $tag__actuel ); ?> </ol> <?php ffeeeedd__pagination(); ?> <?php if ( $tags ) { ?> <h3><?php _e( 'Related tags:', 'ffeeeedd' ); ?></h3> <ul> <?php foreach ( $tags as $slug ) { // Pour chaque mot-clé, on affiche le lien correspondant dans la liste. $tag = get_term_by( 'name', $slug, 'post_tag' ); $lien = get_permalink( $tag->term_id ); ?> <li> <a href="<?php echo $lien; ?>"><?php echo $slug; ?></a> </li> <?php } ?> </ul> <?php } ?> <?php } else { ?> <h2><?php _e( 'No post found tagged', 'ffeeeedd' ); ?> <?php echo single_tag_title( '', false ); ?>.</h2> <?php } ?> <?php get_footer(); ?>
true
d364f445b94c6460d9242e5909f64b6d3a24929b
PHP
fitorec/manual_php
/codigos/cap08/factory.php
UTF-8
1,002
3.328125
3
[]
no_license
<pre> <?php /* * Patron Factory */ class BD{ function mensaje(){ echo "\nfuncion de prueba\n"; } } class Modelo{} class Controlador{} class Fabrica { //protected private static $data; public function __construct() { if(is_null(self::$data) ) self::$data = array(); } function agregar($objeto) { if(! array_key_exists($objeto, self::$data) ){ self::$data[ $objeto ] = new $objeto(); var_dump(self::$data[$objeto]); }else{ echo "El objeto {$objeto} ya es existente \n"; var_dump(self::$data[$objeto]); } } function __get($objeto){ if(! array_key_exists($objeto,self::$data)){ return self::$data[$objeto]; }else return null; } } $fabrica = new Fabrica(); $fabrica->agregar('BD'); $fabrica->agregar('Controlador'); $fabrica2 = new Fabrica(); $fabrica2->agregar('Modelo'); //genera un error $fabrica2->agregar('Controlador'); var_dump( $fabrica2->Modelo ); #$fabrica2->BD->mensaje(); #echo $unico::singleton; #var_dump( Unico::singleton ); ?> </pre>
true
c65f6370c4b9c7bbbed622e00dc8c656911fd4ec
PHP
hashshura/line-bot-tutorial
/handler/calculate.php
UTF-8
480
2.90625
3
[]
no_license
<?php use \LINE\LINEBot\MessageBuilder\TextMessageBuilder as TextMessageBuilder; function calculate($query, $userId){ if ($query == null){ $result = new TextMessageBuilder("MathJS Calculator\n\nUsage:\n/calculate (query)\n\nExample:\n/calculate (3e+2i)*(2e-3i)"); } else { $query = urlencode($query); $result = file_get_contents('http://api.mathjs.org/v4/?expr=' . $query); $result = new TextMessageBuilder($result); } return $result; }
true
461542952a535a227d8b45ca4981a001b7b52e76
PHP
am1970/test-tamagochi
/app/Models/UserAnimalAttribute.php
UTF-8
1,363
2.796875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; /** * Class UserAnimalAttribute * * Properties * @property integer $id * @property integer $user_animal_id * @property integer $attribute_id * @property integer $value * @property Carbon $updated_at * @property Carbon $created_at * * Relationships * @property UserAnimal $userAnimal * @property Attribute $attribute */ class UserAnimalAttribute extends Model { #region Properties /** * @var array */ protected $fillable = [ 'user_animal_id', 'attribute_id', 'value' ]; /** * @var array */ protected $dates = [ 'created_at', 'updated_at' ]; /** * @var array */ protected $casts = [ 'id' => 'integer', 'user_animal_id' => 'integer', 'attribute_id' => 'integer', 'value' => 'integer' ]; #endregion #region Methods #endregion #region Relationships /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function attribute() { return $this->belongsTo(Attribute::class); } /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function userAnimal() { return $this->belongsTo(UserAnimal::class); } #endregion }
true
2776e87282cac972184209d75ae8fc2b38ebf9d7
PHP
spiceup-it/Login-System---PHP
/login.php
UTF-8
3,918
2.8125
3
[]
no_license
<?php session_start(); //check if the user is loggedin, if not the redirect him to login page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] == true){ header("location: welcome.php"); exit; } require_once('./includes/config.php'); $username = $password = ""; $username_err = $password_err = ""; if($_SERVER["REQUEST_METHOD"] == "POST"){ //validate username if(empty($_POST["username"])){ $username_err = "please enter a username"; }else{ $username = $_POST["username"]; } //validate password if(empty($_POST["password"])){ $password_err = "please enter a password"; }else{ $password = $_POST["password"]; } if(empty($username_err) && empty($password_err)){ $sql = "SELECT id, username, password FROM user WHERE username = ?"; if($stmt = mysqli_prepare($conn, $sql)){ mysqli_stmt_bind_param($stmt,"s",$param_username); $param_username = $username; if(mysqli_stmt_execute($stmt)){ mysqli_stmt_store_result($stmt); if(mysqli_stmt_num_rows($stmt) == 1){ mysqli_stmt_bind_result($stmt, $id,$username,$hashed_password); if(mysqli_stmt_fetch($stmt)){ // if($password == $hashed_password){ if(password_verify($password,$hashed_password)){ session_start(); $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; header("location: welcome.php"); } else $password_err = "The password you entered was not valid"; } }else $username_err = "No account found with this username"; }else echo "Oops! Something went wrong. Please try again later"; } mysqli_stmt_close($stmt); } mysqli_close($conn); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>LOGIN</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <style> body{ background-color: #59F4C0; } .wrapper{ width: 550px; padding:100px 100px; margin-left: 30%; } .error{ color: red; } </style> </head> <body> <div class="wrapper"> <h1>Login</h1> <form action="login.php" method="post"> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control"> <span class="error">*<?php echo $username_err; ?></span> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" name="password" class="form-control"> <span class="error">*<?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" name="btn btn-primary" value="Submit"> <input type="reset" name="btn btn-default" value="Reset"> </div> <p>Don't have an account? <a href="register.php">Sign Up here</a></p> </form> </div> </body> </html>
true
97782eeb7fc8e7e631596634631cedd526ab2edf
PHP
ipunkt/rancherize
/app/Blueprint/PublishUrls/PublishUrlsYamlWriter/PublishUrlsYamlWriterVersion.php
UTF-8
516
2.515625
3
[ "MIT" ]
permissive
<?php namespace Rancherize\Blueprint\PublishUrls\PublishUrlsYamlWriter; use Rancherize\Blueprint\PublishUrls\PublishUrlsExtraInformation\PublishUrlsExtraInformation; /** * Interface PublishUrlsYamlWriterVersion * @package Rancherize\Blueprint\PublishUrls\PublishUrlsYamlWriter */ interface PublishUrlsYamlWriterVersion { /** * @param PublishUrlsExtraInformation $extraInformation * @param array $dockerService */ function write( PublishUrlsExtraInformation $extraInformation, array &$dockerService ); }
true
0f3b65527ec3656257c0bc21b7366bfeec52cff2
PHP
maxlen/webcrawler
/strategies/SiteBase.php
UTF-8
2,703
2.828125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: w * Date: 8.12.16 * Time: 11:21 */ namespace maxlen\webcrawler\strategies; use maxlen\webcrawler\Client; use maxlen\webcrawler\interfaces\CrawlStrategy; abstract class SiteBase implements CrawlStrategy { public $params = []; public $url; public $domain; public $scheme; public $result =[]; public function search($params) { } protected function validateParams($params) { if (!isset($params['url'])) { throw new InvalidConfigException('You should set url'); } } protected function setParamsForRequest($params) { $result = []; $this->setDomain($params['url']); $this->setScheme($params['url']); if (!empty($params['proxy'])) { $result['curl'] = [ CURLOPT_PROXY => $params['proxy']['host'], CURLOPT_PROXYPORT => $params['proxy']['port'], CURLOPT_PROXYUSERPWD => "{$params['proxy']['login']}:{$params['proxy']['password']}", ]; } return $result; } private function setDomain($url) { $parts = parse_url($url); $this->domain = $parts['host']; } private function setScheme($url) { $parts = parse_url($url); $this->scheme = $parts['scheme']; } protected function getAbsoluteUrl($url) { $hrefDomain = $this->getDomain($url); if (is_null($hrefDomain)) { if (is_null($hrefDomain)) { $url = (strpos($url, '/') !== FALSE && strpos($url, '/') == 0) ? "{$this->domain}{$url}" : "{$this->domain}/{$url}"; } else { $url = self::cleanDomain($url); } $url = $this->scheme . '://' . $url; } return $url; } private function getDomain($url, $isDom = false, $saveWww = false) { if ($isDom) { $parse = parse_url($url); $domain = (isset($parse['host']) && !is_null($parse['host'])) ? $parse['host'] : rtrim($url, '/'); } else { $parse = parse_url($url); $domain = (isset($parse['host']) && !is_null($parse['host'])) ? $parse['host'] : null; } if (!is_null($domain)) { $domain = $this->cleanDomain($domain, $saveWww); } return $domain; } private function cleanDomain($url, $saveWww = false) { if (strpos($url, 'http://') == 0) { $url = str_replace('http://', '', $url); } if (!$saveWww && strpos($url, 'www.') == 0) { $url = str_replace('www.', '', $url); } return $url; } }
true
2608a5811b852e81e4c703d8830a292c6351bc3f
PHP
leDebutant/EcoleDuNumFiles
/07_fonctions/12_controleType.php
UTF-8
474
3.578125
4
[]
no_license
<?php // On va afficher les fonction qui se charge // de controler le type des variables $var = 4; $r = is_numeric($var); // renvera un booleen -> float, int $r = is_int($var); // vérifie si entier $r = is_float($var); // vérifie si un décimal $r = is_string($var); // vérifie si c'est une chaine $r = is_bool($var); // vérifie si c'est un bool $r = is_array($var); // vérifie si c'est un array $r = is_object($var); // vérifie si c'est un objet var_dump($r); ?>
true
d9c9385d3d2cb63bda0876e98920a52a85c8ae51
PHP
federicojaime/jonyfood
/appcalls/addvoto.php
UTF-8
1,531
2.59375
3
[]
no_license
<?php header('Access-Control-Allow-Origin: *'); require_once("../core/init.php"); $resp = new stdClass(); $resp->err = 0; $resp->msg = array(); $postdata = @json_decode(file_get_contents("php://input")); foreach($postdata as $key => $value) { $_POST[$key] = $value; } $validate = new Validate(); if(!$validate->check($_POST, array( "idcliente" => array( "required" => true, "numeric" => true, "mayorcero" => true ), "idcomercio" => array( "required" => true, "numeric" => true, "mayorcero" => true ), "estrellas" => array( // 1 a 5 "required" => true, "numeric" => true, "mayorcero" => true ) ))->passed()) { $resp->err = 1; foreach($validate->errors() as $error) { $resp->msg[] = $error; } } else { //Verificar si ya existe el voto $xSQL = "SELECT * FROM votos"; $xSQL .= " WHERE idcliente = " . Input::get("idcliente"); $xSQL .= " AND idcomercio = " . Input::get("idcomercio"); if(DB::getInstance()->query($xSQL)->count()) { $resp->err = 1; $resp->msg[] = "El usuario ya voto este comercio"; } else { //Agregar a votos $estrellas = intval(Input::get("estrellas"), 10); if($estrellas > 5) { $estrellas = 5; } $data = array( "idcliente" => Input::get("idcliente"), "idcomercio" => Input::get("idcomercio"), "estrellas" => $estrellas ); $votos = DB::getInstance()->insert("votos", $data); if($votos->error()) { $resp->err = 1; $resp->msg[] = $votos->errMsg(); } } } echo(json_encode($resp)); ?>
true
1d3c58c6f2e41f42d25e7aa92aab64f1f68e65b2
PHP
SierraTecnologia/Population
/src/Models/Components/Productions/Stage.php
UTF-8
1,111
2.609375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Population\Models\Components\Productions; /** * Tipos de Produções */ use Pedreiro\Models\Base; class Stage extends Item { protected $table = 'production_stages'; /** * Esboço * * @var array */ public static $ESBOCO = 1; /** * Criando História * * @var array */ public static $HISTORY = 2; /** * Detalhando Roteiro * * @var array */ public static $ROTEIRO = 3; /** * Produzindo * * @var array */ public static $PRODUCTION = 4; /** * Get all of the slaves that are assigned this tag. */ public function persons() { return $this->morphedByMany(\Illuminate\Support\Facades\Config::get('sitec.core.models.person', \Telefonica\Models\Actors\Person::class), 'skillable'); } /** * Get all of the users that are assigned this tag. */ public function users() { return $this->morphedByMany(\Illuminate\Support\Facades\Config::get('sitec.core.models.user', \App\Models\User::class), 'skillable'); } }
true
068bea0b03f29861868bcb2294705d862acae850
PHP
alwaysblank/schemer
/src/Iterator.php
UTF-8
401
3.0625
3
[]
no_license
<?php namespace AlwaysBlank\Schemer; class Iterator { public static function iterate(callable $callable, array $array): array { foreach ($array as $key => &$value) { $value = $callable($key, $value); if (is_array($value)) { $value = static::iterate($callable, $value); } } return $array; } }
true
edcea2c3d668e19e346d309d8f7ee8c88ddf8765
PHP
jjorgosogarcia/word4pics2
/clases/Utilidades.php
UTF-8
3,083
2.953125
3
[]
no_license
<?php class Utilidades { function removeDirectory($path) { $path = rtrim(strval($path), '/'); $d = dir($path); if (!$d) return false; while (false !== ($current = $d->read())) { if ($current === '.' || $current === '..') continue; $file = $d->path . '/' . $current; if (is_dir($file)) removeDirectory($file); if (is_file($file)) unlink($file); } rmdir($d->path); $d->close(); return true; } static public function isActivo($bd){ require '../clases/ManageUser.php'; $gestor = new ManageUser($bd); $sesion = new Session(); $idUsuario = $sesion->get("_usuario"); $usuarios = $gestor->get($idUsuario); if($usuarios->getActivo()==0){ return false; }else{ return true; } } function generarLetrasInicio($solucion){ $aLetras = Array('A', 'B', 'C','D', 'E', 'F','G', 'H', 'I','J', 'K', 'L','M', 'N', 'O','P', 'Q', 'R','S', 'T', 'U','V', 'W', 'X','Y', 'Z'); $valoresR = Array(); //convertimos en array $sol = strtoupper($solucion); $array = str_split($sol); $resultado2 = Utilidades::generarLetrasFalsas($array,$aLetras); //Coge 4 valores random $valorRandom = array_rand($resultado2, 4); //Agrega el valor de los elementos al array for($i=0; $i<4; $i++){ array_push($valoresR,$resultado2[$valorRandom[$i]]); } $palabrasAparecen = array_merge($array,$valoresR); shuffle($palabrasAparecen); return implode($palabrasAparecen); } function generarLetrasFalsas($array1, $array2){ //sumamos ambos arrays $resultado = array_merge($array1, $array2); //quitamos los valores repetidos $resultado2 = array_unique($resultado); //quitamos del array las primeras posiciones hasta el numero indicado for($i=0; $i<count(array_unique($array1)); $i++){ array_shift($resultado2); } return $resultado2; } //Funcion para dar una letra que contenga la palabra function darLetras($solucion){ $azar = rand(0,strlen($solucion)-1); $dLetra = $solucion[$azar]; $posicionLetra = $azar.strtoupper($dLetra); return $posicionLetra; } function borrarLetras($solucion, $todo){ $array = str_split(strtoupper($solucion)); $resultado2 = Utilidades::generarLetrasFalsas($array,$todo); $valorRandom = array_rand($resultado2, 1); $letraAzar = $resultado2[$valorRandom]; return strtoupper($letraAzar); } static function limpiaEspacios($cadena){ $cadena = str_replace(' ', '', $cadena); return $cadena; } }
true
7cd9aa2285a881d8aa76d3c93baab14416a38eb9
PHP
tim33-23/TestOne
/Service/CheckValidationData.php
UTF-8
1,483
2.84375
3
[]
no_license
<?php require_once ("../Exceptions/ValidationException.php"); require_once ("../dto/User.php"); require_once ("../dto/Ticket.php"); class CheckValidationData { function checkPassword($firstPassword, $secondPassword, $email){ $newUser = null; if($firstPassword===$secondPassword){ $newUser = new User(); $newUser->setEmail($email); $newUser->setPassword($firstPassword); } if($newUser==null) throw new ValidationException("Пароли не совпадают!"); return $newUser; } function checkTicket($subject, $description){ $newTicket = null; if($subject!=='' && $description!==''){ $newTicket = new Ticket(); $newTicket->setSubject($subject); $newTicket->setDescription($description); } else { throw new ValidationException("Проверьте правельность введенных данных."); } if($newTicket==null) throw new ValidationException("Проверьте правельность введенных данных"); $imgName = basename(basename($_FILES['img']['name'])); if(is_uploaded_file($_FILES['img']['tmp_name'])){ move_uploaded_file($_FILES['img']['tmp_name'], '../img/'.$_SESSION['email'].basename($_FILES['img']['name'])); } $newTicket->setImg($imgName); return $newTicket; } }
true
9aef752f347567923d60570bda73ffcb797b7c68
PHP
vossarat/raids
/app/Http/Controllers/MailController.php
UTF-8
1,685
2.609375
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class MailController extends Controller{ public function testsend() { $mail = new \PHPMailer(true); // notice the \ you have to use root namespace here try{ $mail->isSMTP(); // tell to use smtp $mail->CharSet = "utf-8"; // set charset to utf8 $mail->SMTPAuth = true; // use smpt auth $mail->SMTPSecure = "tls"; // or ssl $mail->Host = "mail.tarassov.pro"; $mail->Port = 25; // most likely something different for you. This is the mailtrap.io port i use for testing. $mail->Username = "info"; $mail->Password = "ABC123abc"; $mail->setFrom("info@tarassov.pro", "Firstname Lastname"); $mail->Subject = "Test"; $mail->MsgHTML("This is a test"); $mail->addAddress("d.tarassov@akmzdrav.kz", "Recipient Name"); $mail->send(); } catch(phpmailerException $e){ dd($e); } catch(Exception $e){ dd($e); } die('success'); } } /*define('SMTP_HOST', 'smtp.yandex.ru'); define('SMTP_AUTH', true); define('SMTP_USERNAME', 'advers.autoterm@yandex.ru'); define('SMTP_PASSWORD', '2706864'); define('SMTP_SECURE', 'tsl'); define('SMTP_PORT', '587'); define('SMTP_FROM', 'advers.autoterm@yandex.ru'); $mail = new PHPMailer; $mail->CharSet = "UTF-8"; $mail->isSMTP(); $mail->Host = SMTP_HOST; $mail->SMTPAuth = SMTP_AUTH; $mail->Username = SMTP_USERNAME; $mail->Password = SMTP_PASSWORD; $mail->SMTPSecure = SMTP_SECURE; $mail->Port = SMTP_PORT; $mail->SMTPDebug = 0; $mail->Debugoutput = 'html'; $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; $mail->Subject = "Оплата заказа через Альфа Банк"; $mail->setFrom(SMTP_FROM);*/
true
e4bc2f4909195ceb0952a46d6a9bcea4f62a0a51
PHP
Abinesh-g/student
/DB_tablecreation.php
UTF-8
1,503
2.671875
3
[]
no_license
<?php $con=mysqli_connect('localhost','root',''); if($con) { //echo nl2br( "\n server connected"); } else { echo nl2br("\n server not connected"); } if(mysqli_select_db($con,'r17')) { //echo nl2br("\n db connected "); } else { echo nl2br("\n db not connected"); } $sql="CREATE TABLE itsem1 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem2 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem3 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem4 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem5 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem6 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem7 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } $sql="CREATE TABLE itsem8 (subcode varchar(10), subname varchar(70)) "; $result=mysqli_query($con,$sql); if($result) { echo nl2br("table crated"); } ?>
true
2e7ecbbae7ff8fcb4278e32afc338e6c230ff40f
PHP
Rvjonh/CrudWithPHP
/signup.php
UTF-8
3,383
2.59375
3
[]
no_license
<?php require "database.php"; $message = ""; if(!empty($_POST["nombre"]) && !empty($_POST["apellido"]) && !empty($_POST["telefono"]) && !empty($_POST["cedula"]) && !empty($_POST["correo"]) && !empty($_POST["contrasena"])){ $sql = "INSERT INTO users (nombre, apellido, cedula, telefono, correo, contrasena) VALUES (:nombre, :apellido, :cedula, :telefono, :correo, :contrasena)"; $stmt = $conn->prepare($sql); $stmt->bindParam(":nombre", $_POST["nombre"]); $stmt->bindParam(":apellido", $_POST["apellido"]); $stmt->bindParam(":cedula", $_POST["cedula"]); $stmt->bindParam(":telefono", $_POST["telefono"]); $stmt->bindParam(":correo", $_POST["correo"]); $stmt->bindParam(":contrasena",$_POST["contrasena"]); if($stmt->execute()){ $message = "Registro de nuevo usuario completado!"; }else{ $message = "No se registro correctamente"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Registro</title> <link rel="shortcut icon" href="imagenes\logo.png" type="image/x-icon"> <link rel="stylesheet" href="assets\css\estilos.css"> <link rel="stylesheet" href="assets\css\estilosRegistro.css"> </head> <body> <header> <a class="inicio" href="index.php"> <img class="logo" src="imagenes\logo.png" alt="Pucliship"> <h1>Publiship</h1> </a> <div class="botones"> <a class="botonInicio" href="index.php">Iniciar Sesion</a> <a class="botonInicio" href="">Registrarse</a> </div> </header> <main> <section class="bienvenida"> <div class="presentacion"> <img class="logo" src="imagenes\logo.png"> <h2>Registro nuevo</h2> <p>Registrate para poder iniciar sesion</p> </div> <div class="formInicio"> <form class="formulario" action="signup.php" method="post"> <h2>Formulacio de registro</h2> <?php if(!empty($message)): ?> <p><?= $message ?></p> <?php endif; ?> <input name="nombre" required type="text" placeholder="Nombre" maxlength="50"> <input name="apellido" required type="text" placeholder="Apellido" maxlength="50"> <input name="cedula" required type="cel" title="Debe ingresar solo numeros, sin signos" placeholder="Cedula" maxlength="9" title="Sin caracteres especiales, ni puntos"> <input name="telefono" required type="cel" placeholder="Telefono" maxlength="11" title="Numeros no largos"> <input name="correo" required type="email" placeholder="Correo electronico"> <input name="contrasena" required type="password" placeholder="Contraseña" maxlength="20" title="No mas de 20 caracteres"> <button type="submit">Registrar</button> </form> </div> </section> </main> <footer> <p>Proyecto CRUD(php) por Gomez Jonh</p> <p>&copy and &reg</p> </footer> </body> </html>
true
99205a6ab566c1fc34c9b6bb0ba1f870e72a4f84
PHP
furkankartal29/framework
/src/Conversation/Activators/Attachment.php
UTF-8
1,288
2.875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace FondBot\Conversation\Activators; use FondBot\Contracts\Activator; use FondBot\Events\MessageReceived; use FondBot\Templates\Attachment as Template; class Attachment implements Activator { protected $type; protected function __construct(string $type = null) { $this->type = $type; } public static function make(string $type = null) { return new static($type); } public function file(): self { $this->type = Template::TYPE_FILE; return $this; } public function image(): self { $this->type = Template::TYPE_IMAGE; return $this; } public function audio(): self { $this->type = Template::TYPE_AUDIO; return $this; } public function video(): self { $this->type = Template::TYPE_VIDEO; return $this; } /** * Result of matching activator. * * @param MessageReceived $message * * @return bool */ public function matches(MessageReceived $message): bool { if ($this->type === null) { return $message->getAttachment() !== null; } return hash_equals($message->getAttachment()->getType(), $this->type); } }
true