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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
3118a1ad89a656eddf7e9ef093ac3c85b0fbc487 | PHP | e2simplon/immobourse | /controllers/DetailsOffersController.php | UTF-8 | 415 | 2.53125 | 3 | [] | no_license | <?php
class DetailsOffersController extends Controller
{
public function detailsOffer($offerId)
{
global $offersModel;
// envoi des variables à la vue
$this->set('detailOffer', $offersModel->getOne($offerId));
// chargement de la vue
$this->displayView('detailAnnonce');
}
}
// instance du controlleur
$detailsOffersController = new DetailsOffersController(); | true |
a075862d55ed077e771dfd116f126af9765feb4b | PHP | IFPB-PRPIPG/periodicos-ifpb | /lib/pkp/classes/payment/QueuedPayment.inc.php | UTF-8 | 1,120 | 2.53125 | 3 | [] | no_license | <?php
/**
* @file classes/payment/QueuedPayment.inc.php
*
* Copyright (c) 2013-2015 Simon Fraser University Library
* Copyright (c) 2000-2015 John Willinsky
* Distributed under the GNU GPL v2. For full terms see the file docs/COPYING.
*
* @class QueuedPayment
* @ingroup payment
* @see QueuedPaymentDAO
*
* @brief Queued (unfulfilled) payment data structure
*
*/
import('lib.pkp.classes.payment.Payment');
class QueuedPayment extends Payment {
/**
* Constructor
*/
function QueuedPayment($amount, $currencyCode, $userId = null, $assocId = null) {
parent::Payment($amount, $currencyCode, $userId, $assocId);
}
/**
* Set the queued payment ID
* @param $queuedPaymentId int
*/
function setQueuedPaymentId($queuedPaymentId) {
if (Config::getVar('debug', 'deprecation_warnings')) trigger_error('Deprecated function.');
return parent::setPaymentId($queuedPaymentId);
}
/**
* Get the queued payment ID
* @return int
*/
function getQueuedPaymentId() {
if (Config::getVar('debug', 'deprecation_warnings')) trigger_error('Deprecated function.');
return parent::getPaymentId();
}
}
?>
| true |
5298a2fff4d892fc9eb5cb25d823fb9e0aac1b11 | PHP | vishwakarma09/jexcel-php-socket | /src/Chat.php | UTF-8 | 2,831 | 2.546875 | 3 | [] | no_license | <?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Evolution\CodeIgniterDB as CI;
class Chat implements MessageComponentInterface {
protected $clients;
protected $router;
protected $db;
public function __construct() {
$this->clients = new \SplObjectStorage;
$this->router = new Router;
$db_data = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ratchet',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
$this->db =& CI\DB($db_data);
}
public function onOpen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numRecv = count($this->clients) - 1;
// echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n"
// , $from->resourceId, $msg, $numRecv, $numRecv == 1 ? '' : 's');
if (json_decode($msg) == FALSE)
{
$from->send(json_encode(["status"=>1, "message"=>"Improper json format"]));
}
$msg = json_decode($msg);
if ($msg->controller == NULL || $msg->action == NULL) {
$from->send(json_encode(["status"=>1, "message"=>"No controller or action specified"]));
}
if ($msg->controller == "die") {
die('halting...');
}
$this->router->route($this->db, $msg->controller, $msg->action, $msg, $from, $this->clients);
// foreach ($this->clients as $client) {
// if ($from !== $client) {
// // The sender is not the receiver, send to each client connected
// $client->send($msg);
// }
// }
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed, remove it, as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
} | true |
feda7305325c1f069bd5fed4592a591ce3dbe0c0 | PHP | miguelsimoes/jwt-authentication-service | /src/Security/Core/Authentication/Provider/JWTAuthenticationProvider.php | UTF-8 | 3,531 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of Miguel Simões API Gateway package.
*
* (c) Miguel Simões <msimoes@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Application\Security\Core\Authentication\Provider;
use Application\Security\Core\Authentication\Token\Encoder\Exception\InvalidTokenException;
use Application\Security\Core\Authentication\Token\JWTToken;
use Application\Security\Core\Authentication\Token\PreAuthenticationJWTToken;
use Application\Service\JWT\ManagerInterface;
use Application\Service\JWT\Signer\Factory as SignerFactory;
use Lcobucci\JWT\Signer;
use Lcobucci\JWT\Token;
use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
*
*
* @author Miguel Simões <msimoes@gmail.com>
*/
class JWTAuthenticationProvider implements AuthenticationProviderInterface
{
/**
* @var ManagerInterface
*/
private $manager;
/**
* @var string
*/
private $secret;
/**
* @var Signer
*/
private $signer;
/**
* Constructor
*
* @param ManagerInterface $manager
* @param string $algorithm
* @param string $secret
*/
public function __construct(ManagerInterface $manager, $algorithm, $secret)
{
$this->manager = $manager;
$this->secret = $secret;
$this->signer = (new SignerFactory())->create($algorithm);
}
/**
* {@inheritdoc}
*/
public function authenticate(TokenInterface $token)
{
try {
/* We will attempt to decode the provided token, being aware that it may be invalid */
$data = $this->manager->decode($token);
} catch (InvalidTokenException $ex) {
/* We were provided with an invalid token, we will not be able to authenticate the user */
throw new AuthenticationException($ex->getMessage(), null, $ex);
}
#
# We need to ensure we received a valid token associated with the authentication request
if ($data && $this->validateTokenData($data)) {
/* We have been able to validate the token with success, we will now allow access */
return new JWTToken($data, $data->getClaim('roles'));
}
#
# We were not able to validate the token with success, we will not allow
# the authentication
throw new AuthenticationException('Unable to authenticate user with provided JWT token');
}
/**
* {@inheritdoc}
*/
public function supports(TokenInterface $token)
{
return $token instanceof PreAuthenticationJWTToken;
}
/**
* Validates the JWT token to ensure we will authenticate a valid user with
* a valid token
*
* @return bool
*
* @throws AuthenticationException
*/
private function validateTokenData(Token $token): bool
{
if (false === $token->verify($this->signer, $this->secret)) {
/* We were not able to verify the token, we will not be able to use it to authenticate the request */
throw new AuthenticationException(
sprintf('Unable to use JWT token using algorithm "%s" when expected is "%s"', $token->getHeader('alg'), $this->signer->getAlgorithmId())
);
}
return true;
}
}
| true |
6229d21248d5aedf65102bbfa724924db4c4b6c4 | PHP | TruthfulTiger/YADVT-MVC | /Controller.php | UTF-8 | 2,177 | 2.9375 | 3 | [] | no_license | <?php
namespace Main\Control;
use \Main\Misc\Request;
use Main\Misc\Response;
use \Main\Command\CommandResolver;
use \Main\Control\ApplicationController;
use \Main\View\View;
require_once 'CommandResolver.php';
require_once 'Request.php';
require_once 'Response.php';
require_once 'ApplicationController.php';
require_once 'View.php';
// Often referred to as the Front Controller.
// Fairly simple in our case, this class finds the command it wants
// to execute, executes it and then renders the view.
// We could make this a lot more complicated by implementing
// a Chain of Responisibility design pattern for example.
//
class Controller
{
static private $_instance; // Singleton pattern, only one object instance of this class required
private $_commandResolver; // Convert Request to the associated Command object
private function __construct() // Private to prevent object being instantiated outside class
{
// Do nothing
}
static public function Instance() // Static so we use classname itself to create object i.e. Controller::Instance()
{
// Check if the object has been created
// Only one object of this class is required
// so we only create if it hasn't already
// been created.
if(!isset(self::$_instance))
{
self::$_instance = new self(); // Make new instance of the Controler class
self::$_instance->_commandResolver = new CommandResolver();
ApplicationController::LoadViewMap();
}
return self::$_instance;
}
// Manage the recovery of the command we need to execute,
// execute it and then render the view.
public function HandleRequest(Request $request)
{
$command = $this->_commandResolver->GetCommand($request); // Create command object for Request
$response = $command->Execute($request); // Execute the command to get response
$view = ApplicationController::GetView($response); // Send response to the appropriate view for display
$view->Render(); // Display the view
}
}
?> | true |
1c03b12149fcba7c15e1da7b39922788d2840693 | PHP | sattip/upload_form | /plaincart/admin/config/main.php | UTF-8 | 3,270 | 2.578125 | 3 | [] | no_license | <?php
if (!defined('WEB_ROOT')) {
exit;
}
// get current configuration
$sql = "SELECT sc_name, sc_address, sc_phone, sc_email, sc_shipping_cost, sc_currency, sc_order_email
FROM tbl_shop_config";
$result = dbQuery($sql);
// extract the shop config fetched from database
// make sure we query return a row
if (dbNumRows($result) > 0) {
extract(dbFetchAssoc($result));
} else {
// since the query didn't return any row ( maybe because you don't run plaincart.sql as is )
// we just set blank values for all variables
$sc_name = $sc_address = $sc_phone = $sc_email = $sc_shipping_cost = $sc_currency = '';
$sc_order_email = 'y';
}
// get available currencies
$sql = "SELECT cy_id, cy_code
FROM tbl_currency
ORDER BY cy_code";
$result = dbQuery($sql);
$currency = '';
while ($row = dbFetchAssoc($result)) {
extract($row);
$currency .= "<option value=\"$cy_id\"";
if ($cy_id == $sc_currency) {
$currency .= " selected";
}
$currency .= ">$cy_code</option>\r\n";
}
?>
<p> </p>
<form action="processConfig.php?action=modify" method="post" name="frmConfig" id="frmConfig">
<table width="100%" border="0" cellspacing="1" cellpadding="2" class="entryTable">
<tr id="entryTableHeader">
<td colspan="2">Shop Configuration</td>
</tr>
<tr>
<td width="150" class="label">Shop Name</td>
<td class="content"><input name="txtShopName" type="text" class="box" id="txtShopName" value="<?php echo $sc_name; ?>" size="50" maxlength="50"></td>
</tr>
<tr>
<td width="150" class="label">Address</td>
<td class="content"><textarea name="mtxAddress" cols="50" rows="3" id="mtxAddress" class="box"><?php echo $sc_address; ?></textarea></td>
</tr>
<tr>
<td width="150" class="label">Telephone</td>
<td class="content"><input name="txtPhone" type="text" class="box" id="txtPhone" value="<?php echo $sc_phone; ?>" size="30" maxlength="30"></td>
</tr>
<tr>
<td class="label">Email</td>
<td class="content"><input name="txtEmail" type="text" class="box" id="txtEmail" value="<?php echo $sc_email; ?>" size="30" maxlength="30"></td>
</tr>
</table>
<p> </p>
<table width="100%" border="0" cellspacing="1" cellpadding="2" class="entryTable">
<tr id="entryTableHeader">
<td colspan="2">Misc. Configuration</td>
</tr>
<tr>
<td width="150" class="label">Currency</td>
<td class="content"><select name="cboCurrency" id="cboCurrency" class="box">
<?php echo $currency; ?>
</select> </td>
</tr>
<tr>
<td width="150" class="label">Shipping Cost</td>
<td class="content"><input name="txtShippingCost" type="text" class="box" id="txtShippingCost" value="<?php echo $sc_shipping_cost; ?>" size="5"></td>
</tr>
<tr>
<td class="label">Send Email on New Order </td>
<td class="content"><input name="optSendEmail" type="radio" value="y" id="optEmail" <?php echo $sc_order_email == 'y' ? 'checked' : ''; ?> />
<label for="optsEmail">Yes </label>
<input name="optSendEmail" type="radio" value="n" id="optNoEmail" <?php echo $sc_order_email == 'n' ? 'checked' : ''; ?> />
<label for="optNoEmail">No</label></td>
</tr>
</table>
<p align="center">
<input name="btnUpdate" type="submit" id="btnUpdate" value="Update Config" class="box">
</p>
</form>
| true |
59e3d582baf51fe9d2a99e1e5b68cbb137426e1b | PHP | fligthlich/dossierAfpa | /exos_pdo/connexion.php | UTF-8 | 336 | 2.5625 | 3 | [] | no_license | <?php
// Connection à la base de donnée
$bdd = new PDO('mysql:host=localhost;dbname=record','root','root');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
// foreach ($result as $key => $value) {
// echo $key .' '. $value->disc_title ."\n";
// } | true |
292b8bf0baed333bcbd789b1d74c84a942b7acf8 | PHP | ercsctt/quizzer | /App/Controllers/GET/Login.php | UTF-8 | 421 | 2.5625 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace App\Controllers\GET;
use Core\Utilities;
use Core\View;
use Core\Controller;
use App\Models\User;
use App\Flash;
class Login extends Controller {
/**
* Show the Login page
*
* @return void
*/
public function runAction() {
$user = new User();
if($user->isLoggedIn()){
header("Location: /");
return;
}
View::renderTemplate('Home/login.twig');
}
}
| true |
e6c0e2832890c39a615f6ddbc0433e86dde0e981 | PHP | jiahetian/hyperf-douyin | /src/Kernel/Contracts/StreamResponseInterface.php | UTF-8 | 392 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace Jiahetian\HyperfDouyin\Kernel\Contracts;
use Psr\Http\Message\StreamInterface;
interface StreamResponseInterface
{
public function save(string $directory, string $filename = '', bool $appendSuffix = true): string;
public function saveAs(string $directory, string $filename, bool $appendSuffix = true): string;
public function getStream(): StreamInterface;
} | true |
2ed035bac1318127407f9d1615786e572b71e075 | PHP | reenz/card-game | /src/Game.php | UTF-8 | 1,044 | 3.53125 | 4 | [] | no_license | <?php
require_once './src/Deck.php';
require_once './src/Player.php';
require_once './src/Card.php';
class Game
{
private $deck;
private $playerArray = array();
private $playerCount;
public function __construct($playerCount = 4)
{
$this->playerCount = $playerCount;
$this->addPlayers();
$this->deck = new Deck();
}
public function shuffleCards()
{
$this->deck->shuffleCards();
}
public function deal($noOfCardsToDeal = 7)
{
for ($i = 0; $i < $noOfCardsToDeal; $i++) {
$this->getCardsFromDeck();
}
}
public function getCardsFromDeck()
{
foreach ($this->playerArray as $player) {
$player->addCard($this->deck->getCardFromDeck());
}
}
public function getPlayers()
{
return $this->playerArray;
}
private function addPlayers()
{
for ($i = 0; $i < $this->playerCount; $i++) {
array_push($this->playerArray, new Player($i + 1));
}
}
}
| true |
431cb2f1f22e7e578353a1833db80eeecb3d559d | PHP | corycollier/mvc-lite | /tests/ViewTest.php | UTF-8 | 9,235 | 2.765625 | 3 | [] | no_license | <?php
/**
* Unit tests for the \MvcLite\View class
*
* @category PHP
* @package MVCLite
* @subpackage Tests
* @since File available since release 1.0.6
* @author Cory Collier <corycollier@corycollier.com>
*/
namespace MvcLite;
/**
* Unit tests for the \MvcLite\View class
*
* @category PHP
* @package MVCLite
* @subpackage Tests
* @since Class available since release 1.0.6
* @author Cory Collier <corycollier@corycollier.com>
*/
class ViewTest extends TestCase
{
/**
* The setup method, called before each test
*/
public function setUp()
{
$this->sut = View::getInstance();
}
/**
* Tests MvcLite\View::init.
*/
public function testInit()
{
$title = 'App title testing';
$section = [
'key' => 'value',
];
$sut = $this->getMockBuilder('\MvcLite\View')
->disableOriginalConstructor()
->setMethods(['getConfig'])
->getMock();
$config = $this->getMockBuilder('\MvcLite\Config')
->disableOriginalConstructor()
->setMethods(['get', 'getSection'])
->getMock();
$config->expects($this->once())
->method('get')
->with($this->equalTo('app.title'))
->will($this->returnValue($title));
$config->expects($this->exactly(2))
->method('getSection')
->will($this->returnValue($section));
$sut->expects($this->once())
->method('getConfig')
->will($this->returnValue($config));
$result = $sut->init();
$this->assertEquals($sut, $result);
}
/**
* tests the filter method of the view object
*/
public function testFilter()
{
$unfiltered = 'asdasdfads';
$expected = 'asdasdfads';
$result = $this->sut->filter($unfiltered);
$this->assertSame($expected, $result);
}
/**
* test the setting and getting of variables to the view.
*
* @param array $variables The variables to use for testing.
*
* @dataProvider provideVariables
*/
public function testSetAndGet($variables = [])
{
foreach ($variables as $name => $value) {
$this->sut->set($name, $value);
}
foreach ($variables as $name => $value) {
$result = $this->sut->get($name);
$this->assertSame($result, $value);
}
$this->assertNull($this->sut->get('bad-value'));
}
/**
* method to provide data for test methods
*
* @return array
*/
public function provideVariables()
{
return [
'first test' => [
'variables' => [
'var1' => 'val1',
'var2' => 'val2',
'var3' => 'val3',
],
]
];
}
/**
* Tests the MvcLite\View::getViewScript method.
*
* @dataProvider provideGetViewScript
*/
public function testGetViewScript($expected, $script, $filepath, $paths)
{
$sut = $this->getMockBuilder('\MvcLite\View')
->disableOriginalConstructor()
->setMethods(['getViewScriptPaths', 'getScript', 'filepath'])
->getMock();
$sut->expects($this->once())
->method('getViewScriptPaths')
->will($this->returnValue($paths));
$sut->expects($this->once())
->method('getScript')
->will($this->returnValue($script));
$sut->expects($this->exactly(count($paths)))
->method('filepath')
->will($this->returnValue($filepath));
$result = $sut->getViewScript();
$this->assertEquals($expected, $result);
}
/**
* Data Provider for testGetViewScript.
*
* @return array An array of data to use for testing.
*/
public function provideGetViewScript()
{
return [
'file does not exist' => [
'expected' => '',
'script' => '',
'filepaths' => '',
'paths' => [''],
],
'file does exist' => [
'expected' => __FILE__,
'script' => '',
'filepaths' => __FILE__,
'paths' => [''],
],
];
}
/**
* Tests MvcLite\View::addViewScriptPath
*
* @dataProvider provideAddViewScriptPath
*/
public function testAddViewScriptPath($path)
{
$sut = $this->getMockBuilder('MvcLite\View')
->disableOriginalConstructor()
->setMethods(['filepath'])
->getMock();
$sut->expects($this->any())
->method('filepath')
->will($this->returnValue($path));
$result = $sut->addViewScriptPath($path);
$this->assertSame($sut, $result);
}
/**
* Data Provider for testAddViewScriptPath.
*
* @return array An array of data to use for testing.
*/
public function provideAddViewScriptPath()
{
return [
'path not in APP_PATH' => [
'path' => '/some/path',
],
'path in APP_PATH' => [
'path' => APP_PATH . '/some/path',
]
];
}
/**
* Tests \MvcLite\View::getFormat.
*/
public function testGetFormat()
{
$expected = 'json';
$sut = \MvcLite\View::getInstance();
$property = $this->getReflectedProperty('\MvcLite\View', 'format');
$property->setValue($sut, $expected);
$result = $sut->getFormat();
$this->assertEquals($expected, $result);
}
/**
* Tests MvcLite\View::setFormat.
*
* @param string $format The format to send to the view
* @param boolean $exception If true, expect an exception.
*
* @dataProvider provideSetFormat
*/
public function testSetFormat($format)
{
$sut = \MvcLite\View::getInstance();
$result = $sut->setFormat($format);
$this->assertSame($sut, $result);
}
/**
* Data provider for testSetFormat.
*
* @return array An array of data to use for testing.
*/
public function provideSetFormat()
{
return [
'json' => [
'format' => 'json',
],
'html' => [
'format' => 'html',
],
'plain' => [
'format' => 'text',
],
'xml' => [
'format' => 'xml',
],
];
}
/**
* Tests the MvcLite\View::getHelper method.
*
* @dataProvider provideGetHelper
* @runInSeparateProcess
*/
public function testGetHelper($helper, $helpers = [], $exception = false)
{
if ($exception) {
$this->setExpectedException('\MvcLite\Exception');
}
$loader = $this->getMockBuilder(('\Composer\Loader\Autoloader'))
->disableOriginalConstructor()
->setMethods(['loadClass'])
->getMock();
$loader->expects($this->any())
->method('loadClass')
->will($this->returnValueMap([
['\App\View\Helper\\' . ucfirst($helper), false],
['\MvcLite\View\Helper\\' . ucfirst($helper), $exception ? false : true],
]));
$sut = \MvcLite\View::getInstance();
$this->getReflectedProperty('\MvcLite\View', 'helpers')->setValue($sut, $helpers);
$sut->setLoader($loader);
$result = $sut->getHelper($helper);
$this->assertInstanceOf('\MvcLite\View\HelperAbstract', $result);
}
/**
* Data provider for testGetHelper.
*
* @return array An array of data to use for testing.
*/
public function provideGetHelper()
{
return [
'Csv helper' => [
'helper' => 'csv',
],
'Exception helper' => [
'helper' => 'exception',
],
'InputCheckbox helper' => [
'helper' => 'InputCheckbox',
],
'InputPassword helper' => [
'helper' => 'InputPassword',
],
'InputPassword helper' => [
'helper' => 'InputPassword',
],
'InputSelect helper' => [
'helper' => 'InputSelect',
],
'InputSubmit helper' => [
'helper' => 'InputSubmit',
],
'InputTextarea helper' => [
'helper' => 'InputTextarea',
],
'InputText helper' => [
'helper' => 'InputText',
],
'InputText helper, but already has it' => [
'Helper' => 'InputText',
'helpers' => [
'InputText' => new \MvcLite\View\Helper\InputText,
],
],
'Bad Helper, expect exception' => [
'helper' => 'does not exist',
'helpers' => [],
'exception' => true,
]
];
}
}
| true |
3b0ee03608dc9c7aeedfc9ee3ba6e7cb40137eef | PHP | delr3ves/SymfonyRestApiBundle | /Docs/ApiObjectPopulator.php | UTF-8 | 2,246 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* In charge to generate some example data for ApiObjects.
*
*
* @author Sergio Arroyo <@delr3ves>
*/
namespace Delr3ves\RestApiBundle\Docs;
use Delr3ves\RestApiBundle\ApiObject\BaseApiObject;
use Delr3ves\RestApiBundle\Annotations\ApiAnnotationReader;
class ApiObjectPopulator {
/**
* @var \Delr3ves\RestApiBundle\Annotations\ApiAnnotationReader
*/
private $annotationReader;
private $typeMatrix;
public function __construct(ApiAnnotationReader $annotationReader) {
$this->annotationReader = $annotationReader;
$this->typeMatrix = array(
'int' => 1,
'integer' => 1,
'boolean' => true,
'bool' => true,
'string' => '...',
'\date' => new \DateTime(),
'\datetime' => new \DateTime(),
);
}
/**
* In charge to get an element populated with some example data.
*
* @param \Delr3ves\RestApiBundle\ApiObject\BaseApiObject $apiObject
* @return \Delr3ves\RestApiBundle\ApiObject\BaseApiObject
*/
public function populate($apiClass, $level=0) {
$reflectionClass = new \ReflectionClass($apiClass);
$apiObject = $reflectionClass->newInstanceArgs();
foreach ($reflectionClass->getProperties() as $property) {
$propertyName = $property->getName();
$setterMethod = sprintf('set%s', ucfirst($propertyName));
$value = $this->getValue($property, $level + 1);
if ($reflectionClass->hasMethod($setterMethod)) {
$apiObject->$setterMethod($value);
}
}
return $apiObject;
}
public function getValue($property, $level) {
$value = null;
$embedded = $this->annotationReader->isEmbedded($property);
$type = $this->annotationReader->getPropertyType($property);
if (isset($this->typeMatrix[strtolower($type)])) {
$value = $this->typeMatrix[strtolower($type)];
} else if (!$embedded || $embedded && $level <= 2) {
$value = $this->populate($type, $level);
}
if ($this->annotationReader->isCollection($property)) {
$value = array($value);
}
return $value;
}
}
| true |
de9e4dafe8f2c9dffba777c690d33bc63bd37124 | PHP | diegovalenzueladuque/farmacia | /class/marcaModel.php | UTF-8 | 1,880 | 2.984375 | 3 | [] | no_license | <?php
require_once('modelo.php');
class marcaModel extends Modelo
{
public function __construct(){
//disponemos de lo declarado en el constructor de la clase modelo
parent::__construct();
}
//traemos todos los roles de la tabla roles
public function getMarcas(){
//consulta a la tabla roles usando el objeto db de la clase modelo
$marcas = $this->_db->query("SELECT id, nombre FROM marcas ORDER BY nombre");
//retornamos lo que haya en la tabla roles
return $marcas->fetchall();
}
public function getMarcaId($id){
$id = (int) $id;
$marca = $this->_db->prepare("SELECT id, nombre, created_at, updated_at FROM marcas WHERE id = ?");
$marca->bindParam(1, $id);
$marca->execute();
return $marca->fetch();
}
public function getMarcaNombre($nombre){
$marca = $this->_db->prepare("SELECT id FROM marcas WHERE nombre = ?");
$marca->bindParam(1, $nombre);
$marca->execute();
return $marca->fetch();
}
public function setMarcas($nombre){
$marca = $this->_db->prepare("INSERT INTO marcas VALUES(null, ?, now(), now())");
$marca->bindParam(1, $nombre); //definimos el valor de cada ?
$marca->execute();//ejecutamos la consulta
$row = $marca->rowCount(); //devuelve la cantidad de registros insertados
return $row;
}
public function editMarcas($id, $nombre){
//print_r($nombre);exit;
$id = (int) $id;
$marca = $this->_db->prepare("UPDATE marcas SET nombre = ?, updated_at = now() WHERE id = ?");
$marca->bindParam(1, $nombre);
$marca->bindParam(2, $id);
$marca->execute();
$row = $marca->rowCount(); //devuelve la cantidad de registros modificadas
//print_r($row);exit;
return $row;
}
public function deleteMarcas($id){
$id = (int) $id;
$marca =$this->_db->prepare("DELETE FROM marcas WHERE id = ?");
$marca->bindParam(1, $id);
$marca->execute();
$row = $marca->rowCount();
return $row;
}
} | true |
7bcc67ddf13ce8bc6ba656fc3a39ee0877db8ef4 | PHP | Inggo/BndoBot | /src/Trivia/Trivia.php | UTF-8 | 5,202 | 2.75 | 3 | [] | no_license | <?php
namespace Inggo\BndoBot\Trivia;
use Inggo\BndoBot\Commands\BaseCommand;
use Inggo\BndoBot\Trivia\Question;
use Inggo\BndoBot\Shuffle\Scores;
class Trivia extends BaseCommand
{
use Scores;
const SLEEP_TIME = 15;
private $round = 0;
private $trivia;
public function __construct($command)
{
parent::__construct($command);
$this->setupGameFiles('trivia');
$this->run();
}
public function run()
{
$subcommand = strtolower($this->command->args[1]);
if ($subcommand === 'stop' && file_exists($this->gamefile)) {
return $this->endGame();
} elseif ($subcommand === 'start' && !file_exists($this->gamefile)) {
ini_set('max_execution_time', 0);
$this->sendMessage('Trivia game started.');
$this->startRound(true);
return $this->game();
} elseif ($subcommand === 'stats' && file_exists($this->scorefile)) {
$this->showGameScores();
} elseif ($subcommand === 'top10' && file_exists($this->globalscorefile)) {
$this->showTopTen();
} elseif ($subcommand === 'mystats' && file_exists($this->globalscorefile)) {
$this->showUserStats($this->command->from_id, $this->command->from);
} elseif (!file_exists($this->gamefile)) {
$this->sendMessage('Type `/trivia start` to start a game');
} elseif (file_exists($this->gamefile)) {
$this->sendMessage('Game is currently running. Type `/trivia stop` to stop the game');
} else {
/* Ignore? */
}
}
protected function endGame()
{
$this->sendMessage('Game stopped. Type `/trivia start` to start game.');
$this->showGameScores();
$this->unlinkIfExists($this->gamefile);
$this->unlinkIfExists($this->answerfile);
$this->unlinkIfExists($this->scorefile);
}
protected function getGameState()
{
return file_get_contents($this->gamefile);
}
protected function setGameState($state, $force = false)
{
if (!$force && !file_exists($this->gamefile)) {
return;
}
file_put_contents($this->gamefile, $state);
}
protected function generateAnswer()
{
$this->trivia = $this->getRandomQuestion();
file_put_contents($this->answerfile, $this->trivia->answer);
$this->sendMessage('Question: ' . $this->trivia->question . "\n" .
'Answer: `' . $this->getHint(0) . '`');
$this->setGameState('1');
sleep(self::SLEEP_TIME);
}
protected function getHint($count)
{
$answer = $this->getAnswer();
$hint = '';
for ($i = 0; $i/strlen($answer) < $count/4; $i++) {
$hint .= $answer[$i];
}
while ($i < strlen($answer)) {
if ($answer[$i] == ' ') {
$hint .= ' ';
} else {
$hint .= '*';
}
$i++;
}
return $hint;
}
protected function showHint($count)
{
if (!file_exists($this->answerfile)) {
return $this->endRound(false);
}
$hint = $this->getHint($count);
$this->sendMessage('Hint ' . $count . ': `' . $hint . '`');
$this->setGameState($count + 1);
sleep(self::SLEEP_TIME);
}
protected function getAnswer()
{
return file_get_contents($this->answerfile);
}
protected function getRandomQuestion()
{
// Get random file
$files = glob('questions/questions_*');
shuffle($files);
$questions = file($files[0]);
return new Question(trim($questions[rand(0, count($questions) - 1)]));
}
protected function startRound($force = false)
{
if ($this->round > 0 && $this->round % 5 === 0) {
$this->showGameScores();
}
$this->round++;
$this->sendMessage('Next question will appear in 15 seconds');
$this->setGameState('0', $force);
sleep(self::SLEEP_TIME);
}
protected function endRound($times_up = true)
{
if ($times_up) {
$this->sendMessage('Times up! Answer is: `' . $this->getAnswer() . '`');
}
$this->setGameState('5');
$this->unlinkIfExists($this->answerfile);
sleep(self::SLEEP_TIME);
}
public function game()
{
if (!file_exists($this->gamefile)) {
return;
}
set_time_limit(0);
switch ($this->getGameState()) {
case '0':
$this->generateAnswer();
break;
case '1':
case '2':
case '3':
$this->showHint($this->getGameState());
break;
case '4':
$this->endRound();
break;
default:
$this->startRound();
break;
}
return $this->game();
}
}
| true |
2960a0f60a02d9074f9759f710a254e1b53f349c | PHP | zkrat/basic-power | /src/Abstracts/DataRow.php | UTF-8 | 447 | 2.921875 | 3 | [] | no_license | <?php
namespace zkrat\BasicPower\Abstracts;
use zkrat\BasicPower\Helper\HelperString;
abstract class DataRow
{
protected $parent;
public function __construct(array $array =[],$parent=null){
foreach ($array as $key =>$val ){
$var=HelperString::underscoreToCamelCase($key);
if (property_exists($this,$var))
$this->$var =$array[$key];
}
$this->parent=$parent;
}
} | true |
30a558a5844184a8f9d0b10da3308c17bd47fb9c | PHP | rafaelp/brapi-php | /tests/BrapiTest.php | UTF-8 | 1,319 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
require_once 'src/Brapi/Client.php';
class BrapiTest extends PHPUnit_Framework_TestCase {
private $client;
public function setUp() {
$access_token = getenv('BRAPI_ACCESS_TOKEN');
$this->client = new \Brapi\Client($access_token, 'BrapiPHP');
}
public function tearDown() {
unset($this->client);
}
public function testValidZipcode() {
$zipcode = $this->client->zipcode('20071003');
$this->assertInstanceOf('\Brapi\Zipcode', $zipcode);
$this->assertEquals("Presidente Vargas", $zipcode->address);
$this->assertEquals("Presidente Vargas", $zipcode->address);
$this->assertEquals("Avenida", $zipcode->address_type);
$this->assertEquals("Rio de Janeiro", $zipcode->city);
$this->assertEquals("3304557", $zipcode->city_ibge_code);
$this->assertEquals("Centro", $zipcode->neighborhood);
$this->assertEquals("RJ", $zipcode->state);
$this->assertEquals("20071003", $zipcode->zipcode);
}
public function testInvalidZipcode() {
$this->setExpectedException('\Brapi\Error', 'Not Found');
$this->client->zipcode('ola');
}
public function testInvalidAccessToken() {
$this->client = new \Brapi\Client('invalid', 'BrapiPHP');
$this->setExpectedException('\Brapi\Error', 'Unauthorized');
$this->client->zipcode('20071003');
}
}
| true |
ff47c32ed796005430be562bb281f57eeb62a511 | PHP | ProgPassion/SmallTime | /include/class_absenz.php | UTF-8 | 2,879 | 3.046875 | 3 | [] | no_license | <?php
/*******************************************************************************
* Absenzen - Klasse
/*******************************************************************************
* Version 0.9
* Author: IT-Master GmbH
* www.it-master.ch / info@it-master.ch
* Copyright (c), IT-Master GmbH, All rights reserved
*******************************************************************************/
class time_absenz{
public $_array = NULL;
public $_filetext = NULL;
public $_calc = NULL;
private $ordnerpfad = NULL;
function __construct($ordnerpfad,$jahr){
$this->ordnerpfad = $ordnerpfad;
$_file = "./Data/".$this->ordnerpfad."/Timetable/A" . $jahr;
$this->_filetext = file("./Data/".$this->ordnerpfad."/absenz.txt");
if(file_exists($_file)){
$this->_array = file($_file);
$i=0;
foreach($this->_array as $string){
$string = explode(";", $string);
foreach($this->_filetext as $_zeile){
$_zeile = explode(";", $_zeile);
if (trim($string[1]) == trim($_zeile[1])){
$string[3] = trim($_zeile[0]);
if (!trim($string[2])<>0) $string[2]=1;
$string[4] = trim($_zeile[2]);
}
}
$this->_array[$i] = $string;
$i++;
}
}
$this->calc();
return $this->_array;
}
function calc(){
if(!$this->_calc){
$o=0;
foreach($this->_filetext as $_zeile){
$_zeile = str_replace("ä","ae", $_zeile);
$_zeile = str_replace("ö","oe", $_zeile);
$_zeile = str_replace("ü","ue", $_zeile);
$_zeile = explode(";", $_zeile);
$this->_calc[$o] = array($_zeile[0], $_zeile[1], $_zeile[2], 0);
$o++;
}
}
}
function get_absenztext(){
return $this->_filetext;
}
function insert_absenz($ordnerpfad, $_w_jahr){
$_zeilenvorschub = "\r\n";
$_file = "./Data/".$ordnerpfad."/Timetable/A" . $_w_jahr;
if (!file_exists($_file)) {
$_meldung= "Keine Daten vorhanden, folgende Datei wurde versucht zu öffnen ". $_file;
}else{
$_abwesenheit = file($_file);
}
$_timestamp = $_GET['timestamp'];
$_grund = $_POST['_grund'];
$_anzahl = $_POST['_anzahl'];
$fp = fopen($_file,"a+");
fputs($fp, $_timestamp.";".$_grund.";".$_anzahl.$_zeilenvorschub);
fclose($fp);
}
function delete_absenz($ordnerpfad, $_w_jahr){
$_timestamp = $_GET['timestamp'];
$_file = "./Data/".$ordnerpfad."/Timetable/A" . $_w_jahr;
$_absenzliste = file($_file);
$i=0;
foreach($_absenzliste as $string){
$string = explode(";", $string);
if ($string[0] == $_timestamp) {
unset($_absenzliste[$i]);
}
$i++;
}
$neu = implode( "", $_absenzliste);
$open = fopen($_file,"w+");
fwrite ($open, $neu);
fclose($open);
}
public function __destruct() {
}
} | true |
89a35064e625187e68ddec7613a4ab8af51e5238 | PHP | piotzkhider/IDDD_Samples_PHP | /src/IdentityAccess/Domain/Model/Identity/ContactInformation.php | UTF-8 | 5,390 | 2.875 | 3 | [] | no_license | <?php
namespace SaasOvation\IdentityAccess\Domain\Model\Identity;
use SaasOvation\Common\AssertionConcern;
final class ContactInformation extends AssertionConcern
{
/**
* @var EmailAddress
*/
private $emailAddress;
/**
* @var string
*/
private $postalAddressCity;
/**
* @var string
*/
private $postalAddressCountryCode;
/**
* @var string
*/
private $postalAddressPostalCode;
/**
* @var string
*/
private $postalAddressStateProvince;
/**
* @var string
*/
private $postalAddressStreetAddress;
/**
* @var Telephone
*/
private $primaryTelephone;
/**
* @var Telephone
*/
private $secondaryTelephone;
public function __construct(
EmailAddress $anEmailAddress,
PostalAddress $aPostalAddress,
Telephone $aPrimaryTelephone,
Telephone $aSecondaryTelephone
) {
$this->setEmailAddress($anEmailAddress);
$this->setPostalAddress($aPostalAddress);
$this->setPrimaryTelephone($aPrimaryTelephone);
$this->setSecondaryTelephone($aSecondaryTelephone);
}
public static function fromContactInformation(ContactInformation $aContactInformation)
{
return new ContactInformation(
$aContactInformation->emailAddress(),
$aContactInformation->postalAddress(),
$aContactInformation->primaryTelephone(),
$aContactInformation->secondaryTelephone()
);
}
public function changeEmailAddress(EmailAddress $anEmailAddress)
{
return new ContactInformation(
$anEmailAddress,
$this->postalAddress(),
$this->primaryTelephone(),
$this->secondaryTelephone()
);
}
public function changePostalAddress(PostalAddress $aPostalAddress)
{
return new ContactInformation(
$this->emailAddress(),
$aPostalAddress,
$this->primaryTelephone(),
$this->secondaryTelephone()
);
}
public function changePrimaryTelephone(Telephone $aTelephone)
{
return new ContactInformation(
$this->emailAddress(),
$this->postalAddress(),
$aTelephone,
$this->secondaryTelephone()
);
}
public function changeSecondaryTelephone(Telephone $aTelephone)
{
return new ContactInformation(
$this->emailAddress(),
$this->postalAddress(),
$this->primaryTelephone(),
$aTelephone
);
}
public function emailAddress()
{
return new EmailAddress($this->emailAddress);
}
public function postalAddress()
{
return new PostalAddress(
$this->postalAddressStreetAddress,
$this->postalAddressCity,
$this->postalAddressStateProvince,
$this->postalAddressPostalCode,
$this->postalAddressCountryCode
);
}
public function primaryTelephone()
{
return new Telephone($this->primaryTelephone);
}
public function secondaryTelephone()
{
return new Telephone($this->secondaryTelephone);
}
public function equals($anObject)
{
$equalObjects = false;
if (null !== $anObject && get_class($this) == get_class($anObject)) {
$equalObjects =
$this->emailAddress()->equals($anObject->emailAddress()) &&
$this->postalAddress()->equals($anObject->postalAddress()) &&
$this->primaryTelephone()->equals($anObject->primaryTelephone()) &&
(($this->secondaryTelephone() == null && $anObject->secondaryTelephone() == null) ||
($this->secondaryTelephone() != null && $this->secondaryTelephone()->equals($anObject->secondaryTelephone())));
}
return $equalObjects;
}
public function __toString()
{
return 'ContactInformation [emailAddress=' . $this->emailAddress . ', postalAddress=' . $this->postalAddress() . ', primaryTelephone=' . $this->primaryTelephone . ', secondaryTelephone=' . $this->secondaryTelephone . ']';
}
private function setEmailAddress(EmailAddress $anEmailAddress)
{
$this->assertArgumentNotNull($anEmailAddress, 'The email address is required.');
$this->emailAddress = $anEmailAddress->address();
}
private function setPostalAddress(PostalAddress $aPostalAddress)
{
$this->assertArgumentNotNull($aPostalAddress, 'The postal address is required.');
$this->postalAddressCity = $aPostalAddress->city();
$this->postalAddressCountryCode = $aPostalAddress->countryCode();
$this->postalAddressPostalCode = $aPostalAddress->postalCode();
$this->postalAddressStateProvince = $aPostalAddress->stateProvince();
$this->postalAddressStreetAddress = $aPostalAddress->streetAddress();
}
private function setPrimaryTelephone(Telephone $aPrimaryTelephone)
{
$this->assertArgumentNotNull($aPrimaryTelephone, 'The primary telephone is required.');
$this->primaryTelephone = $aPrimaryTelephone->number();
}
private function setSecondaryTelephone(Telephone $aSecondaryTelephone)
{
$this->secondaryTelephone = $aSecondaryTelephone->number();
}
}
| true |
eb79a40c99ccc4334ffbbd256bd64a4bf1badc51 | PHP | atoroc/chatbot-voxibot | /mailer/mail3.php | UTF-8 | 4,134 | 2.609375 | 3 | [] | no_license | <?php
require("../config.php");
require("include/class.phpmailer.php");
$json_response = file_get_contents("php://input");
if ($json_response)
{
$json = json_decode($json_response, true);
if (isset($json['key']))
{
$key = $json['key'];
if ($key != "moreno")
{
echo "BAD KEY";
exit();
}
}
else
{
echo "ACCESS DENIED";
exit();
}
if (isset($json['address']))
$address = $json['address'];
else
if (isset($json['to']))
$address = $json['to'];
else
$address = "borja.sixto@ulex.fr";
if (isset($json['from']))
$from = $json['from'];
else
$from = "Voximal";
if (isset($json['subject']))
$subject = $json['subject'];
else
$subject = "No subject";
if (isset($json['body']))
{
$body = $json['body'];
}
else
$body = "";
}
else
{
if (isset($_REQUEST['key']))
{
$key = $_REQUEST['key'];
if ($key != "moreno")
{
echo "BAD KEY";
exit();
}
}
else
{
echo "ACCESS DENIED";
exit();
}
if (isset($_REQUEST['address']))
$address = $_REQUEST['address'];
else
if (isset($_REQUEST['to']))
$address = $_REQUEST['to'];
else
$address = "borja.sixto@ulex.fr";
if (isset($_REQUEST['from']))
$from = $_REQUEST['from'];
else
$from = "Voximal";
if (isset($_REQUEST['subject']))
$subject = $_REQUEST['subject'];
else
$subject = "No subject";
if (isset($_REQUEST['body']))
{
$body = $_REQUEST['body'];
//$body2 = mb_convert_encoding($body, "UTF-8", "UTF-8");
//$body = $body2;
}
else
$body = "";
if (isset($_REQUEST['logs']))
{
$logs = $_REQUEST['logs'];
//$logs2 = mb_convert_encoding($logs, "iso-8859-1", "UTF-8");
//echo $logs;
//echo "DEBUG :".$logs2;
$body .= "\n\nLogs2:\n";
}
if (isset($_REQUEST['format']))
{
$format = $_REQUEST['format'];
}
if (isset($_FILES['attachment']))
{
$message = $_FILES['attachment']['tmp_name'];
$message_type = $_FILES['attachment']['type'];
}
else
$message = false;
if ($message)
{
if ($format=="mp3")
{
$outfile="/tmp/".$caller.".mp3";
@unlink($outfile);
system("ffmpeg -i $message -ab 16k $outfile");
@unlink($message);
$message = $outfile;
$message_type = "audio/mpeg";
}
else
if ($format=="ogg")
{
$outfile="/tmp/".$caller.".ogg";
@unlink($outfile);
system("ffmpeg -i $message $outfile");
@unlink($message);
$message = $outfile;
$message_type = "audio/ogg";
}
}
}
// Instantiate your new class
$mail = new PHPMailer();
// Now you only need to add the necessary stuff
//$mail->Host = "";
//$mail->Port = "22";
$mail->Mailer = "mail";
// Now you only need to add the necessary stuff
$mail->IsSMTP();
$mail->SMTPAuth = $config['mail']['smtpauth']; // enable SMTP authentication
$mail->SMTPSecure = $config['mail']['smtpauth']; // sets the prefix to the servier
$mail->Host = $config['mail']['host']; // sets GMAIL as the SMTP server
$mail->Port = $config['mail']['port']; // set the SMTP port for the GMAIL server
$mail->Username = $config['mail']['user']; // GMAIL username
$mail->Password = $config['mail']['password']; // GMAIL password
//$mail->AddReplyTo("bsixto@gmail.com", "First Last");
$mail->FromName = $from;
$arr = explode(';', $address);
foreach ($arr as &$value) {
$mail->AddAddress($value);
}
//$mail->AddAddress($address);
$mail->Subject = $subject;
$mail->CharSet = "UTF-8";
if ($message)
{
$extension = pathinfo($message, PATHINFO_EXTENSION);
if ($message_type == "audio/mpeg")
$mail->AddAttachment($message, "file.mp3");
else
if ($message_type == "audio/x-wav")
$mail->AddAttachment($message, "file.wav");
else
$mail->AddAttachment($message, "file.".$extension);
$mail->Body = $body."\n\nA file is attached ($message_type)";
}
else
{
$mail->Body = $body;
}
if(!$mail->Send())
{
$result="ERROR";
}
else
{
$result="OK";
}
if ($message)
@unlink($message);
$data = $result;
//header('Content-Type: application/json');
//echo json_encode($data);
header('Content-Type: text/plain');
echo $result;
?>
| true |
0be4dca10b55460303674ef68320120f1e2d1112 | PHP | lldakila/DocTrak | /DOCTRAk/procedures/home/document/common/previewfile.php | UTF-8 | 3,394 | 2.546875 | 3 | [] | no_license | <?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
$_SESSION['in'] ="start";
header('Location:../../../../index.php');
}
require_once("encrypt.php");
$id=decryptText(base64_decode($_GET['download_file']));
require_once("../../../connection.php");
global $DB_HOST, $DB_USER,$DB_PASS, $BD_TABLE;
$con=mysqli_connect($DB_HOST,$DB_USER,$DB_PASS,$BD_TABLE);
$query="select document_file,document_mime from documentlist where document_id = '".$id."'";
//echo $query;
$RESULT=mysqli_query($con,$query);
while ($row = mysqli_fetch_array($RESULT))
{
// echo $row['document_mime'];
// die;
//header('Content-type: "'.$row['document_mime'].'');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="downloaded.pdf"');
header("Content-Transfer-Encoding: binary");
//header('Content-Disposition: attachment; filename="downloaded.pdf"');
ob_clean();
flush();
echo $row['document_file'];
}
//
//
//echo "die";
// die;
//echo "<br>";
////echo $fullpath;
//
// $file = $path;
//echo $file;
//if (file_exists($file))
// {
// header('Content-Description: File Transfer');
// header('Content-Type: application/octet-stream');
// header('Content-Disposition: attachment; filename='.basename($file));
// header('Expires: 0');
// header('Cache-Control: must-revalidate');
// header('Pragma: public');
// header('Content-Length: ' . filesize($file));
// ob_clean();
// flush();
// readfile($file);
// exit;
// }
//
//
//
//
//
//
//
//
//echo $fullpath;
//echo "<br>";
//echo pathinfo($path .decryptText(base64_decode($_GET['download_file'])));
//
//if (file_exists ($path)) {
//$fsize = filesize($fullpath);
//$path_parts = pathinfo($fullpath);
////echo decryptText(base64_decode($_GET['download_file']));
////echo $path.basename(decryptText(base64_decode($_GET['download_file'])));
////echo "<br>";
////echo $file;
//$ext = strtolower($path_parts["extension"]);
//echo "valid req";
//die;
//switch ($ext) {
// case "pdf":
// header("Content-type: application/pdf"); // add here more headers for diff. extensions
// header("Content-Disposition: attachment; filename=\"".$fullpath."\""); // use 'attachment' to force a download
// break;
// default;
// header("Content-type: application/octet-stream");
// header("Content-Disposition: filename=\"".$fullpath."\"");
//}
//header("Content-length: $fsize");
//header("Cache-control: private"); //use this to open files directly
//readfile($file);
//exit;
//} else {
// die("Invalid request");
//}
////
////header('Content-Description: File Transfer');
////header('Content-type: application/pdf');
////header("Content-Type: application/force-download");// some browsers need this
////header("Content-Disposition: attachment; filename=\"$file\"");
////header('Expires: 0');
////header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
////header('Pragma: public');
////header('Content-Length: ' . filesize($file));
////ob_clean();
////flush();
////readfile($file);
////echo $file;
////exit;
| true |
2389a47e285b8f5380641531551cec2eeaff3b61 | PHP | Edivald0/PROYECTOS-PHP | /codejobs/v1/index.php | UTF-8 | 6,450 | 2.859375 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"; > <!-- Para la codificacion usada-->
<meta name="description" content="Ejemplo de CSS3 y HTML5" >
<meta name="keywords" content="html5, css3" >
<meta name="author" content="Edivaldo Martínez Moreno" >
<link rel="stylesheet" type="text/css" href="css/stylev11.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>V1-1.php</title>
<!-- menu -->
<!--<link rel="stylesheet" type="text/css" href="css/estilos.css">-->
<script src="http://code.jquery.com/jquery-latest.js"></script><!-- Jquery para hacer responsive desing -->
</head>
<body>
<header>
<figure>
<img src="imagenes/header.jpg">
</figure>
<div class="titulo">
VIDEO 1<br>
<a href="https://www.codejobs.biz/es/blog/category/php" class="subtitulo"> Curso CodeJobs php.<br></a>
<a href="ejercicio/ejercicios1.php" class="subtitulo2">Ejercicios</a>
</div>
<!-- MENU-->
<div class="menu_bar">
<a href="" class="bt-menu">Temas</a>
</div>
<nav>
<ul>
<li><a href="">What is php?</a></li>
<li><a href="">PHP instalation</a></li>
<li><a href="">How does php work?</a> </li>
<li><a href="">My first web page with php</a></li>
<li><a href=""> how to upload a php file to a server</a></li>
<li><a href=""> Variables</a></li>
<li><a href=""> Comments</a></li>
<li><a href=""> Constants</a></li>
<li><a href=""> Operators</a></li>
<li><a href=""> if</a></li>
<li><a href=""> if...else</a></li>
<li><a href=""> if...else...if</a></li>
<li><a href=""> Compact if(?:)</a></li>
</ul>
</nav>
</header>
<!--
<div class="temas">
<ol>
<li><a href="">What is php?</a></li>
<li><a href="">PHP instalation</a></li>
<li>How does php work?</li>
<li><a href="">My first web page with php</a></li>
<li><a href=""> how to upload a php file to a server</a></li>
<li><a href=""> Variables</a></li>
<li><a href=""> Comments</a></li>
<li><a href=""> Constants</a></li>
<li><a href=""> Operators</a></li>
<li><a href=""> if</a></li>
<li><a href=""> if...else</a></li>
<li><a href=""> if...else...if</a></li>
<li><a href=""> Compact if(?:)</a></li>
i </ol>
</div>
-->
<!-- SECCION 1 -->
<section class="sec1"><h1><?php echo "1er PROGRAMA (HTML)"; ?></h1></section>
<?php
$variable1 = "1er PROGRAMA (PHP)";
$texto = "Seccion 2 del programa";
echo "<section><h1> $variable1 </h1></section>";
?>
<!-- SECCION 2 -->
<section class="sec2">
<?php
$a = 2;
$b = 3;
function variable2(){ //Funcion para la suma de a+b = 5
global $a, $b, $texto; //Global palabra reservada para hace las variables locales.
$a = $a + $b;
}
variable2(); //Se espercifica el nombre de la función para poder imprimir el resultado de $a
echo "<h2 id=sec2>$texto</h2><br>", $a; //Se impirme $a = 5
?>
</section>
<!-- SECCION 3 -->
<section class="sec3">
<h2>STATIC SCOPE</h2>
<?php
function foo(){
static $index = 0;
$index ++;
echo "<br>" ;
echo "$index";
}
echo "<p>resultado de incremento de index = 0: ";
foo(); foo(); foo();
?>
</section>
<section class="sec4">
<h2>CONSTANTS</h2>
<article>Se definen con la palabra reservada "define();"<br>
Su valor no puede ser modificado y su alcance es global.
</article>
<?php
define("text2", "El valor de pi = ");
define("PI", 3.1416);
function imprimirConstantes(){
echo text2 . PI;
}
?>
<p><?php imprimirConstantes() ?><br>
</p>
</section>
<section>
<h2>Operaciones.</h2>
<?php
define("valor1", 6);
define("valor2", 7);
function suma (){
$suma = 0;
$suma = valor1 + valor2;
echo $suma;
}
function resta (){
$resta = 0;
$resta = valor1 - valor2;
echo $resta;
}
function division (){
$division = 0;
$division = valor1 / valor2;
echo $division;
}
function multiplicacion(){
$multiplicacion = 0;
$multiplicacion = valor1 * valor2;
echo $multiplicacion;
}
?>
<p>
<strong>Las siguientes son resultados con operaciones ya definidas en el archivo v1-1.php<br>
Valor 1 = 6, Valor 2 = 7</strong>
<nav>
<ul>
<li>Suma: <?php suma(); ?></li>
<li>Resta: <?php resta(); ?></li>
<li>Division: <?php division(); ?></li>
<li>Multiplicacion: <?php multiplicacion(); ?></li>
</ul>
</nav>
</p>
</section>
<section>
<h2>Ciclo FOR</h2>
<p>El siguiente es un ciclo for:<br></p>
<?php
$sum=0;
for ($i=1; $i <= 10; $i++) {
$sum=$sum+$i; //$sum += $i; (Es lo mismo)
echo $i;
echo ($i == 10) ? "<hr/> =" : "+"; /* condicion ($i == 10) ? (SI se cumple) imprime "=" : ( else, SINO se cumple) imprime "+" */
/* ESTO ES LO MISMO QUE LO DE ARRIBA
if ($i==10) {
echo "=";
}else{
echo "+";
} */
}
echo "$sum";
?>
</section>
<section>
<?php
function cicloForeach (){
$array = array("Apple", "Pear", "Banana");
reset ($array);
foreach ($array as $fruit) {
echo "Fruit: $fruit <br>";
}
}
?>
<h2>FOREACH (para hacer iteraciones con arrays)</h2>
<p>El resultado del foreach es: <br> <?php cicloForeach(); ?></p>
</section>
<section>
<h2>WHILE (mientras)</h2>
<?php
$i = 1;
while ( $i <= 10) {
echo "El numero es: ". $i ."<br/>";
$i++;
}
?>
</section>
<section>
<h2>MD5</h2>
<?php
$contraseña = "Edivaldo";
echo md5($contraseña);
?>
</section>
<section>
<h2>NL2BR</h2>
<?php
echo nl2br("1a linea \n 2a linea ");
?>
</section>
<section>
<h2>SHA1</h2>
<?php
$contraseña2 = "Edivaldo";
echo sha1($contraseña2);
?>
</section>
<script src="js/main.js"></script>
</body>
</html>
| true |
2944352255acda481d41457ca277a1baf39e0e81 | PHP | projectEmotion/eMotion | /src/FrontBundle/Controller/OrderController.php | UTF-8 | 2,186 | 2.578125 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Christian
*/
namespace FrontBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
/**
* This controller is used to simulate an order from a customer.
* Class OrderController
*/
class OrderController extends Controller
{
public function prepareAction()
{
return $this->render('FrontBundle:Default:prepare.html.twig');
}
public function Session()
{
$frontSession = $this->get('front.session');
$frontSession->initiate($this->get('session'));
return $frontSession;
}
public function checkoutSuccessAction()
{
return $this->render('FrontBundle:Default:checkout.html.twig');
}
public function checkoutAction(Request $request)
{
$cart = $this->Session()->getCart();
$totalPrice = 0;
if(!empty($cart)){
foreach ($cart as $c){
$totalPrice+= $c->getPrice();
}
}
\Stripe\Stripe::setApiKey("sk_test_Mtp40DUIRNqfrkWgxvmZWLyG");
// Get the credit card details submitted by the form
$token = $request->get('stripeToken');
// Create a charge: this will charge the user's card
try {
$amount = $totalPrice*100;
// Create a Customer:
$customer = \Stripe\Customer::create(array(
"email" => "paying.user@example.com",
"source" => $token,
));
$charge = \Stripe\Charge::create(array(
"amount" => $amount, // Amount in cents
"currency" => "eur",
"customer" => $customer->id
));
$this->addFlash("success","Bravo ça marche !");
return $this->redirect($this->generateUrl('order_checkout_success'));
//return $this->redirectToRoute("order_checkout");
} catch(\Stripe\Error\Card $e) {
$this->addFlash("error","Snif ça marche pas :(");
return $this->redirectToRoute("prepare_page");
// The card has been declined
}
}
} | true |
9865a5540d283db6b0d887e6c0721cd78ee846e3 | PHP | PeeHaa/asgard | /Core/Commands/Generator.php | UTF-8 | 832 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace Asgard\Core\Commands;
class Generator {
use \Asgard\Container\ContainerAware;
protected $overrideFiles = false;
public function __construct($container) {
$this->container = $container;
}
public function setOverrideFiles($overrideFiles) {
$this->overrideFiles = $overrideFiles;
}
public function processFile($_src, $_dst, $vars) {
if(!$this->overrideFiles && file_exists($_dst))
return;
$container = $this->container;
extract($vars);
ob_start();
include $_src;
$content = ob_get_contents();
ob_end_clean();
$content = str_replace('<%=', '<?=', $content);
$content = str_replace('<%', '<?php', $content);
$content = str_replace('%>', '?>', $content);
\Asgard\File\FileSystem::write($_dst, $content);
}
public function outputPHP($v) {
return var_export($v, true);
}
} | true |
fd71212cb55b1967c90fc6559608be5ab6d6cf04 | PHP | tapirs/lunisolar | /tests/commonTest.php | UTF-8 | 5,042 | 2.75 | 3 | [] | no_license | <?php
declare(strict_types=1);
require_once('common.php');
use PHPUnit\Framework\TestCase;
class commonTest extends TestCase {
public function setUp(){
}
public function tearDown(){ }
public function testInputCanBeProcessed(): void {
$this->assertEquals(processInput("hello"), "hello");
$this->assertEquals(processInput(" hello "), "hello");
$this->assertEquals(processInput("\'\\hello\\"), "'hello");
$this->assertEquals(processInput("<hello>"), "<hello>");
$this->assertEquals(processInput(" \'<hello>\' "), "'<hello>'");
}
public function testCanReturnAnError(): void {
$this->expectOutputString( "<form id=\"error_form\" action=\"index.php\" method=\"post\">
<input type=\"hidden\" name=\"error\" value=\"this is a test error message\">
<input type=\"hidden\" name=\"formname\" value=\"error_form\">
</form>
<script type=\"text/javascript\">
document.getElementById('error_form').submit();
</script>");
returnError("this is a test error message", "index.php");
}
public function testCanReturnAnSuccess(): void {
$this->expectOutputString( "<form id=\"success_form\" action=\"index.php\" method=\"post\">
<input type=\"hidden\" name=\"success\" value=\"this is a test success message\">
<input type=\"hidden\" name=\"formname\" value=\"success_form\">
</form>
<script type=\"text/javascript\">
document.getElementById('success_form').submit();
</script>");
returnSuccess("this is a test success message", "index.php");
}
public function testCanReturnToLogin(): void {
$this->expectOutputString( "<form id=\"login_form\" action=\"login.php\" method=\"post\">
<input type=\"hidden\" name=\"error\" value=\"please login before continuing.\">
<input type=\"hidden\" name=\"redirect\" value=\"index.php\">
<input type=\"hidden\" name=\"formname\" value=\"login_form\">
</form>
<script type=\"text/javascript\">
document.getElementById('login_form').submit();
</script>");
returnToLogin("login.php", "index.php");
}
public function testCanLogout(): void {
$this->expectOutputString( "<form id=\"logout_form\" action=\"index.php\" method=\"post\">
<input type=\"hidden\" name=\"success\" value=\"you have logged out\">
</form>
<script type=\"text/javascript\">
document.getElementById('logout_form').submit();
</script>");
logout();
}
public function CanCheckLogin(): void {
$username = "andrew.partis@tapirs-technologies.co.uk";
$auth_hash = password_hash("andrew.partis@tapirs-technologies.co.uk" . "test", PASSWORD_BCRYPT);
$this->assertTrue(checkLogin($username, $auth_hash));
}
public function testCanCheckIsYear(): void {
$this->assertTrue(isYear("2018"));
$this->assertFalse(isYear("gnnuaguraghur"));
$this->assertFalse(isYear("uahgruag ragrao;hgra 2018 vjriao;rha;gr gr aragr"));
}
public function testCanCheckIsMonth(): void {
$this->assertTrue(isMonth("January"));
$this->assertFalse(isMonth("gnnuaguraghur"));
$this->assertFalse(isMonth("uahgruag ragrao;hgra January vjriao;rha;gr gr aragr"));
}
public function testCanCheckIsDate(): void {
$this->assertTrue(isDate("mon 2"));
$this->assertFalse(isDate("bob"));
$this->assertFalse(isDate("fheue mon 2 fjeiwo;nvn VVE 22 34 GIRMAR "));
}
public function testCanCheckIsTime(): void {
$this->assertTrue(isTime("10.30 am"));
$this->assertTrue(isTime("9 pm"));
$this->assertFalse(isTime("few 9 pm fe2 am vv"));
$this->assertFalse(isTime("9. pm"));
$this->assertFalse(isTime("nfuo;g"));
}
public function testCanReadSpreadsheet(): void {
$filename = "uploads/JHSpring18Calendar161017-9.xlsx";
#lets check the test file exists before we start
$this->assertFileExists($filename);
#then we'll try and load it up
$this->assertThat(readSpreadsheet($filename), $this->logicalNot($this->IsNull()));
#check an excpetion is thrown when the file doesnt exist
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage("File \"uploads/JHSpring18Calendar161017-9.xlsx.bak\" does not exist.");
readSpreadsheet($filename . ".bak");
}
public function testCanGetWorkSheet(): void {
$filename = "uploads/JHSpring18Calendar161017-9.xlsx";
$spreadSheet = readSpreadsheet($filename);
$this->assertThat(getWorksheet($spreadSheet, 0), $this->logicalNot($this->IsNull()));
}
public function testCanGetCalendarFilename(): void {
$filename = "uploads/JHSpring18Calendar161017-9.xlsx";
$spreadSheet = readSpreadsheet($filename);
$worksheet = getWorksheet($spreadSheet, 0);
$this->assertEquals(getCalendarFilename($worksheet), "SPRING_TERM_2018_JUNIOR_HOUSE_CALENDAR");
}
}
?>
| true |
6c61fdd1c704853fb23f100126ccfca59dc89af4 | PHP | paulocorazza/curso-php | /funcoes/recursividade.php | UTF-8 | 871 | 3.765625 | 4 | [] | no_license | <div class="titulo">
Recursividade
</div>
<?php
echo '<h3>Decrementando</h3>';
function somaUmAte($numero){
$soma = 0;
for(; $numero >= 1; $numero--){
$soma += $numero;
}
return $soma;
}
echo somaUmAte(5) . '<br>';
echo '<h3>Incrementando</h3>';
function somaUmAte2($numero){
$soma = 0;
for($i = 0; $i <= $numero; $i++){
$soma += $i;
}
return $soma;
}
echo somaUmAte2(10) . '<br>';
echo '<h3>Com Recursividade</h3>';
function somaRecursivaUmAte($numero){
if($numero === 1){
return 1;
}
return $numero + somaRecursivaUmAte($numero - 1);
}
echo somaRecursivaUmAte(2) . '<br>';
echo '<h3>Com Recursividade Economica</h3>';
function somaRecursivaEconomica($numero){
return $numero === 1 ? 1 : $numero + somaRecursivaEconomica($numero - 1);
}
echo somaRecursivaEconomica(150) . '<br>'; | true |
896fb87657113bba0d242f8cedf627ff9a5b0dd2 | PHP | othercodes/rest | /examples/post_json_request.php | UTF-8 | 559 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
require_once '../vendor/autoload.php';
try {
$api = new \OtherCode\Rest\Rest();
$api->configuration->url = "http://jsonplaceholder.typicode.com/";
$api->configuration->addHeader('some_header', 'some_value');
$api->setEncoder("json");
$api->setDecoder("json");
$payload = new stdClass();
$payload->userId = 3400;
$payload->title = "Some title";
$payload->body = "Some test data";
$response = $api->post("posts/", $payload);
var_dump($response);
} catch (\Exception $e) {
print $e->getMessage();
}
| true |
aeacc7d0c7b07acf9bec82fb5639abb44a6cf8f5 | PHP | PixelPoncho/SENG401 | /ATM_Project/database/migrations/2019_04_07_214359_create_accounts_table.php | UTF-8 | 987 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAccountsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('accounts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('userID')->unsigned();
$table->enum('type', array('chequing', 'savings', 'investment', 'tfsa'));
$table->bigInteger('balance');
$table->timestamp('open_date')->nullable();
$table->timestamp('created_at')->nullable();
$table->timestamp('updated_at')->nullable();
$table->foreign('userID')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('accounts');
}
}
| true |
f4dddb97cf9fb3a44ba6894cfbdcae43c61e4333 | PHP | chief1983/SquadWar-v2 | /inc/squad/record/league/detail.php | UTF-8 | 755 | 2.546875 | 3 | [] | no_license | <?php
class squad_record_league_detail extends base_recorddetail
{
protected $SWSquad_SquadID;
protected $Leagues;
protected $League_PW;
public function __construct()
{
parent::__construct();
$this->datamodel_name = 'squad_data_league';
$this->required_fields = array(
'SWSquad_SquadID','Leagues'
);
}
public function get_SWSquad_SquadID()
{
return $this->SWSquad_SquadID;
}
public function set_SWSquad_SquadID($val)
{
$this->SWSquad_SquadID = $val;
}
public function get_Leagues()
{
return $this->Leagues;
}
public function set_Leagues($val)
{
$this->Leagues = $val;
}
public function get_League_PW()
{
return $this->League_PW;
}
public function set_League_PW($val)
{
$this->League_PW = $val;
}
}
?>
| true |
1a1b587fde4afea0ced300e8a37ce3384893ee49 | PHP | mbcraft/frozen | /src/framework/core/lib/controller/Result.class.php | UTF-8 | 1,019 | 2.96875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | <?php
/* This software is released under the BSD license. Full text at project root -> license.txt */
class Result
{
static function is_result($data)
{
return is_array($data) && isset($data["result"]);
}
static function ok()
{
return array("result" => "ok");
}
static function is_ok($result)
{
return $result["result"]==="ok";
}
static function is_warning($result)
{
return $result["result"]==="warning";
}
static function warning($message)
{
return array("result" => "warning","warning" => $message);
}
static function is_error($result)
{
return $result["result"]==="error";
}
static function error($message_or_exception)
{
if ($message_or_exception instanceof Exception)
return array("result" => "error","error" => $message_or_exception->getMessage());
else
return array("result" => "error","error" => $message_or_exception);
}
}
?> | true |
a5438cb300493b8b0361c1bdab9a87382d4ea2f6 | PHP | jrebs/easyship-php | /src/Modules/Products.php | UTF-8 | 1,958 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
namespace Easyship\Modules;
use Easyship\Module;
use Psr\Http\Message\ResponseInterface;
class Products extends Module
{
/**
* Returns a list of products that are available with your account.
*
* @link https://developers.easyship.com/reference/products_index
* @param array $query
* @return \Psr\Http\Message\ResponseInterface
*/
public function list(array $query = []): ResponseInterface
{
$endpoint = sprintf('%s/products', self::API_VERSION);
return $this->easyship->request('get', $endpoint, $query);
}
/**
* Create a single product into your account.
*
* @link https://developers.easyship.com/reference/products_create
* @param array $payload
* @return \Psr\Http\Message\ResponseInterface
*/
public function create(array $payload): ResponseInterface
{
$endpoint = sprintf('%s/products', self::API_VERSION);
return $this->easyship->request('post', $endpoint, $payload);
}
/**
* Delete a single product from your account.
*
* @link https://developers.easyship.com/reference/products_delete
* @param string $productId
* @return \Psr\Http\Message\ResponseInterface
*/
public function delete(string $productId): ResponseInterface
{
$endpoint = sprintf('%s/products/%s', self::API_VERSION, $productId);
return $this->easyship->request('delete', $endpoint);
}
/**
* Update a single product in your account.
*
* @link https://developers.easyship.com/reference/products_update
* @param string $productId
* @param array $payload
* @return \Psr\Http\Message\ResponseInterface
*/
public function update(string $productId, array $payload): ResponseInterface
{
$endpoint = sprintf('%s/products/%s', self::API_VERSION, $productId);
return $this->easyship->request('patch', $endpoint, $payload);
}
}
| true |
7663026c01465aa5dd9204db37a08327e5aa9325 | PHP | jigar586/frinza | /application/libraries/adminlib/Banners.php | UTF-8 | 1,120 | 2.609375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
class Banners
{
function __construct()
{
$this->tableName='banner_mst';
$this->CI =& get_instance();
$this->CI->load->model('AdminModel');
}
function insertBanner($data)
{
return $this->CI->AdminModel->insertData($data,$this->tableName);
}
function getBanner($cond)
{
$select = 'banner_id, category_id, banner_name, banner_type, banner_img, is_active, url, child_id';
return $this->CI->AdminModel->getCondSelectedData($cond,$select,$this->tableName);
}
function getAllBanner($cond)
{
$select = 'banner_id, category_name, banner_name, banner_type, banner_img, banner_mst.is_active, url, child_name';
$join = [];
$join[] = [ 'table' => 'category_mst', 'on' => 'category_mst.category_id = banner_mst.category_id', 'type' => 'left' ];
$join[] = [ 'table' => 'childcategory_mst', 'on' => 'childcategory_mst.child_id = banner_mst.child_id', 'type' => 'left' ];
return $this->CI->AdminModel->getSelectWithJoinData($cond, $this->tableName, $join, $select);
}
function updateBanner($cond,$newData)
{
return $this->CI->AdminModel->updateData($cond,$newData,$this->tableName);
}
} | true |
8ce3b048514a598bd08836bc338725b753fbf349 | PHP | smurf100/p2 | /Q2/a3-b2.php | UTF-8 | 335 | 2.625 | 3 | [] | no_license | <html>
<body>
<table border ="1" align="center">
<tr><th>File name </th><tr>
<?php
$dir=$_GET["dir"];
$extn=$_GET["ext"];
echo $dir;
echo $extn;
$hndl=opendir($dir);
while(($file=readdir($hndl))!==false)
{
if(strstr($file,$extn))
echo"<tr><td>$file</td></tr>";
}
closedir($hndl);
?>
</table>
</body>
</html> | true |
526a3cb45a0b054c78cc56d840077a409376758c | PHP | Nikuusi/dfc2api-platform | /src/Entity/Categorie.php | UTF-8 | 5,193 | 2.578125 | 3 | [] | no_license | <?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
use Doctrine\ORM\Mapping\ManyToOne;
use Doctrine\ORM\Mapping\OneToMany;
use Gedmo\Mapping\Annotation as Gedmo;
use App\Validator\Constraints as ApiAssert;
/**
* @ApiResource()
* @ORM\Entity(repositoryClass="App\Repository\CategorieRepository")
*/
class Categorie
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(name="old_id", type="integer", nullable=true)
*/
private $oldId;
/**
* @ORM\Column(name="old_id_parent", type="integer", nullable=true)
*/
private $oldIdParent;
/**
* @ORM\Column(type="string", length=255)
*/
private $name;
/**
* @Gedmo\Slug(fields={"name"})
* @ORM\Column(name="slug", type="string", length=190, unique=true)
*/
private $slug;
/**
* @ORM\Column(name="icon", type="string", length=255, nullable=true)
*/
private $icon;
/**
* One Category has Many children Categories.
* @OneToMany(targetEntity="Categorie", mappedBy="parent", cascade={"persist"})
*/
private $children;
/**
* Many ArticleCategories have One parent ArticleCategorie.
* @ManyToOne(targetEntity="Categorie", inversedBy="children", cascade={"persist"})
* @JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
* @ApiAssert\ParentCategorieIsEmpty()
*/
private $parent;
/**
* @ORM\ManyToMany(targetEntity="Article", inversedBy="categories", cascade={"persist"})
* @ORM\JoinTable(name="article_categorie",
* joinColumns={@JoinColumn(name="categorie_id", referencedColumnName="id")},
* inverseJoinColumns={@JoinColumn(name="article_id", referencedColumnName="id")}
* )
*/
private $articles;
public function __construct() {
$this->children = new ArrayCollection();
$this->articles = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getOldId()
{
return $this->oldId;
}
/**
* @param mixed $oldId
*/
public function setOldId($oldId)
{
$this->oldId = $oldId;
return $this;
}
/**
* @return mixed
*/
public function getOldIdParent()
{
return $this->oldIdParent;
}
/**
* @param mixed $oldIdParent
*/
public function setOldIdParent($oldIdParent)
{
$this->oldIdParent = $oldIdParent;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getIcon(): ?string
{
return $this->icon;
}
public function setIcon(string $icon): self
{
$this->icon = $icon;
return $this;
}
/**
* @return mixed
*/
public function getSlug()
{
return $this->slug;
}
/**
* @param mixed $slug
* @return mixed
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* @return Collection|Categorie[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChildren(Categorie $children): self
{
if (!$this->children->contains($children)) {
$this->children[] = $children;
$children->setParent($this);
}
return $this;
}
/**
* @param Categorie $children
* @return Categorie
*/
public function removeChildren(Categorie $children): self
{
if ($this->children->contains($children)) {
$this->children->removeElement($children);
// set the owning side to null (unless already changed)
if ($children->getParent() === $this) {
$children->setParent(null);
}
}
return $this;
}
/**
* @return Categorie
*/
public function getParent()
{
return $this->parent;
}
/**
* @param Categorie $parent
* @return $this
*/
public function setParent(Categorie $parent)
{
$this->parent = $parent;
return $this;
}
/**
* @return Collection|Article[]
*/
public function getArticles(): Collection
{
return $this->articles;
}
public function addArticle(Article $article): self
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
}
return $this;
}
public function removeArticle(Article $article): self
{
if ($this->articles->contains($article)) {
$this->articles->removeElement($article);
}
return $this;
}
}
| true |
8a6e9516a08d89b276b785ae8e45edf33b6d6ebb | PHP | renatocosta/Domain-driven-Design | /CrossCutting/DataManagement/Collection/Items.php | UTF-8 | 337 | 2.765625 | 3 | [] | no_license | <?php
namespace CrossCutting\DataManagement\Collection;
interface Items extends \Countable
{
/**
* @return \Iterator
*/
public function getItems(): \Iterator;
/**
* @param mixed $item
*/
public function add($item): void;
/**
* @return bool
*/
public function isEmpty(): bool;
} | true |
51fa50bd6b647b1fbe554f8672809b8711cb8ffd | PHP | XephorNova/CSI | /admin/view_problems.php | UTF-8 | 1,605 | 2.578125 | 3 | [] | no_license | <?php include('../layout/header.php')?>
<div class="container mt-4 ml-auto mr-auto">
<h3 class="text-center">All Question</h3>
<p class="text-center lead">Below are the Questions created.</p>
<div class="wrap-blog"></div>
</div>
<?php
include('../configuration/database.php');
$one="option_1";
$two="option_2";
$three="option_3";
$four="option_4";
$answer="correct_option";
$getProblems = "SELECT * FROM
`problem_of_the_week_admin`";
$result= mysqli_query($connec,$getProblems);
if($result)
//Fetch one and one row from database
while($row=mysqli_fetch_assoc($result))
{
echo '<div class="container mt-4 ml-auto mr-auto">';
echo '<form method="get" action="view_problems.php" >';
echo '<div class="form-group">';
echo '<label for="problem">Problem: </label>';
echo '<textarea name="problem" class="form-control" disabled>';
echo "$row[problem]";
echo '</textarea>';
echo '</div>';
echo "<ul>";
echo "option-1: "."<li>".$row[$one]."</li>";
echo "Option-2: "."<li>".$row[$two]."</li>";
echo "Option-3: "."<li>".$row[$three]."</li>" ;
echo "Option-4: "."<li>".$row[$four]."</li>";
echo '<div class "text-success>';
echo "Correctoption: "."<li>".$row[$answer]."</li>";
echo '</div>';
echo "</ul>";
echo "</form>";
echo "</div>";
// print_r($array);
}
mysqli_free_result($result);
?>
<?php include('../layout/footer.php') ?>
| true |
3c299916ebcea4b00988e30170be440219c8d1c6 | PHP | ArifKh29/DumbWays | /2.php | UTF-8 | 560 | 2.9375 | 3 | [] | no_license | <?php
$kata = ['D','U','M','B','W','A','I','S','I','D'];
function cetakGambar($kata){
echo "<table>";
$pjg = count($kata);
for($i=0;$i<$pjg;$i++){
echo "<tr>";
for($x=0,$y=$pjg-1;$x<$pjg;$x++,$y--){
if($x==$i||$y==$i){
echo "<td>".$kata[$i]."</td>";
}
else{
echo "<td>"."="."</td>";
}
}
echo "</tr>";
}
echo "</table>";
}
?>
<html>
<body>
<?php
cetakGambar($kata);
?>
</body>
</html> | true |
6018ead73502747b92166efa35fe291182afe7ef | PHP | peterlafferty/silex-request-validation | /index.php | UTF-8 | 1,911 | 2.65625 | 3 | [] | no_license | <?php
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
$app = new Silex\Application();
$app['emoji'] = json_decode('[
{
"id": 1,
"code": "U+1F600",
"value": "😀",
"description": "grinning face",
"hasSkinTone": false
},
{
"id": 2,
"code": "U+1F601",
"value": "😁",
"description": "grinning face with smiling eyes",
"hasSkinTone": false
},
{
"id": 99,
"code": "U+1F466",
"value": "👦",
"description": "boy",
"hasSkinTone": true
},
{
"id": 105,
"code": "U+1F467",
"value": "👧",
"description": "girl",
"hasSkinTone": true
}
]');
/* ignore this hackiness, it makes it simpler to set the headers and escape options*/
class Utf8JsonResponse extends JsonResponse
{
public function __construct($data = null, $status = 200, $headers = array(), $json = false)
{
$headers = array_merge(
["Content-Type" => "application/json; charset=utf-8"],
$headers
);
$this->encodingOptions = JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE;
parent::__construct($data, $status, $headers, $json);
}
}
$app->get('/emoji/', function () use ($app) {
return new Utf8JsonResponse(["emoji" => $app['emoji']]);
});
$app->get('/emoji/{id}', function (int $id) use ($app) {
$filtered = array_filter($app['emoji'], function ($k) use ($id) {
return $k->id == $id;
});
if (empty($filtered)) {
return new Utf8JsonResponse(null, 404);
}
$response = new Utf8JsonResponse(array_pop($filtered));
return $response;
});
$app->post('/emoji/', function (Request $request) use ($app) {
return new Utf8JsonResponse(null, 204);
});
$app->run();
| true |
0a2f0b0bc659b1f54969f12b67948d4b773971b9 | PHP | hugomastromauro/Cataya-PHP | /lib/FMW/Utilities/String/String.php | UTF-8 | 3,287 | 2.8125 | 3 | [] | no_license | <?php
namespace FMW\Utilities\String;
/**
*
* Classe String
*
* @author Hugo Mastromauro <hugomastromauro@gmail.com>
* @version 2.0
* @copyright GPL © 2014, catayaphp.com.
* @access public
* @package String
* @subpackage Utilities
*
*/
class String
extends \FMW\Object {
/**
*
* @param string $text
* @param number $length
* @param string $tail
* @return string
*/
public static function snippet($text, $length=64, $tail="...") {
$text = trim($text);
$txtl = strlen($text);
if($txtl > $length) {
for($i=1;$text[$length-$i]!=" ";$i++) {
if($i == $length) {
return substr($text,0,$length) . $tail;
}
}
$text = substr($text, 0, $length-$i+1) . $tail;
}
return $text;
}
/**
*
* @param string $text
* @param number $length
* @param string $tail
* @return string
*/
public static function snippetgreedy($text, $length=64, $tail="...") {
$text = trim($text);
if(strlen($text) > $length) {
for($i=0;$text[$length+$i]!=" ";$i++) {
if(!$text[$length+$i]) {
return $text;
}
}
$text = substr($text,0,$length+$i) . $tail;
}
return $text;
}
/**
*
* @param string $text
* @param number $length
* @param string $tail
* @return string
*/
public static function snippetwop($text, $length=64, $tail="...") {
$text = trim($text);
$txtl = strlen($text);
if($txtl > $length) {
for($i=1;$text[$length-$i]!=" ";$i++) {
if($i == $length) {
return substr($text, 0, $length) . $tail;
}
}
for(;$text[$length-$i]=="," || $text[$length-$i]=="." || $text[$length-$i]==" ";$i++) {;}
$text = substr($text,0,$length-$i+1) . $tail;
}
return $text;
}
/**
*
* @param string $string
* @param string $enc
* @return string
*/
public static function normalize($string, $enc = "UTF-8") {
$string = html_entity_decode($string, ENT_QUOTES, $enc);
$non = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj', 'Ž'=>'Z', 'ž'=>'z', 'C'=>'C', 'c'=>'c', 'C'=>'C', 'c'=>'c',
'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
'ÿ'=>'y', 'R'=>'R', 'r'=>'r'
);
return strtr(htmlspecialchars($string, ENT_NOQUOTES, $enc), $non);
}
/**
*
* @param string $string
* @param string $enc
* @return mixed
*/
public static function seo($string, $enc = "UTF-8") {
$string = String::normalize($string, $enc);
return preg_replace('/[^a-z0-9_-]/i', '', strtolower(str_replace(' ', '-', trim($string))));
}
} | true |
d922e07cd6eeac9c1de1725a4b09cfddb2971876 | PHP | unl/sitemaster_plugin_unl | /scripts/framework_audit.php | UTF-8 | 5,461 | 2.53125 | 3 | [] | no_license | <?php
use SiteMaster\Plugins\Unl\VersionHistory;
ini_set('display_errors', true);
//Initialize all settings and autoloaders
require_once(__DIR__ . '/../../../init.php');
$sites = new \SiteMaster\Core\Registry\Sites\WithGroup(['group_name'=>'unl']);
$found_versions = array();
$date_of_scan = date("Y-m-d", strtotime('today midnight'));
$csv = array();
$csv[] = array(
'date of report',
'expected HTML version',
'expected DEP version'
);
$helper = new \SiteMaster\Plugins\Unl\FrameworkVersionHelper();
$versions = $helper->getVersions();
$metric = new SiteMaster\Plugins\Unl\Metric('unl');
$csv[] = array(
\SiteMaster\Core\Util::epochToDateTime(),
$versions['html'][0],
$versions['dep'][0]
);
$csv[] = array();
//Headers
$csv[] = array(
'Site URL',
'Site Title',
'HTML Version Found',
'DEP Version Found',
'Template Type Found',
);
function getXPath($url)
{
$parser = new \SiteMaster\Core\Auditor\Parser\HTML5();
$html = @file_get_contents($url);
//Sleep for half a second to prevent flooding
usleep(500000);
if (!$html) {
return false;
}
return $parser->parse($html);
}
foreach ($sites as $site) {
/**
* @var $site \SiteMaster\Core\Registry\Site
*/
$title = html_entity_decode(strip_tags($site->title));
if ($site->production_status != \SiteMaster\Core\Registry\Site::PRODUCTION_STATUS_PRODUCTION) {
//Only export sites that are in production.
continue;
}
echo 'checking: ' . $site->base_url . PHP_EOL;
$xpath = getXPath($site->base_url);
if (!$xpath) {
echo "\tunable to parse" . PHP_EOL;
continue;
}
$dep = $metric->getDEPVersion($xpath);
$html = $metric->getHTMLVersion($xpath);
$type = $metric->getTemplateType($xpath);
//convert null to a string for more accurate array access (php converts a null key to an empty string '')
if (null === $dep) {
$dep = 'null';
}
if (null === $html) {
$html = 'null';
}
if (null === $type) {
$type = 'null';
}
if (!isset($found_versions['dep'][$dep])) {
$found_versions['dep'][$dep] = 0;
}
if (!isset($found_versions['html'][$html])) {
$found_versions['html'][$html] = 0;
}
if (!isset($found_versions['type'][$type])) {
$found_versions['type'][$type] = 0;
}
$found_versions['dep'][$dep]++;
$found_versions['html'][$html]++;
$found_versions['type'][$type]++;
$csv[] = array(
$site->base_url,
str_replace(array("\r","\n"), ' ', $title),
$html,
$dep,
$type
);
}
//Write CSV
$fp = fopen(__DIR__ . '/../files/framework_audit.csv', 'w');
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
//Write DB LOG
foreach ($found_versions['html'] as $html_version=>$num_sites) {
if ($record = VersionHistory::getByDateAndVersion($date_of_scan, VersionHistory::VERSION_TYPE_HTML, $html_version)) {
$record->number_of_sites = $num_sites;
$record->save();
} else {
VersionHistory::createHistoryRecord(VersionHistory::VERSION_TYPE_HTML, $html_version, $num_sites, $date_of_scan);
}
}
foreach ($found_versions['dep'] as $dep_version=>$num_sites) {
if ($record = VersionHistory::getByDateAndVersion($date_of_scan, VersionHistory::VERSION_TYPE_DEP, $dep_version)) {
$record->number_of_sites = $num_sites;
$record->save();
} else {
VersionHistory::createHistoryRecord(VersionHistory::VERSION_TYPE_DEP, $dep_version, $num_sites, $date_of_scan);
}
}
foreach ($found_versions['type'] as $template_type=>$num_sites) {
if ($record = VersionHistory::getByDateAndVersion($date_of_scan, VersionHistory::VERSION_TYPE_TYPE, $template_type)) {
$record->number_of_sites = $num_sites;
$record->save();
} else {
VersionHistory::createHistoryRecord(VersionHistory::VERSION_TYPE_TYPE, $template_type, $num_sites, $date_of_scan);
}
}
//Clean up existing data for the day.
$existing_html = new \SiteMaster\Plugins\Unl\VersionHistory\ByTypeAndDate(array(
'version_type' => VersionHistory::VERSION_TYPE_HTML,
'dates' => array($date_of_scan)
));
foreach ($existing_html as $version_record) {
if (!array_key_exists($version_record->version_number, $found_versions['html'])) {
echo $version_record->version_number . ' was no longer found, deleting...' . PHP_EOL;
$version_record->delete();
}
}
$existing_dep = new \SiteMaster\Plugins\Unl\VersionHistory\ByTypeAndDate(array(
'version_type' => VersionHistory::VERSION_TYPE_DEP,
'dates' => array($date_of_scan)
));
foreach ($existing_dep as $version_record) {
if (!array_key_exists($version_record->version_number, $found_versions['dep'])) {
echo $version_record->version_number . ' was no longer found, deleting...' . PHP_EOL;
$version_record->delete();
}
}
$existing_type = new \SiteMaster\Plugins\Unl\VersionHistory\ByTypeAndDate(array(
'version_type' => VersionHistory::VERSION_TYPE_TYPE,
'dates' => array($date_of_scan)
));
foreach ($existing_type as $version_record) {
if (!array_key_exists($version_record->version_number, $found_versions['type'])) {
echo $version_record->version_number . ' was no longer found, deleting...' . PHP_EOL;
$version_record->delete();
}
}
| true |
35c1ceb874c135517535f5e07fe40cadaa3465cf | PHP | atlance/jwt-auth | /Token/UseCase/Decode/Handler.php | UTF-8 | 1,316 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Atlance\JwtAuth\Token\UseCase\Decode;
use Atlance\JwtAuth\Token\Contracts\Claimset\ClaimsetInterface;
use Atlance\JwtAuth\Token\Contracts\DecodeInterface;
use Atlance\JwtAuth\Token\Factory\ClaimsetFactory;
use Atlance\JwtAuth\Token\Validation\Validator;
use Lcobucci\JWT;
final class Handler implements DecodeInterface
{
public function __construct(private readonly JWT\Parser $parser, private readonly Validator $validator)
{
}
/**
* @psalm-suppress ArgumentTypeCoercion
*
* @param non-empty-string $value
*
* @throws JWT\Encoding\CannotDecodeContent when something goes wrong while decoding
* @throws JWT\Token\InvalidTokenStructure when token string structure is invalid
* @throws JWT\Token\UnsupportedHeaderFound when parsed token has an unsupported header
* @throws JWT\Validation\RequiredConstraintsViolated
* @throws JWT\Validation\NoConstraintsGiven
*/
public function decode(string $value): ClaimsetInterface
{
$token = $this->parser->parse($value);
\assert($token instanceof JWT\UnencryptedToken);
$this->validator->assert($token);
return ClaimsetFactory::create($token->claims()->all()); // @phpstan-ignore-line
}
}
| true |
8f330344c03e25527ac65bd0559d84f2094c1b49 | PHP | iptomar/codematch_11-12 | /Programadores/Scripts/scriptsInsert/yahoo_sourceforge.php | WINDOWS-1252 | 2,557 | 2.859375 | 3 | [] | no_license | <?php
include "APIS/sourceforge.php"; //include da api sourceforge
include "db_insert.php";
//o ciclo while e para ir mudando de pagina
$i=0;
while ($i <= 1000) {
$yahoo_array = get_yahoo_sourceforge(50, $i);
foreach($yahoo_array as $arg) {
list ($name_project, $title, $source, $owner, $language, $created_date, $logo) = $arg;
if (isset($name_project)) {
insert_db($name_project, $title, $source, "Sourceforge", $owner, $language, $created_date, $logo);
// print_r("<b>Project:</b> ".$name_project."<br>");
// print_r("<b>Title:</b> ".$title."<br>");
// print_r("<b>Source:</b> ".$source."<br>");
// print_r("<b>Repository:</b> Sourceforge<br>");
// foreach($owner as $arg_owner) {
// print_r("<b>Owner:</b> ".$arg_owner."<br>");
// }
// foreach($language as $arg_lang) {
// print_r("<b>Languages:</b> ".$arg_lang."<br>");
// }
// print_r("<b>Date Created:</b> ".$created_date[0]."<br>");
// print_r("<b>Date Updated:</b> ".$created_date[1]."<br>");
// print_r("<b>Logo:</b> <img src='".$logo."'><br><hr><br>");
}
}
$i=$i+50;
}
print_r("Done Yahoo Sourceforge ".date("Y-m-d")."\n");
// Parametros:
// - n/a
// Retorna:
// - array() (retorna array com os dados do get_project_sourceforge)
function get_yahoo_sourceforge($lenght, $offset) {
$thequery = urlencode('"http://sourceforge.net/projects/"');
$apikey = 'po6V4W7IkY2t6hn8Ab51nFT_HKtEocokU.E-';
$url = 'http://boss.yahooapis.com/ysearch/web/v1/'.$thequery.'?&sites=sourceforge.net&format=json&count='.$lenght.'&appid='.$apikey.'&start='.$offset.'';
$ch = @curl_init(); //inicia uma nova sessao
curl_setopt($ch, CURLOPT_URL, $url); //faz a pesquisa contida no url
curl_setopt($ch, CURLOPT_USERAGENT, 'Googlebot/2.1'); //utiliza Googlebot 2.1
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //define o retorno como string
$page = curl_exec($ch); //executa as opcoes definidas
curl_close($ch); //encerra sessao
$yahoo_json = json_decode($page); //descodifica string JSON
$yahoo_array = array(); //cria o array
foreach($yahoo_json->ysearchresponse->resultset_web as $arg) {
//retira o nome do utilizador atraves do URL
preg_match("/http:\/\/([A-Za-z0-9-_]*).*/", $arg->url, $match);
// $match = preg_split('@[/]@', $arg->title, -1);
if ((isset($match[1])) && ($match[1]!="sourceforge")) {
//match[1] = utilizador
array_push($yahoo_array, get_project_sourceforge($match[1])); //adiciona os projectos ao array
}
}
unset($yahoo_array[0]); //remove 1 posicao em branco
return (array)$yahoo_array;
}
?> | true |
6e67b1d409aa20fd2178f583b3f960449b9111a6 | PHP | siddhichechani22/Learn-on-the-Go---Smart-Learning-Management-System | /oopm1.php | UTF-8 | 1,998 | 2.828125 | 3 | [] | no_license | <?php
//OOPM1 no of students appeared
$sql="SELECT count(*) as count FROM student.stud_termtest WHERE oopm1 >=0 AND oopm1 <=20";
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) > 0) {
// output data of each row
if($row = mysql_fetch_assoc($result))
$oopm1_A= $row['count'];
} else
$oopm1_A="0";
//OOPM1 no of students absent
$sql="SELECT count(*) as count FROM student.stud_termtest WHERE oopm1 ='NULL'";
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) > 0) {
// output data of each row
if($row = mysql_fetch_assoc($result))
$oopm1_B= $row['count'];
} else
$oopm1_B="0";
//oopm1 no of students passed
$sql="SELECT count(*) as count FROM student.stud_termtest WHERE oopm1 >=8";
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) > 0) {
// output data of each row
if($row = mysql_fetch_assoc($result))
$oopm1_C= $row['count'];
} else
$oopm1_C="0";
// oopm1 no of students between 60% - 70%
$sql="SELECT count(*) as count FROM student.stud_termtest WHERE oopm1 >=12 AND oopm1 <=14";
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) > 0) {
// output data of each row
if($row = mysql_fetch_assoc($result))
$oopm1_D= $row['count'];
} else
$oopm1_D="0";
//oopm1 no of students above 70%
$sql="SELECT count(*) as count FROM student.stud_termtest WHERE ds1 >14 ";
$result = mysql_query($sql,$conn);
if (mysql_num_rows($result) > 0) {
if($row = mysql_fetch_assoc($result))
$oopm1_E= $row['count'];
} else
$oopm1_E="0";
//oopm1 u-percent of students passed
$oopm1_F=($oopm1_C/$oopm1_A)*100;
//oopm1 -percent of students between 60 to 70 percent
$oopm1_G=($oopm1_D/$oopm1_A)*100;
//oopm1 u-percent of students above 70 percent
$oopm1_H=($oopm1_E/$oopm1_A)*100;
?> | true |
bf2d2bb8f96d31cfa9a3acddd6ed9f727452b477 | PHP | neitanod/dotfiles | /bin/template | UTF-8 | 934 | 2.890625 | 3 | [] | no_license | #! env php
<?php
$optind = null;
$opts = getopt('h', [], $optind);
$pos_args = array_slice($argv, $optind);
// var_dump($opts); // options are here
// var_dump($pos_args); // postional arguments are here
if( isset($opts['h']) ) {
echo <<<HERE
template:
Transform input lines using a template string.
Use {@} to mark the places where input should be used in the template.
Example:
ls | template "mv {@} tmpfile && mkdir {@} && mv tmpfile {@}/{@}" > move.sh
HERE;
die();
}
if( !isset($pos_args[0]) ) {
$template = "{@}";
} else {
$template = json_decode('["'.$pos_args[0].'"]');
$template = $template[0];
}
$f = fopen( 'php://stdin', 'r' );
while ($line = fgets($f)) {
$line = nolf($line);
echo str_replace("{@}", $line, $template)."\n";
}
fclose($f);
function nolf($line) {
if (substr( $line , -1 ) == "\n") {
return substr( $line, 0 , -1 );
}
return $line;
}
| true |
d8add21a0141a65b05b8ba46b9dd2518ad75ce88 | PHP | CTA-K12/RuleBundle | /Entity/ConditionEntity.php | UTF-8 | 2,487 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace Mesd\RuleBundle\Entity;
/**
* ConditionEntity.
*/
class ConditionEntity
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $operator_value;
/**
* @var string
*/
private $raw_input_value;
/**
* @var \Mesd\RuleBundle\Entity\AttributeEntity
*/
private $attribute;
/**
* @var \Mesd\RuleBundle\Entity\ConditionCollectionEntity
*/
private $collection;
/**
* Get id.
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set operator_value.
*
* @param string $operatorValue
*
* @return ConditionEntity
*/
public function setOperatorValue($operatorValue)
{
$this->operator_value = $operatorValue;
return $this;
}
/**
* Get operator_value.
*
* @return string
*/
public function getOperatorValue()
{
return $this->operator_value;
}
/**
* Set raw_input_value.
*
* @param string $rawInputValue
*
* @return ConditionEntity
*/
public function setRawInputValue($rawInputValue)
{
$this->raw_input_value = $rawInputValue;
return $this;
}
/**
* Get raw_input_value.
*
* @return string
*/
public function getRawInputValue()
{
return $this->raw_input_value;
}
/**
* Set attribute.
*
* @param \Mesd\RuleBundle\Entity\AttributeEntity $attribute
*
* @return ConditionEntity
*/
public function setAttribute(\Mesd\RuleBundle\Entity\AttributeEntity $attribute = null)
{
$this->attribute = $attribute;
return $this;
}
/**
* Get attribute.
*
* @return \Mesd\RuleBundle\Entity\AttributeEntity
*/
public function getAttribute()
{
return $this->attribute;
}
/**
* Set collection.
*
* @param \Mesd\RuleBundle\Entity\ConditionCollectionEntity $collection
*
* @return ConditionEntity
*/
public function setCollection(\Mesd\RuleBundle\Entity\ConditionCollectionEntity $collection = null)
{
$this->collection = $collection;
return $this;
}
/**
* Get collection.
*
* @return \Mesd\RuleBundle\Entity\ConditionCollectionEntity
*/
public function getCollection()
{
return $this->collection;
}
}
| true |
6e775181820e725ef96d9d9039645f05fcf78d86 | PHP | Kaapiii/concrete5_storage_locations | /src/Concrete/File/StorageLocation/Configuration/AwsS3Configuration.php | UTF-8 | 6,461 | 2.609375 | 3 | [] | no_license | <?php
namespace Concrete\Package\Concrete5StorageLocations\File\StorageLocation\Configuration;
use Aws\S3\S3Client;
use Concrete\Core\File\StorageLocation\Configuration\ConfigurationInterface;
use Concrete\Core\File\StorageLocation\Configuration\Configuration;
use Concrete\Core\Error\ErrorList\ErrorList;
use Concrete\Core\Error\ErrorList\Error\Error;
use Concrete\Core\Http\Request;
use League\Flysystem\AdapterInterface;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
/**
* Class AwsS3Configuration
*/
class AwsS3Configuration extends Configuration implements ConfigurationInterface
{
/**
* S3 access key
*
* @var string
*/
private $accessKey;
/**
* S3 secret key
*
* @var string
*/
private $secret;
/**
* S3 bucket name
*
* @var string
*/
private $bucketName;
/**
* S3 bucket region
*
* @var string
*/
private $region;
/**
* S3 API version
*
* @var string
*/
private $version;
/**
* Get the AWS S3 Adapter
*
* @return AdapterInterface|AwsS3Adapter
*/
public function getAdapter()
{
$client = new S3Client([
'credentials' => [
'key' => $this->accessKey,
'secret' => $this->secret,
],
'region' => $this->region,
'version' => $this->version, // or "latest"
//'profile' => 'default', #if enabled - the library searches for credentials in {webserver_root}/.aws/credentials
]);
$bucket = 'mbt-public-media';
return new AwsS3Adapter($client, $bucket);
}
/**
* @return bool
*/
public function hasPublicURL()
{
return true;
}
/**
* @param string $file
* @return string
*/
public function getPublicURLToFile($file)
{
return $this->getBucketUrl().$file;
}
/**
* Needs to be true, otherwise the thumbnails won't show up in the file manager
*
* @return bool
*/
public function hasRelativePath()
{
return false;
}
/**
* Relative paths needs to be prefixed with external url
*
* @param string $file
* @return string
*/
public function getRelativePathToFile($file)
{
return $this->getBucketUrl().$file;
}
/**
* Used on the add and update view
*
* @param Request $req
*/
public function loadFromRequest(Request $req)
{
$config = $req->get('storageLocationConfig');
$this->bucketName = $config['bucketName'];
$this->accessKey = $config['accessKey'];
$this->secret = $config['secret'];
$this->region = $config['region'];
$this->version = $config['version'];
}
/**
* Validate a request, this is used during saving
*
* @param Request $req
* @return Error|void
*/
public function validateRequest(Request $req)
{
$error = new ErrorList();
$config = $req->get('storageLocationConfig');
$this->bucketName = $config['bucketName'];
$this->accessKey = $config['accessKey'];
$this->secret = $config['secret'];
$this->region = $config['region'];
$this->version = $config['version'];
// Check for required settings
if(!$this->bucketName) {
$error->add(t('Please provide an AWS S3 bucket name.'));
} else if(!$this->accessKey) {
$error->add(t('Please provide a AWS S3 access key'));
} else if(!$this->secret) {
$error->add(t('Please provide a AWS S3 secret key.'));
} else if(!$this->version) {
$error->add(t('Please provide a AWS S3 API version.'));
}
}
public function getAccessKey()
{
return $this->accessKey;
}
public function getSecret()
{
return $this->secret;
}
public function getBucketName()
{
return $this->bucketName;
}
public function getRegion()
{
return $this->region;
}
public function getVersion()
{
return $this->version;
}
/**
* Get supported AWS S3 Regions
* Up to date regions: https://docs.aws.amazon.com/en_en/general/latest/gr/rande.html
*
* @return array
*/
public function getRegions()
{
$regions = array(
"" => "Default (empty)",
"us-east-2" => "US East (Ohio)",
"us-east-1" => "US East (N. Virginia)",
"us-west-1" => "US West (N. California)",
"us-west-2" => "US West (Oregon)",
//"ap-east-1" => "Asia Pacific (Hong Kong)***",
"ap-south-1" => "Asia Pacific (Mumbai)",
//"ap-northeast-3" => "Asia Pacific (Osaka-Local)****",
"ap-northeast-2" => "Asia Pacific (Seoul)",
"ap-southeast-1" => "Asia Pacific (Singapore)",
"ap-southeast-2" => "Asia Pacific (Sydney)",
"ap-northeast-1" => "Asia Pacific (Tokyo)",
"ca-central-1" => "Canada (Central)",
"cn-north-1" => "China (Beijing)",
"cn-northwest-1" => "China (Ningxia)",
"eu-central-1" => "EU (Frankfurt)",
"eu-west-1" => "EU (Ireland)",
"eu-west-2" => "EU (London)",
"eu-west-3" => "EU (Paris)",
"eu-north-1" => "EU (Stockholm)",
"sa-east-1" => "South America (São Paulo)",
"me-south-1" => "Middle East (Bahrain)",
);
// ***You must enable this Region before you can use it.
// ****You can use the Asia Pacific (Osaka-Local) Region only in conjunction with the Asia Pacific
// (Tokyo) Region. To request access to the Asia Pacific (Osaka-Local) Region, contact your sales representative.
return $regions;
}
/**
* Get the Rest API Version
*
* @return array
*/
public function getApiVersions()
{
$version = array(
"2006-03-01" => "2006-03-01 (default)",
"latest" => "latest",
);
return $version;
}
/**
* Build the bucket URL
*
* @return string
*/
protected function getBucketUrl()
{
return 'https://'.$this->bucketName.'.s3.'.($this->region ? $this->region : '').'.amazonaws.com';
}
}
| true |
7934ed3feacc0f2cd0cb80d46642b39cb422dfef | PHP | FriendsOfFlarum/prevent-necrobumping | /src/Util.php | UTF-8 | 1,177 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of fof/prevent-necrobumping.
*
* Copyright (c) FriendsOfFlarum.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FoF\PreventNecrobumping;
use Flarum\Discussion\Discussion;
use Flarum\Settings\SettingsRepositoryInterface;
class Util
{
public static function getDays(SettingsRepositoryInterface $settings, Discussion $discussion): ?int
{
$days = $settings->get('fof-prevent-necrobumping.days');
$tags = $discussion->tags;
if ($tags && $tags->isNotEmpty()) {
$tagDays = $tags->map(function ($tag) use ($settings) {
return $settings->get("fof-prevent-necrobumping.days.tags.{$tag->id}");
})->filter(function ($days) {
return $days != null && $days != '' && !is_nan($days) && (int) $days >= 0;
});
if ($tagDays->isNotEmpty()) {
$days = $tagDays->contains(0)
? null
: $tagDays->min();
}
}
return is_nan($days) || $days < 1 ? null : (int) $days;
}
}
| true |
30500dbbb8e64a25d89b482700f67b9037af4b89 | PHP | hu19891110/cms-2 | /upload/CMS/Core/Validator/LinkedinProfile.php | UTF-8 | 2,246 | 2.953125 | 3 | [] | no_license | <?php
namespace Core\Validator;
/**
* @category Modo
* @package Validator
* @copyright Copyright (c) 2010 Modo Design Group (http://mododesigngroup.com)
* @version $Id: LinkedinProfile.php 528 2010-03-30 13:43:19Z court $
*/
class LinkedinProfile extends \Zend_Validate_Abstract
{
const INVALID_URL = 'invalidUrl';
const TOO_LONG = 'tooLong';
const NOT_LINKEDIN = 'notLinkedin';
/**
* Error messages
*
* @var array
*/
protected $_messageTemplates = array(
self::INVALID_URL => "'%value%' is not a valid url",
self::NOT_LINKEDIN => "'%value%' is not a valid linkedin profile",
self::TOO_LONG => "Linkedin profile must be no more than 255 characters"
);
/**
* Domain to validate against
*
* @var string
*/
protected $_domain = 'linkedin.com';
/**
* Is $value a valid facebook profile link
*
* @param string $value
* @param array $context
* @return boolean
*/
public function isValid($value, array $context = array())
{
$valueString = (string) $value;
$this->_setValue($valueString);
if ((!$uri = $this->_getUri($valueString)) || !$uri->valid()) {
$this->_error(self::INVALID_URL);
return false;
}
$path = trim($uri->getPath(), '/');
$query = $uri->getQuery();
$domain = $uri->getHost();
if (0 === strpos($domain, 'www.')) {
$domain = substr($domain, 4);
}
if ($domain != $this->_domain || ($path == '' && $query == '')) {
$this->_error(self::NOT_LINKEDIN);
return false;
}
$lengthValidator = new \Zend_Validate_StringLength(array('max' => 255));
if (!$lengthValidator->isValid($valueString)) {
$this->_error(self::TOO_LONG);
return false;
}
return true;
}
/**
* Get the uri
*
* @param string $value
* @return \Zend_Uri_Http
*/
protected function _getUri($value)
{
try {
$uri = \Zend_Uri::factory($value);
} catch (\Exception $e) {
return false;
}
return $uri;
}
} | true |
3bc22c383592081764591da30e603fe103ddb9c0 | PHP | GreyInori/sup | /application/user/model/UserModel.php | UTF-8 | 4,413 | 2.5625 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: admin
* Date: 2019/11/11
* Time: 13:42
*/
namespace app\user\model;
use think\Db;
/**
* 用户相关model类
* @package app\user\model
*/
class UserModel extends Db
{
/**
* 用户登录查询方法
* @param $field
* @param $where
* @return false|\PDOStatement|string|\think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function getUserMain($field, $where)
{
$list = self::table('hy_user')
->alias('hu')
->join('hy_department hd','hd.user_mobile = hu.user_mobile','left')
->where($field, $where)
->field(['user_id','hu.user_mobile','user_cut_time','admin_role','department_id','department_name'])
->select();
return $list;
}
/**
* 执行用户数据修改方法
* @param $where
* @param $update
* @return int|string
* @throws \think\Exception
* @throws \think\exception\PDOException
*/
public static function userEdit($where, $update)
{
$list = self::table('hy_user')
->alias('hu')
->where($where)
->update($update);
return $list;
}
/**
* 查询部门方法
* @param $field
* @param $where
* @return false|\PDOStatement|string|\think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function findDepartment($field, $where)
{
$list = self::table('hy_department')
->where($field, $where)
->select();
return $list;
}
/**
* 查询单位列表数据并进行分页方法
* @param $where
* @param $page
* @return array
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function fetchDepartmentList($where, $page = array(0, 200))
{
$list = self::table('hy_department')
->where($where)
->limit($page[0],$page[1])
->field(['department_id','department_name','user_mobile'])
->select();
$count = self::table('hy_department')
->where($where)
->count();
$result = array(
'list' => $list,
'count' => ceil($count/$page[1])
);
return $result;
}
/**
* 执行单位修改操作
* @param $where
* @param $update
* @return array|string
*/
public static function doEditDepartment($where, $update)
{
try{
$update = self::table('hy_department')
->where($where)
->update($update);
return array('update' => $update);
}catch(\Exception $e) {
return $e->getMessage();
}
}
/**
* 判断用户是否为部门管理员方法
* @param $mobile
* @return false|\PDOStatement|string|\think\Collection
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function isDepartment($mobile)
{
$list = self::table('hy_department')
->where('user_mobile',$mobile)
->field(['department_id'])
->select();
return $list;
}
/**
* 用户创建方法
* @param $mobile
* @return int|string
*/
public static function createUser($mobile)
{
$id = self::table('hy_user')->insertGetId($mobile);
return $id;
}
/**
* 创建部门方法
* @param $data
* @return array|string
*/
public static function createDepartment($data)
{
try{
$id = self::table('hy_department')->insertGetId($data);
return array('department' => $id);
}catch(\Exception $e) {
return $e->getMessage();
}
}
public static function getUserMeeting()
{
}
} | true |
e8325a6e5024b0a74bbe1c1f7d4270a1f64d8e49 | PHP | MauricioBuzata/Vaga-Trabalho | /adm/Salas.php | UTF-8 | 1,549 | 2.6875 | 3 | [] | no_license | <?php
if((!isset ($_SESSION['Nome']) == true) and (!isset ($_SESSION['Senha']) == true))
{
unset($_SESSION['Nome']);
unset($_SESSION['Senha']);
header('location:login.php');
}
?>
<?php
if(isset($_GET['msg'])){
$msg = $_GET['msg'];
if($msg==0)
{
?>
<h4 id="cor">Sala excluida com sucesso!</h4>
<?php
}
if($msg==1)
{
?>
<h4 id="cor">Sala criada com sucesso!</h4>
<?php
}
}
?>
<?php
include '../cls/salasClass.php';
include '../cls/conexaoClass.php';
?>
<?php
$sala = new salasClass();
$sala -> mostrar();
?>
<div>
<?php
if ($_SESSION['Nome']=='adm' AND $_SESSION['Senha']=='adm'){
?>
<h4><a href="?b=si">Nova</a></h4>
<?php
}
?>
</div>
<table class='tabela'>
<?php
$limitePorLinha=0;
$result = $sala -> getConsulta();
while($linha = $result -> fetch_assoc())
{
$limitePorLinha++;
if($limitePorLinha%6==0){
?>
<tr>
<td>
<?php echo"<br>";?>
</td>
</tr>
<tr>
<td id="td">
<a href="?b=se&IdSala=<?php echo $linha['IdSala'];?>"><img src="../img/sala.jpg"/></a>
<br>
<a href="?b=se&IdSala=<?php echo $linha['IdSala'];?>"><?php echo $linha['NomeSala'];?></a>
<br>
</td>
<?php
}
else{
?>
<td id="td">
<a href="?b=se&IdSala=<?php echo $linha['IdSala'];?>"><img src="../img/sala.jpg"/></a>
<br>
<a href="?b=se&IdSala=<?php echo $linha['IdSala'];?>"><?php echo $linha['NomeSala'];?></a>
<br>
</td>
<?php
}
if($limitePorLinha%5==0){
?>
</tr>
<?php
}
}
?>
</table>
| true |
966ae7c90af2bcc84a937283b33a82044a78ef52 | PHP | Sywooch/golodniy-lev | /frontend/widgets/MainPageReceipts.php | UTF-8 | 821 | 2.625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace frontend\widgets;
use frontend\repositories\ReceiptsRepository;
use yii\base\Widget;
/**
* Main page receipts widget.
*
* @author Pak Sergey
*/
class MainPageReceipts extends Widget {
/** @var ReceiptsRepository */
protected $repository;
/**
* @inheritDoc
*
* @author Pak Sergey
*/
public function __construct(ReceiptsRepository $repository, $config = []) {
$this->repository = $repository;
parent::__construct($config);
}
/**
* @inheritDoc
*
* @author Pak Sergey
*/
public function run() {
$receipts = $this->repository->getAll(12);
if (count($receipts) === 0) {
return '';
}
return $this->render('main-page-receipts', compact('receipts'));
}
}
| true |
f4d488a48a3c5e925f5a64df8c32d70ea1282f0a | PHP | jackyliang/Schedulizer | /database/migrations/2015_07_13_143604_create_classes_table.php | UTF-8 | 1,724 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateClassesTable extends Migration {
/**
* Run the migrations.
* This adds in the `classes` table that saves the scraped information
* from TMS (Drexel Term Master Schedule)
*
* @return void
*/
public function up()
{
Schema::create('classes', function(Blueprint $table)
{
$table->integer('year')->nullable();
$table->text('term')->nullable();
$table->text('subject_code')->nullable();
$table->text('course_no')->nullable();
$table->text('instr_type')->nullable();
$table->text('instr_method')->nullable();
$table->text('section')->nullable();
$table->integer('crn')->unique();
$table->primary('crn');
$table->text('course_title')->nullable();
$table->float('credits')->nullable();
$table->text('day')->nullable();
$table->text('time')->nullable();
$table->text('instructor')->nullable();
$table->text('campus')->nullable();
$table->integer('max_enroll')->nullable();
$table->integer('enroll')->nullable();
$table->text('building')->nullable();
$table->text('room')->nullable();
$table->text('description')->nullable();
$table->text('pre_reqs')->nullable();
$table->text('co_reqs')->nullable();
$table->timestamp('timestamp')->default(DB::raw('CURRENT_TIMESTAMP'))->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('classes');
}
}
| true |
4555e8508f26ea1e3a8998c6e92379e8f1556bf3 | PHP | robert-the-bruce/movies | /src/show_movie.php | UTF-8 | 1,009 | 2.53125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: regin
* Date: 02.01.2018
* Time: 15:08
*/
?>
<div class="row">
<div class="four columns">
<h4>Aktuelle Filmliste</h4>
</div>
<div class="seven columns">
<div class="movielist">
<?php
try {
$query = 'select
gen_name as "Genre",
CONCAT_WS(" ", move_title_1, move_title_2) as "Filmtitel",
mov_year as "Jahr",
CONCAT_WS(" ", per_fname, per_secname, per_lname) as "Regie"
from movie
left join genre using(gen_id)
left join movie_director using(mov_id)
left join person using(per_id)
group by Filmtitel
order by Filmtitel;';
$stmt = $con->GetStatement($query);
$con->ShowTable($stmt);
} catch (exception $e) {
echo $e->getMessage();
}
?>
</div>
</div>
</div>
| true |
b185ec49fa3e94bae0ca669916bcec21b5dcc058 | PHP | kitdelivery/sdk-kit-api | /src/Model/Request/Order/GetListOrderRequest.php | UTF-8 | 1,512 | 2.734375 | 3 | [] | no_license | <?php
namespace service\KitAPI\Model\Request\Order;
use service\KitAPI\Interfaces\RequestInterface;
use service\KitAPI\Component\FormData\Mapping as Form;
class GetListOrderRequest implements RequestInterface
{
/**
* @var string
*
* @Form\SerializedName("date_start")
* @Form\Type("string")
*/
public $date_start;
/**
* @var string
*
* @Form\SerializedName("date_end")
* @Form\Type("string")
*/
public $date_end;
/**
* @var int
*
* @Form\SerializedName("limit")
* @Form\Type("int")
*/
public $limit;
/**
* @var int
*
* @Form\SerializedName("offset")
* @Form\Type("int")
*/
public $offset;
/**
* @var int
*
* @Form\SerializedName("profile_id")
* @Form\Type("int")
*/
public $profile_id;
/**
* @param string $date_start
* @param string $date_end
* @param int|null $limit
* @param int|null $offset
* @param int|null $profile_id
*/
public function __construct(string $date_start, string $date_end, ?int $limit = null, ?int $offset = null, ?int $profile_id = null)
{
$this->date_start = $date_start;
$this->date_end = $date_end;
if ($limit !== null) {
$this->limit = $limit;
}
if ($offset !== null) {
$this->offset = $offset;
}
if ($profile_id !== null) {
$this->profile_id = $profile_id;
}
}
} | true |
463d13027fbe4f181415fc48f3045cd8282ff39b | PHP | joy2323/iot-RealTime-Network-Monitoring- | /database/migrations/2020_02_19_011741_create_powers_table.php | UTF-8 | 1,756 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePowersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('powers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('serial_number');
$table->string('current_power')->default('0000.00');
$table->string('power_hourly')->default('0000.00');
$table->string('power_daily')->default('0000.00');
$table->string('power_weekly')->default('0000.00');
$table->string('power_monthly')->default('0000.00');
$table->string('power_yearly')->default('0000.00');
$table->string('hour')->default(date('H'));
$table->string('day')->default(date('d'));
$table->string('week')->default(date('w'));
$table->string('month')->default(date('m'));
$table->string('year')->default(date('Y'));
$table->string('countperhr')->default('0');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')
->onDelete('cascade')
->onUpdate('cascade');
$table->unsignedBigInteger('site_id');
$table->foreign('site_id')->references('id')->on('sites')
->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('powers');
}
}
| true |
6044a15354fca59c65d31d320c5e10f9521056bb | PHP | minhliem86/lawyer | /app/myLib/TachchuoiImg.php | UTF-8 | 167 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
class TachchuoiImg {
public static function make($chuoi,$kytu,$vitricanlay){
$mang = explode($kytu,$chuoi);
$str = $mang[$vitricanlay];
return $str;
}
} | true |
9c0455f05c4f8adad1e6192637d70cdc0d2bd866 | PHP | Jasmine-Alamassi/socail | /app/Http/Controllers/Api/UserController.php | UTF-8 | 6,059 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
/*
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
class UserController extends Controller
{
public function login(Request $request)
{
$proxy = Request::create(
'oauth/token',
'POST'
);
$response = Route::dispatch($proxy);
$response = json_decode($response->getContent());
$token = $response;
$proxy = Request::create(
'api/user',
'get'
);
$proxy->headers->set('Authorization', 'Bearer '.$token->access_token);
$response = Route::dispatch($proxy);
$user = json_decode($response->getContent());
$data = [
'token' => $token,
'user' => $user,
];
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $data]);
}
public function refreshToken(Request $request)
{
$proxy = Request::create(
'oauth/token',
'POST'
);
$response = Route::dispatch($proxy);
$response = json_decode($response->getContent());
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $response]);
}
public function getUser($user_id = null)
{
if (isset($user_id)) {
$user = User::find($user_id);
} else
$user = auth()->user();
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $user]);
}
public function postUser(Request $request)
{
$user = new User();
// $user->fname = $request->get('fname');
$user->lname = $request->get('name');
// $user->phone = $request->get('phone');
$user->email = $request->get('email');
$user->password = bcrypt($request->get('password'));
$user->save();
return response()->json(true);
}
public function putUser(Request $request)
{
$user = User::find(auth()->user()->id);
$user->fname = $request->get('fname');
$user->lname = $request->get('lname');
$user->phone = $request->get('phone');
$user->email = $request->get('email');
$user->password = bcrypt($request->get('password'));
$user->save();
return response()->json(true);
}
}
*/
namespace App\Http\Controllers\Api;
use App\ApiCode;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Requests\ResetPasswordRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Password;
class AuthController extends Controller
{
public function register(Request $request)
{
$validateData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required|max:1000'
]);
$validateData['password'] = bcrypt($request->password);
$user = User::create($validateData);
$accessToken = $user->createToken('authToken')->accessToken; ///authToken تم تسمية الtoken باي اسم
return response(['user' => $user, 'access_token' => $accessToken]);
}
/**
* @throws \Exception
*/
public function login(Request $request)
{
$proxy = Request::create(
'oauth/token',
'POST'
);
// $response = app()->handle($proxy);
$response = Route::dispatch($proxy);
$token = json_decode($response->getContent());
$request->headers->set('Authorization', 'Bearer' . $token->access_token);
$proxy = Request::create(
'api/user',
'get'
);
// $response = app()->handle($proxy);
$response = Route::dispatch($proxy);
$user = json_decode($response->getContent());
$data = [
'token' => $token,
'user' => $user,
];
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $data]);
}
public function refreshToken(Request $request)
{
$proxy = Request::create(
'oauth/token',
'POST'
);
$response = Route::dispatch($proxy);
$response = json_decode($response->getContent());
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $response]);
}
public function getUser($user_id = null)
{
if (isset($user_id)) {
$user = User::find($user_id);
} else
$user = auth()->user();
return response()->json(['status' => true, 'statusCode' => 200, 'message' => 'Success', 'items' => $user]);
}
public function forgotPassword(Request $request): \Illuminate\Http\JsonResponse
{
$credentials = $request->validate(['email' => 'required|email']);
Password::sendResetLink($credentials);
return response()->json(["message" => 'If an account with the corresponding e-mail exists a password reset link will be send to the provided address.'], 200);
}
public function reset(ResetPasswordRequest $request)
{
$reset_password_status = Password::reset($request->validated(), function ($user, $password) {
$user->password = $password;
$user->save();
});
if ($reset_password_status == Password::INVALID_TOKEN) {
return $this->respondBadRequest(ApiCode::INVALID_RESET_PASSWORD_TOKEN);
}
return $this->respondWithMessage("Password has been successfully changed");
}
private function respondBadRequest($INVALID_RESET_PASSWORD_TOKEN)
{
}
private function respondWithMessage(string $string)
{
}
}
| true |
a9ba4796aad39eaecb301c341960733e4d9334ed | PHP | andrewroth/c4c_intranet | /modules/app_Rad/objects_bl/page_ViewModule.php | UTF-8 | 6,938 | 2.6875 | 3 | [] | no_license | <?php
/**
* @package RAD
*/
/**
* class page_ViewModule
* <pre>
* This page displays the details of the selected Module.
* </pre>
* @author Johnny Hausman
* Date: 17 Jan 2005
*/
class page_ViewModule {
//CONSTANTS:
/** The Querystring Field for which entry is currently being edited ... */
const MULTILINGUAL_PAGE_KEY = 'page_ViewModule';
//VARIABLES:
/** @var [OBJECT] The viewer object. */
protected $viewer;
/** @var [STRING] The path to this module's root directory. */
protected $pathModuleRoot;
/** @var [OBJECT] The labels object for this page of info. */
protected $labels;
/** @var [ARRAY] The links used on this page. */
protected $links;
/*[RAD_SYSVAR_VAR]*/
/** @var [INTEGER] Desired Region ID to view Applications for. */
// protected $regionID;
/*[RAD_DAOBJ_VAR]*/
/** @var [OBJECT] The Module Manager Object. */
protected $dataManager;
/** @var [OBJECT] The list of state variables for this module. */
protected $listStateVar;
/** @var [OBJECT] The list of Data Access Objects for this module. */
protected $listDAObjects;
/** @var [OBJECT] The list of Page Objects for this module. */
protected $listPageObjects;
/** @var [OBJECT] The list of Transitions for this module. */
protected $listTransitions;
//CLASS CONSTRUCTOR
//************************************************************************
/**
* function __construct
* <pre>
* Initialize the object.
* </pre>
* @param $pathModuleRoot [STRING] The path to the module's root dir.
* @param $viewer [OBJECT] The viewer object.
* @param $moduleID [INTEGER] The module ID of the module we are viewing.
//[RAD_DAOBJ_INIT_VAR_DOC]
* @return [void]
*/
function __construct($pathModuleRoot, $viewer, $moduleID )
{
$this->pathModuleRoot = $pathModuleRoot;
$this->viewer = $viewer;
$this->links = array();
/*[RAD_DAOBJ_INIT_VAR_SAVE]*/
// $this->regionID = $regionID;
$this->dataManager = new RowManager_ModuleManager( $moduleID );
// now initialize the labels for this page
// start by loading the default field labels for this Module
$languageID = $viewer->getLanguageID();
$seriesKey = moduleRAD::MULTILINGUAL_SERIES_KEY;
$pageKey = moduleRAD::MULTILINGUAL_PAGE_FIELDS;
$this->labels = new XMLObject_MultilingualManager( $languageID, $seriesKey, $pageKey );
$this->listStateVar = new StateVarList( $moduleID );
$this->listDAObjects = new DAObjList( $moduleID );
$this->listPageObjects = new PageList( $moduleID );
$this->listTransitions = new TransitionsList( $moduleID );
// then load the page specific labels for this page
$pageKey = page_ViewModule::MULTILINGUAL_PAGE_KEY;
$this->labels->loadPageLabels( $seriesKey, $pageKey );
$this->labels->loadPageLabels( SITE_LABEL_SERIES_SITE, SITE_LABEL_PAGE_FORM_LINKS );
}
//CLASS FUNCTIONS:
//************************************************************************
/**
* function classMethod
* <pre>
* [classFunction Description]
* </pre>
* <pre><code>
* [Put PseudoCode Here]
* </code></pre>
* @param $param1 [$param1 type][optional description of $param1]
* @param $param2 [$param2 type][optional description of $param2]
* @return [returnValue, can be void]
*/
function classMethod($param1, $param2)
{
// CODE
}
//************************************************************************
/**
* function loadFromForm
* <pre>
* mimiks the loading from a form.
* </pre>
* @return [void]
*/
function loadFromForm()
{
}
//************************************************************************
/**
* function isDataValid
* <pre>
* Verifies the returned data is valid.
* </pre>
* @return [BOOL]
*/
function isDataValid()
{
return true;
}
//************************************************************************
/**
* function processData
* <pre>
* Processes the steps needed to create the current module.
* </pre>
* @return [void]
*/
function processData()
{
// store values in table manager object.
$moduleID = $this->dataManager->getModuleID();
$moduleCreator = new ModuleCreator( $moduleID, $this->pathModuleRoot);
$moduleCreator->createModule();
} // end processData()
//************************************************************************
/**
* function getHTML
* <pre>
* This method returns the HTML data generated by this object.
* </pre>
* @return [STRING] HTML Display data.
*/
function getHTML()
{
// Make a new Template object
$this->template = new Template( $this->pathModuleRoot.'templates/' );
// store the link info
$this->template->set( 'links', $this->links );
// store the page labels
$name = $this->dataManager->getModuleName();
$this->labels->setLabelTag( '[Title]', '[moduleName]', $name);
$this->template->setXML( 'pageLabels', $this->labels->getLabelXML() );
// store XML List of Applicants ...
$this->template->setXML( 'dataList', $this->dataManager->getXML() );
/*
* Set up any additional data transfer to the Template here...
*/
// store XML list of State Vars
$this->template->setXML( 'stateVarList', $this->listStateVar->getXML() );
// store XML list of Data Access Objects
$this->template->setXML( 'daObjectList', $this->listDAObjects->getXML() );
// store XML list of Page Objects
$this->template->setXML( 'pageList', $this->listPageObjects->getXML() );
// store XML list of Page Transitions
$this->template->setXML( 'transitionList', $this->listTransitions->getXML() );
// now store an array of Page Names so the transitions can list
// the names of the Pages Objects ...
$pageNames = array();
$this->listPageObjects->setFirst();
while ( $page = $this->listPageObjects->getNext() ) {
$pageNames[ $page->getID() ] = $page->getName();
}
$this->template->set( 'pageNames', $pageNames );
return $this->template->fetch( 'page_ViewModule.php' );
}
//************************************************************************
/**
* function setLinks
* <pre>
* stores the value of the links array
* </pre>
* @param $link [ARRAY] list of href links
* @return [void]
*/
function setLinks($link)
{
$this->links = $link;
} // end setLinks()
}
?> | true |
e26892ab48037672c2b7f30607fb1fc8c2e90cfe | PHP | luketlancaster/searcher | /tests/Criteria/Collection/NamedCriteriaCollectionTest.php | UTF-8 | 1,761 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace KGzocha\Searcher\Test\Criteria\Collection;
use KGzocha\Searcher\Criteria\Collection\NamedCriteriaCollection;
class NamedCriteriaCollectionTest extends CriteriaCollectionTest
{
public function testMagicMethods()
{
$criteria = $this->getCriteria();
$collection = new NamedCriteriaCollection();
$collection->crtieria1 = $criteria;
$collection->crtieria2 = $criteria;
$this->assertEquals(
$criteria,
$collection->crtieria1
);
$this->assertEquals(
$criteria,
$collection->crtieria2
);
}
public function testNonMagicMethods()
{
$criteria = $this->getCriteria();
$collection = new NamedCriteriaCollection();
$collection->addNamedCriteria('test1', $criteria);
$collection->addNamedCriteria('test2', $criteria);
$collection->addNamedCriteria('test3', $criteria);
$collection->addNamedCriteria('test3', $criteria); // Duplicate
$this->assertCount(3, $collection->getCriteria());
}
public function testMissingCriteria()
{
$collection = new NamedCriteriaCollection();
$this->assertEmpty($collection->getNamedCriteria('non-existing-criteria'));
}
public function testFluentInterface()
{
$collection = new NamedCriteriaCollection();
$this->assertInstanceOf(
'\KGzocha\Searcher\Criteria\Collection\NamedCriteriaCollection',
$collection->addCriteria($this->getCriteria())
);
$this->assertInstanceOf(
'\KGzocha\Searcher\Criteria\Collection\NamedCriteriaCollection',
$collection->addNamedCriteria('name', $this->getCriteria())
);
}
}
| true |
db118e079ddb3fa0e52e9577f8e842153cbf9c54 | PHP | tautvydascoding/2019-01 | /uzduotys/diena_18/DESTYTOJAS/1-php-rekursija/index.php | UTF-8 | 227 | 2.671875 | 3 | [] | no_license | <?php
// paleisti f-ja 10 kartu ir atspausdinti, kuris jau kartas
function rekursija() {
static $k = 0;
if ($k < 10) {
echo " $k -as kartas <br />";
$k++;
rekursija();
}
}
rekursija();
| true |
db825ee60a600081d2330edee06106277d244ef5 | PHP | fajrika/api_php_android | /index.php | UTF-8 | 6,687 | 2.5625 | 3 | [] | no_license | <?php
class prepare
{
public $response;
public $data;
public $put;
public function __construct()
{
require_once('achievement.php');
require_once('input.php');
$this->input = new input;
$this->data = (object)[];
$this->response = (object)[];
$this->response->code = 500;
$this->response->timestamp = date("Y-m-d H:i:s");
$this->response->message = 'function not found';
}
public function login()
{
require_once('auth.php');
$this->data->username = $this->input->get_attribute('username');
$this->data->password = $this->input->get_attribute('password');
if ($this->data->username && $this->data->password) {
if ((new auth)->login($this->data->username, $this->data->password)) {
$this->response->code = 200;
$this->response->message = 'login successfully';
} else {
$this->response->code = 209;
$this->response->message = 'failed username or password';
}
} else {
$this->response->code = 500;
$this->response->message = 'Parameter not complete';
}
}
public function get_achievement()
{
require_once('achievement.php');
$this->response->code = 200;
$this->response->message = 'successfully';
$id = strtolower(explode('/', $_SERVER['PATH_INFO'] ?? '')[2] ?? '');
if($id != ''){
$this->response = (new achievement($this->response))->show($id);
}else{
$this->response = (new achievement($this->response))->read();
}
}
public function store_achievement()
{
require_once('achievement.php');
$this->data->nisn = $this->input->get_attribute('nisn');
$this->data->nama = $this->input->get_attribute('nama');
$this->data->nama_lomba = $this->input->get_attribute('nama_lomba');
$this->data->tgl_lomba = $this->input->get_attribute('tgl_lomba');
$this->data->penyelenggara = $this->input->get_attribute('penyelenggara');
$this->data->tingkatan = $this->input->get_attribute('tingkatan');
$this->data->peringkat = $this->input->get_attribute('peringkat');
$this->data->pembimbing = $this->input->get_attribute('pembimbing');
$this->data->keterangan = $this->input->get_attribute('keterangan')??null;
if ($this->data->nisn && $this->data->nama && $this->data->nama_lomba && $this->data->tgl_lomba && $this->data->penyelenggara && $this->data->tingkatan && $this->data->peringkat && $this->data->pembimbing) {
$this->response = (new achievement($this->response))->create(
$this->data->nisn,
$this->data->nama,
$this->data->nama_lomba,
$this->data->tgl_lomba,
$this->data->penyelenggara,
$this->data->tingkatan,
$this->data->peringkat,
$this->data->pembimbing,
$this->data->keterangan
);
} else {
$this->response->code = 500;
$this->response->message = 'Parameter not complete';
}
}
public function edit_achievement()
{
$this->data->id = $this->input->put('id');
$this->data->nisn = $this->input->put('nisn');
$this->data->nama = $this->input->put('nama');
$this->data->nama_lomba = $this->input->put('nama_lomba');
$this->data->tgl_lomba = $this->input->put('tgl_lomba');
$this->data->penyelenggara = $this->input->put('penyelenggara');
$this->data->tingkatan = $this->input->put('tingkatan');
$this->data->peringkat = $this->input->put('peringkat');
$this->data->pembimbing = $this->input->put('pembimbing');
$this->data->keterangan = $this->input->put('keterangan')??null;
if ($this->data->id && $this->data->nisn && $this->data->nama && $this->data->nama_lomba && $this->data->tgl_lomba && $this->data->penyelenggara && $this->data->tingkatan && $this->data->peringkat && $this->data->pembimbing) {
$this->response = (new achievement($this->response))
->update(
$this->data->id,
$this->data->nisn,
$this->data->nama,
$this->data->nama_lomba,
$this->data->tgl_lomba,
$this->data->penyelenggara,
$this->data->tingkatan,
$this->data->peringkat,
$this->data->pembimbing,
$this->data->keterangan
);
} else {
$this->response->code = 500;
$this->response->message = 'Parameter not complete';
}
}
public function destroy_achievement()
{
$this->data->id = strtolower(explode('/', $_SERVER['PATH_INFO'] ?? '')[2] ?? '');
// $this->data->id = $this->input->get_attribute('id');
if ($this->data->id)
$this->response = (new achievement($this->response))->delete($this->data->id);
else {
$this->response->code = 500;
$this->response->message = 'Parameter not complete';
}
}
}
class route
{
public function __invoke()
{
$this->prepare = new prepare;
$this->prepare->path = strtolower(explode('/', $_SERVER['PATH_INFO'] ?? '')[1] ?? '');
switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
if ($this->prepare->path == 'achievement')
$this->prepare->get_achievement();
break;
case 'POST':
if ($this->prepare->path == 'login')
$this->prepare->login();
elseif ($this->prepare->path == 'achievement')
$this->prepare->store_achievement();
break;
case 'PUT':
if ($this->prepare->path == 'achievement')
$this->prepare->edit_achievement();
break;
case 'DELETE':
if ($this->prepare->path == 'achievement')
$this->prepare->destroy_achievement();
break;
default:
$this->prepare->response->message = 'Method cant use';
break;
}
return $this->prepare->response;
}
}
header('Content-type: application/json');
$response = (new route)();
http_response_code($response->code);
echo json_encode($response);
| true |
e482e06bda66fdf02d1fd7a96e5a4ec327ca5574 | PHP | sinri/sadame | /test/common.php | UTF-8 | 685 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: Sinri
* Date: 2017/4/12
* Time: 22:09
*/
require_once __DIR__ . '/../autoload.php';
echo __FILE__ . PHP_EOL;
echo "STACK" . PHP_EOL;
$stack = new \sinri\sadame\bin\ArrayStack();
$stack->push(1);
$stack->push(2);
echo $stack->pop();
echo $stack->isEmpty() ? 'E' : 'F';
echo $stack->size();
$stack->push(3);
echo $stack->pop();
echo $stack->pop();
echo PHP_EOL;
echo "QUEUE" . PHP_EOL;
$queue = new \sinri\sadame\bin\ArrayQueue();
$queue->inQueue(1);
$queue->inQueue(2);
$queue->inQueue(3);
echo $queue->outQueue();
echo $queue->size();
echo $queue->isEmpty() ? 'E' : 'F';
echo $queue->outQueue();
echo $queue->outQueue();
echo PHP_EOL;
| true |
24b37f17fd06208cfef97c70ad9652fbcbd8d03a | PHP | krakphp/config | /src/ConfigItemFactory/StdConfigItemFactory.php | UTF-8 | 909 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
namespace Krak\Config\ConfigItemFactory;
use Krak\Config;
class StdConfigItemFactory implements Config\ConfigItemFactory
{
private $load_file;
public function __construct(Config\LoadFile $load_file = null) {
$this->load_file = $load_file ?: new Config\LoadFile\AggregateLoadFile();
}
public function createConfigItem($value) {
if ($value instanceof Config\ConfigItem) {
return $value;
}
if (is_callable($value)) {
return new Config\ConfigItem\CallableConfigItem($value);
}
if (is_array($value)) {
return new Config\ConfigItem\ArrayConfigItem($value);
}
if (is_string($value)) {
return new Config\ConfigItem\FileConfigItem($this->load_file, $value);
}
throw new LogicException("Invalid type provided for loading file: " . print_r($value, true));
}
}
| true |
99572d9dfebc6a8d2bc335603d72bcff1370d995 | PHP | ares0310/projet-MVC | /portfolio/classes/model/ModelRef.php | UTF-8 | 3,019 | 3.015625 | 3 | [] | no_license | <?php
require_once "connexion.php";
class ModelRef
{
public static function ajoutRef($user_id, $lien, $type_ref_id, $nom, $techno, $contributeurs)
{
$idcon = connexion();
$requete = $idcon->prepare("INSERT INTO reference VALUES (null, :type_ref_id, :nom, :techno, :contributeurs)");
$requete->execute([":type_ref_id" => $type_ref_id, ":nom" => $nom, ":techno" => $techno, ":contributeurs" => $contributeurs]);
$ref_id = $idcon->lastInsertId();
$requete2 = $idcon->prepare("INSERT INTO user_ref VALUES (:user_id, :ref_id, :lien)"); // - insertion dans user ref - créer formulaire d'abord (lien pas de require car facultatif)
$requete2->execute([":lien" => $lien, ":ref_id" => $ref_id, ":user_id" => $user_id]);
}
public static function listeRef()
{
$idcon = connexion();
$requete = $idcon->prepare("
SELECT reference.id as ref_id, user.id as user_id, user.nom, prenom, type_ref, support,reference.nom as nom_ref, techno, lien, contributeurs
FROM reference
INNER JOIN user_ref
ON reference.id=ref_id
INNER JOIN user
ON user.id=user_id
INNER JOIN type_ref
ON type_ref.id=type_ref_id
ORDER BY user_id
"); // mettre toutes les colonnes qu'on veut et inner join
$requete->execute();
return $requete->fetchAll();
}
public static function ModifRef($idRef, $idType,$nom, $techno, $contributeurs, $lien)
{
$idcon = connexion();
$requete = $idcon->prepare("
UPDATE reference
INNER JOIN user_ref
ON ref_id=reference.id
SET type_ref_id=:idType, nom=:nom, techno=:techno, contributeurs=:contributeurs, lien=:lien
WHERE reference.id=:idRef
");
$requete->execute([
':idType' => $idType,
':nom' => $nom,
':techno' => $techno,
':contributeurs' => $contributeurs,
':lien' => $lien,
':idRef' => $idRef,
]);
}
// {
// $idcon = connexion();
// $requete = $idcon->prepare(
// "UPDATE reference
// INNER JOIN type_ref
// ON reference.type_ref_id = type_ref.id
// INNER JOIN user_ref -- inclure encore quelques tables
// ON reference.id = user_ref.ref_id
// INNER JOIN user
// ON user_ref.user_id = user.id
// INNER JOIN
// SET
// -- inclure quel colonne exactement faut il changer
// ");
// $requete->execute();
// }
public static function getReferenceById($id){
$idcon = connexion();
$requete = $idcon->prepare("
SELECT * FROM reference
INNER JOIN user_ref
ON ref_id=reference.id
WHERE reference.id=:id
");
$requete->execute([
':id' => $id
]);
return $requete->fetch();
}
}
| true |
e9db78c6231a763686e49a21f111cfe564351d58 | PHP | orangesource/pizzatoday | /classes/databaseclass.php | UTF-8 | 1,507 | 2.921875 | 3 | [] | no_license | <?php
class database extends PDO{
private $host, $dbname, $username, $pass;
protected $row_count, $dbb;
public $db;
public function __construct()
{
}
public function startConnect($host, $dbname, $username, $pass)
{
$this->host = $host;
$this->dbname = $dbname;
$this->pass = $pass;
$this->username = $username;
$this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $this->username, $this->pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function query($query)
{
$sth = $this->db->query($query);
$data = $sth->fetch(PDO::FETCH_OBJ);
return $data;
{
}
public function startConnect($host, $dbname, $username, $pass)
{
$this->host = $host;
$this->dbname = $dbname;
$this->pass = $pass;
$this->username = $username;
$this->db = new PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $this->username, $this->pass);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function query($query)
{
$sth = $this->db->query($query);
$data = $sth->fetch(PDO::FETCH_OBJ);
return $data;
}
public function countRows($query)
{
$sth = $this->db->query($query);
$row_count = $sth->rowCount();
return $row_count;
}
public function deleteData($query)
{
$sth = $this->db->query($query);
return true;
}
}
?> | true |
ae92711afd9115b300011599c0fe4b10b24d428c | PHP | buzzingpixel/corbomite-user | /src/interfaces/UserRecordToModelTransformerInterface.php | UTF-8 | 539 | 2.796875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | <?php
declare(strict_types=1);
namespace corbomite\user\interfaces;
interface UserRecordToModelTransformerInterface
{
/**
* Transforms a user record into a user model
*
* @param mixed[] $record Array of record values from PDO fetch
*/
public function __invoke(array $record) : UserModelInterface;
/**
* Transforms a user record into a user model
*
* @param mixed[] $record Array of record values from PDO fetch
*/
public function transform(array $record) : UserModelInterface;
}
| true |
46b1ad26f7c8f91265b432f0993855fd7943c332 | PHP | NoTrueAcc/Test_Shop_PHP | /library/manageClass.php | UTF-8 | 5,423 | 2.609375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Alex
* Date: 07.06.2017
* Time: 6:41
*/
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/config/configClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/helper/formatClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/dataBase/tableClasses/productClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/dataBase/tableClasses/discountClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/dataBase/tableClasses/orderClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/messages/systemMessageClass.php";
require_once $_SERVER['DOCUMENT_ROOT'] . "/library/messages/mailClass.php";
use config\configClass;
use helper\formatClass;
use database\tableClasses\productClass;
use database\tableClasses\discountClass;
use database\tableClasses\orderClass;
use messages\systemMessageClass;
use messages\mailClass;
class manageClass
{
private $config;
private $format;
private $data;
private $product;
private $discount;
private $order;
private $systemMessage;
private $mail;
public function __construct()
{
session_start();
$this->config = new configClass();
$this->format = new formatClass();
$this->product = new productClass();
$this->discount = new discountClass();
$this->order = new orderClass();
$this->systemMessage = new systemMessageClass();
$this->mail = new mailClass();
$this->data = $this->format->checkDataFromXSS($_REQUEST);
$this->saveData();
}
private function saveData()
{
foreach ($this->data as $key => $value)
{
$_SESSION[$key] = $value;
}
}
public function addToCart($id = false)
{
if($id === false)
{
$id = isset($this->data['id']) ? $this->data['id'] : '';
}
if(!$this->product->isExistsId($id))
{
return false;
}
$_SESSION['cart'] = isset($_SESSION['cart']) ? $_SESSION['cart'] . ",$id" : "$id";
}
public function deleteFromCart()
{
$id = isset($this->data['id']) ? $this->data['id'] : '';
$sessionIdsList = explode(',', $_SESSION['cart']);
unset($_SESSION['cart']);
for($i = 0; $i < count($sessionIdsList); $i++)
{
if($sessionIdsList[$i] != $id)
{
$this->addToCart($sessionIdsList[$i]);
}
}
}
public function updateCartData()
{
if(empty($_SESSION['cart']))
{
return false;
}
unset($_SESSION['cart']);
foreach ($this->data as $key => $value)
{
if(preg_match('/^count_[0-9]*$/i', $key))
{
$id = substr($key, strlen('count_'));
for($i = 0; $i < $value; $i++)
{
$this->addToCart($id);
}
}
}
$_SESSION['discount'] = (isset($this->data['discount']) && !empty($this->data['discount'])) ? $this->data['discount'] : '';
}
public function addOrder()
{
$tempData = array();
$tempData['delivery'] = $this->data['delivery'];
$tempData['product_ids'] = $_SESSION['cart'];
$tempData['price'] = $this->getPrice();
$tempData['name'] = $this->data['name'];
$tempData['phone'] = $this->data['phone'];
$tempData['email'] = $this->data['email'];
$tempData['address'] = $this->data['address'];
$tempData['notice'] = $this->data['notice'];
$tempData['date_order'] = $this->format->getTimeStamp();
$tempData['date_send'] = 0;
$tempData['date_pay'] = 0;
$success = $this->order->insertData($tempData);
if($success)
{
$sendData = array();
$productDataList = $this->product->getTitleAndCountOnIds($tempData['product_ids']);
$sendData['products'] = $this->__getProductsDataToSend($productDataList);
$sendData['name'] = $tempData['name'];
$sendData['phone'] = $tempData['phone'];
$sendData['email'] = $tempData['email'];
$sendData['address'] = $tempData['address'];
$sendData['notice'] = $tempData['notice'];
$sendData['delivery'] = $tempData['delivery'];
$sendData['price'] = $tempData['price'];
$this->mail->sendMail($tempData['email'], $sendData, 'ORDER');
$_SESSION = array();
return $this->systemMessage->getPageMessage('ADD_ORDER');
}
else
{
return false;
}
}
private function getPrice()
{
$ids = isset($_SESSION['cart']) ? explode(',', $_SESSION['cart']) : array();
$price = $this->product->getCartPriceOnIds($ids);
$discount = isset($_SESSION['discount']) ? $this->discount->getDiscountOnCode($_SESSION['discount']) : 0;
return $price * (1 - $discount);
}
private function __getProductsDataToSend($productsDataList)
{
$productDataToSend = '';
for($i = 0; $i < count($productsDataList); $i++)
{
$productDataToSend .= $productsDataList[$i]['title'] . ' x ' . $productsDataList[$i]['count'] . ' | ';
}
$productDataToSend = substr($productDataToSend, 0, -3);
return $productDataToSend;
}
} | true |
7bae44948a015876688be040cb7f1fbc9b217b36 | PHP | ertprs/pluton | /apps/backend/controllers/PostController.php | UTF-8 | 11,262 | 2.765625 | 3 | [] | no_license | <?php
/**
* Class and Function List:
* Function list:
* - indexAction()
* - verifyPermissionEditPost()
* - listPostsAction()
* - newPostAction()
* - editPostAction()
* - insertPostCategories()
* - updatePostCategories()
* - newCategorieAction()
* - getCategoriesByPost()
* Classes list:
* - PostController extends BaseController
*/
namespace Multiple\Backend\Controllers;
use Multiple\Backend\Models\Posts;
use Multiple\Backend\Models\PostStatus;
use Multiple\Backend\Models\Categories;
use Multiple\Backend\Models\Users;
use Multiple\Backend\Models\PostCategorie;
/**
* Classe responsável pela manipulação das postagens e elementos relacionados as mesmas
*/
class PostController extends BaseController {
/**
* Carrega a view para criação de um novo post
*/
public function indexAction() {
$this->session->start();
if ($this->session->get('user_id') != NULL) {
$vars = $this->getUserLoggedInformation();
$edit_post = false;
//busca o usuário logado para exibir como autor
$vars['author'] = Users::findFirstByUser_id($this->session->get("user_id"));
$vars['menus'] = $this->getSideBarMenus();
//Caso a tela seja carregada para edição de post
//Busca os dados do post informado via POST e envia para view
if ($this->request->get('post_id') != NULL) {
$post[0] = Posts::findFirstByPost_id($this->request->get('post_id'));
$author = Users::findFirstByUser_id($post[0]->post_author);
$user_logged = Users::findFirstByUser_id($this->session->get('user_id'));
if ($this->verifyPermissionEditPost($author, $user_logged)) {
foreach ($post as $p) {
$post_content = $string = str_replace(PHP_EOL, '', html_entity_decode($p->post_content));
$post_date = $this->dateFormat($p->post_date_posted, 2);
}
$edit_post = true;
$vars['author'] = $author;
$vars['post_categories'] = $this->getCategoriesByPost($post);
$vars['post_content'] = $post_content;
$vars['post_date'] = $post_date;
$vars['post'] = $post[0];
}
else {
$this->response->redirect("dashboard/notPermission");
}
}
//Monta um array com todas as categorias cadastradas no sistema
$obj_categories = Categories::getCategories();
foreach ($obj_categories as $categorie) {
$array_categories[] = $categorie->categorie_name;
}
$vars['categories'] = json_encode($array_categories);
$vars['post_status'] = PostStatus::getPostStatus();
$vars['edit_post'] = $edit_post;
$this->view->setVars($vars);
$this->view->render("post", "index");
}
else {
$this->response->redirect(URL_PROJECT . 'admin');
}
}
/**
* Verifica se usuário possui permissão para editar postagens do autor
* @param \Phalcon\Mvc\Resultset Objeto do tipo Resultset contendo informações sobre o autor da postagem
* @param \Phalcon\Mvc\Resultset Objeto do tipo Resultset contendo informações sobre o usuário logado
* @return boolean verdadeiro caso o usário logado possa editar postagens do autor ou falsó caso contrário
*/
private function verifyPermissionEditPost($author, $user_logged) {
if ($user_logged->user_type_id == 1) {
return true;
}
elseif ($author->user_type_id == 1 && ($user_logged->user_id != $author->user_id)) {
return false;
}
elseif (($author->user_type_id == 2 && $user_logged->user_type_id == 2) && ($author->user_id != $user_logged->user_id)) {
return false;
}
elseif (($author->user_type_id == 3 && $user_logged->user_type_id > 3)) {
return false;
}
elseif (($author->user_type_id > 3 && $user_logged->user_type_id > 3) && ($author->user_id != $user_logged->user_id)) {
return false;
}
else {
return true;
}
}
/**
* Carrega uma tabela listando as postagens existentes no sistema
*/
public function listPostsAction() {
$this->session->start();
if ($this->session->get('user_id') != NULL) {
$vars = $this->getUserLoggedInformation();
$user = Users::findFirstByUser_id($this->session->get('user_id'));
if ($user->user_type_id < 3) {
$posts = Posts::find(array(
"order" => "post_date_posted DESC"
));
}
elseif ($user->user_type_id == 3) {
$usr = Users::find(array(
"conditions" => "user_type_id > :user_type_id: OR user_id = :user_id: ",
"bind" => array(
"user_type_id" => $user->user_type_id,
"user_id" => $user->user_id
)
));
foreach ($usr as $u) {
$arr_id_users[] = $u->user_id;
}
$string_users = implode(",", $arr_id_users);
$posts = Posts::find(array(
"conditions" => "post_author IN ({$string_users})",
"order" => "post_date_posted DESC"
));
}
else {
$posts = Posts::findByPost_author($user->user_id);
}
$vars['menus'] = $this->getSideBarMenus();
$vars['posts'] = $posts;
$vars['categories'] = $this->getCategoriesByPost($posts);
$this->view->setVars($vars);
$this->view->render("post", "listPosts");
}
else {
$this->response->redirect(URL_PROJECT . 'admin');
}
}
/**
* Cria uma nova postagem utilizando os dados recebidos via Post
* @return boolean true caso a postagem tenha sido salva ou false caso contrário
*/
public function newPostAction() {
$this->view->disable();
$post_date_create = date("Y-m-d H:i:s");
$post_date_posted = $this->dateFormat($this->request->getPost('post_date_posted') , 1);
$post_date_changed = date("Y-m-d H:i:s");
$post_author = $this->request->getPost('post_author');
$post_editor = $this->request->getPost('post_author');
$post_title = $this->request->getPost('post_title');
$post_content = htmlentities($this->request->getPost('post_content'));
//print_r($post_content); die();
$post_status_id = $this->request->getPost('post_status_id');
$categories = explode(", ", $this->request->getPost('list_categories'));
$post_id = Posts::createNewPost($post_date_create, $post_date_posted, $post_date_changed, $post_author, $post_editor, $post_title, $post_content, $post_status_id);
if ($post_id > 0) $data['success'] = $this->insertPostCategories($categories, $post_id);
echo json_encode($data);
}
/**
* Atualiza uma postagem conforme os dados recebidos via POST
*/
public function editPostAction() {
$this->view->disable();
$post_id = $this->request->getPost("post_id");
$post_date_posted = $this->dateFormat($this->request->getPost('post_date_posted') , 1);
$post_date_changed = date("Y-m-d H:i:s");
$post_author = $this->request->getPost('post_author');
$post_editor = $this->request->getPost('post_author');
$post_title = $this->request->getPost('post_title');
$post_content = addslashes(htmlentities($this->request->getPost('post_content')));
$post_status_id = $this->request->getPost('post_status_id');
$categories = explode(", ", $this->request->getPost('list_categories'));
$post_id = Posts::updatePostAction($post_id, $post_date_posted, $post_date_changed, $post_author, $post_editor, $post_title, $post_content, $post_status_id);
if ($post_id > 0) $data['success'] = $this->updatePostCategories($categories, $post_id);
echo json_encode($data);
}
/**
* Insere todas as categorias do post na tabela categorie_post
* @param array $categories array contendo todas as categorias do post
* @param int $id_post id do post
* @return boolean true caso salve todos os ids ou false caso ocorra um erro
*/
private function insertPostCategories($categories, $post_id) {
foreach ($categories as $categorie) {
$cat = Categories::findFirstByCategorie_name($categorie);
$success = PostCategorie::createPostCategorie($post_id, $cat->categorie_id);
if (!$success) break;
}
return $success;
}
/**
* Recebe as novas categorias e o id da postagem; Remove todos os PostCategories antigos e insere os novos;
* @param array $categories array contendo todas as categorias do post
* @param int $post_id id do post
* @return boolean true caso salve todos os ids ou false caso ocorra um erro
*/
private function updatePostCategories($categories, $post_id) {
foreach ($categories as $categorie) {
$cat = Categories::findFirstByCategorie_name($categorie);
$success = PostCategorie::deleteAllPostCategorieByPost($post_id);
$success = $success ? PostCategorie::createPostCategorie($post_id, $cat->categorie_id) : $success;
if (!$success) break;
}
return $success;
}
/**
* Verifica se uma categoria informada já existe, caso não, insere no banco de dados
*/
public function newCategorieAction() {
$this->view->disable();
$new_categorie = $this->request->getPost("categorie");
$categories = Categories::find();
$exists = 1;
foreach ($categories as $categorie) {
if ($exists != 0) {
$exists = strcmp($categorie->categorie_name, $new_categorie);
}
else {
break;
}
}
$data['success'] = ($exists != 0) ? Categories::newCategorie($new_categorie) : true;
echo json_encode($data);
}
/**
* Recebe um objeto do tipo \Phalcon\Mvc\ResultSet e retorna todas as categorias dos posts do objeto
* @param object \Phalcon\Mvc\ResultSet
* @return array Array contendo o array de cada post e uma string com as categorias dos posts
*/
private function getCategoriesByPost($posts) {
foreach ($posts as $post) {
$post_categories = $post->post_categorie;
foreach ($post_categories as $post_categorie) {
$categories = $post_categorie->categories;
foreach ($categories as $categorie) {
$ctg[$post->post_id].= empty($ctg[$post->post_id]) ? $categorie->categorie_name : ", " . $categorie->categorie_name;
}
}
}
return $ctg;
}
}
| true |
aa3961c627592eec4f78e9ea3474e8afcd8912ef | PHP | henryfw/algo | /morgan/php/ch7-combination-permutation.php | UTF-8 | 612 | 3.4375 | 3 | [] | no_license | <?php
function combination($inputs, $size) {
$ans = [];
foreach($inputs AS $v) {
$ans[] = [ $v ];
}
return doCombination($inputs, $size - 1, $ans);
}
function doCombination($inputs, $size, $ans) {
if ($size == 0) return $ans;
$newAns = [];
foreach ($ans AS $item) {
foreach ($inputs AS $v) {
if (!in_array($v, $item)) {
$newItem = $item;
$newItem[] = $v;
$newAns[] = $newItem;
}
}
}
return doCombination($inputs, $size - 1, $newAns);
}
print_r(combination([1,2,3], 2)); | true |
b632045809cf253098a99ec434931db9bf8338de | PHP | glinskiwieslaw/PhP_Zadania | /Zadanie14.php | UTF-8 | 842 | 3.328125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: wg
* Date: 2015-11-26
* Time: 02:47
*/
/*Zadanie 14. Napisz funkcje o nazwie FooBar, przyjmującą jedną zmienną. Funkcja ta ma wypisywać kolejne liczby, ale:
W miejsce liczb podzielnych przez 3 wypisywać Foo
W miejsce liczb podzielnych przez 5 wypisywać Bar
W miejsce liczb podzielnych przez 3 i 5 wypisywać FOOBAR
Np. Dla parametru $x = 15 wynik ma być:
12Foo4BarFoo78FooBar11Foo1314FOOBAR*/
function fooBar($arg)
{
for ($i=1; $i<=$arg; $i=$i+1){
if ($i % 3==0 && $i % 5!=0 ){
echo "Foo";
}
elseif ($i % 5==0 && $i % 3!=0){
echo "Bar";
}
elseif ($i % 3==0 && $i % 5==0){
echo "FooBar";
}
else {
echo $i;
}
}
/* return TRUE;*/
}
echo fooBar(15);
| true |
5f894b238c2c6d8736b12b37d1042a20e49e7a5e | PHP | ravivegda/www.schups.local | /APIs/Data/userInfo.class.php | UTF-8 | 1,608 | 2.875 | 3 | [] | no_license | <?php
/*
* User Info
*/
require_once "config.php";
class userInfo{
public function __construct() {}
/*
* list all users info
*/
public function listUsers()
{
global $db;
$user_db_data = array();
$cache = Cache::getInstance();
// $cache->flush();
if($cache->exists("user_info_data"))
{
$user_db_data = $cache->get("user_info_data");
} else {
$e = $db->prepare("SELECT * FROM user_info");
$e->execute();
$user_data = $e->fetchAll();
// cache will clear in every 1 min.
$cache->set("user_info_data", $user_data, 60 * 60 * 0.1);
$user_db_data = $user_data;
}
return $user_db_data;
}
/*
* list all users info
*/
public function getUserById($user_id)
{
global $db;
$user_db_data = array();
$cache = Cache::getInstance();
// $cache->flush();
if($cache->exists("user_data"))
{
$user_db_data = $cache->get("user_data");
} else {
$qry = "SELECT * FROM user_info WHERE id = ".$user_id;
$e = $db->prepare($qry);
$e->execute();
$user_data = $e->fetch();
// cache will clear in every 1 min.
$cache->set("user_data", $user_data, 60 * 60 * 0.1);
if($e->rowCount() > 0)
$user_db_data = $user_data;
else
$user_db_data = "";
}
return $user_db_data;
}
}
?>
| true |
f2da3457aa004b676db471f79080fff9fd8f8d03 | PHP | systemowiec/dockerized-api-starter-kit | /src/Starter/Product/VirtualProduct.php | UTF-8 | 1,318 | 3.21875 | 3 | [] | no_license | <?php
namespace Starter\Product;
use Money\Money;
use Ramsey\Uuid\UuidInterface;
/**
* @author Jarosław Stańczyk <jaroslaw@stanczyk.co.uk>
* @copyright 2017 Jarosław Stańczyk. All rights reserved.
*/
class VirtualProduct implements Product
{
/**
* @var UuidInterface
*/
private $uuid;
/**
* @var string
*/
private $name;
/**
* @var Money
*/
private $price;
/**
* @var int
*/
private $quantity;
/**
* @param UuidInterface $uuid
* @param string $name
* @param Money $price
* @param int $quantity
*/
public function __construct(UuidInterface $uuid, string $name, Money $price, int $quantity)
{
$this->uuid = $uuid;
$this->name = $name;
$this->quantity = $quantity;
$this->price = $price;
}
/**
* @return UuidInterface
*/
public function getUuid(): UuidInterface
{
return $this->uuid;
}
/**
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* @return Money
*/
public function getPrice(): Money
{
return $this->price;
}
/**
* @return int
*/
public function getQuantity(): int
{
return $this->quantity;
}
}
| true |
fde1432a28c437bada62dadc1e75ddc3fc265c68 | PHP | alex-kalanis/remote-request | /php-src/Protocols/Fsp/Traits/TChecksum.php | UTF-8 | 1,766 | 3.046875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace kalanis\RemoteRequest\Protocols\Fsp\Traits;
/**
* Trait TChecksum
* @package kalanis\RemoteRequest\Protocols\Fsp\Traits
* Process checksums
/-* assume that we have already zeroed checksum in packet - that means set it to zero - chr(0) *-/
unsigned int sum,checksum;
unsigned char *t;
for(t = packet_start, sum = 0; t < packet_end; sum += *t++);
checksum= sum + (sum >> 8);
* PHP, Perl
$len = strlen($packet);
$packet[1] = chr(0); // at first null checksum in packet
$sum = 0; // or $len for client->server
for ($i = 0; $i < $len; $i++) {
$sum += ord($packet[$i]);
}
$checksum = ($sum + ($sum >> 8));
$byteChecksum = $checksum & 0xff;
*/
trait TChecksum
{
/*
* Slower, can be understand and ported
*/
// protected function computeCheckSum(): int
// {
// $data = $this->getChecksumPacket();
// $len = strlen($data);
// $sum = $this->getInitialSumChunk();
// for ($i = 0; $i < $len; $i++) {
// $sum += ord($data[$i]);
//// print_r(['chkcc', $i, ord($data[$i]), $sum]);
// }
// $checksum = ($sum + ($sum >> 8));
//// var_dump(['chks', $sum, decbin($sum), decbin($sum >> 8)]);
// return $checksum & 0xff; // only byte
// }
/*
* Faster, less intelligible
*/
protected function computeCheckSum(): int
{
$sum = array_reduce((array) str_split($this->getChecksumPacket()), [$this, 'sumBytes'], $this->getInitialSumChunk());
return ($sum + ($sum >> 8)) & 0xff;
}
abstract protected function getChecksumPacket(): string;
abstract protected function getInitialSumChunk(): int;
public function sumBytes(int $sum, string $char): int
{
return $sum + ord($char);
}
}
| true |
bbafbd1a470fbcf0cca1081dc2e81fca59109ea0 | PHP | webimpress/coding-standard | /src/WebimpressCodingStandard/Sniffs/Classes/NoNullValuesSniff.php | UTF-8 | 2,285 | 2.90625 | 3 | [
"BSD-2-Clause"
] | permissive | <?php
declare(strict_types=1);
namespace WebimpressCodingStandard\Sniffs\Classes;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\AbstractVariableSniff;
use PHP_CodeSniffer\Util\Tokens;
use function in_array;
use const T_EQUAL;
use const T_NULL;
use const T_WHITESPACE;
class NoNullValuesSniff extends AbstractVariableSniff
{
/**
* @param int $stackPtr
*/
protected function processMemberVar(File $phpcsFile, $stackPtr) : void
{
$tokens = $phpcsFile->getTokens();
$next = $phpcsFile->findNext(Tokens::$emptyTokens, $stackPtr + 1, null, true);
if ($tokens[$next]['code'] !== T_EQUAL) {
return;
}
$value = $phpcsFile->findNext(Tokens::$emptyTokens, $next + 1, null, true);
if ($tokens[$value]['code'] === T_NULL) {
$props = $phpcsFile->getMemberProperties($stackPtr);
if ($props['type'] !== '' && $props['nullable_type'] === true) {
return;
}
$error = $props['type'] !== '' && $props['nullable_type'] === false
? 'Default null value for not-nullable property is invalid'
: 'Default null value for the property is redundant';
$code = $props['type'] !== '' && $props['nullable_type'] === false
? 'Invalid'
: 'NullValue';
$fix = $phpcsFile->addFixableError($error, $value, $code);
if ($fix) {
$phpcsFile->fixer->beginChangeset();
for ($i = $stackPtr + 1; $i <= $value; ++$i) {
if (! in_array($tokens[$i]['code'], [T_WHITESPACE, T_EQUAL, T_NULL], true)) {
continue;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->endChangeset();
}
}
}
/**
* @param int $stackPtr
*/
protected function processVariable(File $phpcsFile, $stackPtr) : void
{
// Normal variables are not processed in this sniff.
}
/**
* @param int $stackPtr
*/
protected function processVariableInString(File $phpcsFile, $stackPtr) : void
{
// Variables in string are not processed in this sniff.
}
}
| true |
a379e19a5ca5a2c8f4efd5834eb99de5aad283d4 | PHP | Truczkin/test-laravel-4G | /Projekt/test-laravel-4G/app/Http/Requests/Contact/StoreRequest.php | UTF-8 | 598 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Requests\Contact;
use Illuminate\Foundation\Http\FormRequest;
class StoreRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules(): array
{
return [
'firstname' => ['required', 'min:3', 'max:20'],
'lastname' => ['required', 'min:3', 'max:50'],
'email' => ['required', 'min:3', 'max:50'],
'phone' => ['required', 'min:3', 'max:10'],
'text' => ['required', 'min:5', 'max:255'],
];
}
}
| true |
205cfd6feef6b914ac8a8319e5c7aaf1f636b355 | PHP | christianperl/threesixfive-lumen | /database/migrations/2019_03_08_143609_create_user_day_table.php | UTF-8 | 984 | 2.53125 | 3 | [
"Unlicense",
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUserDayTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('user_days', function (Blueprint $table) {
$table->unsignedInteger('pk_fk_user_id');
$table->String('weekday');
$table->boolean('breakfast');
$table->boolean('lunch');
$table->boolean('main_dish');
$table->boolean('snack');
});
DB::unprepared('ALTER TABLE user_days ADD PRIMARY KEY (pk_fk_user_id, weekday)');
DB::unprepared('ALTER TABLE user_days ADD FOREIGN KEY (pk_fk_user_id) REFERENCES users ON DELETE CASCADE');
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('user_days');
}
}
| true |
5f80722c7dbe3f39ff7c38a331ccfd86f6bd3b55 | PHP | zhaolei/stoneLearn | /src/shuse/ent.php | UTF-8 | 242 | 3.109375 | 3 | [] | no_license | <?php
$a = file('t1');
$arr=array();
foreach($a as $t) {
$t = intval($t);
$arr[$t]++;
}
$c = count($arr);
$x = 0.0;
foreach($arr as $k=>$v) {
$w = $v/$c;
$f1 = log($w, 2);
$m = $w * $f1;
$x += $m * -1;
}
echo $x;
| true |
61efd45b41dd405898ec05b779c746be9fd37af1 | PHP | MouseHappy123/shop-BMS | /core/user.inc.php | UTF-8 | 5,310 | 2.515625 | 3 | [] | no_license | <?php
function reg()
{
require_once 'swiftmailer-master/lib/swift_required.php';
$emailPassword = ''; //密码
$arr = $_POST;
$arr['password'] = md5($_POST['password']);
$arr['regTime'] = time();
$arr['token'] = md5($arr['username'].$arr['password'].$arr['regTime']);
$arr['token_exptime'] = $arr['regTime'] + 24 * 3600; //过期时间
$uploadFile = uploadFile();
//print_r($uploadFile);
if ($uploadFile && is_array($uploadFile)) {
$arr['face'] = $uploadFile[0]['name'];
} else {
return '注册失败';
}
// print_r($arr);exit;
if (insert('user', $arr, 'ssssssss')) {
//发送邮件,以QQ邮箱为例
//配置邮件服务器,得到传输对象
$transport = Swift_SmtpTransport::newInstance('smtp.qq.com', 25);
//设置登陆帐号和密码
$transport->setUsername('');
$transport->setPassword($emailPassword);
//得到发送邮件对象Swift_Mailer对象
$mailer = Swift_Mailer::newInstance($transport);
//得到邮件信息对象
$message = Swift_Message::newInstance();
//设置管理员的信息
$message->setFrom(array('' => 'admin'));
//将邮件发给谁
$message->setTo(array($arr['email'] => 'user'));
//设置邮件主题
$message->setSubject('激活邮件');
$url = 'http://'.$_SERVER['HTTP_HOST'].'/shop/doAction.php'."?act=active&token={$arr['token']}";
$urlencode = urlencode($url);
$str = <<<EOF
亲爱的{$arr['username']}您好~!感谢您注册我们网站<br/>
请点击此链接激活帐号即可登陆!<br/>
<a href="{$url}">{$urlencode}</a>
<br/>
如果点此链接无反映,可以将其复制到浏览器中来执行,链接的有效时间为24小时。
EOF;
$message->setBody("{$str}", 'text/html', 'utf-8');
try {
if ($mailer->send($message)) {
$mes = "恭喜您{$arr['username']}注册成功,请到邮箱激活之后登陆<br/>3秒钟后跳转到登陆页面";
echo '<meta http-equiv="refresh" content="3;url=login.php"/>';
} else {
$PdoMySQL->delete($table, 'id='.$lastInsertId);
echo '注册失败,请重新注册';
echo '3秒钟后跳转到注册页面';
echo '<meta http-equiv="refresh" content="3;url=login.php"/>';
}
} catch (Swift_ConnectionException $e) {
echo '邮件发送错误'.$e->getMessage();
}
} else {
$filename = 'uploads/'.$uploadFile[0]['name'];
if (file_exists($filename)) {
unlink($filename);
}
$mes = "注册失败!<br/><a href='reg.php'>重新注册</a>|<a href='index.php'>查看首页</a>";
}
return $mes;
}
function login()
{
$username = $_POST['username'];
//addslashes():使用反斜线引用特殊字符
$username = addslashes($username);
// $username = mysql_escape_string($username);
$password = md5($_POST['password']);
$sql = 'select * from user where username=? and password=?';
$type = 'ss';
$data = array($username, $password);
//$resNum=getResultNum($sql);
$row = fetchOne($sql, $type, $data);
//echo $resNum;
if ($row) {
if ($row['status'] == 1) {
$_SESSION['loginFlag'] = $row['id'];
$_SESSION['username'] = $row['username'];
$mes = "登陆成功!<br/>3秒钟后跳转到首页<meta http-equiv='refresh' content='3;url=index.php'/>";
} else {
$mes = "登陆失败!请先激活在登陆!<br/><a href='login.php'>重新登陆</a>";
}
} else {
$mes = "用户不存在!<br/><a href='login.php'>重新登陆</a>";
}
return $mes;
}
function userOut()
{
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 1);
}
session_destroy();
header('location:index.php');
}
function active()
{
$token = addslashes($_GET['token']);
$row = fetchOne('select * from user where token=? AND status=0', 's', array($token));
$now = time();
if ($now > $row['token_exptime']) {
$mes = '激活时间过期,请重新登陆激活';
} else {
$res = update('user', array('status' => 1), 'id='.$row['id']);
if ($res) {
$mes = '激活成功,3秒钟后跳转到登陆页面<br/><meta http-equiv="refresh" content="3;url=login.php"/>';
} else {
$mes = '激活失败,请重新激活<br/><meta http-equiv="refresh" content="3;url=index.php"/>';
}
}
return $mes;
}
function getUserByPage($page, $pageSize = 5)
{
$sql = 'select * from user';
global $totalUserRows;
$totalUserRows = getResultNum($sql);
global $totalUserPage;
$totalUserPage = ceil($totalUserRows / $pageSize);
if ($page < 1 || $page == null || !is_numeric($page)) {
$page = 1;
}
if ($page >= $totalUserPage) {
$page = $totalUserPage;
}
$offset = ($page - 1) * $pageSize;
$sql = 'select id,username,email,status from user limit ?,?';
$type = 'ii';
$data = array($offset, $pageSize);
$rows = fetchAll($sql, $type, $data);
return $rows;
}
| true |
7c3da3a9a1dff1bb1430cb75355aed5f03d3aaf3 | PHP | fllflee/calendar-fllflee | /hwc1.php | UTF-8 | 3,372 | 3.03125 | 3 | [] | no_license | <?php
// 某年
//$year=$_GET['y']?$_GET{'y'}:date('Y',time());
// 與以下相同
//加上@是為了避免不必要的錯誤訊息
if (@$_GET['y']){
$year=$_GET{'y'};
}
else{
$year=date('Y',time());
}
date_default_timezone_set('Asia/Taipei');
$datetimenow = date ("Y年 m月 d日 / H 點 i 分");
// 某月
$month=@$_GET['m']?$_GET['m']:date('n',time());
// 本月總天數
$days=date('t',strtotime("{$year}-{$month}-1"));
// 本月1號是周幾
$week=date('w',strtotime("{$year}-{$month}-1"));
// 真正的第一天
$firstday=1-$week;
//月數大於12月年+1,月變成1月
if($month>=12){
//下一年和下一月
$nextYear=$year+1;
$nextMonth=1;
}else{
//下一年和下一月
$nextYear=$year;
$nextMonth=$month+1;
}
//月數小於1月份時,則年-1,月變成12月
if($month<=1){
//下一年和下一月
$prevYear=$year-1;
$prevMonth=12;
}else{
//下一年和下一月
$prevYear=$year;
$prevMonth=$month-1;
}
// 上月總天數
$prevdays1=date('t',strtotime("{$year}-{$prevMonth}-1"));
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>萬年曆</title>
<link rel=stylesheet type="text/css" href="hwc1.css">
</head>
<body>
<div class="time1">現在時間:<?php echo $datetimenow; ?></div>
<div class="ddd1">
<h1>西元-<?php echo $year ?>年-<?php echo $month ?>月</h1>
<table>
<tr>
<th class='sunday1'>SUN</th>
<th>MON</th>
<th>TUE</th>
<th>WED</th>
<th>THU</th>
<th>FRI</th>
<th class='sat1'>SAT</th>
</tr>
<?php
for($i=$firstday;$i<=$days;){
echo '<tr>';
for($j=0;$j<7;$j++){
if($i<=$days && $i>=1){
if($j==0){
echo "<td class='sunday1'>$i<br>";
}
else if($j==6){
echo "<td class='sat1'>$i<br>";
}
else {
echo "<td class='yy1'>$i<br>";
}
include 'hwc2.php';
echo "</td>";
}
else{
if($i<1){
echo "<td class='gray1'>";
echo $i+$prevdays1;
echo "<br> </td>";
}
else {
echo "<td class='gray1'>";
echo $i-$days;
echo "<br> </td>";
}
}
$i++;
}
echo '</tr>';
}
?>
</table>
<center> <?PHP include 'hwc1opt1.php'; ?></center>
</div>
<div class="pre1"><a class="rm1" href="hwc1.php?y=<?php echo $prevYear ?>&m=<?php echo $prevMonth ?>">上一月</a></div>
<div class="next1"><a class="rm1" href="hwc1.php?y=<?php echo $nextYear ?>&m=<?php echo $nextMonth ?>">下一月</a></div>
<div class="word1"> <?PHP include 'hwcword1.php'; ?></div>
</body>
</html> | true |
78e13b1f50347e686ef366a965864bbdd9461621 | PHP | phacility/phabricator | /src/applications/diffusion/ssh/DiffusionGitSSHWorkflow.php | UTF-8 | 7,337 | 2.546875 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
abstract class DiffusionGitSSHWorkflow
extends DiffusionSSHWorkflow
implements DiffusionRepositoryClusterEngineLogInterface {
private $engineLogProperties = array();
private $protocolLog;
private $wireProtocol;
private $ioBytesRead = 0;
private $ioBytesWritten = 0;
private $requestAttempts = 0;
private $requestFailures = 0;
protected function writeError($message) {
// Git assumes we'll add our own newlines.
return parent::writeError($message."\n");
}
public function writeClusterEngineLogMessage($message) {
parent::writeError($message);
$this->getErrorChannel()->update();
}
public function writeClusterEngineLogProperty($key, $value) {
$this->engineLogProperties[$key] = $value;
}
protected function getClusterEngineLogProperty($key, $default = null) {
return idx($this->engineLogProperties, $key, $default);
}
protected function identifyRepository() {
$args = $this->getArgs();
$path = head($args->getArg('dir'));
return $this->loadRepositoryWithPath(
$path,
PhabricatorRepositoryType::REPOSITORY_TYPE_GIT);
}
protected function waitForGitClient() {
$io_channel = $this->getIOChannel();
// If we don't wait for the client to close the connection, `git` will
// consider it an early abort and fail. Sit around until Git is comfortable
// that it really received all the data.
while ($io_channel->isOpenForReading()) {
$io_channel->update();
$this->getErrorChannel()->flush();
PhutilChannel::waitForAny(array($io_channel));
}
}
protected function raiseWrongVCSException(
PhabricatorRepository $repository) {
throw new Exception(
pht(
'This repository ("%s") is not a Git repository. Use "%s" to '.
'interact with this repository.',
$repository->getDisplayName(),
$repository->getVersionControlSystem()));
}
protected function newPassthruCommand() {
return parent::newPassthruCommand()
->setWillWriteCallback(array($this, 'willWriteMessageCallback'))
->setWillReadCallback(array($this, 'willReadMessageCallback'));
}
protected function newProtocolLog($is_proxy) {
if ($is_proxy) {
return null;
}
// While developing, do this to write a full protocol log to disk:
//
// return new PhabricatorProtocolLog('/tmp/git-protocol.log');
return null;
}
final protected function getProtocolLog() {
return $this->protocolLog;
}
final protected function setProtocolLog(PhabricatorProtocolLog $log) {
$this->protocolLog = $log;
}
final protected function getWireProtocol() {
return $this->wireProtocol;
}
final protected function setWireProtocol(
DiffusionGitWireProtocol $protocol) {
$this->wireProtocol = $protocol;
return $this;
}
public function willWriteMessageCallback(
PhabricatorSSHPassthruCommand $command,
$message) {
$this->ioBytesWritten += strlen($message);
$log = $this->getProtocolLog();
if ($log) {
$log->didWriteBytes($message);
}
$protocol = $this->getWireProtocol();
if ($protocol) {
$message = $protocol->willWriteBytes($message);
}
return $message;
}
public function willReadMessageCallback(
PhabricatorSSHPassthruCommand $command,
$message) {
$log = $this->getProtocolLog();
if ($log) {
$log->didReadBytes($message);
}
$protocol = $this->getWireProtocol();
if ($protocol) {
$message = $protocol->willReadBytes($message);
}
// Note that bytes aren't counted until they're emittted by the protocol
// layer. This means the underlying command might emit bytes, but if they
// are buffered by the protocol layer they won't count as read bytes yet.
$this->ioBytesRead += strlen($message);
return $message;
}
final protected function getIOBytesRead() {
return $this->ioBytesRead;
}
final protected function getIOBytesWritten() {
return $this->ioBytesWritten;
}
final protected function executeRepositoryProxyOperations($for_write) {
$device = AlmanacKeys::getLiveDevice();
$refs = $this->getAlmanacServiceRefs($for_write);
$err = 1;
while (true) {
$ref = head($refs);
$command = $this->getProxyCommandForServiceRef($ref);
if ($device) {
$this->writeClusterEngineLogMessage(
pht(
"# Request received by \"%s\", forwarding to cluster ".
"host \"%s\".\n",
$device->getName(),
$ref->getDeviceName()));
}
$command = PhabricatorDaemon::sudoCommandAsDaemonUser($command);
$future = id(new ExecFuture('%C', $command))
->setEnv($this->getEnvironment());
$this->didBeginRequest();
$err = $this->newPassthruCommand()
->setIOChannel($this->getIOChannel())
->setCommandChannelFromExecFuture($future)
->execute();
// TODO: Currently, when proxying, we do not write an event log on the
// proxy. Perhaps we should write a "proxy log". This is not very useful
// for statistics or auditing, but could be useful for diagnostics.
// Marking the proxy logs as proxied (and recording devicePHID on all
// logs) would make differentiating between these use cases easier.
if (!$err) {
$this->waitForGitClient();
return $err;
}
// Throw away this service: the request failed and we're treating the
// failure as persistent, so we don't want to retry another request to
// the same host.
array_shift($refs);
$should_retry = $this->shouldRetryRequest($refs);
if (!$should_retry) {
return $err;
}
// If we haven't bailed out yet, we'll retry the request with the next
// service.
}
throw new Exception(pht('Reached an unreachable place.'));
}
private function didBeginRequest() {
$this->requestAttempts++;
return $this;
}
private function shouldRetryRequest(array $remaining_refs) {
$this->requestFailures++;
if ($this->requestFailures > $this->requestAttempts) {
throw new Exception(
pht(
"Workflow has recorded more failures than attempts; there is a ".
"missing call to \"didBeginRequest()\".\n"));
}
if (!$remaining_refs) {
$this->writeClusterEngineLogMessage(
pht(
"# All available services failed to serve the request, ".
"giving up.\n"));
return false;
}
$read_len = $this->getIOBytesRead();
if ($read_len) {
$this->writeClusterEngineLogMessage(
pht(
"# Client already read from service (%s bytes), unable to retry.\n",
new PhutilNumber($read_len)));
return false;
}
$write_len = $this->getIOBytesWritten();
if ($write_len) {
$this->writeClusterEngineLogMessage(
pht(
"# Client already wrote to service (%s bytes), unable to retry.\n",
new PhutilNumber($write_len)));
return false;
}
$this->writeClusterEngineLogMessage(
pht(
"# Service request failed, retrying (making attempt %s of %s).\n",
new PhutilNumber($this->requestAttempts + 1),
new PhutilNumber($this->requestAttempts + count($remaining_refs))));
return true;
}
}
| true |
5a4c6761bc41bf51ecbd83160e74978d402f0449 | PHP | Expendables3/FGameServer | /libs/BillingAPI.php | UTF-8 | 18,029 | 2.796875 | 3 | [] | no_license | <?php
define("BILLING_BALANCE_INQUIRY", 1);
define("BILLING_PURCHASEID_INQUIRY", 2);
define("BILLING_ITEM_PURCHASE", 3);
define("BILLING_PAY_PACK_CASHID", 5);
define("BILLING_PAY_PACK_PROMO", 4);
/**
* @author ToanTN GSN
*/
class Utilities {
public static function packInt32($int32) {
$data = "";
$data .= chr($int32 & 0xFF);
$data .= chr(($int32>>8) & 0xFF);
$data .= chr(($int32>>16) & 0xFF);
$data .= chr(($int32>>24) & 0xFF);
return $data;
}
public static function unpackInt32($data) {
return (float) sprintf("%u",
((ord($data[3]) << 24) |
(ord($data[2]) << 16) |
(ord($data[1]) << 8) |
(ord($data[0]))));
}
public static function packInt64Hex($int64Hex) {
//$data is hex number string
//return 8bytes in little-endian
return strrev(pack("H*", $int64Hex));
}
public static function unpackInt64Hex($data) {
//$data is 8bytes in little-endian
//return hex number string
$tokens = unpack("H*", strrev($data));
return $tokens[1];
}
public static function int64FromInt64Hex($int64Hex) {
return (float)sprintf("%.0f", hexdec($int64Hex));
}
public static function decFromInt64Hex($int64Hex) {
return hexdec($int64Hex);
}
public static function packString($str, $packlen) {
$data = "";
$len = strlen($str);
for($i=0; $i<$len; $i++) {
$data .= pack("c", ord(substr($str, $i, 1)));
}
return pack("a$packlen", $data);
}
public static function unpackString($data, $len) {
$tmp_arr = unpack("c".$len."chars", $data);
$str = "";
foreach($tmp_arr as $v) {
if($v>0) {
$str .= chr($v);
}
}
return $str;
}
public static function packUniString($str, $packlen) {
$data = mb_convert_encoding($str, 'UCS-2LE', 'UTF-8');
return pack("a$packlen", $data);
}
public static function unpackUniString($data, $len) {
$tmp_arr = unpack("C".$len."chars", $data);
$uniStr = "";
foreach($tmp_arr as $v) {
if($v > 0) {
$uniStr .= chr($v);
}
}
return $uniStr;
}
public static function showDecBlock($data) {
$length = strlen($data);
echo("<b><u>[$length bytes]</u></b><br>{");
for ($i=0; $i<$length; $i++) {
if ($length === 116) {
if ($i === 2)
echo("<b><u>");
elseif ($i === 4)
echo("</u></b>");
elseif ($i === 6)
echo("<b><u>");
else if ($i === 108)
echo("</u></b>");
elseif ($i === 116)
echo("<b><u>");
}
if ($i > 0)
echo(":");
echo(hexdec(bin2hex($data[$i])));
}
echo("}<br>");
}
public static function showHexBlock($data) {
$length = strlen($data);
echo("<b><u>[$length bytes]</u></b><br>{");
for ($i=0; $i<$length; $i++) {
if ($length === 116) {
if ($i === 2)
echo("<b><u>");
elseif ($i === 4)
echo("</u></b>");
elseif ($i === 6)
echo("<b><u>");
else if ($i === 108)
echo("</u></b>");
elseif ($i === 116)
echo("<b><u>");
}
if ($i > 0)
echo(":");
echo(bin2hex($data[$i]));
}
echo("}<br>");
}
public static function showCharBlock($data) {
$length = strlen($data);
echo("<b><u>[$length bytes]</u></b><br>{");
for ($i=0; $i<$length; $i++) {
if ($i > 0)
echo(":");
echo($data[$i]);
}
echo("}<br>");
}
}
class Inquiry {
public $ReqLen; //WORD
public $ReqType; //WORD
public $RetCode; //_int16
function __construct($ReqType, $RetCode=1) {
$this->ReqLen = 3*2; //2xWORD + _int16
$this->ReqType = $ReqType;
$this->RetCode = $RetCode;
}
public function socketDataPack() {
$data = pack("vvs", $this->ReqLen, $this->ReqType, $this->RetCode);
return $data;
}
public function socketDataUnpack($data) {
$offset = 0; //at the begin
$len = 6; //3xWORD
$tokens = unpack("vReqLen/vReqType/sRetCode", substr($data, $offset, $len));
$this->ReqLen = $tokens["ReqLen"];
$this->ReqType = $tokens["ReqType"];
$this->RetCode = $tokens["RetCode"];
$offset += $len;
return $offset;
}
}
class BalanceInq extends Inquiry {
public $AccountName; //WCHAR 50+1
public $CashRemain; //_int64Hex
function __construct($ReqType, $AccountName, $CashRemain="0", $RetCode=0) {
parent::__construct($ReqType, $RetCode);
$this->AccountName = $AccountName;
$this->CashRemain = str_pad(ltrim($CashRemain, "0x"), 16, "0", STR_PAD_LEFT);
$this->ReqLen += 51*2 + 8; //51wchars + _int64
}
public function socketDataPack() {
$data = parent::socketDataPack();
$data .= Utilities::packUniString($this->AccountName, 51*2);
$data .= Utilities::packInt64Hex($this->CashRemain);
return $data;
}
public function socketDataUnpack($data) {
$offset = parent::socketDataUnpack($data);
//AccountName
$len = 51*2;
$this->AccountName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
//CashRemain
$len = 8;
$this->CashRemain = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
}
}
class PurchaseIDInq extends Inquiry {
public $AccountName; //WCHAR 50+1
public $PurchaseID; //_int64Hex
function __construct($ReqType, $AccountName, $PurchaseID="0", $RetCode=0) {
parent::__construct($ReqType, $RetCode);
$this->AccountName = $AccountName;
$this->PurchaseID = str_pad(ltrim($PurchaseID, "0x"), 16, "0", STR_PAD_LEFT);
$this->ReqLen += 51*2 + 8; //51wchars + _int64
}
public function socketDataPack() {
$data = parent::socketDataPack();
$data .= Utilities::packUniString($this->AccountName, 51*2);
$data .= Utilities::packInt64Hex($this->PurchaseID);
return $data;
}
public function socketDataUnpack($data) {
$offset = parent::socketDataUnpack($data);
//AccountName
$len = 51*2;
$this->AccountName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
//PurchaseID
$len = 8;
$this->PurchaseID = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
}
}
/**
* ToanTN write for Promo Function
*/
class CashIDInq extends Inquiry {
public $AccountName; //WCHAR 50+1
public $CashID; //_int64Hex
function __construct($ReqType, $AccountName, $CashID="0", $RetCode=0) {
parent::__construct($ReqType, $RetCode);
$this->AccountName = $AccountName;
$this->CashID = str_pad(ltrim($CashID, "0x"), 16, "0", STR_PAD_LEFT);
$this->ReqLen += 51*2 + 8; //51wchars + _int64
}
public function socketDataPack() {
$data = parent::socketDataPack();
$data .= Utilities::packUniString($this->AccountName, 51*2);
$data .= Utilities::packInt64Hex($this->CashID);
return $data;
}
public function socketDataUnpack($data) {
$offset = parent::socketDataUnpack($data);
//AccountName
$len = 51*2;
$this->AccountName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
//PurchaseID
$len = 8;
$this->CashID = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
}
}
/**
* ToanTN write for Promo Function
*/
class PromoCash extends Inquiry {
public $CashID; //_int64Hex
public $AccountName; //WCHAR 50+1
public $AccountNumb; //int64Hex
public $CashAmt; //_int64Hex
public $CashCode; //CHAR 32+1 //WCHAR 20+1
public $AdminId; //WCHAR 50+1 //WCHAR 32+1
public $PromoCampaignId; //_int32
public $CashRemain; //_int64Hex
function __construct($ReqType, $CashID, $AccountName, $CashRemain = "0",
$AccountNumb=0, $CashAmt="0", $CashCode="", $AdminId ="ToanTN",$PromoCampaignId =1,
$RetCode=0) {
parent::__construct($ReqType, $RetCode);
$this->CashID = str_pad(ltrim($CashID, "0x"), 16, "0", STR_PAD_LEFT);
$this->AccountName = $AccountName;
$this->AccountNumb = str_pad(ltrim($AccountNumb, "0x"), 16, "0", STR_PAD_LEFT); ;
$this->CashAmt = str_pad(ltrim($CashAmt, "0x"), 16, "0", STR_PAD_LEFT);
$this->CashCode = $CashCode;
$this->AdminId = $AdminId;
$this->PromoCampaignId = $PromoCampaignId ;
$this->CashRemain = str_pad(ltrim($CashRemain, "0x"), 16, "0", STR_PAD_LEFT);
$this->ReqLen += 8*4 + 4*1 + 51*2 + 21*2 + 33*2 ; //4x_int64 + 1x_int32 + 1x51wchars + 1x20wchars + 1x32wchars
}
public function socketDataPack() {
$data = parent::socketDataPack();
$data .= Utilities::packInt64Hex($this->CashID);
$data .= Utilities::packUniString($this->AccountName, 51*2);
$data .= Utilities::packInt64Hex($this->AccountNumb);
$data .= Utilities::packInt64Hex($this->CashAmt);
$data .= Utilities::packUniString($this->CashCode,21*2);
$data .= Utilities::packUniString($this->AdminId, 33*2);
$data .= Utilities::packInt32($this->PromoCampaignId);
$data .= Utilities::packInt64Hex($this->CashRemain);
return $data;
}
public function socketDataUnpack($data) {
$offset = parent::socketDataUnpack($data);
//PurchaseID
$len = 8;
$this->CashID = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
//AccountName
$len = 51*2;
$this->AccountName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
$len = 8;
$this->AccountNumb = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
//CashAmt
$len = 8;
$this->CashAmt = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
//PurchaseCode
$len = 21*2;
$this->CashCode = Utilities::unpackUniString(substr($data, $offset, $len),$len/2);//Utilities::unpackString(substr($data, $offset, $len), $len);
$offset += $len;
//AdminName
$len = 33*2;
$this->AdminId = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
$len = 4;
$this->PromoCampaignId = Utilities::unpackInt32(substr($data, $offset, $len));
$offset += $len;
//CashRemain
$len = 8;
$this->CashRemain = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
}
}
class ItemPurchase extends Inquiry {
public $PurchaseID; //_int64Hex
public $AccountName; //WCHAR 50+1
public $ItemID; //_int32
public $ItemQuantity; //_int32
public $ItemName; //WCHAR 50+1
public $CashAmt; //_int64Hex
public $PurchaseCode; //CHAR 32+1
public $Reserved; //_int32
public $CashRemain; //_int64Hex
function __construct($ReqType, $PurchaseID, $AccountName, $CashRemain = "0",
$ItemID=0, $ItemQuantity=0, $ItemName="", $CashAmt="0", $PurchaseCode="", $Reserved=0,
$RetCode=0) {
parent::__construct($ReqType, $RetCode);
$this->PurchaseID = str_pad(ltrim($PurchaseID, "0x"), 16, "0", STR_PAD_LEFT);
$this->AccountName = $AccountName;
$this->ItemID = $ItemID;
$this->ItemQuantity = $ItemQuantity;
$this->ItemName = $ItemName;
$this->CashAmt = str_pad(ltrim($CashAmt, "0x"), 16, "0", STR_PAD_LEFT);
$this->PurchaseCode = $PurchaseCode;
$this->Reserved = $Reserved;
$this->CashRemain = str_pad(ltrim($CashRemain, "0x"), 16, "0", STR_PAD_LEFT);
$this->ReqLen += 8*3 + 4*3 + 2*51*2 + 33; //3x_int64 + 3x_int32 + 2x51wchars + 33chars
}
public function socketDataPack() {
$data = parent::socketDataPack();
$data .= Utilities::packInt64Hex($this->PurchaseID);
$data .= Utilities::packUniString($this->AccountName, 51*2);
$data .= Utilities::packInt32($this->ItemID);
$data .= Utilities::packInt32($this->ItemQuantity);
$data .= Utilities::packUniString($this->ItemName, 51*2);
$data .= Utilities::packInt64Hex($this->CashAmt);
$data .= pack("a33", $this->PurchaseCode);
$data .= Utilities::packInt32($this->Reserved);
$data .= Utilities::packInt64Hex($this->CashRemain);
return $data;
}
public function socketDataUnpack($data) {
$offset = parent::socketDataUnpack($data);
//PurchaseID
$len = 8;
$this->PurchaseID = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
//AccountName
$len = 51*2;
$this->AccountName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
$len = 4;
$this->ItemID = Utilities::unpackInt32(substr($data, $offset, $len));
$offset += $len;
$len = 4;
$this->ItemQuantity = Utilities::unpackInt32(substr($data, $offset, $len));
$offset += $len;
//ItemName
$len = 51*2;
$this->ItemName = Utilities::unpackUniString(substr($data, $offset, $len), $len/2);
$offset += $len;
//CashAmt
$len = 8;
$this->CashAmt = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
//PurchaseCode
$len = 33;
$this->PurchaseCode = trim(substr($data, $offset, $len), "\0");//Utilities::unpackString(substr($data, $offset, $len), $len);
$offset += $len;
$len = 4;
$this->Reserved = Utilities::unpackInt32(substr($data, $offset, $len));
$offset += $len;
//CashRemain
$len = 8;
$this->CashRemain = Utilities::unpackInt64Hex(substr($data, $offset, $len));
$offset += $len;
}
}
class BillingSocket {
public $ip;
public $port;
public $sk;
function __construct($ip, $port) {
$this->ip = $ip;
$this->port = $port;
}
public function openSocket($timeout, &$errnum, &$errstr) {
$this->sk=fsockopen($this->ip, $this->port, $errnum, $errstr, $timeout);
if (!is_resource($this->sk)) {
return null;
} else {
return $this->sk;
}
}
public function writeSocket($data) {
return fputs($this->sk, $data);
}
public function readSocket($length) {
return fgets($this->sk, $length);
}
public function endOfSocket() {
return feof($this->sk);
}
public function closeSocket() {
return fclose($this->sk);
}
}
class BillingAPI {
public $billingSocket;
public $errnum;
public $errstr;
function __construct($ip, $port, $timeout=30) {
$this->billingSocket = new BillingSocket($ip, $port);
$sk = $this->billingSocket->openSocket($timeout, $this->errnum, $this->errstr);
if ($sk === null) {
unset($this->billingSocket);
//exit("Socket connection fail: ".$this->errnum." ".$this->errstr);
}
}
function __destruct() {
$this->billingSocket->closeSocket();
unset($this->billingSocket);
}
public static function getErrorCodeString($errorCode) {
$errorCodeString = "";
switch ($errorCode) {
case 1:
$errorCodeString = "SUCCESSFUL";
break;
case 0:
$errorCodeString = "SYSTEM_BUSY";
break;
case -1:
$errorCodeString = "FAIL_TO_RECEIVE_REQ_MSG";
break;
case -2:
$errorCodeString = "INVALID_REQ_LEN";
break;
case -3:
$errorCodeString = "INVALID_REQ_TYPE";
break;
case -4:
$errorCodeString = "FAIL_TO_DECODE_MSG";
break;
case -5:
$errorCodeString = "INVALID_DEFAULT_REQ_LEN";
break;
case -6:
$errorCodeString = "NOT_ALLOWED_IP";
break;
case -7:
$errorCodeString = "INVALID_INPUT";
break;
case -8:
$errorCodeString = "INVALID_PRODUCT_ID";
break;
case -9:
$errorCodeString = "CLIENT_DISCONNECTED";
break;
case -10:
$errorCodeString = "UNDEFINE_ERRORCODE";
break;
case -11:
$errorCodeString = "UNDEFINE_ERRORCODE";
break;
//Account
case -101:
$errorCodeString = "INVALID_ACCOUNT_NO";
break;
case -102:
$errorCodeString = "INVALID_ACCOUNT_NAME";
break;
case -103:
$errorCodeString = "SUSPENDED_ACCOUNT";
break;
//Cash
case -201:
$errorCodeString = "INVALID_CASH_ID";
break;
case -202:
$errorCodeString = "INVALID_CASH_TYPE";
break;
case -203:
$errorCodeString = "INVALID_CASH_AMT";
break;
case -204:
$errorCodeString = "INSUFFICIENT_CASH_POSSESSION";
break;
//Purchase
case -301:
$errorCodeString = "INVALID_PURCHASE_ID";
break;
//Item
case -401:
$errorCodeString = "INVALID_ITEM_ID";
break;
case -402:
$errorCodeString = "INVALID_ITEM_NAME";
break;
case -403:
$errorCodeString = "INVALID_ITEM_QUANTITY";
break;
}
return $errorCodeString;
}
public function doBalanceInqiry($username, &$cashRemain) {
$queryObject = new BalanceInq(BILLING_BALANCE_INQUIRY, $username, "", 0);
$data = $queryObject->socketDataPack();
$this->billingSocket->writeSocket($data);
$data="";
while (!$this->billingSocket->endOfSocket()) {
$token = $this->billingSocket->readSocket(1024);
$data.= $token;
}
$queryObject->socketDataUnpack($data);
$retCode = $queryObject->RetCode;
if ($retCode === 1) {
$cashRemain = $queryObject->CashRemain;
}
unset($queryObject);
return $retCode;
}
public function doPurchaseIDInqiry($username, &$purchaseID) {
$queryObject = new PurchaseIDInq(BILLING_PURCHASEID_INQUIRY, $username, "", 0);
$data = $queryObject->socketDataPack();
$this->billingSocket->writeSocket($data);
$data="";
while (!$this->billingSocket->endOfSocket()) {
$token = $this->billingSocket->readSocket(1024);
$data.= $token;
}
$queryObject->socketDataUnpack($data);
$retCode = $queryObject->RetCode;
if ($retCode === 1) {
$purchaseID = $queryObject->PurchaseID;
}
unset($queryObject);
return $retCode;
}
public function doItemPurchase(
$purchaseID, $username, &$cashRemain = "0",
$itemID=0, $itemQuantity=0, $itemName="", $cashAmt="0", $purchaseCode="") {
$queryObject = new ItemPurchase(
BILLING_ITEM_PURCHASE,
$purchaseID,
$username,
$cashRemain,
$itemID,
$itemQuantity,
$itemName,
$cashAmt,
$purchaseCode,
0,
0);
$data = $queryObject->socketDataPack();
$this->billingSocket->writeSocket($data);
$data="";
while (!$this->billingSocket->endOfSocket()) {
$token = $this->billingSocket->readSocket(1024);
$data.= $token;
}
$queryObject->socketDataUnpack($data);
$retCode = $queryObject->RetCode;
if ($retCode === 1) {
$cashRemain = $queryObject->CashRemain;
}
unset($queryObject);
return $retCode;
}
}
?>
| true |
5ab32901bba526d0933d73fd3c6f3d7d1762e71e | PHP | Seafnox/CMS6 | /CMS/protected/extensions/imgresizer/ImagePng.php | UTF-8 | 314 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | <?
class ImagePng extends ImageResizer
{
function createImg()
{
$this->img_res = imagecreatefrompng($this->source_path);
$this->processBg($this->img_res);
}
function processBg($img)
{
imageAlphaBlending($img, false);
imageSaveAlpha($img, true);
}
}
?> | true |
b2cc4582e8ffa35fe28e2dbdb4cd72bc173bd10e | PHP | trailburning/tb-api | /src/AppBundle/Entity/RaceEventAttribute.php | UTF-8 | 3,327 | 2.515625 | 3 | [] | no_license | <?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use JMS\Serializer\Annotation as Serializer;
use Swagger\Annotations as SWG;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* MediaAttribute.
*
* @ORM\Table(name="api_race_event_attribue")
* @ORM\Entity(repositoryClass="AppBundle\Repository\RaceEventAttributeRepository")
* @SWG\Definition(required={"id", "name"}, @SWG\Xml(name="RaceEventAttribute"))
* @Serializer\ExclusionPolicy("all")
*/
class RaceEventAttribute
{
/**
* @var int
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
* @SWG\Property()
* @Serializer\Expose
* @Serializer\Groups({"raceEvent"})
*/
private $id;
/**
* @var string
*
* @ORM\Column(type="string", length=255)
* @SWG\Property()
* @Serializer\Expose
* @Serializer\Groups({"raceEvent"})
*/
private $name;
/**
* @var string
*
* @Gedmo\Slug(fields={"name"}, updatable=false)
* @ORM\Column(type="string", length=255, unique=true)
*/
protected $slug;
/**
* @var RaceEvents[]
*
* @ORM\ManyToMany(targetEntity="RaceEvent", mappedBy="attributes")
*/
private $raceEvents;
/**
* ################################################################################################################.
*
* User Defined
*
* ################################################################################################################
*/
public function __construct($name = null)
{
$this->setName($name);
$this->raceEvents = new ArrayCollection();
}
/**
* ################################################################################################################.
*
* Getters and Setters
*
* ################################################################################################################
*/
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param string $name
*
* @return self
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @param RaceEvent $raceEvent
*
* @return self
*/
public function addRaceEvent(RaceEvent $raceEvent)
{
$this->raceEvents[] = $raceEvent;
return $this;
}
/**
* @param RaceEvent $raceEvent
*/
public function removeRaceEvent(RaceEvent $raceEvent)
{
$this->raceEvents->removeElement($raceEvent);
}
/**
* @return \Doctrine\Common\Collections\Collection
*/
public function getRaceEvents()
{
return $this->raceEvents;
}
/**
* @param string $slug
*
* @return self
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* @return string
*/
public function getSlug()
{
return $this->slug;
}
}
| true |
01adf16f447e427c3aff2f7f3909c79617cc7068 | PHP | epipav/subscription-management | /app/Http/Middleware/JwtAuth.php | UTF-8 | 971 | 2.78125 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use \Firebase\JWT\JWT;
use \Firebase\JWT\ExpiredException;
class JwtAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$requestArray = $request->all();
try{
$jwt_decoded = JWT::decode($requestArray["client-token"], env('JWT_SECRET'), array('HS256'));
}
catch(\Firebase\JWT\ExpiredException $ex){
return response(["message"=> "Client token expired, please register again."],401);
}
catch(\Exception $e){
return response(["message"=> "Bad client token."],401);;
}
$input = $request->all();
$input["device"] = $jwt_decoded;
$request->replace($input);
return $next($request);
}
}
| true |
f235e3f6a67a390f54a180083f6c3bc45db704af | PHP | vinicius-developer/manager-controll-go-back | /app/Http/Middleware/CompanySet.php | UTF-8 | 1,357 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Middleware;
use App\Models\RelacaoUsuarioEmpresa;
use App\Traits\ResponseMessage;
use App\Traits\Authenticate;
use Illuminate\Http\Request;
use App\Models\Empresa;
use Exception;
use Closure;
class CompanySet
{
use Authenticate, ResponseMessage;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
try {
$token = $this->decodeToken($request);
} catch (Exception $e) {
return $this->formateMenssageError('Você não tem acesso ao a essa ação', 401);
}
try {
if(!Empresa::checkEmpreIsActiveStatic($token->com)->exists()) {
return $this->formateMenssageError('Você não tem acesso a essa ação', 403);
}
} catch (Exception $e) {
return $this->formateMenssageError('Empresa invalida', 403);
}
try {
if(RelacaoUsuarioEmpresa::getRelationshipStatic($token->sub, $token->com)) {
return $next($request);
}
} catch (Exception $e) {
return $this->formateMenssageError('Não foi possível concluir ação', 401);
}
}
}
| true |
4f1d93b2d0016a033a104fc085aa573e0b610b2c | PHP | GeorgeKariukiNgugi/MrInsuranceBackEnd | /app/Http/Controllers/Payments/IntentionToPayController.php | UTF-8 | 2,450 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Payments;
use App\Payments\IntentionToPay;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class IntentionToPayController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//! this action is used to expres the intention to pay.
$intentionToPay = new IntentionToPay();
$intentionToPay->uuid = $request->uuid;
$intentionToPay->MerchantRequestID = $request->MerchantRequestID;
$intentionToPay->CheckoutRequestID = $request->CheckoutRequestID;
$intentionToPay->amountPayable =$request->amountPayable;
$intentionToPay->visitorId =$request->visitorId;
$intentionToPay->InsuranceCoverId = $request->insuranceCoverID;
$intentionToPay->save();
return response("Successfully Added Intention To Pay.",200);
}
/**
* Display the specified resource.
*
* @param \App\Payments\IntentionToPay $intentionToPay
* @return \Illuminate\Http\Response
*/
public function show(IntentionToPay $intentionToPay)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Payments\IntentionToPay $intentionToPay
* @return \Illuminate\Http\Response
*/
public function edit(IntentionToPay $intentionToPay)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Payments\IntentionToPay $intentionToPay
* @return \Illuminate\Http\Response
*/
public function update(Request $request, IntentionToPay $intentionToPay)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Payments\IntentionToPay $intentionToPay
* @return \Illuminate\Http\Response
*/
public function destroy(IntentionToPay $intentionToPay)
{
//
}
}
| true |
97cc9d8ec4441279d7c711174eb8abcddec22807 | PHP | RebieKong/mp-tools | /src/Exception/HookException.php | UTF-8 | 1,107 | 2.765625 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: rebie
* Date: 17-1-30
* Time: 上午12:31
*/
namespace RebieKong\MpTools\Exception;
use RebieKong\MpTools\Entity\MessageBean;
use RebieKong\MpTools\Hook\HookInterface;
class HookException extends MpException
{
const HOOK_NOT_EXIST = 1;
const HOOK_CALL_ERROR = 2;
public function __construct($code, $message = '')
{
parent::__construct($message, $code, null);
}
/**
* @param MessageBean $bean
* @param HookInterface $hook
*
* @return string
*/
public function handle($bean, $hook)
{
switch ($this->getCode()) {
case HookException::HOOK_NOT_EXIST:
$response = $hook->call(HookInterface::HOOK_FUNCTION_NOT_EXIST, ['bean' => $bean]);
break;
case HookException::HOOK_CALL_ERROR:
$response = $hook->call(HookInterface::HOOK_FUNCTION_CALL_ERROR, ['bean' => $bean]);
break;
default:
$response = 'success';
break;
}
return $response;
}
} | true |
9c1b61c453f445209c09f6db42173cbaf0bca7ec | PHP | epiecs/phpmiko | /src/Protocols/Telnet.php | UTF-8 | 3,053 | 3.34375 | 3 | [
"MIT"
] | permissive | <?php
namespace Epiecs\PhpMiko\Protocols;
class Telnet implements ProtocolInterface
{
const DEFAULTPORT = 23;
const DEFAULTTIMEOUT = 5;
private $connection = false;
private $readBytes = 128;
public function __construct($hostname, $port = null, $timeout = null)
{
$port = $port ?? self::DEFAULTPORT;
$timeout = $timeout ?? self::DEFAULTTIMEOUT;
$this->connection = @fsockopen($hostname, $port, $errno, $errstr, $timeout);
stream_set_timeout($this->connection, 5);
return $this->connection;
}
/**
* Will try and log in with the given password and/or usename.
* @param boolean $username Optional username
* @param boolean $password Optional password
*/
public function login($username = null, $password = null) : bool
{
/**
* If the read value is null it means the prompt has stopped at a password/username input
*/
if(!in_array($username, [null, ""]))
{
$this->read(false);
fputs($this->connection, "{$username}\r\n");
}
if(!in_array($password, [null, ""]))
{
$this->read(false);
fputs($this->connection, "{$password}\r\n");
}
return true;
}
public function write($command) : void
{
fputs($this->connection, "{$command}");
}
/**
* Keeps on reading the connection until the expect is matched
*
* Mode 1 is literal [default]
* Mode 2 is regex
*
* @param mixed $expect Can be false or a string. If false is given reads will continue until a there is no more output
* @param integer $mode Match mode, 1 is literal [default] and 2 is regex
* @return string All output from the command
*/
public function read($expect, $mode = 1) : string
{
$outputBuffer = "";
while (!feof($this->connection) && $this->connection)
{
$read = fgets($this->connection, $this->readBytes);
$outputBuffer .= $read;
switch ($mode)
{
case 2:
if(preg_match($expect, $read)) {break 2;}
break;
case 1:
default:
if($read == $expect) {break 2;}
break;
}
}
return $outputBuffer;
}
/**
* Will flush all data from the connection and return it.
*
* @return string The output buffer
*/
public function flush() : string
{
// read with a value false keeps on reading until the end of the buffer
$outputBuffer = $this->read(false);
return $outputBuffer;
}
/**
* Gracefully closes the connection
*
* @return boolean
*/
public function disconnect() : void
{
fclose($this->connection);
}
}
| true |
81cdc8ed1368d35083f84773d9a455cde83dcc10 | PHP | lsv/uber-api | /src/Entity/User/History.php | UTF-8 | 6,294 | 2.890625 | 3 | [
"MIT"
] | permissive | <?php
/*
* This file is part of the Lsv\UberApi package
*
* (c) Martin Aarhof <martin.aarhof@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Lsv\UberApi\Entity\User;
use Lsv\UberApi\Entity\AbstractEntity;
use Lsv\UberApi\Entity\City;
use Lsv\UberApi\Entity\EntityInterface;
use Lsv\UberApi\Util\EntityUtil;
/**
* User history (version 1.2).
*/
class History extends AbstractEntity implements EntityInterface
{
/**
* Unique activity identifier.
*
* @var string
*/
protected $requestId;
/**
* Unix timestamp of activity request time.
*
* @var \DateTime
*/
protected $requestTime;
/**
* Unique identifier representing a specific product.
*
* @var string
*/
protected $productId;
/**
* Status of the activity. Only returns completed for now.
*
* @var string
*/
protected $status;
/**
* Length of activity in miles.
*
* @var float
*/
protected $distance;
/**
* Date of activity start time.
*
* @var \DateTime
*/
protected $startTime;
/**
* Date of activity end time.
*
* @var \DateTime
*/
protected $endTime;
/**
* Details about the city the activity started in.
*
* @var City
*/
protected $startCity;
/**
* Constructor.
*
* @param string $requestId Unique activity identifier.
* @param int $requestTime Unix timestamp of activity request time.
* @param string $productId Unique identifier representing a specific product
* @param string $status Status of the activity. Only returns completed for now.
* @param float $distance Length of activity in miles.
* @param int $startTime Unix timestamp of activity start time.
* @param int $endTime Unix timestamp of activity end time.
* @param City $startCity Details about the city the activity started in.
*/
public function __construct($requestId = null, $requestTime = null, $productId = null, $status = null, $distance = null, $startTime = null, $endTime = null, City $startCity = null)
{
$this->requestId = $requestId;
$this->requestTime = $requestTime;
$this->productId = $productId;
$this->status = $status;
$this->distance = $distance;
$this->startTime = $startTime;
$this->endTime = $endTime;
$this->startCity = $startCity;
}
/**
* Gets the RequestId.
*
* @return string
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Sets the RequestId.
*
* @param string $requestId
*
* @return History
*/
public function setRequestId($requestId)
{
$this->requestId = $requestId;
return $this;
}
/**
* Gets the RequestTime.
*
* @return \DateTime
*/
public function getRequestTime()
{
return $this->requestTime;
}
/**
* Sets the RequestTime.
*
* @param int $requestTime
*
* @return History
*/
public function setRequestTime($requestTime)
{
$date = new \DateTime('@'.$requestTime);
$this->requestTime = $date;
return $this;
}
/**
* Gets the ProductId.
*
* @return string
*/
public function getProductId()
{
return $this->productId;
}
/**
* Sets the ProductId.
*
* @param string $productId
*
* @return History
*/
public function setProductId($productId)
{
$this->productId = $productId;
return $this;
}
/**
* Gets the Status.
*
* @return string
*/
public function getStatus()
{
return $this->status;
}
/**
* Sets the Status.
*
* @param string $status
*
* @return History
*/
public function setStatus($status)
{
$this->status = $status;
return $this;
}
/**
* Gets the Distance.
*
* @return float
*/
public function getDistance()
{
return $this->distance;
}
/**
* Sets the Distance.
*
* @param float $distance
*
* @return History
*/
public function setDistance($distance)
{
$this->distance = $distance;
return $this;
}
/**
* Gets the StartTime.
*
* @return \DateTime
*/
public function getStartTime()
{
return $this->startTime;
}
/**
* Sets the StartTime.
*
* @param int $startTime
*
* @return History
*/
public function setStartTime($startTime)
{
$date = new \DateTime('@'.$startTime);
$this->startTime = $date;
return $this;
}
/**
* Gets the EndTime.
*
* @return \DateTime
*/
public function getEndTime()
{
return $this->endTime;
}
/**
* Sets the EndTime.
*
* @param int $endTime
*
* @return History
*/
public function setEndTime($endTime)
{
$date = new \DateTime('@'.$endTime);
$this->endTime = $date;
return $this;
}
/**
* Gets the StartCity.
*
* @return City
*/
public function getStartCity()
{
return $this->startCity;
}
/**
* Sets the StartCity.
*
* @param City $startCity
*
* @return History
*/
public function setStartCity(City $startCity)
{
$this->startCity = $startCity;
return $this;
}
/**
* Create entity from array.
*
* @param array|null $results
* @param array $queryParameters
* @param array $pathParameters
*
* @return array|null|object
*/
public static function createFromArray(array $results = null, array $queryParameters = null, array $pathParameters = null)
{
return EntityUtil::multipleCreateFromArray(self::class, $queryParameters, $pathParameters, $results, [
'StartCity' => ['setter' => 'setStartCity', 'class' => City::class],
]);
}
}
| true |
4c8b7eb0ce34b89b912be4316dbda68bf32895d4 | PHP | kauandotnet/catalogo-digital-whatsapp | /vendor/telegram-bot/api/src/Types/MessageEntity.php | UTF-8 | 3,732 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: iGusev
* Date: 13/04/16
* Time: 04:10
*/
namespace TelegramBot\Api\Types;
use TelegramBot\Api\BaseType;
use TelegramBot\Api\TypeInterface;
class MessageEntity extends BaseType implements TypeInterface
{
const TYPE_MENTION = 'mention';
const TYPE_HASHTAG = 'hashtag';
const TYPE_CASHTAG = 'cashtag';
const TYPE_BOT_COMMAND = 'bot_command';
const TYPE_URL = 'url';
const TYPE_EMAIL = 'email';
const TYPE_PHONE_NUMBER = 'phone_number';
const TYPE_BOLD = 'bold';
const TYPE_ITALIC = 'italic';
const TYPE_UNDERLINE = 'underline';
const TYPE_STRIKETHROUGH = 'strikethrough';
const TYPE_CODE = 'code';
const TYPE_PRE = 'pre';
const TYPE_TEXT_LINK = 'text_link';
const TYPE_TEXT_MENTION = 'text_mention';
/**
* {@inheritdoc}
*
* @var array
*/
static protected $requiredParams = ['type', 'offset', 'length'];
/**
* {@inheritdoc}
*
* @var array
*/
static protected $map = [
'type' => true,
'offset' => true,
'length' => true,
'url' => true,
'user' => User::class,
'language' => true,
];
/**
* Type of the entity.
* One of mention (@username), hashtag (#hashtag), cashtag ($USD), bot_command, url, email, phone_number,
* bold (bold text), italic (italic text), underline (underlined text), strikethrough (strikethrough text),
* code (monowidth string), pre (monowidth block), text_link (for clickable text URLs),
* text_mention (for users without usernames)
*
* @var string
*/
protected $type;
/**
* Offset in UTF-16 code units to the start of the entity
*
* @var int
*/
protected $offset;
/**
* Length of the entity in UTF-16 code units
*
* @var int
*/
protected $length;
/**
* Optional. For “text_link” only, url that will be opened after user taps on the text
*
* @var string
*/
protected $url;
/**
* Optional. For “text_mention” only, the mentioned user
*
* @var User
*/
protected $user;
/**
* Optional. For “pre” only, the programming language of the entity text
*
* @var string
*/
protected $language;
/**
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* @return int
*/
public function getOffset()
{
return $this->offset;
}
/**
* @param int $offset
*/
public function setOffset($offset)
{
$this->offset = $offset;
}
/**
* @return int
*/
public function getLength()
{
return $this->length;
}
/**
* @param int $length
*/
public function setLength($length)
{
$this->length = $length;
}
/**
* @return string
*/
public function getUrl()
{
return $this->url;
}
/**
* @param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* @return string
*/
public function getLanguage()
{
return $this->language;
}
/**
* @param string $language
*/
public function setLanguage($language)
{
$this->language = $language;
}
}
| true |
25e0246f0ffced5406584f6f9f5bc35aa42ccb5f | PHP | Qinjianbo/blog | /app/Http/Controllers/CaptchaController.php | UTF-8 | 697 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Validator;
class CaptchaController extends Controller
{
/**
* check
*
* @param Illuminate\Http\Request $request
*
* @access public
*
* @return Illuminate\Support\Collection
*/
public function check(Request $request)
{
$rules = ['captcha' => 'required|captcha'];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return $this->result(collect(), '验证码输入错误', 100);
}
return $this->result(collect(), '验证码输入正确');
}
}
| true |
fee8fb3e097707f20a0ece87c4e064b4cf91c1f0 | PHP | landasystems/akademik | /ams/models/SmsKeyword.php | UTF-8 | 47,843 | 2.5625 | 3 | [] | no_license | <?php
/**
* This is the model class for table "{{sms_keyword}}".
*
* The followings are the available columns in table '{{sms_keyword}}':
* @property integer $id
* @property string $name
* @property string $description
* @property string $type
* @property string $options
* @property string $autoreplys
*/
class SmsKeyword extends CActiveRecord {
/**
* @return string the associated database table name
*/
public function tableName() {
return '{{sms_keyword}}';
}
/**
* @return array validation rules for model attributes.
*/
public function rules() {
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('', 'length', 'max' => 45),
array('name, description', 'length', 'max' => 255),
array('type', 'length', 'max' => 20),
array('options, autoreplys', 'safe'),
// The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
array('id, name, description, type, options, autoreplys', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array();
}
/**
* @return array customized attribute labels (name=>label)
*/
public function attributeLabels() {
return array(
'id' => 'ID',
'name' => 'Keyword',
'description' => 'Description',
'type' => 'Type',
'options' => 'Options',
'autoreplys' => 'Autoreplys',
);
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* Typical usecase:
* - Initialize the model fields with values from filter form.
* - Execute this method to get CActiveDataProvider instance which will filter
* models according to data in model fields.
* - Pass data provider to CGridView, CListView or any similar widget.
*
* @return CActiveDataProvider the data provider that can return the models
* based on the search/filter conditions.
*/
public function search() {
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria = new CDbCriteria;
$criteria->compare('id', $this->id);
$criteria->compare('name', $this->name, true);
$criteria->compare('description', $this->description, true);
$criteria->compare('type', $this->type, true);
$criteria->compare('options', $this->options, true);
$criteria->compare('autoreplys', $this->autoreplys, true);
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
));
}
/**
* Returns the static model of the specified AR class.
* Please note that you should have this exact method in all your CActiveRecord descendants!
* @param string $className active record class name.
* @return SmsKeyword the static model class
*/
public static function model($className = __CLASS__) {
return parent::model($className);
}
public function ses() {
if (empty(Yii::app()->session['SmsKeyword'])) {
app()->session['SmsKeyword'] = $this->findAll();
}
return app()->session['SmsKeyword'];
}
public function type() {
$result = array();
$result['info'] = 'Informasi';
$result['register'] = 'Register';
$result['register_reff'] = 'Register Referal';
$result['update'] = 'Update';
if (in_array('game', param('menu'))) {
$result['saldo'] = 'Saldo';
$result['transfer'] = 'Transfer';
$result['2d'] = 'Play 2D';
$result['3d'] = 'Play 3D';
$result['4d'] = 'Play 4D';
$result['cj_satuan'] = 'Colok Jitu Satuan';
$result['cj_puluhan'] = 'Colok Jitu Puluhan';
$result['cj_ratusan'] = 'Colok Jitu Ratusan';
$result['cj_ribuan'] = 'Colok Jitu Ribuan';
$result['cr'] = 'Colok Raun';
$result['deposit'] = 'Deposit';
$result['withdrawal'] = 'Withdrawal';
$result['playresult'] = 'Rekap Pemasangan';
$result['result'] = 'Keluaran Angka';
}
return $result;
}
public function getKey() {
$result = explode("#", $this->name);
return (isset($result[0])) ? strtolower($result[0]) : '';
}
public function check($text, $phone) {
$sDisabled = 'Account anda sedang non aktif,selesaikan tagihan Anda terlebih dahulu. Silahkan kontak Customer Service kami';
$is_keyword = FALSE;
$arrText = explode("#", strtolower(trim($text)));
$sesSmsKeyword = $this->findAll();
// logs("aaaa");
foreach ($sesSmsKeyword as $val) {
if ($val->key == $arrText[0]) {
$is_keyword = TRUE;
$arrOptions = json_decode($val->options, true);
$arrAutoreplys = json_decode($val->autoreplys, true);
$arrVal = explode("#", strtolower(trim($val->name)));
//check wrong keyword
if (count($arrText) == count($arrVal)) {
//do nothing
} else {
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_register']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
if ($val->type == 'register') {
//check number is register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) {
//do nothing
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
//insert to user table
$arrOthers = array();
$oUserNew = new User();
//set for options
if (isset($arrOptions['register_is_generate_code']) && $arrOptions['register_is_generate_code'] == 1)
$oUserNew->code = SiteConfig::model()->formatting('user', false);
if (isset($arrOptions['status_register']) && $arrOptions['status_register'] == 1)
$oUserNew->enabled = true;
if (isset($arrOptions['register_is_generate_password']) && $arrOptions['register_is_generate_password'] == 1) {
$pwdText = rand(1000, 9999);
$oUserNew->password = sha1($pwdText);
}
$oUserNew->roles_id = $arrOptions['roles_id'];
$oUserNew->saldo = $arrOptions['saldo'];
// $arrOthers['saldo_credit'] = ($arrOptions['saldo'] * 75) / 100;
$arrOthers['saldo_prize'] = 0;
$oUserNew->phone = $phone;
//replace insert value from keyword
foreach ($arrVal as $no => $keyVal) {
// echo $val;
if ($keyVal == '{name}')
$oUserNew->name = $arrText[$no];
if ($keyVal == '{address}')
$oUserNew->address = $arrText[$no];
if ($keyVal == '{bank_name}')
$arrOthers['bank_name'] = $arrText[$no];
if ($keyVal == '{bank_account}')
$arrOthers['bank_account'] = $arrText[$no];
if ($keyVal == '{bank_account_name}')
$arrOthers['bank_account_name'] = $arrText[$no];
}
$oUserNew->others = json_encode($arrOthers);
$oUserNew->save();
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success']);
$sReply = str_replace("{code}", $oUserNew->code, $sReply);
$sReply = str_replace("{password}", $pwdText, $sReply);
// logs($sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
}elseif ($val->type == 'info') {
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'register_reff') {
//check number is register
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) {
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//insert to user table
$arrOthers = array();
$oUserNew = new User();
//set for options
if (isset($arrOptions['register_is_generate_code']) && $arrOptions['register_is_generate_code'] == 1)
$oUserNew->code = SiteConfig::model()->formatting('user', false);
if (isset($arrOptions['status_register']) && $arrOptions['status_register'] == 1)
$oUserNew->enabled = true;
if (isset($arrOptions['register_is_generate_password']) && $arrOptions['register_is_generate_password'] == 1) {
$pwdText = rand(1000, 9999);
$oUserNew->password = sha1($pwdText);
}
$oUserNew->referal_user_id = $oUser->id;
$oUserNew->roles_id = $arrOptions['roles_id'];
$oUserNew->saldo = $arrOptions['saldo'];
// $arrOthers['saldo_credit'] = ($arrOptions['saldo'] * 75) / 100;
$arrOthers['saldo_prize'] = 0;
//replace insert value from keyword
$password = '';
foreach ($arrVal as $no => $keyVal) {
// echo $val;
if ($keyVal == '{name}')
$oUserNew->name = $arrText[$no];
if ($keyVal == '{address}')
$oUserNew->address = $arrText[$no];
if ($keyVal == '{bank_name}')
$arrOthers['bank_name'] = $arrText[$no];
if ($keyVal == '{bank_account}')
$arrOthers['bank_account'] = $arrText[$no];
if ($keyVal == '{bank_account_name}')
$arrOthers['bank_account_name'] = $arrText[$no];
if ($keyVal == '{phone_destination}')
$oUserNew->phone = substr($arrText[$no], 1);
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
//check number is register
if (!empty($oUserNew->phone)) {
$oUserDestination = User::model()->find(array('condition' => 'phone="' . $oUserNew->phone . '"'));
if (empty($oUserDestination)) {
//do nothing
} else {
$sReply = str_replace("{phone_destination}", landa()->hp($oUserNew->phone), $arrAutoreplys['failed_wrong_destination']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
$oUserNew->others = json_encode($arrOthers);
$oUserNew->save();
//save ke tabel diagram
MlmDiagram::model()->create($oUserNew, $oUser->id);
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success']);
$sReply = str_replace("{code}", $oUser->code, $sReply);
$sReply = str_replace("{phone_destination}", landa()->hp($oUserNew->phone), $sReply);
$sReply = str_replace("{code_destination}", $oUserNew->code, $sReply);
$sReply = str_replace("{password_destination}", $pwdText, $sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
//kirim sms ke yang di daftarkan
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success_destination']);
$sReply = str_replace("{code}", $oUser->code, $sReply);
$sReply = str_replace("{phone_destination}", landa()->hp($oUserNew->phone), $sReply);
$sReply = str_replace("{code_destination}", $oUserNew->code, $sReply);
$sReply = str_replace("{password_destination}", $pwdText, $sReply);
Sms::model()->insertMsgNumber(0, $oUserNew->phone, $sReply, false, '', true);
} elseif ($val->type == 'update') {
//check number is register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//update to user table
$arrOthers = json_decode($oUser->others, true);
//replace insert value from keyword
foreach ($arrVal as $no => $keyVal) {
//echo $val;
if ($keyVal == '{name}')
$oUser->name = $arrText[$no];
if ($keyVal == '{address}')
$oUser->address = $arrText[$no];
if ($keyVal == '{bank_name}')
$arrOthers['bank_name'] = $arrText[$no];
if ($keyVal == '{bank_account}')
$arrOthers['bank_account'] = $arrText[$no];
if ($keyVal == '{bank_account_name}')
$arrOthers['bank_account_name'] = $arrText[$no];
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
if ($keyVal == '{password_new}')
$passwordNew = trim($arrText[$no]);
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
if (isset($passwordNew)) { //any new password, meaning this action is update password
$oUser->password = sha1($passwordNew);
}
$pwdText = '';
if (isset($arrOptions['is_generate_password']) && $arrOptions['is_generate_password'] == 1) {
$pwdText = rand(1000, 9999);
$oUser->password = sha1($pwdText);
}
$oUser->others = json_encode($arrOthers);
$oUser->save();
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success']);
$sReply = str_replace("{code}", $oUser->code, $sReply);
$sReply = str_replace("{password}", $pwdText, $sReply);
$sReply = str_replace("{password_new}", $passwordNew, $sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'saldo') {
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
//check number is register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $arrAutoreplys['success']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'transfer') {
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{phone}')
$keyPhone = substr($arrText[$no], 1); //remove zero number in front
if ($keyVal == '{amount}')
$keyAmount = $arrText[$no] * 1000;
if ($keyVal == '{type}')
$type = $arrText[$no];
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
if (isset($type) && ($type == 'saldo' || $type == 'bonus')) {
// do nothing
} else {
$sReply = 'Type transfer yang anda tuju salah. type tersedia : SALDO / BONUS';
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
//check number is register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
$others = json_decode($oUser->others, true);
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//check saldo is enought
if ($type == 'saldo') {
if ($oUser->saldo < $keyAmount) {
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $arrAutoreplys['saldo_not_enough']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
} elseif ($type == 'bonus') {
if (!isset($others['saldo_prize']) || $others['saldo_prize'] < $keyAmount) {
$sReply = 'Saldo bonus Anda tidak mencukupi untuk di transfer';
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
}
//check destination number is any or not
$oUserDestination = User::model()->find(array('condition' => 'phone="' . $keyPhone . '"'));
if (empty($oUserDestination)) { //not register
$sReply = str_replace("{phone}", landa()->hp($keyPhone), $arrAutoreplys['failed_wrong_destination']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
//save to transfer table
$mTransfer = new Transfer();
$mTransfer->amount = $keyAmount;
$mTransfer->to_user_id = $oUserDestination->id;
$mTransfer->created_user_id = $oUser->id;
$mTransfer->save();
//change saldo each user
if ($type == 'saldo') {
$oUser->saldo -= $keyAmount;
$oUser->save();
//tambahkan tagihan khusus member pasca bayar, diskon 30%
if ($oUser->roles_id == 27) {
$others = json_decode($oUser->others, true);
if (isset($others['saldo_credit'])) {
$others['saldo_credit'] += ($keyAmount * 30) / 100;
} else {
$others['saldo_credit'] = ($keyAmount * 30) / 100;
}
}
$oUserDestination->saldo += $keyAmount;
$oUserDestination->save();
} elseif ($type == 'bonus') {
$others = json_decode($oUser->others, true);
$others['saldo_prize'] -= $keyAmount;
$oUser->others = json_encode($others);
$oUser->save();
$others = json_decode($oUserDestination->others, true);
if (isset($others['saldo_prize'])) {
$others['saldo_prize'] +=$keyAmount;
} else {
$others['saldo_prize'] = $keyAmount;
}
$oUserDestination->others = json_encode($others);
$oUserDestination->save();
}
//
//notif to user destination
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['success_destination']);
$sReply = str_replace("{phone_transfer}", landa()->hp($keyPhone), $sReply);
$sReply = str_replace("{amount}", landa()->rp($keyAmount), $sReply);
Sms::model()->insertMsgNumber(0, $keyPhone, $sReply, false, '', true);
$sReply = str_replace("{phone_transfer}", landa()->hp($keyPhone), $arrAutoreplys['success']);
$sReply = str_replace("{phone}", landa()->hp($phone), $sReply);
$sReply = str_replace("{amount}", landa()->rp($keyAmount), $sReply);
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'deposit') {
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{bank_account}')
$keyBankAccount = $arrText[$no]; //remove zero number in front
if ($keyVal == '{amount}')
$keyAmount = $arrText[$no] * 1000;
if ($keyVal == '{password}')
$password = trim($arrText[$no]);;
}
//check number is register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
//check destination number is any or not
$oUserDestination = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUserDestination)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//insert to deposit
$mDeposit = new Payment();
$mDeposit->bank_account = $keyBankAccount;
$mDeposit->amount = $keyAmount;
$mDeposit->module = 'deposit';
$mDeposit->created_user_id = $oUser->id;
$mDeposit->save();
$sReply = str_replace("{bank_account}", $keyBankAccount, $arrAutoreplys['success']);
$sReply = str_replace("{amount}", landa()->rp($keyAmount), $sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'withdrawal') {
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{amount}')
$keyAmount = $arrText[$no] * 1000;
if ($keyVal == '{password}')
$password = trim($arrText[$no]);;
}
//check destination number is any or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
$others = json_decode($oUser->others, true);
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//check saldo is enought
if ($oUser->saldoPrize < $keyAmount) { //not register
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $arrAutoreplys['saldo_not_enough']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
//insert to saldo withdrawal
$mDeposit = new SaldoWithdrawal();
$mDeposit->amount = $keyAmount;
$mDeposit->created_user_id = $oUser->id;
$mDeposit->save();
$sReply = str_replace("{amount}", landa()->rp($keyAmount), $arrAutoreplys['success']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'playresult') {
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{output}')
$keyOutput = $arrText[$no];
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
//check output
if ($keyOutput == 's' || $keyOutput == 'h') {
//do nothing
} else {
$sReply = str_replace("{output}", $keyOutput, $arrAutoreplys['wrong_output']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
$mPlay = Play::model()->findAll(array('order' => 'id Desc', 'select' => 'number, sum(amount) as sum_amount', 'group' => 'number', 'condition' => 'DATE_FORMAT( created, "%Y-%m-%d" )="' . date('Y-m-d') . '" AND output="' . $keyOutput . '" AND created_user_id=' . $oUser->id));
$sReply = $keyOutput . ' : ';
foreach ($mPlay as $valPlay) {
$sReply .= $valPlay->number . 'x' . ($valPlay->sum_amount / 1000) . '.';
// $sReply .= $valPlay->number . 'x' . landa()->rp($valPlay->sum_amount) . '.';
}
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == 'result') {
// $oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
// if (empty($oUser)) { //not register
// $sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
// Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
// break;
// } elseif ($oUser->enabled == 0) {
// $sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
// Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
// break;
// } else {
// //do nothing
// }
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{output}')
$keyOutput = $arrText[$no];
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
//check output
if ($keyOutput == 's' || $keyOutput == 'h') {
//do nothing
} else {
$sReply = str_replace("{output}", $keyOutput, $arrAutoreplys['wrong_output']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
$mPlayResult = PlayResult::model()->findAll(array('condition' => 'output="' . $keyOutput . '"', 'order' => 'id Desc', 'limit' => 3));
$sReply = 'Hasil keluaran ' . $keyOutput . ' : ';
foreach ($mPlayResult as $valPlayResult) {
$sReply .= date('d-M-Y', strtotime($valPlayResult->date_number)) . ' => ' . $valPlayResult->number . '. ';
}
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
} elseif ($val->type == '2d' || $val->type == '3d' || $val->type == '4d' || $val->type == 'cr' || $val->type == 'cj_satuan' || $val->type == 'cj_puluhan' || $val->type == 'cj_ratusan' || $val->type == 'cj_ribuan') {
//detect value
foreach ($arrVal as $no => $keyVal) {
if ($keyVal == '{output}')
$keyOutput = $arrText[$no];
// if ($keyVal == '{number}')
// $keyNumber = $arrText[$no];
// if ($keyVal == '{amount}'){
// $keyAmount = $arrText[$no] * 1000;
// }
if ($keyVal == '{numberxamount}') {
$sNumberAmount = explode('.', $arrText[$no]);
$keyNumber = array();
$keyAmount = array();
$keyAmountTotal = 0;
foreach ($sNumberAmount as $valNumberAmount) {
$sTemp = explode('x', $valNumberAmount);
if (count($sTemp) == 2) {
$keyNumber[] = $sTemp[0];
$keyAmount[] = $sTemp[1] * 1000;
$keyAmountTotal += $sTemp[1] * 1000;
} else {
$sReply = 'Digit angka & jumlah pemasangan salah format';
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break 3;
}
}
}
if ($keyVal == '{password}')
$password = trim($arrText[$no]);
}
//check register or not
$oUser = User::model()->find(array('condition' => 'phone="' . $phone . '"'));
if (empty($oUser)) { //not register
$sReply = str_replace("{phone}", landa()->hp($phone), $arrAutoreplys['failed_any_number']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} elseif ($oUser->enabled == 0) {
$sReply = str_replace("{phone}", landa()->hp($phone), $sDisabled);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//check saldo is enought
if ($oUser->saldo < $keyAmountTotal) { //not register
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $arrAutoreplys['saldo_not_enough']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
} else {
//do nothing
}
//check output
if ($keyOutput == 's' || $keyOutput == 'h') {
//do nothing
} else {
$sReply = str_replace("{output}", $keyOutput, $arrAutoreplys['wrong_output']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
//check number which put
foreach ($keyNumber as $valKeyNumber) {
if ((strlen($valKeyNumber) == 2 && $val->type == '2d') || (strlen($valKeyNumber) == 3 && $val->type == '3d') || (strlen($valKeyNumber) == 4 && $val->type == '4d') || (strlen($valKeyNumber) == 1 && ($val->type == 'cr' || $val->type == 'cj_satuan' || $val->type == 'cj_puluhan' || $val->type == 'cj_ratusan' || $val->type == 'cj_ribuan'))) {
//do nothing
} else {
//echo strlen($keyNumber) . '--' .;
$sReply = str_replace("{number}", $valKeyNumber, $arrAutoreplys['wrong_digit']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break 2;
}
}
if (isset($password)) { //check password
if (sha1($password) == $oUser->password) {
//do nothing
} else {
$sReply = str_replace("{password}", $password, $arrAutoreplys['failed_password']);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
}
//check hour of transaction
$siteConfig = SiteConfig::model()->findByPk(1);
$settings = json_decode($siteConfig->settings);
$hkg_day = (isset($settings->game->hkg_day)) ? $settings->game->hkg_day : array();
$hkg_time_start = (isset($settings->game->hkg_time_start)) ? strtotime($settings->game->hkg_time_start) : '00:00';
$hkg_time_end = (isset($settings->game->hkg_time_end)) ? strtotime($settings->game->hkg_time_end) : '00:00';
$sgp_day = (isset($settings->game->sgp_day)) ? $settings->game->sgp_day : array();
$sgp_time_start = (isset($settings->game->sgp_time_start)) ? strtotime($settings->game->sgp_time_start) : '00:00';
$sgp_time_end = (isset($settings->game->sgp_time_end)) ? strtotime($settings->game->sgp_time_end) : '00:00';
$discount_2d = (isset($settings->game->{$oUser->roles_id}->discount_2d)) ? $settings->game->{$oUser->roles_id}->discount_2d : 0;
$discount_3d = (isset($settings->game->{$oUser->roles_id}->discount_3d)) ? $settings->game->{$oUser->roles_id}->discount_3d : 0;
$discount_4d = (isset($settings->game->{$oUser->roles_id}->discount_4d)) ? $settings->game->{$oUser->roles_id}->discount_4d : 0;
$discount_cj = (isset($settings->game->{$oUser->roles_id}->discount_cj)) ? $settings->game->{$oUser->roles_id}->discount_cj : 0;
$discount_cr = (isset($settings->game->{$oUser->roles_id}->discount_cr)) ? $settings->game->{$oUser->roles_id}->discount_cr : 0;
if ($val->type == '2d') {
$tempDiscount = $discount_2d;
} else if ($val->type == '3d') {
$tempDiscount = $discount_3d;
} else if ($val->type == '4d') {
$tempDiscount = $discount_4d;
} else if ($val->type == 'cj_satuan' || $val->type == 'cj_puluhan' || $val->type == 'cj_ratusan' || $val->type == 'cj_ribuan') {
$tempDiscount = $discount_cj;
} else {
$tempDiscount = $discount_cr;
}
$discount = ($keyAmountTotal * $tempDiscount) / 100;
// if ($keyOutput == 's' && ((date('N') == 1 || date('N') == 3 || date('N') == 4 || date('N') == 6 || date('N') == 7) && (date('H') >= 8 && date('H') < 17))) {
// //do nothing
// } elseif ($keyOutput == 'h' && (date('H') >= 17 && date('H') < 22)) {
if ($keyOutput == 's' && ((in_array(date('N'), $sgp_day)) && (time() >= $sgp_time_start && time() < $sgp_time_end))) {
//do nothing
} elseif ($keyOutput == 'h' && ((in_array(date('N'), $hkg_day)) && (time() >= $hkg_time_start && time() < $hkg_time_end))) {
//do nothing
} else {
$sReply = $arrAutoreplys['failed_hour'];
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
break;
}
foreach ($keyNumber as $keyKn => $valKn) {
//save to play
$mPlay = new Play();
$mPlay->number = $valKn;
$mPlay->output = $keyOutput;
$mPlay->amount = $keyAmount[$keyKn];
$mPlay->type = $val->type;
$mPlay->created_user_id = $oUser->id;
$mPlay->save();
}
$saldo = $keyAmountTotal - $discount;
//jika pasca bayar, tambahkan juga ke tagihan
if ($oUser->roles_id == 27) {
$others = json_decode($oUser->others, true);
if (isset($others['saldo_credit'])) {
$others['saldo_credit'] += $saldo;
} else {
$others['saldo_credit'] = $saldo;
}
$oUser->others = json_encode($others);
}
//less the user saldo
$oUser->saldo -= $saldo;
$oUser->save();
//bonus referall
// MlmPrize::model()->mlt($oUser->id,$keyAmountTotal);
$sReply = $arrAutoreplys['success'];
$sReply = str_replace("{saldo}", $oUser->saldoMlt, $sReply);
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
}
}
}
//check if any sms with #, but wrong and not match in keyword in database
if (count($arrText) >= 2 && $is_keyword == false && strlen($phone) >= 10) {
$sReply = 'Keyword yang anda tuju, tidak terdaftar di system kami. Mohon cek lagi keyword anda.';
Sms::model()->insertMsgNumber(0, $phone, $sReply, false, '', true);
}
}
}
| true |
4d9c27f38d8c6b34203d46ce10b5a6123f667002 | PHP | milton2913/JobPortal | /app/Helpers/Skill.php | UTF-8 | 6,687 | 2.578125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Milton
* Date: 1/8/2019
* Time: 11:00 AM
*/
namespace App\Helpers;
use App\Models\Address;
use App\Models\Employer;
use App\Models\Experience;
use App\Models\Profile;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use File;
class Skill{
//after profile create and after login check this function
public static function checkUserStatus(){
if (auth()->user()->is_status == '3') {
$rul = 'profile/create';
}elseif (auth()->user()->is_status=='2'){
$service = self::checkService();
if ($service==false){
$rul = "choose-service";
}else{
$rul = self::dashboard($service);
}
}elseif (auth()->user()->is_status=='1'){
$rul = 'profile done!';
}elseif (auth()->user()->is_status==0){
$rul = 'profile inactive!';
}else{
$rul = '/home';
}
return $rul;
}
//check user service if found any service then return default service
public static function checkService(){
$service = User::findOrFail(Auth::id());
$service_user = $service->service()
->wherePivot('user_id',Auth::id())
->get(); // execute the query
if($service_user->count() >0 ){
$current_service = $service->service()
->wherePivot('user_id',Auth::id())
->wherePivot('is_active','1')
->first();
}else{
$current_service = false;
}
return $current_service;
}
//redirect dashboard
public static function dashboard($service){
switch ($service->role_id){
case 1:
return 'admin/dashboard';
case 2:
return self::checkEmployerIfCreate();
case 3:
return 'jobseeker/dashboard';
default:
return 'home';
}
}
public static function checkEmployerIfCreate(){
$employer = Employer::where('user_id',Auth::id())->first();
if ($employer==null){
return 'employer/employer-profile-add';
}else{
return 'employer/dashboard';
}
}
//get employer id throw user id
public static function getEmployerId($user_id){
$employer = Employer::where('user_id',$user_id)->first();
return $employer->id;
}
//check jobs seeker CV status
public static function checkCvInfo(){
}
//create or update user profile
public static function profile($profile){
$pro = Profile::where('user_id',Auth::id())->first();
if ($pro){
$pro->update($profile);
}else{
Profile::create($profile);
}
}
//return user avatar
public static function getAvatar(){
$avatarUrl = Auth::user()->avatar;
$http = 'http';
$pos = strpos($avatarUrl, $http);
if ($pos === false) {
$url = url(auth()->user()->avatar);
} else {
$url = auth()->user()->avatar;
}
return $url;
}
//create or update user address
public static function address($address){
$addre = Address::where('user_id',Auth::id())->where('address_type',$address['address_type'])->first();
if ($addre){
$addre->update($address);
}else{
Address::create($address);
}
}
//return present address
public static function presentAddress(){
$address = Address::where('user_id', Auth::id())
->where('address_type', "Present")
->first();
return $address;
}
// return permanent address
public static function permanentAddress(){
$address = Address::where('user_id', Auth::id())
->where('address_type', "Permanent")
->first();
return $address;
}
//return experience year month and day
public static function experienceCalculator($start_date,$end_date,$is_current){
$start_date = strtotime($start_date);
if ($is_current==1 && $end_date=="Continue"){
$end_date = strtotime(date('Y-m-d'));
}else{
$end_date = strtotime($end_date);
}
$months = 0;
$years = 0;
while (strtotime('+1 MONTH', $start_date) < $end_date) {
$months++;
$start_date = strtotime('+1 MONTH', $start_date);
if($months>11){
$years++;
$months=0;
}
}
return $years." year, ". $months. ' month, '. ($end_date - $start_date) / (60*60*24). ' days';
}
//return total experience year month and day
public static function totalExperience($id){
$experiences = Experience::where('user_id',$id)->get();
$months = 0;
$years = 0;
$days = 0;
foreach ($experiences as $experience){
$start_date = strtotime($experience->start_date);
if ($experience->is_current==1 && $experience->end_date=="Continue"){
$end_date = strtotime(date('Y-m-d'))+$days*60*60*24;
}else{
$end_date = strtotime($experience->end_date)+$days*60*60*24;
}
while (strtotime('+1 MONTH', $start_date) < $end_date) {
$months++;
$start_date = strtotime('+1 MONTH', $start_date);
if($months>11){
$years++;
$months=0;
}
}
$days = ($end_date - $start_date) / (60*60*24);
}
return $years." year, ". $months. ' month, '. $days . ' days';
}
//create file directory
public static function makeFilePath($path){
$year_path = $path.'/'.date('Y');
if (File::exists($year_path)) {
if (File::exists($year_path.'/'.date('m'))){
$uploadPath = $year_path.'/'.date('m');
}else{
File::makeDirectory($year_path.'/'.date('m'));
$uploadPath = $year_path.'/'.date('m');
}
}else{
File::makeDirectory($year_path);
$month_path =$year_path.'/'.date('m');
File::makeDirectory($month_path);
$uploadPath = $month_path;
}
return $uploadPath;
}
//return username or name
public static function getUsername(){
$name = Auth::user()->name;
return $name;
}
public static function getEmail(){
$email = Auth::user()->email?Auth::user()->email:Auth::user()->profile->alternate_email;
return $email;
}
} | true |
919477b36029686eb08cec7b7bdc9e0fc0a52c7b | PHP | tamayoac/EventCalendar | /app/Service/BaseCommand.php | UTF-8 | 850 | 2.890625 | 3 | [] | no_license | <?php
namespace App\Service;
class BaseCommand
{
public function doCommand($arr, $user)
{
return $this->createReturn(1, "unhandled command");
}
public function createReturn($error_code, $message = "", $result = null)
{
$ret = new \stdClass();
$ret->error_code = $error_code;
$ret->message = $message;
$ret->result = $result;
return $ret;
}
public function execute($arr, $user)
{
try {
\DB::beginTransaction();
$ret = $this->doCommand($arr, $user);
\DB::commit();
return $ret;
} catch (\Exception $exc) {
\DB::rollback();
$str = $exc->getMessage() . " On Line " . $exc->getLine() . " On File " . $exc->getFile();
return $this->createReturn(2, $str);
}
}
} | true |
06439e1b7acae3b3d2dac9e3532a118a1405a0fc | PHP | mateomurphy/php-work | /micro/lib/micro/db.php | UTF-8 | 3,714 | 3.359375 | 3 | [
"MIT"
] | permissive | <?php
/**
* Although a full blown ORM layer is out of the scope of Micro, using PDO directly can be a bit of a laborious process. This Db class wraps PDO
* making it easier to execute common queries.
*
*/
class Micro_Db {
/**
* PDO object
*
* @var PDO
*/
private $pdo;
private $tables;
public $resultClass = 'Micro_Db_Row';
/**
* Constructor. The arguments are the same as PDOs
*
* @param string $dns
* @param string $username
* @param string $passwd
* @param array $options
* @return MicroDb
*/
function __construct($dns, $username, $passwd, $options = null) {
$this->tables = array();
$this->pdo = new PDO($dns, $username, $passwd, $options);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->execute("SET NAMES 'utf8'");
}
function __get($name) {
if (!isset($this->tables[$name])) $this->tables[$name] = new Micro_Db_Table($this, $name);
return $this->tables[$name];
}
/**
* Returns an array containing all the rows that match the query
*
* @param string $sql The query to execute. Can contain parameter markers
* @param string $args,... Any additional argument is bound to markers in the query
* @return array
*/
function findAll($sql) {
$args = func_get_args();
array_shift($args);
$statement = $this->execute($sql, $args);
return $statement->fetchAll(PDO::FETCH_CLASS, $this->resultClass, array($this));
}
function findAllAs($class, $sql, $args = array()) {
$statement = $this->execute($sql, $args);
return $statement->fetchAll(PDO::FETCH_CLASS, $class, array($this));
}
/**
* Returns the first row that match the query
*
* @param string $sql The query to execute. Can contain parameter markers
* @param string $args,... Any additional argument is bound to markers in the query
* @return array
*/
function findFirst($sql) {
$args = func_get_args();
array_shift($args);
$statement = $this->execute($sql, $args);
$obj = $statement->fetchObject($this->resultClass, array($this));
return $obj;
}
function findFirstAs($class, $sql, $args = array()) {
$statement = $this->execute($sql, $args);
$obj = $statement->fetchObject($class, array($this));
return $obj;
}
/**
* Performs an insert query, returning the insert id
*
* @param string $sql The query to execute. Can contain parameter markers
* @param string $args,... Any additional argument is bound to markers in the query
* @return int
*/
function insert($sql) {
$args = func_get_args();
array_shift($args);
$statement = $this->execute($sql, $args);
return $this->pdo->lastInsertId();
}
/**
* Performs an update query, returning the number of rows affected
*
* @param string $sql The query to execute. Can contain parameter markers
* @param string $args,... Any additional argument is bound to markers in the query
* @return int
*/
function update($sql) {
$args = func_get_args();
array_shift($args);
$statement = $this->execute($sql, $args);
return $statement->rowCount();
}
function delete($sql) {
$args = func_get_args();
array_shift($args);
$statement = $this->execute($sql, $args);
return $statement->rowCount();
}
/**
* Prepares and performs a query
*
* @param string $sql The query to execute. Can contain parameter markers
* @param array $args An array of parameters to bind to the query's markers
* @return PDOStatement
*/
private function execute($sql, $args = array()) {
if (isset($args[0]) && is_array($args[0])) $args = $args[0];
$statement = $this->pdo->prepare($sql);
$statement->execute($args);
return $statement;
}
}
class Micro_Db_Exception extends Micro_Exception {
}
?> | true |
2f76568224d0f02d3e642dd494aae4bb7607d409 | PHP | atpjulio/fundacion | /app/Phone.php | UTF-8 | 423 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Phone extends Model
{
protected $fillable = [
'model_id',
'model_type', // 1 = Company, 2 = Eps, 3 = Patient
'phone',
'phone2',
];
public function getFullPhoneAttribute()
{
if (!$this->phone2) {
return $this->phone;
}
return $this->phone.' - '.$this->phone2;
}
}
| true |
1642f70b828e9547d7828f957c17de1d141f6fc1 | PHP | dol-leodagan/phpbb-dol-extension | /controller/main.php | UTF-8 | 16,307 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
/**
*
* @package DOL Extension 0.0.1
* @copyright (c) 2016 Leodagan
* @license MIT
*
*/
namespace dol\status\controller;
use phpbb\config\config;
use phpbb\controller\helper;
use phpbb\template\template;
use phpbb\user;
use phpbb\request\request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class main
{
/* @var config */
protected $config;
/* @var helper */
protected $helper;
/* @var template */
protected $template;
/* @var user */
protected $user;
/* @var request */
protected $request;
/**
* phpBB root path
* @var string
*/
protected $phpbb_root_path;
/**
* PHP file extension
* @var string
*/
protected $php_ext;
/**
* Extension root path
* @var string
*/
protected $root_path;
/** @var \dol\status\controller\helper */
protected $controller_helper;
/**
* Constructor
*
* @param config $config
* @param helper $helper
* @param template $template
* @param user $user
* @param string $phpbb_root_path
* @param string $php_ext
*/
public function __construct(config $config, helper $helper, template $template, user $user, request $request, $phpbb_root_path, $php_ext, $controller_helper)
{
$this->config = $config;
$this->helper = $helper;
$this->template = $template;
$this->user = $user;
$this->request = $request;
$this->phpbb_root_path = $phpbb_root_path;
$this->php_ext = $php_ext;
$this->root_path = $phpbb_root_path . 'ext/dol/status/';
$this->controller_helper = $controller_helper;
}
/** Ladder Handler **/
public function handle_ladder($cmd)
{
if ($cmd == 'guilds')
{
$ladder = $this->controller_helper->backend_yaml_query($cmd, 5 * 60);
// Build Guilds Routes
if (isset($ladder['Ladder']))
{
foreach ($ladder['Ladder'] as $key => $value)
{
$ladder['Ladder'][$key]['LastPlayed'] = date('M j Y', $value['LastPlayed']);
$ladder['Ladder'][$key]['GUILD_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'guild', 'params' => $value['GuildName']));
}
}
$this->controller_helper->assign_yaml_vars($ladder);
}
else
{
$ladder = array();
$ladder = $this->controller_helper->backend_yaml_query($cmd, 5 * 60);
// Build URL Routes
if (isset($ladder['Ladder']))
{
foreach ($ladder['Ladder'] as $key => $value)
{
$ladder['Ladder'][$key]['LastPlayed'] = date('M j Y', $value['LastPlayed']);
$ladder['Ladder'][$key]['PLAYER_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'player', 'params' => $value['PlayerName']));
if ($value['GuildName'] !== "")
$ladder['Ladder'][$key]['GUILD_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'guild', 'params' => $value['GuildName']));
}
}
$this->controller_helper->assign_yaml_vars($ladder);
}
if ($cmd == 'albion' || $cmd == 'midgard' || $cmd == 'hibernia')
$this->assign_class_uris($cmd);
$this->template->assign_var('U_HERALD_COMMAND', $cmd);
$this->template->assign_var('U_HERALD_ENABLE', true);
return $this->helper->render('herald_body.html');
}
/** Class List Helper **/
private function assign_class_uris($cmd, $params = '')
{
$classes = $this->controller_helper->backend_yaml_query('classes', 24 * 60 * 60);
$existing_classes = array();
// Build URL Routes
if (isset($classes['Classes']))
{
foreach ($classes['Classes'] as $key => $value)
{
if (is_array($value))
{
foreach($value as $num => $item)
{
$classes['Classes'][$key][$num] = array('VALUE' => $item, 'URL' => $this->helper->route('dol_herald_search', array('cmd' => $cmd, 'params' => $item)));
$existing_classes[] = $item;
}
}
}
}
$this->controller_helper->assign_yaml_vars($classes);
if ($params !== "" && array_search($params, $existing_classes) === false)
return false;
return true;
}
/** Guild/Player Handler **/
public function handle_sheet($cmd, $params)
{
if ($this->user->data['user_id'] == ANONYMOUS)
return $this->helper->message('LOGIN_REQUIRED', array(), 'NO_AUTH_OPERATION', 403);
if ($params === null || $params === '')
return $this->handle_badsearch();
if ($cmd == 'player')
{
$player_display = $this->controller_helper->backend_yaml_query('getplayer/'.$params, 5 * 60);
//Build Routes and Stats
if (isset($player_display['Player']))
{
if (isset($player_display['Player']['GuildName']) && $player_display['Player']['GuildName'] !== '')
{
$player_display['Player']['GUILD_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'guild', 'params' => $player_display['Player']['GuildName']));
$player_display['Player']['BANNER_URL'] = $this->helper->route('dol_herald_images', array('cmd' => 'banner', 'params' => $player_display['Player']['GuildName']));
}
$player_display['Player']['SIGSMALL_URL'] = $this->helper->route('dol_herald_images', array('cmd' => 'sigsmall', 'params' => $params));
$player_display['Player']['SIGSMALL_ABSURL'] = $this->helper->route('dol_herald_images', array('cmd' => 'sigsmall', 'params' => $params), true, false, UrlGeneratorInterface::ABSOLUTE_URL);
$player_display['Player']['SIGDETAILED_URL'] = $this->helper->route('dol_herald_images', array('cmd' => 'sigdetailed', 'params' => $params));
$player_display['Player']['SIGDETAILED_ABSURL'] = $this->helper->route('dol_herald_images', array('cmd' => 'sigdetailed', 'params' => $params), true, false, UrlGeneratorInterface::ABSOLUTE_URL);
$player_display['Player']['SIGLARGE_URL'] = $this->helper->route('dol_herald_images', array('cmd' => 'siglarge', 'params' => $params));
$player_display['Player']['SIGLARGE_ABSURL'] = $this->helper->route('dol_herald_images', array('cmd' => 'siglarge', 'params' => $params), true, false, UrlGeneratorInterface::ABSOLUTE_URL);
// Stats
$player_display['Player']['KILLSTOTAL'] = $player_display['Player']['KillsAlbionPlayers'] + $player_display['Player']['KillsMidgardPlayers'] + $player_display['Player']['KillsHiberniaPlayers'];
$player_display['Player']['DEATHBLOWSTOTAL'] = $player_display['Player']['KillsAlbionDeathBlows'] + $player_display['Player']['KillsMidgardDeathBlows'] + $player_display['Player']['KillsHiberniaDeathBlows'];
$player_display['Player']['SOLOTOTAL'] = $player_display['Player']['KillsAlbionSolo'] + $player_display['Player']['KillsMidgardSolo'] + $player_display['Player']['KillsHiberniaSolo'];
$player_display['Player']['KILLSRATIODEATHBLOWS'] = round($player_display['Player']['DEATHBLOWSTOTAL'] / ($player_display['Player']['KILLSTOTAL'] == 0 ? 1 : $player_display['Player']['KILLSTOTAL']) * 100, 2);
$player_display['Player']['KILLSRATIOSOLO'] = round($player_display['Player']['SOLOTOTAL'] / ($player_display['Player']['KILLSTOTAL'] == 0 ? 1 : $player_display['Player']['KILLSTOTAL']) * 100, 2);
$player_display['Player']['KILLSRATIO_ALBION'] = round($player_display['Player']['KillsAlbionPlayers'] / ($player_display['Player']['KILLSTOTAL'] == 0 ? 1 : $player_display['Player']['KILLSTOTAL']) * 100, 2);
$player_display['Player']['KILLSRATIO_MIDGARD'] = round($player_display['Player']['KillsMidgardPlayers'] / ($player_display['Player']['KILLSTOTAL'] == 0 ? 1 : $player_display['Player']['KILLSTOTAL']) * 100, 2);
$player_display['Player']['KILLSRATIO_HIBERNIA'] = round($player_display['Player']['KillsHiberniaPlayers'] / ($player_display['Player']['KILLSTOTAL'] == 0 ? 1 : $player_display['Player']['KILLSTOTAL']) * 100, 2);
$player_display['Player']['DEATHBLOWSRATIO_ALBION'] = round($player_display['Player']['KillsAlbionDeathBlows'] / ($player_display['Player']['DEATHBLOWSTOTAL'] == 0 ? 1 : $player_display['Player']['DEATHBLOWSTOTAL']) * 100, 2);
$player_display['Player']['DEATHBLOWSRATIO_MIDGARD'] = round($player_display['Player']['KillsMidgardDeathBlows'] / ($player_display['Player']['DEATHBLOWSTOTAL'] == 0 ? 1 : $player_display['Player']['DEATHBLOWSTOTAL']) * 100, 2);
$player_display['Player']['DEATHBLOWSRATIO_HIBERNIA'] = round($player_display['Player']['KillsHiberniaDeathBlows'] / ($player_display['Player']['DEATHBLOWSTOTAL'] == 0 ? 1 : $player_display['Player']['DEATHBLOWSTOTAL']) * 100, 2);
$player_display['Player']['SOLORATIO_ALBION'] = round($player_display['Player']['KillsAlbionSolo'] / ($player_display['Player']['SOLOTOTAL'] == 0 ? 1 : $player_display['Player']['SOLOTOTAL']) * 100, 2);
$player_display['Player']['SOLORATIO_MIDGARD'] = round($player_display['Player']['KillsMidgardSolo'] / ($player_display['Player']['SOLOTOTAL'] == 0 ? 1 : $player_display['Player']['SOLOTOTAL']) * 100, 2);
$player_display['Player']['SOLORATIO_HIBERNIA'] = round($player_display['Player']['KillsHiberniaSolo'] / ($player_display['Player']['SOLOTOTAL'] == 0 ? 1 : $player_display['Player']['SOLOTOTAL']) * 100, 2);
$player_display['Player']['KILLDEATHRATIO'] = round($player_display['Player']['KILLSTOTAL'] / ($player_display['Player']['DeathsPvP'] == 0 ? 1 : $player_display['Player']['DeathsPvP']), 2);
$player_display['Player']['RPDEATHRATIO'] = round($player_display['Player']['RealmPoints'] / ($player_display['Player']['DeathsPvP'] == 0 ? 1 : $player_display['Player']['DeathsPvP']));
$player_display['Player']['LastPlayed'] = date('M j Y', $player_display['Player']['LastPlayed']);
}
$this->controller_helper->assign_yaml_vars($player_display);
}
else if ($cmd == 'guild')
{
$guild_display = $this->controller_helper->backend_yaml_query('getguild/'.$params, 5 * 60);
//Build Routes
if (isset($guild_display['Guild']))
{
$guild_display['Guild']['BANNER_URL'] = $this->helper->route('dol_herald_images', array('cmd' => 'banner', 'params' => $guild_display['Guild']['Name']));
if (isset($guild_display['Guild']['Players']) && is_array($guild_display['Guild']['Players']))
{
foreach($guild_display['Guild']['Players'] as $num => $player)
{
$guild_display['Guild']['Players'][$num]['PLAYER_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'player', 'params' => $player['PlayerName']));
$guild_display['Guild']['Players'][$num]['LastPlayed'] = date('M j Y', $player['LastPlayed']);
}
}
}
$this->controller_helper->assign_yaml_vars($guild_display);
}
$this->template->assign_var('U_HERALD_COMMAND', $cmd);
$this->template->assign_var('U_HERALD_ENABLE', true);
return $this->helper->render('herald_body.html');
}
/** Warmap Handler **/
public function handle_warmap()
{
$warmap = $this->controller_helper->backend_yaml_query('warmap', 5 * 60);
if (isset($warmap['Structures']))
{
foreach($warmap['Structures'] as $realm => $structures)
{
if (is_array($structures))
{
foreach($structures as $num => $structure)
{
if (isset($structure['Claimed']) && $structure['Claimed'] === true)
$warmap['Structures'][$realm][$num]['IMGURL'] = $this->helper->route('dol_herald_images', array('cmd' => 'banner', 'params' => $structure['ClaimedBy']));
$warmap['Structures'][$realm][$num]['Since'] = $this->controller_helper->human_timing($structure['Since']).' '.$this->user->lang['DOL_STATUS_AGO'];
}
}
}
}
$this->controller_helper->assign_yaml_vars($warmap);
$this->template->assign_var('U_HERALD_COMMAND', '');
$this->template->assign_var('U_HERALD_ENABLE', true);
$this->template->assign_var('U_WARMAP_ENABLE', true);
return $this->helper->render('herald_body.html');
}
/** Search Form Handler **/
public function handle_searchform()
{
if ($this->user->data['user_id'] == ANONYMOUS)
return $this->helper->message('LOGIN_REQUIRED', array(), 'NO_AUTH_OPERATION', 403);
/** Redirect Search POST **/
if ($this->request->is_set('herald_search'))
{
$search_string = $this->request->variable('herald_search', '', true);
if (preg_match('/^([[:alnum:]À-ÿ ]+){3,}$/s', $search_string))
{
$headers = array('Location' => $this->helper->route('dol_herald_search', array('cmd' => 'search', 'params' => $search_string)));
return new Response('', 303, $headers);
}
}
return $this->handle_badsearch();
}
/** Search and Class Ladder **/
public function handle($cmd, $params)
{
$ladder = array();
/** Search **/
if ($cmd == 'search')
{
if ($this->user->data['user_id'] == ANONYMOUS)
return $this->helper->message('LOGIN_REQUIRED', array(), 'NO_AUTH_OPERATION', 403);
if (strlen($params) > 2)
$ladder = $this->controller_helper->backend_yaml_query($cmd.'/'.$params, 5 * 60);
else
$cmd = 'badsearch';
}
/** Realm / Classes **/
else if ($cmd == 'albion' || $cmd == 'midgard' || $cmd == 'hibernia')
{
if ($this->assign_class_uris($cmd, $params))
$ladder = $this->controller_helper->backend_yaml_query($cmd.'/'.$params, 5 * 60);
}
// Build URL Routes
if (isset($ladder['Ladder']))
{
foreach ($ladder['Ladder'] as $key => $value)
{
$ladder['Ladder'][$key]['LastPlayed'] = date('M j Y', $value['LastPlayed']);
$ladder['Ladder'][$key]['PLAYER_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'player', 'params' => $value['PlayerName']));
if ($value['GuildName'] !== "")
$ladder['Ladder'][$key]['GUILD_URL'] = $this->helper->route('dol_herald_sheet', array('cmd' => 'guild', 'params' => $value['GuildName']));
}
$this->controller_helper->assign_yaml_vars($ladder);
}
$this->template->assign_var('U_HERALD_COMMAND', $cmd);
$this->template->assign_var('U_HERALD_PARAM', $params);
$this->template->assign_var('U_HERALD_ENABLE', true);
return $this->helper->render('herald_body.html');
}
public function handle_badsearch($cmd, $params)
{
return $this->handle('badsearch', $params);
}
/** Book Handler **/
public function handle_book()
{
return $this->helper->render('book_body.html');
}
}
| true |
1f07e576cd0b9dff6e7f5e3840448ead442285eb | PHP | fiasco/Archimedes-Client-Drupal | /archimedes.inc | UTF-8 | 9,788 | 2.53125 | 3 | [] | no_license | <?php
/**
* @file Archimedes toolset.
*/
/**
* Find and load the archimedes library.
*/
function archimedes_load_library() {
if (class_exists('Archimedes')) {
return;
}
// Use the libraries module if its enabled.
if (module_exists('libraries')) {
$file = libraries_get_path('archimedes') . '/archimdes.class.php';
if (file_exists($file)) {
include_once $file;
return TRUE;
}
}
// If the file is already in the module, use that.
if (file_exists(dirname(__FILE__) . '/archimedes.class.php')) {
include_once dirname(__FILE__) . '/archimedes.class.php';
return TRUE;
}
global $conf;
$options = array(
'sites/all/libraries/archimedes/archimedes.class.php',
'profiles/' . $conf['install_profile'] . '/libraries/archimedes/archimedes.class.php',
conf_path() . '/libraries/archimedes/archimedes.class.php',
);
foreach ($options as $path) {
if (!file_exists($path)) {
continue;
}
include_once $path;
return TRUE;
}
return FALSE;
}
// Its safe to assume that if this file gets included that
// the archimedes library is needed so load it automatically.
class_exists('Archimedes') || archimedes_load_library();
/**
* Produce a unique value to represent this instance of Drupal.
*/
function archimedes_get_token() {
$keys = module_invoke_all('archimedes_id'); sort($keys);
return drupal_hmac_base64(implode('|', $keys), drupal_get_private_key() . drupal_get_hash_salt());
}
/**
* Send a report to the Archimedes server via email or HTTP.
*
* Doesn't use Drupal's messaging system because the communication
* with the server is independant of Drupal.
*/
function archimedes_send_report() {
global $base_url;
if ($base_url == 'http://default'){ // must have accurate servername
drupal_set_message('Cannot accurately determine servername. You should set this in settings.php. Update was not sent.','warning');
return FALSE;
}
$server_key = variable_get('archimedes_server_key','');
$site_name = variable_get('site_name', 'unknown');
if (variable_get('archimedes_send_method', 'postXML') == 'postXML') {
$destination = variable_get('archimedes_server_url', FALSE);
}
else {
$destination = 'Archimedes Server <' . variable_get('archimedes_server_email', FALSE) . '>';
}
if (!$destination) {
drupal_set_message('Update failed to send as the ' . l('server email address','admin/reports/archimedes/settings') . ' is not yet set.','error');
return FALSE;
}
$owl = archimedes_build_report();
$ekey = $owl->encrypt($server_key);
try {
if (!call_user_func(array($owl, variable_get('archimedes_send_method', 'postXML')), $destination)) {
throw new Exception('Update failed to send for an unknown reason.');
}
drupal_set_message('Update sent successfully to ' . $destination. '. This may take some time to become visible on the server.');
variable_set('archimedes_cron_last',time());
}
catch (Exception $e) {
drupal_set_message($e->getMessage(), 'error');
watchdog('Archimedes', $e->getMessage(), array(), WATCHDOG_ERROR);
}
}
/**
* Use Archimedes to build a report of the site.
*/
function archimedes_build_report() {
global $databases;
$owl = new Archimedes('drupal', variable_get('site_mail', FALSE), archimedes_get_token());
$owl->createField('title', variable_get('site_name', "Drupal"));
$owl->createField('field_drupal_version', VERSION);
// This allows site instances of the same project to be
// related. For example my.site.com may also have staging.my.site.com
// and we don't want the reports to clash, but grouping these sites
// is still useful.
$owl->createField('field_common_hash', variable_get('archimedes_common_key', ''));
if (variable_get('archimedes_description', '') != '') {
$nid = arg(1,drupal_get_normal_path(variable_get('archimedes_description', 'node')));
$node = node_load($nid);
$body = trim(substr(drupal_html_to_text($node->body,array('b','strong','i','em','p')),0,500));
$owl->createField('body', $body);
} else {
$owl->createField('body', variable_get('site_mission', 'No description has been set.'));
}
// If Drush (or some other CLI passed method) is used to
// run cron. You'll need to ensure a correct servername is
// passed to PHP. With drush, use -l http://mysite.com.
$owl->createField('field_servername', url('', array('absolute' => 1)));
// The location where Drupal believes it resides.
$owl->createField('field_webroot', DRUPAL_ROOT);
// Build an understanding of the databases Drupal
// can connect too. At this stage, Archimedes only
// reports on the default connections, i.e, master
// slave databases for Drupal only.
$values = array();
$connections = array();
foreach($databases['default'] as $key => $connection) {
if ($key == 'slave') {
foreach ($connection as $slave) {
$connections[] = $slave;
}
}
else {
$connections[] = $connection;
}
}
foreach ($connections as $url) {
//format into url like drupal 6
$db_url = $url['driver'] . '://' . $url['username'] . ':' . $url['password'] . '@' . $url['host'] . '/' . $url['database'];
$db = parse_url($db_url);
if (!isset($database_name)) {
$database_name = substr($db['path'],1);
$owl->createField('field_dbname', $database_name);
}
$dbhost = ($db['host'] == 'localhost' || $db['host'] == '127.0.0.1') ? 'localhost' : $db['host'];
$values[] = archimedes_value($dbhost,'nodereference')->addNode(array('title' => $dbhost, 'type' => 'host'));
}
$owl->createField('field_dbhost', $values)
->invokeFacet();
$user = array(
'type' => 'mail',
'mailto' => 'mailto:' . db_query("SELECT u.mail FROM {users} u WHERE uid = 1 LIMIT 1")->fetchField(),
);
$value = archimedes_value($user['mailto'],'userreference')
->addUser($user);
$owl->createField('field_users', array($value))
->invokeFacet();
// Graphable data.
$users = archimedes_value(db_query("SELECT COUNT(uid) as count FROM {users}")->fetchField() - 1, 'dataset')->setTitle('Users');
$nodes = archimedes_value(db_query("SELECT COUNT(nid) as count FROM {node}")->fetchField(), 'dataset')->setTitle('Nodes');
$revisions = archimedes_value(db_query("SELECT COUNT(nid) as count FROM {node_revision}")->fetchField(), 'dataset')->setTitle('Revisions');
$owl->createField('field_c_dataset', array($nodes, $revisions, $users));
$modules = $themes = array();
foreach (module_list() as $module) {
$info = drupal_parse_info_file(drupal_get_path('module', $module) . '/' . $module . '.info');
$node = array(
'title' => (isset($info['name']) ? $info['name'] : ''),
'body' => (isset($info['description']) ? $info['description'] : ''),
'field_name' => $module,
'field_dru_pkg' => (isset($info['package']) ? $info['package'] : ''),
'field_dru_proj' => (isset($info['project']) ? $info['project'] : 'drupal'),
'field_mod_version' => (isset($info['version']) ? $info['version'] : ''),
'field_mod_url' => (isset($info['project status url']) ? $info['project status url'] : ''),
'type' => 'drupal_module',
);
if (empty($node['field_dru_proj']) && !empty($node['field_dru_pkg']) && (strpos($node['field_dru_pkg'], 'Core -') !== FALSE)) {
$node['field_dru_proj'] = 'drupal';
}
$value = archimedes_value($node['title'], 'drupalmod')
->addNode($node);
$modules[] = $value;
}
$owl->createField('field_drupal_mod', $modules)
->invokeFacet();
$result = db_query("SELECT name FROM {system} WHERE status = 1 AND type = 'theme'");
while ($theme = $result->fetchField()) {
$info = drupal_parse_info_file(drupal_get_path('theme', $theme) . '/' . $theme . '.info');
$node = array(
'title' => (isset($info['name']) ? $info['name'] : ''),
'body' => (isset($info['description']) ? $info['description'] : ''),
'field_name' => $theme,
'field_mod_version' => (isset($info['version']) ? $info['version'] : ''),
'field_dru_proj' => (isset($info['project']) ? $info['project'] : 'drupal'),
'field_mod_url' => (isset($info['project status url']) ? $info['project status url'] : ''),
'type' => 'drupal_theme',
);
if (empty($node['field_dru_proj']) && in_array($theme, array('bluemarine', 'chameleon', 'garland', 'marvin', 'minnelli', 'pushbutton'))) {
// Unfortunately, there's no way to tell if a theme is part of core,
// so we must hard-code a list here.
$node['field_dru_proj'] = 'drupal';
}
$value = archimedes_value($node['title'], 'drupalmod')
->addNode($node);
$themes[] = $value;
}
$owl->createField('field_drupal_theme', $themes)
->invokeFacet();
$environment = array_shift(environment_current(NULL,NULL,TRUE));
$owl->createField('field_site_env', $environment['label']);
$ignore = array('#(\w*/)*sites/\w*/files#', '#.*\.(git|svn|bzr|cvs)/.*#');
// The point of the directory hash is to record the state of the deployed code base.
// If the code base changes, then the site could have been redeployed or hacked! However,
// in development scenarios, the code changes very frequently so we don't care to change
// it.
$dir_hash = archimedes_directory_hash(DRUPAL_ROOT, $ignore);
$owl->createField('field_directory_hash', $dir_hash);
if (variable_get('archimedes_use_unsafe_collection', FALSE)) {
$collect = new ArchimedesDrupalUnsafeCollection($owl);
$collect->servername()
->database_size()
->storage_usage();
}
// Allow other modules to add data via hook_archimedes.
drupal_alter('archimedes', $owl);
return $owl;
} // archimedes_collect()
| true |
352425bc04eda3d15a07ff77c5cd543ed6f4d317 | PHP | john-needham/model-doc | /src/Database/Inspector.php | UTF-8 | 1,006 | 2.65625 | 3 | [] | no_license | <?php
namespace Needham\ModelDoc\Database;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Needham\ModelDoc\Attribute;
class Inspector
{
const SQL_TABLE_NAME = 'TABLE_NAME';
const SQL_COL_NAME = 'COLUMN_NAME';
const SQL_COL_TYPE = 'DATA_TYPE';
public function inspect($class) : array {
$attributes = [];
if(class_exists($class)) {
$instance = new $class;
} else {
dd($class);
}
$table = $instance->getTable();
$columns = DB::table('INFORMATION_SCHEMA.COLUMNS')
->select(DB::raw('*'))
->where('TABLE_NAME', $table)
->get()->toArray();
foreach ($columns as $column) {
$attributes[] = new Attribute(
data_get($column, self::SQL_COL_NAME),
// data_get($column, self::SQL_COL_TYPE)
'mixed'
);
}
return $attributes;
}
}
| true |
640d9a1d42d16de8bb25636e84a555e471d57009 | PHP | harshildarji/PHP-Examples | /Database/basic.php | UTF-8 | 966 | 2.609375 | 3 | [] | no_license | <?php
require('connect.php');
?>
<form action='basic.php' method='GET'>
User name:
<br>
<input type='text' name='uname'>
<br>
<br>
<input type='submit' value='Submit'>
</form>
<?php
if(isset($_GET['uname'])){
$uname = strtolower($_GET['uname']);
if(!empty($uname)){
$query = "SELECT `name`, `password` FROM `users` WHERE `name` = '".$uname."'";
if($query_run = mysql_query($query)){
//echo 'Query success!';
if(mysql_num_rows($query_run) == NULL){
echo 'No results found!';
} else{
while($row = mysql_fetch_assoc($query_run)){
$name = $row['name'];
$pass = $row['password'];
echo $name.': '.$pass.'<br>';
}
}
} else{
echo 'Query failed!';
}
} else{
echo 'Fill above box!';
}
}
?> | true |
51dbe378b4b44d899a953041e3e211b21aba519c | PHP | Brandioo/PHPExercises | /InterfaceInsuranceExercise/index.php | UTF-8 | 1,702 | 3.5 | 4 | [] | no_license | //Brandio
<?php
interface Insurance
{
public function getInsuranceName();
public function getYearsOfSponsorShip();
}
interface InsuranceWithParameters
{
public function getInsuranceName(string $name);
public function getYearsOfSponsorShip(int $years);
}
class Sigal implements InsuranceWithParameters
{
public function getInsuranceName(string $name)
{
// TODO: Implement getInsuranceName() method.
return $name;
}
public function getYearsOfSponsorShip(int $years)
{
// TODO: Implement getYearsOfSponsorShip() method.
return $years;
}
}
//$brand = new Brand;
//echo $brand->getFullName();
class Sigma implements Insurance
{
public function getInsuranceName()
{
// TODO: Implement getInsuranceName() method.
return "Sigma";
}
public function getYearsOfSponsorShip()
{
// TODO: Implement getYearsOfSponsorShip() method.
return "Years Of Sponsorships 20";
}
}
class Run
{
public function getFullInfo(Insurance $instance)
{
return "<br> {$instance->getInsuranceName()}---{$instance->getYearsOfSponsorShip()} <br>";
}
}
//$run = new Run;
//$sigal = new Sigal;
//$sigma = new Sigma;
//
////echo $run->getFullInfo($sigal);
//echo $run->getFullInfo($sigma);
class RunWithParameters
{
public function getFullInfo(InsuranceWithParameters $instance)
{
$name = "Insurance for Car";
$years = 5;
return "<br> {$instance->getInsuranceName($name)}---{$instance->getYearsOfSponsorShip($years)} <br>";
}
}
$runWithParameters = new RunWithParameters;
$sigal = new Sigal();
echo $runWithParameters->getFullInfo($sigal);
| true |