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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7cb806d2bc86a97cb5604219e42078de68abcde2 | PHP | Bronskiy/Companies-Reviews | /application/modules/companies/models/CouponReviewTable.php | UTF-8 | 1,396 | 2.59375 | 3 | [] | no_license | <?php
/**
* Companies_Model_CouponReviewTable
*
* This class has been auto-generated by the Doctrine ORM Framework
*/
class Companies_Model_CouponReviewTable extends Doctrine_Table {
/**
* Returns an instance of this class.
* @return object Companies_Model_CouponReviewTable
*/
public static function getInstance() {
return Doctrine_Core::getTable('Companies_Model_CouponReview');
}
/**
* Check if coupon was sent
* @param $couponId
* @param $reviewId
* @return bool
*/
public function wasSent($couponId, $reviewId) {
$couponReview = $this->findOneByCouponIdAndReviewId($couponId, $reviewId);
if ($couponReview !== false) {
return !empty($couponReview->is_coupon_sended);
}
return false;
}
/**
* Mark coupon as sent
* @param $couponId
* @param $reviewId
*/
public function setSent($couponId, $reviewId) {
$couponReview = $this->findOneByCouponIdAndReviewId($couponId, $reviewId);
if ($couponReview === false) {
$couponReview = new Companies_Model_CouponReview();
$couponReview->coupon_id = $couponId;
$couponReview->review_id = $reviewId;
}
$couponReview->is_coupon_sended = true;
$couponReview->save();
}
} | true |
ad9e1331438f439b9496e1e4122ef8202bdc2228 | PHP | thiagovictor/TestesAutomatizadosTDD | /tests/src/TDD/Componentes/QuebraTest.php | UTF-8 | 507 | 2.78125 | 3 | [] | no_license | <?php
namespace TDD\Componentes;
class QuebraTest extends \PHPUnit_Framework_TestCase{
private $quebra;
public function setUp() {
$this->quebra = new Quebra();
}
public function testVerificaSeEUmaInstanciaValidaDeComponentesDeInterface() {
$this->assertInstanceOf("TDD\Interfaces\ComponenteInterface", $this->quebra);
}
public function testRender() {
$this->assertEquals("<br>", $this->quebra->render());
}
}
| true |
11768823bfc4b337a5fe1c4fc41b5df4af8d3795 | PHP | originphp/log | /src/Engine/ConsoleEngine.php | UTF-8 | 2,482 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
/**
* OriginPHP Framework
* Copyright 2018 - 2021 Jamiel Sharief.
*
* Licensed under The MIT License
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* @copyright Copyright (c) Jamiel Sharief
* @link https://www.originphp.com
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Origin\Log\Engine;
class ConsoleEngine extends BaseEngine
{
/**
* ANSI color mapping
*
* @internal Some systems do not support 9x/1xx colors, including TravisCI.
* @var array
*/
protected $colors = [
'debug' => '37',
'info' => '32',
'notice' => '36',
'warning' => '33',
'error' => '31',
'critical' => '1;31',
'alert' => '41;37',
'emergency' => '5;41;37',
];
/**
* Holds the resource
*
* @var resource
*/
protected $stream = null;
/**
* Default configuration
*
* @var array
*/
protected $defaultConfig = [
'stream' => 'php://stderr',
'levels' => [],
'channels' => [],
];
protected $supportsAnsi = false;
protected function initialize(array $config): void
{
$this->stream = fopen($this->config('stream'), 'w');
$this->supportsAnsi = function_exists('posix_isatty') and posix_isatty($this->stream);
}
/**
* Workhorse for the logging methods
*
* @param string $level e.g debug, info, notice, warning, error, critical, alert, emergency.
* @param string $message 'this is a {what}'
* @param array $context ['what'='string']
* @return void
*/
public function log(string $level, string $message, array $context = []): void
{
$message = $this->format($level, $message, $context);
if ($this->supportsAnsi) {
$message = $this->colorize($level, $message);
}
$this->write($message . "\n");
}
protected function colorize(string $level, string $message)
{
$code = $this->colors[$level];
return "\033[{$code}m{$message}\033[0m";
}
/**
* Wrapper for testing
*
* @param string $message
* @return void
*/
protected function write(string $message): void
{
fwrite($this->stream, $message);
}
public function __destruct()
{
fclose($this->stream);
}
}
| true |
a0049b22a4e6f82306bf07f9d72bc5a1c3754cb8 | PHP | gegeturambar/silex_rest_api | /src/Controller/LangueController.php | UTF-8 | 2,533 | 2.8125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* Langue: jsimonney
* Date: 23/08/2017
* Time: 10:19
*/
namespace Controller;
use Entity\Langue;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
class LangueController
{
public function indexAction(Application $app, Request $request)
{
$langues = $app['repository.langue']->findAll();
$responseData = array();
foreach($langues as $langue){
$responseData[] = array(
'id' => $langue->getId(),
'name' => $langue->getName(),
'code' => $langue->getCode()
);
}
return $app->json($responseData);
}
public function findAction(Application $app,Request $request,$id)
{
$langue = $app['repository.langue']->find($id);
if(!isset($langue)){
$app->abort(404, 'Langue does not exists');
}
$responseData = array(
'id' => $langue->getId(),
'name' => $langue->getName(),
'code' => $langue->getCode()
);
return $app->json($responseData);
}
public function createAction(Application $app,Request $request)
{
$requiredParams = array('name','code');
foreach($requiredParams as $requiredParam) {
if (!$request->request->has($requiredParam)) {
return $app->json("Missing parameter: $requiredParam",400);
}
}
$langue = new Langue();
$langue->setName($request->request->get('name'));
$langue->setCode($request->request->get('code'));
$app['repository.langue']->save($langue);
$responseData = $langue->getData();
return $app->json($responseData,201);
}
public function deleteAction(Application $app,Request $request,$id)
{
$app['repository.langue']->delete($id);
return $app->json('No content', 204);
}
public function updateAction(Application $app, Request $request,$id)
{
/** @var Langue $langue */
$langue = $app['repository.langue']->find($id);
$attrs = array('name','code');
foreach($attrs as $attr) {
$val = $request->request->get($attr);
if (isset($val)) {
$fct = "set".ucfirst($attr);
$langue->$fct($val);
}
}
$app['repository.langue']->save($langue);
$responseData = $langue->getData();
return $app->json($responseData,202);
}
} | true |
c8ec9ca4a54361eebcad83b6f731928e7c15a020 | PHP | karlozz157/control | /Controller/Controller.php | UTF-8 | 503 | 2.84375 | 3 | [] | no_license | <?php
abstract class Controller
{
public function __construct()
{
$this->className = str_replace('Controller', '', get_class($this));
}
/**
* @param string $fileName
* @param array $vars
*/
protected function view($fileName, array $vars = array())
{
$file = "./Views/Inflow/$fileName.php";
if (!file_exists($file)) {
throw new Exception('The file does not exists.');
}
$vars;
require $file;
}
}
| true |
ba4ed3056ccd4063b7420134fcd7e383e674a9fb | PHP | jesusdiez/codeeval | /easy/simple-or-trump/simple-or-trump.php | UTF-8 | 1,354 | 3.265625 | 3 | [] | no_license | #!/usr/bin/php
<?php
$lines = file($argv[1]);
$sum = function ($a, $b) { return $a + $b; };
foreach ($lines as $line) {
list($hand1, $hand2, $trump) = parse($line);
$hand1Value = calculateHandValue($hand1, $trump);
$hand2Value = calculateHandValue($hand2, $trump);
if ($hand1Value > $hand2Value) {
$output = implode('', $hand1);
} elseif($hand1Value < $hand2Value) {
$output = implode('', $hand2);
} else {
$output = sprintf("%s %s", implode('', $hand1), implode('', $hand2));
}
printf("%s\n", $output);
}
exit(0);
function calculateHandValue(array $hand, $trump) {
$equivalences = [
'J' => 11, 'Q' => 12, 'K' => 13, 'A' => 14,
];
$multiplier = ($hand['suit'] == $trump) ? 100 : 1;
$cardValue = array_key_exists($hand['val'], $equivalences) ? $equivalences[$hand['val']] : $hand['val'];
return $cardValue * $multiplier;
}
function parse($line)
{
$matches = [];
$cardPattern = '(?:[2-9]|10|J|Q|K|A)';
$suitPattern = '[H|C|S|D]';
$pattern = '/^('.$cardPattern.')('.$suitPattern.') ('.$cardPattern.')('.$suitPattern.') \| ('.$suitPattern.')$/';
preg_match($pattern, trim($line), $matches);
return [
['val' => $matches[1], 'suit' => $matches[2]],
['val' => $matches[3], 'suit' => $matches[4]],
$matches[5]
];
}
| true |
172fe104f2fae0231fef83ad09beb27b50141f5e | PHP | nehuenfack142/ProyectoA | /signup_user.php | UTF-8 | 1,788 | 2.578125 | 3 | [] | no_license | <?php
include("include/connection.php");
if(isset($_POST['sign_up'])){
$name=htmlentities(mysqli_real_escape_string($con, $_POST['user_name']));
$pass=htmlentities(mysqli_real_escape_string($con, $_POST['user_pass']));
$email=htmlentities(mysqli_real_escape_string($con, $_POST['user_email']));
$conutry=htmlentities(mysqli_real_escape_string($con, $_POST['user_country']));
$gender=htmlentities(mysqli_real_escape_string($con, $_POST['user_gender']));
$bf=htmlentities(mysqli_real_escape_string($con, $_POST['forgotten_answer']));
$user_hora=htmlentities(mysqli_real_escape_string($con, $_POST['user_hora']));
$rand=rand(1,2);
if($name==''){
echo"<script>alert('No podemos verificar su nombre')</script>";
}
$check_email="select * from users where user_email ='$email'";
$run_email=mysqli_query($con,$check,$email);
$check= mysqli_num_rows($run_email);
if($check==1){
echo"<script>alert('Este mail ya existe, por favor ingresar otro!'</script>";
echo"<script>window.open('signup.php','_self')</script>";
exit();
}
if($rand ==1)
$profile_pic = "images/imagen2.jpg";
else if ($rand == 2)
$profile_pic = "images/imagen3.jpg";
$insert = "insert into users(user_name, user_pass, user_email, user_profile, user_country, user_gender, forgotten_answer, user_hora) values('$name', '$pass','$email','$profile_pic', '$conutry', '$gender', '$bf', '$user_hora')";
$query = mysqli_query($con, $insert);
if($query){
echo"<script>alert('Congratulations $name, your account has been created successfully')</script>";
echo"<script>window.open('signin.php', '_self')</script>";
}
else{
echo"<script>alert('Registration failed, try again!')</script>";
echo"<script>window.open('signup.php', '_self')</script>";
}
}
?> | true |
15a8d8d386b7530b30bc2d611a61b969e9ba03c0 | PHP | Aleyx4/Fundamentals-of-Software-Engineering-Spring-2018 | /submitelection.php | UTF-8 | 1,071 | 2.671875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: teagenkiel
* Date: 4/29/18
* Time: 10:55 AM
*/
include('session.php');
$username = $_POST['username'];
$electionid = $_POST['electionid'];
$sql = "INSERT INTO electionparticipants (username , electionID)
VALUES ('$username', '$electionid')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$candidatename = $_POST['radio'];
echo $candidatename;
$sql1 = "SELECT * FROM candidates WHERE name = '$candidatename'";
$sql5 = mysqli_query($db,$sql1);
$candidate = array();
while ($row_user = mysqli_fetch_assoc($sql5)) {
$candidate[] = $row_user;
}
$pastresults = $candidate[0]['results'];
echo $pastresults;
$newresults = $pastresults + 1;
echo $newresults;
$sql2 = "UPDATE candidates SET results = '$newresults' WHERE name='$candidatename'";
if ($db->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $db->error;
}
header("Location: welcome.php");
exit; | true |
0f7f6913283473e862add671fd1210eed4ada3f2 | PHP | contributte/oauth2-server | /tests/fixtures/Repositories/AccessTokenRepository.php | UTF-8 | 958 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php declare(strict_types = 1);
namespace Tests\Fixtures\Repositories;
use League\OAuth2\Server\Entities\AccessTokenEntityInterface;
use League\OAuth2\Server\Entities\ClientEntityInterface;
use League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface;
final class AccessTokenRepository implements AccessTokenRepositoryInterface
{
/**
* @inheritDoc
*/
public function getNewToken(ClientEntityInterface $clientEntity, array $scopes, $userIdentifier = null)
{
// TODO: Implement getNewToken() method.
}
/**
* @inheritDoc
*/
public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity)
{
// TODO: Implement persistNewAccessToken() method.
}
/**
* @inheritDoc
*/
public function revokeAccessToken($tokenId)
{
// TODO: Implement revokeAccessToken() method.
}
/**
* @inheritDoc
*/
public function isAccessTokenRevoked($tokenId)
{
// TODO: Implement isAccessTokenRevoked() method.
}
}
| true |
cf6223615fae38e1993837846fa458b257f128b0 | PHP | StevenGreen1/ProtoDUNE_Cron | /Website/Cron_MicroBooNE/cron_diff.php | UTF-8 | 1,200 | 2.671875 | 3 | [] | no_license | <!DOCTYPE html>
<html>
<head>
<title>Pandora MicroBooNE Validation</title>
<h1>Pandora MicroBooNE Validation</h1>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<?php
$date1 = $_POST['Date1'];
$date2 = $_POST['Date2'];
$myversion1 = $_POST['SoftwareVersion1'];
$myversion2 = $_POST['SoftwareVersion2'];
$yy = substr($date1,6,2);
$mm = substr($date1,3,2);
$dd = substr($date1,0,2);
$newDateFormat1 = "20".$yy."_".$mm."_".$dd;
$yy = substr($date2,6,2);
$mm = substr($date2,3,2);
$dd = substr($date2,0,2);
$newDateFormat2 = "20".$yy."_".$mm."_".$dd;
if (!empty($date1))
{
echo "<h4>Date 1 : $newDateFormat1</h4>";
}
if (!empty($date2))
{
echo "<h4>Date 2 : $newDateFormat2</h4>";
}
$mydir1 = "CronResults/".$newDateFormat1."/".$myversion1."/RootFiles";
$mydir2 = "CronResults/".$newDateFormat2."/".$myversion2."/RootFiles";
$tableOutput1 = $mydir1. '/TableOutput.txt';
$tableOutput2 = $mydir2. '/TableOutput.txt';
if (file_exists($tableOutput1) && file_exists($tableOutput2))
{
$output = shell_exec("diff -u $tableOutput1 $tableOutput2 | ./../diff2html.sh");
echo $output;
file_put_contents('tmp.php', $output);
include("tmp.php");
}
?>
</html>
| true |
4e37a9761a53c9c1d78d231156ece27a32e1f43e | PHP | kuc-arc-f/php-test01 | /php-test01/libs/ComFunc.php | UTF-8 | 6,587 | 2.96875 | 3 | [] | no_license | <?php
//------------------------------------
// @calling
// @purpose : 共通番号TBLから、Noを取得する。
// @date
// @argment : $date_str=yyyymmdd+hhmmss, $i_num=rand()
// @return : -1 =NG
//------------------------------------
function CM001_def_no( $date_str, $i_num, $sys_id, $uid){
$i_def_id =0;
$db =new ComMysql();
//(1) select
$param["@001"] = $date_str;
$param["@002"] = $i_num;
$param["@003"] = $sys_id;
$result = $db->GetRecord_byId("CM001", 5, $param);
while ($row = mysql_fetch_array ($result)) {
$i_ct = $row["CT_NUM"];
}
if($i_ct > 0){
return -1;
}
//(2) Insert
$param["@001"] = $date_str;
$param["@002"] = $i_num;
$param["@003"] = $sys_id;
$param["@004"] = $uid;
//Insert
$result = $db->Exec_NonQuery( "CM001", 4, $param );
//実行した結果にエラーあったらエラー表示する
if ($result == false) {
print "Data Insert Error!";
return -1;
exit;
}
//(3) Select_ID
$result = $db->GetRecord_byId("CM001", 6, $param);
while ($row = mysql_fetch_array ($result)) {
$i_def_id = $row["ID"];
}
$db =NULL;
return $i_def_id;
//
}
//------------------------------------
// @calling : 時間(int)の差分時間を求める。
// @purpose :
// @date
// @argment : src=YYYY-MM-DD
// @return : 差分時間(YYYY-MM-DD)
//------------------------------------
function CM001_getDiff_Date($src, $i_num){
if(strlen($src) !=10){
return "";
}
/*
$yyyy = substr($src, 0, 4);
$mm = substr($src, 5, 2);
$dd = substr($src, 8, 2);
$st_dt = mktime(0, 0 , 0, $mm, $dd, $yyyy );
*/
$s_add=" +" . $i_num . " day";
// $s_next = date("Y-m-d", $st_dt );
$s_next = $src . $s_add;
var_dump( "s_next=" . $s_next);
$s_next = date("Y-m-d", strtotime($s_next) );
return $s_next;
}
//------------------------------------
// @calling : 時間(int)の差分時間を求める。
// @purpose :
// @date
// @argment :
// @return : 差分時間(分)
//------------------------------------
function CM001_getDiff_mm($start_hh, $start_mm ,$end_hh, $end_mm){
$st_dt = mktime($start_hh , $start_mm , 0, 1, 1, 2000 );
$end_dt = mktime($end_hh , $end_mm , 0, 1, 1, 2000 );
$diff_mm = $end_dt - $st_dt;
$diff_mm = $diff_mm / 60;
return $diff_mm;
}
//------------------------------------
// @calling
// @purpose : 次月、1日の日付を返す。(YYYY-MM-DD 形式)
// @date
// @argment
// @return
//------------------------------------
function CM001_geNextmonth( $bef_dt ){
// $s_buf ='2010-03-01';
$s_yy = substr($bef_dt, 0, 4);
$s_mm = substr($bef_dt, 5, 2);
$now_dt = mktime(1, 0, 0, $s_mm, 1, $s_yy );
$nextmonth = mktime(1, 0, 0, date("m", $now_dt ) +1, 1, date("Y", $now_dt ) );
$s_next = date("Y", $nextmonth ) . "-" . date("m", $nextmonth ) . "-" . date("d", $nextmonth );
return $s_next;
}
//------------------------------------
// @calling
// @purpose : 前/次月、1日の日付を返す。(YYYY-MM-DD 形式)
// @date
// @argment
// @return
//------------------------------------
function CM001_geMovemonth( $typ, $bef_dt ){
$s_yy = substr($bef_dt, 0, 4);
$s_mm = substr($bef_dt, 5, 2);
$now_dt = mktime(1, 0, 0, $s_mm, 1, $s_yy );
$nextmonth = mktime(1, 0, 0, date("m", $now_dt ) + $typ, 1, date("Y", $now_dt ) );
$s_next = date("Y", $nextmonth ) . "-" . date("m", $nextmonth ) . "-" . date("d", $nextmonth );
return $s_next;
}
//nextmonth
//------------------------------------
// @calling
// @purpose
// @date
// @argment
// @return
//------------------------------------
function CM001_Get_CodeStr($kbn, $i_num){
$s_str1="";
$db =new ComMysql();
//(1) select
$param["@001"] = $kbn;
$param["@002"] = $i_num;
$result = $db->GetRecord_byId("CM001", 4, $param);
while ($row = mysql_fetch_array ($result)) {
$s_str1 = $row["STR_VAL_01"];
}
return $s_str1;
}
//------------------------------------
// @calling
// @purpose
// @date
// @argment
// @return : bool
//------------------------------------
function Com_checkAgent(){
$clsConst = new AppConst();
$s_buf = $_SERVER["HTTP_USER_AGENT"];
$i_pos = strpos($s_buf , "MSIE");
if( $i_pos != false){
$_SESSION["CM001"]["HTTP_USER_AGENT"]= $clsConst->VAL014_WEB_IE ;
return true;
}
//var_dump($i_pos);
// exit;
$i_pos_ch = strpos($s_buf , "Chrome");
//Chrome
// var_dump($s_buf ."<br>");
// var_dump($i_pos );
/*
if ($i_pos == false) {
return false;
}
*/
if (($i_pos == false) && ($i_pos_ch == false)) {
return false;
}
return true;
}
//------------------------------------
// @calling
// @purpose
// @date
// @argment
// @return
//------------------------------------
function Com_logWrite($msg){
$s_time = date("Y/m/d H:i:s");
if(LOG_FLG==true){
error_log($s_time . " ". $msg . "\r\n" ,3, LOG_FNAME);
// error_log($s_time . " ". $msg . "\n" ,3, LOG_FNAME);
}
}
//
function init() {
//MySmartyクラスの読み込み
require_once($_SERVER["DOCUMENT_ROOT"]. "/../libs/MySmarty.class.php");
//セッションを開始する
session_start();
session_regenerate_id(true);
}
//------------------------------------
// @calling
// @purpose :
// @date
// @argment :
// @return :
//------------------------------------
function CM001_uploadFile( $obj , $uid){
$uploaddir = BT_IMAGE_USR_DIR;
$uploadfile = $uploaddir . $uid . "_" . basename($obj['name']);
// $uploadfile = $uploaddir . "aa.png";
if (move_uploaded_file($obj['tmp_name'] , $uploadfile) == false ) {
echo "Possible file upload attack!\n";
return false;
}
return true;
// echo "Here is some more debugging info:";
// print_r($_FILES);
}
//------------------------------------
// @calling
// @purpose
// @date
// @argment :
// @return :
//------------------------------------
function CM001_Conv_href( $s_buf ){
// $i_pos = -1;
$i_pos = strpos($s_buf , "http://");
//var_dump($i_pos);
if(is_numeric($i_pos)==true){
// var_dump($i_pos);
// var_dump($s_buf);
if($i_pos ==0){
return "<a href='". $s_buf ."' target='_blank'>" . $s_buf . "</a>";
}
}
return $s_buf;
}
//------------------------------------
// @calling
// @purpose
// @date
// @argment :
// @return :
//------------------------------------
function CM001_Conv_urlString( $s_buf ){
//Replace
$s_buf = trim($s_buf);
$s_buf = str_replace(" ", " ", $s_buf );
$low = explode(" ", $s_buf);
// var_dump(count($low));
// var_dump($low);
if(count($low) > 1){
$s_out ="";
foreach($low as $value){
$s_out .=CM001_Conv_href($value) . " ";
}
}else{
return $s_buf;
}
return $s_out;
}
?> | true |
72f10c81f27f41a28e551969470d2b527e3e6c93 | PHP | 300rub/300rub | /code/tests/phpunit/controllers/user/DeleteSessionsControllerTest.php | UTF-8 | 3,621 | 2.546875 | 3 | [] | no_license | <?php
namespace ss\tests\phpunit\controllers\user;
use ss\models\user\UserSessionModel;
use ss\tests\phpunit\controllers\_abstract\AbstractControllerTest;
/**
* Tests for the controller DeleteSessionsController
*/
class DeleteSessionsControllerTest extends AbstractControllerTest
{
/**
* Test
*
* @param string $user User type
* @param int $userId User ID
* @param bool $hasError Error flag
*
* @dataProvider dataProvider
*
* @return bool
*/
public function testRun($user, $userId = null, $hasError = null)
{
$this->setUser($user);
$sessionsToDelete = new UserSessionModel();
$sessionsToDelete->byUserId($userId);
$sessionsToDelete = $sessionsToDelete->findAll();
foreach ($sessionsToDelete as $sessionModel) {
$this->assertNotNull($sessionModel);
}
$data = [];
if ($userId !== null) {
$data = ['id' => $userId];
}
$this->sendRequest('user', 'sessions', $data, 'DELETE');
if ($hasError === true) {
$this->assertError();
foreach ($sessionsToDelete as $sessionModel) {
$userSessionModel = new UserSessionModel();
$userSessionModel->byId($sessionModel->getId());
$this->assertNotNull($userSessionModel->find());
}
return true;
}
$this->assertSame(
[
'result' => true
],
$this->getBody()
);
foreach ($sessionsToDelete as $sessionModel) {
if ($sessionModel->get('token') === $this->getUserToken()) {
$userSessionModel = new UserSessionModel();
$userSessionModel->byId($sessionModel->getId());
$this->assertNotNull($userSessionModel->find());
continue;
}
$userSessionModel = new UserSessionModel();
$userSessionModel->byId($sessionModel->getId());
$this->assertNull($userSessionModel->find());
$sessionModel->clearId()->save();
}
return true;
}
/**
* Data provider
*
* @return array
*/
public function dataProvider()
{
return [
'ownerDeleteOwner' => [
self::TYPE_OWNER,
1
],
'ownerDeleteHimself' => [
self::TYPE_OWNER
],
'ownerDeleteAdmin' => [
self::TYPE_OWNER,
2
],
'ownerDeleteUser' => [
self::TYPE_OWNER,
3
],
'adminDeleteOwner' => [
self::TYPE_FULL,
1,
true
],
'adminDeleteHimself' => [
self::TYPE_OWNER
],
'adminDeleteAdmin' => [
self::TYPE_OWNER,
2
],
'adminDeleteUser' => [
self::TYPE_OWNER,
3
],
'limitedDeleteOwner' => [
self::TYPE_LIMITED,
1,
true
],
'limitedDeleteHimself' => [
self::TYPE_LIMITED
],
'limitedDeleteAdmin' => [
self::TYPE_LIMITED,
2,
true
],
'limitedDeleteUser' => [
self::TYPE_LIMITED,
3
],
];
}
}
| true |
e2b9dfbff24a52f18fa0cbce439f272b1ecbd1ba | PHP | IlchCMS/ilch2-build | /functions.php | UTF-8 | 3,528 | 2.578125 | 3 | [] | no_license | <?php
function logRequest($message = null, $errorFile = null, $errorLine = null)
{
global $config;
if (!isset($config['logDir']) || !is_dir($config['logDir']) || !is_writable($config['logDir'])) {
return;
}
$logFile = $config['logDir'] . '/' . date('Ymd-His') . '.log';
$fh = fopen($logFile, 'w');
if (!empty($errorLine) && !empty($errorFile)) {
fwrite($fh, sprintf("Error in file %s line %d\n", $errorFile, $errorLine));
}
if (!empty($message)) {
fwrite($fh, sprintf("ErrorMessage: %s\n", $message));
}
fwrite($fh, sprintf("Headers: %s\nPayload: %s\n", print_r(apache_request_headers(), true), $_POST['payload']));
fclose($fh);
}
/**
* @param string $branch
* @param string $commit
* @param string|null $tag
*/
function createArchive($branch, $commit, $tag = null)
{
global $config;
if (preg_match('~^v?\d+(?:\.\d+){0,2}$~',$tag) === 1) {
$archiveName = $tag;
} else {
$archiveName = array_search($branch, $config['allowedBranches']);
if (!is_string($archiveName)) {
$archiveName = $branch;
}
}
$archive = $commit . '_tmp.zip';
$composer = $config['phpBin'] . ' ' . $config['composer'];
if (!empty($config['composerHome'])) {
$composer = 'COMPOSER_HOME=' . escapeshellarg($config['composerHome']) . ' ' . $composer;
}
$commands = array(
'unzip ' . $archive,
'rm ' . $archive,
'cd Ilch-2.0-' . $commit,
$composer . ' install --no-dev --optimize-autoloader --no-interaction',
'if [ -f build/optimize_vendor.php ]; then ' . $config['phpBin'] . ' build/optimize_vendor.php; fi',
'zip -r ../' . $archiveName . '_NEW_.zip .',
'mv ../' . $archiveName . '_NEW_.zip ../' . $archiveName . '.zip',
'cd ..',
'rm -r Ilch-2.0-' . $commit
);
if (!file_exists($archive)) {
if (isset($config['useCurlExecutable']) && $config['useCurlExecutable']) {
array_unshift(
$commands,
sprintf('curl -sL https://codeload.github.com/IlchCMS/Ilch-2.0/zip/%s --output %s', $commit, $archive)
);
} else {
$fp = fopen($archive, 'w+');
$ch = curl_init('https://codeload.github.com/IlchCMS/Ilch-2.0/zip/' . $commit);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($ch, CURLOPT_ENCODING, '');
if (!curl_exec($ch)) {
logRequest('CURL download error: ' . curl_error($ch), __FILE__, __LINE__);
}
curl_close($ch);
fclose($fp);
}
}
$cmdLine = implode(' && ', $commands);
if (isset($config['cmd'])) {
$cmdLine = sprintf($config['cmd'], $cmdLine);
}
exec($cmdLine,$cmdOut,$cmdReturn);
if ($cmdReturn !== 0) {
logRequest('Error while creating archive: ' . implode("\n",$cmdOut),__FILE__, __LINE__);
}
}
if (!function_exists('apache_request_headers')) {
function apache_request_headers()
{
$headers = array();
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
}
}
return $headers;
}
}
| true |
03e8c41b9d90c1a775e6735bf4937b01e77d6817 | PHP | j-grynkiewicz/wu | /app/Http/Controllers/LectureController.php | UTF-8 | 3,229 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Lecture;
use App\User;
class LectureController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$lectures = Lecture::all()->toArray();
return view('lecture.index', compact('lectures'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('lecture.create');
}
public function members($id)
{
$lecture = Lecture::find($id);
$users = User::all()->toArray();
return view('lecture.members', compact('lecture', 'id'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'type' => 'required',
'ects' => 'required',
'group_id' => 'required',
]);
$lecture = new Lecture([
'name' => $request->get('name'),
'type' => $request->get('type'),
'ects' => $request->get('ects'),
'group_id' => $request->get('group_id'),
]);
$lecture->save();
return redirect()->route('lecture.index')->with('success', 'Data Added');
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$lecture = Lecture::find($id);
return view('lecture.edit', compact('lecture', 'id'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'type' => 'required',
'ects' => 'required',
'group_id' => 'required',
]);
$lecture = Lecture::find($id);
$lecture->name = $request->get('name');
$lecture->type = $request->get('type');
$lecture->ects = $request->get('ects');
$lecture->group_id = $request->get('group_id');
$lecture->save();
return redirect()->route('lecture.index')->with('success', 'Data Updated');
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$lecture = Lecture::find($id);
$lecture->delete();
return redirect()->route('lecture.index')->with('success', 'Data Deleted');
}
}
| true |
388c69ab8f79c6702a3cfba4cbb7d1d7964463bf | PHP | sunzhenvip/laravel | /app/models/ApiPayCallBack.php | UTF-8 | 13,899 | 2.625 | 3 | [
"MIT"
] | permissive | <?php
/**
* 所有回调调用的方法model
* @author:wang.hongli
* @since:2016/05/25
*/
class ApiPayCallBack extends ApiCommon{
private $orderid;
private $order_info;
private $good_info;
private $time;
private $apiTianLaiGoods;
/**
* 构造方法
* @param number $orderid 订单id
* @param array $order_info 订单信息
* @param array $good_info 商品信息
*/
function __construct($orderid=0,$order_info=array(),$good_info=array()){
$this->orderid = $orderid;
$this->order_info = $order_info;
$this->good_info = $good_info;
$this->time = time();
$this->apiTianLaiGoods = new ApiTianLaiGoods();
}
/**
* 打赏回调逻辑
* @author:wang.hongli
* @since:2016/05/25
*/
public function callReward(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$time = time();
$arr = array('uid'=>$this->order_info['uid'],'sort'=>1,'flag'=>2,'type'=>3,'addtime'=>$time,'ext'=>$this->order_info['total_price']);
DB::table('diploma')->insert($arr);
//更新订单
$this->updateOrderStatus();
} catch (Exception $e) {
}
return true;
}
/**
* 夏青杯回调逻辑
* @author:wang.hongli
* @since:2016/05/25
*/
public function callSummerCup(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try{
//夏青杯 - 判断是否有权限了
$over_time=strtotime("2015-08-01");
$rlt = DB::table('user_permission')->where('type','=',2)->where('uid','=',$this->order_info['uid'])->first();
if(!empty($rlt)){
DB::table('user_permission')->where('uid',$this->order_info['uid'])->where('type',2)->update(array('over_time'=>$over_time,'update_time'=>$this->time));
}else{
DB::table('user_permission')->insert(array('uid'=>$this->order_info['uid'],'type'=>2,'update_time'=>$this->time,'over_time'=>$over_time));
}
//更新订单状态
$this->updateOrderStatus();
} catch (Exception $e){
}
return true;
}
/**
* 各种比赛回调逻辑
* @author:wang.hongli
* @since:2016/05/25
*/
public function callCompetition(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$match = DB::table('competitionlist')->where('id','=',$this->good_info['competition_id'])->first(array('endtime','has_invitation'));
//添加权限
$over_time=$match['endtime'];
$rlt = DB::table('user_permission')->where('type','=',$this->good_info['competition_id'])->where('uid','=',$this->order_info['uid'])->first();
if(!empty($rlt)){
DB::table('user_permission')->where('uid',$this->order_info['uid'])->where('type',$this->good_info['competition_id'])->update(array('over_time'=>$over_time,'update_time'=>$this->time));
}else{
DB::table('user_permission')->insert(array('uid'=>$this->order_info['uid'],'type'=>$this->good_info['competition_id'],'update_time'=>$this->time,'over_time'=>$over_time,'good_id'=>$this->good_info['id']));
}
//记录邀请码
if($match['has_invitation']==1){
$code_info = DB::table('user_match')->where('uid','=',$this->order_info['uid'])->first();
if(!empty($code_info) && $code_info['invitationcode']){
DB::table('order_list')->where('id',$this->orderid)->update(array('invitationcode'=>$code_info['invitationcode']));
}
}
//更新订单状态
$this->updateOrderStatus();
} catch (Exception $e) {
}
return true;
}
/**
* 班级活动回调逻辑
* @author:wang.hongli
* @since:2016/05/25
*/
public function callClassActive(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
//更新class_active中用户添加的最新一条记录
$class_active_info = DB::table('class_active_form')->where('uid',$this->order_info['uid'])->where('status',0)->orderBy('id','desc')->take(1)->first(array('id','invitationcode'));
if(empty($class_active_info)){
return true;
}
//记录邀请码
if(!empty($class_active_info['invitationcode'])){
DB::table('order_list')->where('id',$this->orderid)->update(array('invitationcode'=>$class_active_info['invitationcode']));
}
//更新提交表单状态
DB::table('class_active_form')->where('id',$class_active_info['id'])->update(array('status'=>1,'orderid'=>$this->orderid,'goods_id'=>$this->good_info['id']));
//更新订单状态
$this->updateOrderStatus();
} catch (Exception $e) {
}
return true;
}
/**
* 结束比赛逻辑处理
* @author :wang.hongli
* @since :2016/07/11
*/
public function callFinishCompetition(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
//判断是否为单独购买光盘
if($this->good_info['flag'] == 2 && !empty($this->good_info['good_pid'])){
try {
DB::table('order_list')->where('goods_id',$this->good_info['good_pid'])->where('uid',$this->order_info['uid'])->where('status',2)->update(['attach_id'=>$this->good_info['id'],'attach_price'=>$this->good_info['price']]);
} catch (Exception $e) {
}
}
$this->updateOrderStatus();
return true;
}
/**
* 中华诵读联合会交过费的自动通过审核
* @author :wang.hongli
* @since :2016/07/14
*/
public function callLeague(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$rs = DB::table('user_permission')->where('uid','=',$this->order_info['uid'])->where('type','=',1)->first();
if(!empty($rs)){
DB::table('league')->where('uid','=',$this->order_info['uid'])->update(array('status'=>2));
DB::table('order_list')->where('orderid','=',$this->orderid)->update(['audit_status'=>2,'audit_time'=>$this->time]);
//更新user_permission过期时间
$num = !empty($this->order_info['num']) ? intval($this->order_info['num']) : 1;
$add_time = $num*365*86400;
$sql = "update user_permission set over_time=over_time+?,update_time=? where uid = ? and type = 1";
DB::update($sql,[$add_time,$this->time,$this->order_info['uid']]);
DB::table('user')->where('id',$this->order_info['uid'])->update(['isleague'=>1]);
//插入到自动审核表
DB::table('league_auto_pass')->insert(['uid'=>$this->order_info['uid'],'type'=>0,'order_id'=>$this->orderid]);
$id = DB::table('league_user')->where('uid',$this->order_info['uid'])->pluck('id');
if(empty($id)){
//将数据插入到league_user联合会冗余表中
$user_info = DB::table('user')->where('id',$this->order_info['uid'])->first(array('praisenum','lnum','repostnum'));
DB::table('league_user')->insert(array('id'=>0,'uid'=>$this->order_info['uid'],'praisenum'=>$user_info['praisenum'],'lnum'=>$user_info['lnum'],'repostnum'=>$user_info['repostnum'],'addtime'=>time()));
//将用户认证信息保留
$auth_content = DB::table('user_auth_content')->where('uid',$this->order_info['uid'])->first(['id','uid','auth_content']);
if(!empty($auth_content['auth_content'])){
DB::table('user')->where('id',$this->order_info['uid'])->update(['authconent'=>$auth_content['auth_content'],'authtype'=>1]);
}
}
}
} catch (Exception $e) {
}
$this->updateOrderStatus();
return true;
}
/**
* 开通会员
* @author :wang.hongli
* @since :2016/08/16
*/
public function callPassMember(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$user_info['id'] = $this->order_info['uid'];
//判断是否为会员
$apicheckPermission = App::make('apicheckPermission');
$user_info['ismember'] = $apicheckPermission->isMember($user_info['id']);
$data['num'] = $this->order_info['num'];
$data['orderid'] = $this->order_info['orderid'];
//众筹商品增加众筹数
// $this->apiTianLaiGoods->incrementCrowdfundinged($this->good_info,$this->order_info['num']);
//开通相关权限
$this->apiTianLaiGoods->passPermission($user_info,$this->good_info,$data);
//赠送钻石等操作
$this->apiTianLaiGoods->giveDiamond($user_info,$this->good_info,$data);
//开通会员赠送下载数
$this->apiTianLaiGoods->giveDownNum($user_info,$this->goods_info,$data);
} catch (Exception $e) {
}
//更新订单状态
$this->updateOrderStatus();
return true;
}
/**
* 开通私信通
* @author:wang.hongli
* @since :2016/08/16
*/
public function callPassPersonLetter(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$user_info['id'] = $this->order_info['uid'];
//判断是否为会员
$apicheckPermission = App::make('apicheckPermission');
$user_info['ismember'] = $apicheckPermission->isMember($user_info['id']);
$data['num'] = $this->order_info['num'];
$data['orderid'] = $this->order_info['orderid'];
//众筹商品增加众筹数
// $this->apiTianLaiGoods->incrementCrowdfundinged($this->good_info,$this->order_info['num']);
//开通相关权限
$this->apiTianLaiGoods->passPermission($user_info,$this->good_info,$data);
//赠送钻石等操作
$this->apiTianLaiGoods->giveDiamond($user_info,$this->good_info,$data);
} catch (Exception $e) {
}
//更新订单状态
$this->updateOrderStatus();
return true;
}
/**
* 实体商品
* @author :wang.hongli
* @since :2016/08/16
*/
public function callEntityGood(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$user_info['id'] = $this->order_info['uid'];
//判断是否为会员
$apicheckPermission = App::make('apicheckPermission');
$user_info['ismember'] = $apicheckPermission->isMember($user_info['id']);
$data['num'] = $this->order_info['num'];
$data['orderid'] = $this->order_info['orderid'];
//众筹商品增加众筹数
$this->apiTianLaiGoods->incrementCrowdfundinged($this->good_info,$this->order_info['num']);
//开通相关权限
// $this->apiTianLaiGoods->passPermission($user_info,$this->good_info,$data);
//赠送钻石等操作
$this->apiTianLaiGoods->giveDiamond($user_info,$this->good_info,$data);
} catch (Exception $e) {
}
//更新订单状态
$this->updateOrderStatus();
return true;
}
/**
* 出版物
* @author :wang.hongli
* @since :2016/08/16
*/
public function callPublicationGood(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$user_info['id'] = $this->order_info['uid'];
//判断是否为会员
$apicheckPermission = App::make('apicheckPermission');
$user_info['ismember'] = $apicheckPermission->isMember($user_info['id']);
$data['num'] = $this->order_info['num'];
$data['orderid'] = $this->order_info['orderid'];
$data['flag'] = 3;
//众筹商品增加众筹数
$this->apiTianLaiGoods->incrementCrowdfundinged($this->good_info,$this->order_info['num']);
//开通相关权限
// $this->apiTianLaiGoods->passPermission($user_info,$this->good_info,$data);
//赠送钻石等操作
$this->apiTianLaiGoods->giveDiamond($user_info,$this->good_info,$data);
} catch (Exception $e) {
}
//更新订单状态
$this->updateOrderStatus();
return true;
}
/**
* 购买钻石
* @author :wang.hongli
* @since :2016/08/17
*/
public function callBuyDiamond(){
if(empty($this->order_info) || empty($this->good_info) || empty($this->orderid)){
return true;
}
//避免多次重复调用
if(!empty($this->order_info['status']) && $this->order_info['status'] == 2){
return true;
}
try {
$user_info['id'] = $this->order_info['uid'];
//判断是否为会员
$apicheckPermission = App::make('apicheckPermission');
$user_info['ismember'] = $apicheckPermission->isMember($user_info['id']);
$data['num'] = $this->order_info['num'];
$data['orderid'] = $this->order_info['orderid'];
$data['flag'] = 3;
//购买钻石
$this->apiTianLaiGoods->buyDiamond($user_info,$this->good_info,$data);
//赠送钻石等操作
$data['flag'] = 5;
$this->apiTianLaiGoods->giveDiamond($user_info,$this->good_info,$data);
} catch (Exception $e) {
}
//更新订单状态
$this->updateOrderStatus();
return true;
}
/**
* 操作成功后,更新订单状态
* @author:wang.hongli
* @since:2016/05/25
*/
public function updateOrderStatus(){
//更新订单状态
try {
DB::table('order_list')->where('orderid',$this->orderid)->update(array('status'=>2,'updatetime'=>$this->time));
} catch (Exception $e) {
}
return ;
}
} | true |
651c77f4c1d3fad2dc45c2c01689c62cc1c51259 | PHP | Muhammad-Rizal-Supriadi/praktikum-git | /v2/model/Pelanggan.php | UTF-8 | 4,529 | 3.109375 | 3 | [] | no_license | <?php
class Pelanggan{
// database connection and table name
private $conn;
private $table_name = "pelanggan";
// object properties
public $id_pelanggan;
public $nama_pelanggan;
public $alamat;
public $telepon;
public $email;
public $tgl_lahir;
// constructor with $db as database connection
public function __construct($db){
$this->conn = $db;
}
// read all products
function read(){
$query = "SELECT
id_pelanggan, nama_pelanggan, alamat, telepon, email, tgl_lahir
FROM
" . $this->table_name . "
ORDER BY
id_pelanggan ASC";
// prepare query statement
$stmt = $this->conn->prepare($query);
// execute query
$stmt->execute();
return $stmt;
}
// read single products by id
function readOne(){
// query to read single record
$query = "SELECT
id_pelanggan, nama_pelanggan, alamat, telepon, email, tgl_lahir
FROM
" . $this->table_name . "
WHERE
id_pelanggan = ?";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind id of product to be updated
$stmt->bindParam(1, $this->id);
// execute query
$stmt->execute();
// get retrieved row
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// set values to object properties
$this->nama_pelanggan = $row['nama'];
$this->alamat = $row['alamat'];
$this->telepon = $row['telepon'];
$this->email = $row['email'];
$this->tgl_lahir = $row['tgl_lahir'];
}
// create product
function create(){
// query to insert record
$query = "INSERT INTO
" . $this->table_name . "
SET
nama_pelanggan=:nama_pelanggan,
alamat=:alamat,
telepon=:telepon,
email=:email,
tgl_lahir=:tgl_lahir";
// prepare query
$stmt = $this->conn->prepare($query);
// bind values
$stmt->bindParam(":nama_pelanggan", $this->nama_pelanggan);
$stmt->bindParam(":alamat", $this->alamat);
$stmt->bindParam(":telepon", $this->telepon);
$stmt->bindParam(":email", $this->email);
$stmt->bindParam(":tgl_lahir", $this->tgl_lahir);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
// update the product
function update(){
// update query
$query = "UPDATE
" . $this->table_name . "
SET
nama_pelanggan = :nama_pelanggan,
alamat = :alamat,
telepon = :telepon,
email = :email,
tgl_lahir = :tgl_lahir
WHERE
id_pelanggan = :id_pelanggan";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind new values
$stmt->bindParam(':nama_pelanggan', $this->nama_pelanggan);
$stmt->bindParam(':alamat', $this->alamat);
$stmt->bindParam(':telepon', $this->telepon);
$stmt->bindParam(':email', $this->email);
$stmt->bindParam(':tgl_lahir', $this->tgl_lahir);
$stmt->bindParam(':id_pelanggan', $this->id_pelanggan);
// execute the query
if($stmt->execute()){
return true;
}
return false;
}
// delete the product
function delete(){
// delete query
$query = "DELETE FROM "
. $this->table_name .
" WHERE id_pelanggan = ?";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
//$this->id=htmlspecialchars(strip_tags($this->id));
// bind id of record to delete
$stmt->bindParam(1, $this->id);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
}
?> | true |
56a34b9ebd8954ba4103d3b90d05180c2e6a4138 | PHP | fossabot/Scriptlog | /src/lib/dao/MediaDao.php | UTF-8 | 15,178 | 2.78125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/**
* Class Media extends Dao
*
*
* @category Dao Class
* @author M.Noermoehammad
* @license MIT
* @version 1.0
* @since Since Release 1.0
*
*/
class MediaDao extends Dao
{
const TIME_BEFORE_EXPIRED = 8;
public function __construct()
{
parent::__construct();
}
/**
* Find All Media
*
* @method public findAllMedia()
* @param integer $ID
* @return array
*
*/
public function findAllMedia($orderBy = 'ID', $user_level = null)
{
if (!is_null($user_level)) {
$sql = "SELECT m.ID,
m.media_filename,
m.media_caption,
m.media_type,
m.media_target,
m.media_user,
m.media_access,
m.media_status,
u.user_level
FROM tbl_media AS m
INNER JOIN tbl_users AS u ON m.media_user = u.user_level
WHERE m.media_user = :user_level
ORDER BY :orderBy DESC";
$this->setSQL($sql);
$allMedia = $this->findAll([':user_level'=> $user_level, ':orderBy' => $orderBy]);
} else {
$sql = "SELECT ID,
media_filename,
media_caption,
media_type,
media_target,
media_user,
media_access,
media_status
FROM tbl_media
ORDER BY :orderBy DESC";
$this->setSQL($sql);
$allMedia = $this->findAll([':orderBy' => $orderBy]);
}
return (empty($allMedia)) ?: $allMedia;
}
/**
* Find media by Id
*
* @method public findMediaById()
* @param integer $mediaId
* @param object $sanitize
*
*/
public function findMediaById($mediaId, $sanitize)
{
$idsanitized = $this->filteringId($sanitize, $mediaId, 'sql');
$sql = "SELECT ID,
media_filename,
media_caption,
media_type,
media_target,
media_user,
media_access,
media_status
FROM tbl_media
WHERE ID = :ID";
$this->setSQL($sql);
$mediaById = $this->findRow([':ID' => $idsanitized]);
return (empty($mediaById)) ?: $mediaById;
}
/**
* Find media by media format type
*
* @method public findMediaByType()
* @param string $type
* @return array
*
*/
public function findMediaByType($type)
{
$sql = "SELECT ID,
media_filename,
media_caption,
media_type,
media_target,
media_user,
media_access,
media_status
FROM tbl_media
WHERE media_type = :media_type
AND media_status = '1'";
$this->setSQL($sql);
$mediaByType = $this->findRow([':media_type' => $type]);
return (empty($mediaByType)) ?: $mediaByType;
}
/**
* find mediameta by it's id and key
*
* @method public findMediaMeta()
* @param int $mediaId
* @param object $sanitize
*
*/
public function findMediaMetaValue($mediaId, $media_filename, $sanitize)
{
$idsanitized = $this->filteringId($sanitize, $mediaId, 'sql');
$sql = "SELECT ID, media_id, meta_key, meta_value FROM tbl_mediameta
WHERE media_id = :media_id AND meta_key = :meta_key";
$this->setSQL($sql);
$mediameta = $this->findRow([':media_id' => $idsanitized, ':meta_key' => $media_filename]);
return (empty($mediameta)) ?: $mediameta;
}
/**
* Find all media for downloaded
*
* @param int $orderBy
* @return void
*
*/
public function findAllMediaDownload($orderBy = 'ID')
{
$sql = "SELECT ID, media_filename, media_caption, media_type, media_taget,
media_user, media_access, media_status
FROM tbl_media
WHERE media_target = 'download'
AND media_access = 'public' AND media_status = '1'
ORDER BY :orderBy DESC";
$this->setSQL($sql);
$items = $this->findAll([':orderBy' => $orderBy]);
return (empty($items)) ?: $items;
}
/**
* Find media for downloaded based on ID
*
* @param int $mediaId
* @param obj $sanitize
* @return void
*
*/
public function findMediaDownload($mediaId, $sanitize)
{
$id_sanitized = $this->filteringId($sanitize, $mediaId, 'sql');
$sql = "SELECT ID, media_filename, media_caption, media_type, media_taget,
media_user, media_access, media_status
FROM tbl_media
WHERE ID = :ID
AND media_target = 'download'
AND media_access = 'public' AND media_status = '1' ";
$this->setSQL($sql);
$item = $this->findRow([':ID' => $id_sanitized]);
return (empty($item)) ?: $item;
}
/**
* Find all media for Blog
*
* @return void
*
*/
public function findAllMediaBlog($orderBy = 'ID')
{
$sql = "SELECT ID, media_filename, media_caption, media_type, media_target
FROM tbl_media WHERE media_target = 'blog'
AND media_access = 'public' AND media_status = '1'
ORDER BY :orderBy DESC";
$this->setSQL($sql);
$items = $this->findAll([':orderBy' => $orderBy]);
return (empty($items)) ?: $items;
}
/**
* Find media for blog based on ID
*
* @param int $mediaId
* @param obj $sanitize
* @return mixed
*/
public function findMediaBlog($mediaId)
{
$sql = "SELECT ID, media_filename, media_caption, media_type, media_target,
media_user, media_access, media_status
FROM tbl_media
WHERE ID = :ID
AND media_target = 'blog'
AND media_access = 'public'
AND media_status = '1'";
$this->setSQL($sql);
$item = $this->findRow([':ID' => (int)$mediaId]);
return (empty($item)) ?: $item;
}
/**
* Find media download based on Id,time before expired and ip
*
* @param integer $mediaId
* @param object $sanitize
* @return array
*
*/
public function findMediaDownloadUrl($mediaId, $sanitize)
{
$ip_address = get_ip_address();
$id_sanitized = $this->filteringId($sanitize, $mediaId, 'sql');
$sql = "SELECT ID, media_id, media_identifier, before_expired, ip_address, created_at
FROM tbl_media_download
WHERE media_id = :media_id
AND ip_address = '".$ip_address."'
AND before_expired >= '".time()."'";
$this->setSQL($sql);
$item = $this->findAll([':media_id'=>$id_sanitized]);
return (empty($item)) ?: $item;
}
/**
* Find media download by it's identifier
*
* @param string $media_identifier
* @return array
*
*/
public function findMediaDownloadByIdentifier($media_identifier)
{
$sql = "SELECT ID, media_id, media_identifier, before_expired, ip_address, created_at
FROM tbl_media_download
WHERE media_identifier = ?";
$this->setSQL($sql);
$item = $this->findAll([$media_identifier]);
return (empty($item)) ?: $item;
}
/**
* Add new media
*
* @method public addMedia()
* @param string|array $bind
*
*/
public function createMedia($bind)
{
$this->create("tbl_media", [
'media_filename' => $bind['media_filename'],
'media_caption' => $bind['media_caption'],
'media_type' => $bind['media_type'],
'media_target' => $bind['media_target'],
'media_user' => $bind['media_user'],
'media_access' => $bind['media_access'],
'media_status' => $bind['media_status']
]);
return $this->lastId();
}
/**
* Add new media meta
*
* @param integer $mediaId
* @param string|array $bind
*
*/
public function createMediaMeta($bind)
{
$this->create("tbl_mediameta", [
'media_id' => $bind['media_id'],
'meta_key' => $bind['meta_key'],
'meta_value' => $bind['meta_value']
]);
}
/**
* create media downloaded
*
* @param array $bind
*
*/
public function createMediaDownload($bind)
{
$this->create("tbl_media_download", [
'media_id' => $bind['media_id'],
'media_identifier' => generate_media_identifier(),
'before_expired' => (time()+self::TIME_BEFORE_EXPIRED*60*60),
'ip_addres' => (get_ip_address())
]);
}
/**
* Update Media
*
* @method public updateMedia()
* @param object $sanitize
* @param array $bind
* @param integer $ID
*
*/
public function updateMedia($sanitize, $bind, $ID)
{
$id_sanitized = $this->filteringId($sanitize, $ID, 'sql');
if(!empty($bind['media_filename'])) {
$this->modify("tbl_media", [
'media_filename' => $bind['media_filename'],
'media_caption' => $bind['media_caption'],
'media_type' => $bind['media_type'],
'media_target' => $bind['media_target'],
'media_access' => $bind['media_access'],
'media_status' => $bind['media_status']
], "ID = {$id_sanitized}");
} else {
$this->modify("tbl_media", [
'media_caption' => $bind['media_caption'],
'media_target' => $bind['media_target'],
'media_access' => $bind['media_access'],
'media_status' => $bind['media_status']
], "ID = {$id_sanitized}");
}
}
/**
* Update media meta
*
* @param object $sanitize
* @param array $bind
* @param integer $ID
* @return void
*
*/
public function updateMediaMeta($sanitize, $bind, $ID)
{
$idsanitized = $this->filteringId($sanitize, $ID, 'sql');
if (!empty($bind['meta_key'])) {
$this->modify("tbl_mediameta", [
'meta_key' => $bind['meta_key'],
'meta_value' => $bind['meta_value']
], "media_id = {$idsanitized}");
}
}
/**
* Delete Media
*
* @method public deleteMedia()
* @param integer $ID
* @param object $sanitize
*
*/
public function deleteMedia($ID, $sanitize)
{
$clean_id = $this->filteringId($sanitize, $ID, 'sql');
$this->deleteRecord("tbl_media", "ID = ".(int)$clean_id, 1);
$this->deleteRecord("tbl_mediameta", "media_id = ".(int)$clean_id, 1);
}
/**
* Check media's Id
*
* @method public checkMediaId()
* @param integer|numeric $id
* @param object $sanitize
* @return numeric
*
*/
public function checkMediaId($id, $sanitize)
{
$sql = "SELECT ID from tbl_media WHERE ID = ?";
$id_sanitized = $this->filteringId($sanitize, $id, 'sql');
$this->setSQL($sql);
$stmt = $this->checkCountValue([$id_sanitized]);
return($stmt > 0);
}
/**
* drop down media access
* set media access
*
* @param string $selected
* @return string
*
*/
public function dropDownMediaAccess($selected = "")
{
$name = 'media_access';
$media_access = array('public' => 'Public', 'private' => 'Private');
if($selected != '') {
$selected = $selected;
}
return dropdown($name, $media_access, $selected);
}
/**
* drop down media target
* set media target
*
* @param string $selected
* @return string
*
*/
public function dropDownMediaTarget($selected = "")
{
$name = 'media_target';
$media_target = array('blog' => 'Blog', 'download' => 'Download', 'gallery' => 'Gallery');
if($selected != '') {
$selected = $selected;
}
return dropdown($name, $media_target, $selected);
}
/**
* Drop down media status
*
* @param int $selected
* @return int
*
*/
public function dropDownMediaStatus($selected = "")
{
$name = 'media_status';
$media_status = array('Enabled', 'Disabled');
if ($selected) {
$selected = $selected;
}
return dropdown($name, $media_status, $selected);
}
public function dropDownMediaSelect($selected = null)
{
$dropdown = '<div class="form-group">';
$dropdown .= '<label>Uploaded image</label><br>';
$dropdown .= '<br><select name="image_id" class="selectpicker" ><br><br>';
if (is_null($selected)) {
$selected = "";
}
$media_ids = [];
$media_ids = $this->findAllMediaBlog();
$sanitizer = new Sanitize;
$picture_bucket_list = ["image/jpeg", "image/png", "image/gif", "image/webp"];
if (is_array($media_ids)) {
$dropdown .= '<option>Select primary image</option>';
foreach ($media_ids as $m => $media) {
$media_meta = $this->findMediaMetaValue($media['ID'], $media['media_filename'], $sanitizer);
$media_properties = isset($media_meta['meta_value']) ? media_properties($media_meta['meta_value']) : null;
$select = $selected === $media['ID'] ? ' selected' : null;
if(in_array($media['media_type'], $picture_bucket_list)) {
$dropdown .= '<option data-content="<img src='.app_url().DS.APP_IMAGE_THUMB.'small_'.rawurlencode(basename(safe_html($media['media_filename']))).'></img>" value="'.(int)$media['ID'].'"'.$select.'>'.safe_html($media_properties['Origin']).'</option>'."\n";
}
}
}
$dropdown .= '</select>'."\n";
$dropdown .= '</div>';
return $dropdown;
}
public function imageUploadHandler($mediaId = null)
{
$mediablog = '<div class="form-group">';
if (!empty($mediaId) && $mediaId != 0) {
$data_media = $this->findMediaBlog((int)$mediaId);
$image_src = invoke_image_uploaded($data_media['media_filename'], false);
$image_src_thumb = invoke_image_uploaded($data_media['media_filename']);
if (!$image_src_thumb) {
$image_src_thumb = app_url().'/public/files/pictures/thumbs/nophoto.jpg';
}
if ($image_src) {
$mediablog .= '<a class="thumbnail" href="'.$image_src.'" ><img src="'.$image_src_thumb.'" class="img-responsive pad"></a>';
$mediablog .= '<label>Change picture:</label>';
$mediablog .= '<input type="file" name="image" id="file" accept="image/*" onchange="loadFile(event)" maxlength="512" >';
$mediablog .= '<input type="hidden" name="image_id" value="'.$mediaId.'">';
$mediablog .= '<img id="output" class="img-responsive pad">';
$mediablog .= '<p class="help-block>Maximum file size: '.format_size_unit(APP_FILE_SIZE).'</p>';
} else {
$mediablog .= '<br><img src="'.$image_src_thumb.'" class="img-responsive pad"><br>';
$mediablog .= '<label>Change picture:</label>';
$mediablog .= '<input type="file" name="image" id="file" accept="image/*" onchange="loadFile(event)" maxlength="512" >';
$mediablog .= '<input type="hidden" name="image_id" value="'.$mediaId.'">';
$mediablog .= '<img id="output" class="img-responsive pad">';
$mediablog .= '<p class="help-block">Maximum file size:'.format_size_unit(APP_FILE_SIZE).'</p>';
}
} else {
$mediablog .= '<div id="image-preview">';
$mediablog .= '<label for="image-upload" id="image-label">Choose picture</label>';
$mediablog .= '<input type="file" name="media" id="image-upload" accept="image/*" maxlength="512" >';
$mediablog .= '</div>';
$mediablog .= '<p class="help-block"> Maximum file size: '.format_size_unit(APP_FILE_SIZE).'</p>';
}
$mediablog .= '</div>';
return $mediablog;
}
/**
* Total media records
*
* @method public totalMediaRecords()
* @param array $data = null
* @return integer|numeric
*
*/
public function totalMediaRecords($data = null)
{
if (!empty($data)) {
$sql = "SELECT ID FROM tbl_media WHERE media_user = ? ";
} else {
$sql = "SELECT ID FROM tbl_media";
}
$this->setSQL($sql);
return $this->checkCountValue($data);
}
} | true |
e0db634cfa4d20577ae548af7e05eadef327f86e | PHP | RomeoVargas/evaluationSystem | /resources/Navigation.php | UTF-8 | 4,854 | 2.53125 | 3 | [] | no_license | <?php
namespace resources;
class Navigation
{
private static $allowedUris = [
'home', 'aboutus', 'teachers', 'contactus', 'teacherlogin', 'studentlogin'
];
private static $adminAllowedUris = [
'adminhome',
'adminteachers', 'adminstudents', 'adminadmins',
'adminteacherstudent', 'adminstudentteacher',
'adminquestionnaires',
'adminreports'
];
private static $nestAdminUris = [
'adminteachers', 'adminstudents', 'adminadmins',
'adminteacherstudent', 'adminstudentteacher'
];
private static $navTemplate = "
<div class='navbar-header'>
<a class='navbar-brand' href='index.php'>Brand</a>
</div>
<ul class='nav navbar-right navbar-nav'>
<li role='presentation' class='%s'><a href='index.php'>Home</a></li>
<li role='presentation' class='%s'><a href='aboutUs.php'>About Us</a></li>
<li role='presentation' class='%s'><a href='teachers.php'>Our Teachers</a></li>
<li role='presentation' class='%s'><a href='contactus.php'>Contact Us</a></li>
<li role='presentation' class='dropdown %s %s'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#' role='button' aria-haspopup='true' aria-expanded='false'>
Login <span class='caret'></span>
</a>
<ul class='dropdown-menu'>
<li role='presentation'><a href='teacherLogin.php'>Teacher Login</a></li>
<li role='presentation'><a href='studentLogin.php'>Student Login</a></li>
</ul>
</li>
</ul>
";
private static $adminNavTemplate = "
<div class='navbar-header'>
<a class='navbar-brand' href='index.php'>Brand</a>
</div>
<ul class='nav navbar-nav navbar-right'>
<li role='presentation' class='%s'><a href='%sindex.php'>Dashboard</a></li>
<li role='presentation' class='dropdown %s %s %s'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#' role='button' aria-haspopup='true' aria-expanded='false'>
User Management <span class='caret'></span>
</a>
<ul class='dropdown-menu'>
<li role='presentation'><a href='%susers/teachers/'>Teachers</a></li>
<li role='presentation'><a href='%susers/students.php'>Students</a></li>
<li role='presentation'><a href='%susers/admin.php'>Admin</a></li>
</ul>
</li>
<li role='presentation' class='dropdown %s %s'>
<a class='dropdown-toggle' data-toggle='dropdown' href='#' role='button' aria-haspopup='true' aria-expanded='false'>
Assignments <span class='caret'></span>
</a>
<ul class='dropdown-menu'>
<li role='presentation'><a href='%sassignments/teacherToStudent'>Teacher - Student</a></li>
<li role='presentation'><a href='%sassignments/studentToTeacher'>Student - Teacher</a></li>
</ul>
</li>
<li role='presentation' class='%s'><a href='%squestionnaires.php'>Questionnaires</a></li>
<li role='presentation' class='%s'><a href='%sreports.php'>Reports</a></li>
<li role='presentation'><a href='%s../app/Requests/admin/logout.php'>Logout</a></li>
</ul>
";
public static function navigate($uri)
{
$isAdminUri = self::isAdminUri($uri);
if (! $isAdminUri && ! in_array($uri, self::$allowedUris)) {
throw new \UnexpectedValueException('Link is not allowed');
}
$allowedUris = ($isAdminUri) ? self::$adminAllowedUris : self::$allowedUris;
$navTemplate = ($isAdminUri) ? self::$adminNavTemplate : self::$navTemplate;
foreach ($allowedUris as $allowedUri) {
$$allowedUri = ($allowedUri == $uri) ? 'active' : '';
}
if ($isAdminUri) {
$uriBack = (in_array($uri, self::$nestAdminUris)) ? ($uri == 'adminteachers' ? '../../' : '../') : '';
return sprintf(
$navTemplate,
$adminhome, $uriBack,
$adminteachers, $adminstudents, $adminadmins, $uriBack, $uriBack, $uriBack,
$adminteacherstudent, $adminstudentteacher, $uriBack, $uriBack,
$adminquestionnaires, $uriBack,
$adminreports, $uriBack,
$uriBack
);
}
return sprintf(
$navTemplate,
$home, $aboutus, $teachers, $contactus, $teacherlogin, $studentlogin
);
}
public static function isAdminUri($uri)
{
return in_array($uri, self::$adminAllowedUris);
}
}
?>
| true |
40132898383e588599861f2a2342be2aa308acb7 | PHP | remi-turini/JobBoard | /API/companies/readAllCompanies.php | UTF-8 | 608 | 2.53125 | 3 | [] | no_license | <?php
$db = new PDO('mysql:host=localhost;dbname=jobboard', 'root','root');
$db->exec('SET NAMES "UTF8"');
$requete = " SELECT * FROM companies ";
$stmt = $db->prepare($requete);
$stmt->execute();
/*$tableau = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tableau[] = $row;
}
header('Content-Type: application/json');
echo json_encode($tableau);*/
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
?> | true |
9e315c73a838477970e224707248b4c39f5c171d | PHP | wcaraza/iwonder | /library/CM/Carrito.php | UTF-8 | 2,043 | 2.65625 | 3 | [] | no_license | <?php
class CM_Carrito
{
public function addItem($item, $cantidad = 'cantidad')
{
if (!isset($_SESSION['carrito'])) {
$_SESSION['carrito'] = array();
$_SESSION['carrito']['items'] = array();
}
if (!array_key_exists($item['id'], $_SESSION['carrito']['items'])) {
$_SESSION['carrito']['items'][$item['id']] = $item;
} else {
$_SESSION['carrito']['items'][$item['id']][$cantidad] += $item[$cantidad];
}
}
public function obtenerTotalCampoXCantidad($campo, $cantidad = 'cantidad')
{
$total = 0;
foreach( $_SESSION['carrito']['items'] as $item) {
$subtotal = $item[$campo] * $item[$cantidad];
$total += $subtotal;
}
return $total;
}
public function quitarItem($id)
{
unset($_SESSION['carrito']['items'][$id]);
}
public function getTotalItems($cantidad = 'cantidad')
{
$totalItems = 0;
if (isset($_SESSION['carrito'])) {
if (count($_SESSION['carrito']['items']) > 0) {
foreach ($_SESSION['carrito']['items'] as $item) {
$totalItems += $item[$cantidad];
}
}
}
return $totalItems;
}
public function getTotal($precio = 'precio')
{
$total = 0;
if (isset($_SESSION['carrito'])) {
if (count($_SESSION['carrito']['items']) > 0) {
foreach ($_SESSION['carrito']['items'] as $item) {
$total += $item[$precio];
}
}
}
return $total;
}
public function vaciarCarrito()
{
unset($_SESSION['carrito']);
}
public function getCarrito()
{
return $_SESSION['carrito']['items'];
}
public function actualizarCantidades($cantidades)
{
foreach ($cantidades as $key => $valor) {
$_SESSION['carrito']['items'][$key]['cantidad'] = $valor;
}
}
} | true |
866d4492ff2873b543ca9e186b60e7b7c8faae6a | PHP | cezarzaleski/commonsphp | /library/Commons/Pattern/Meta/SelfAwareness.php | UTF-8 | 442 | 2.515625 | 3 | [] | no_license | <?php
namespace Commons\Pattern\Meta;
/**
* Auto-conhecimento.
*/
interface SelfAwareness
{
/**
* Retorna a instância do alterego do objeto ou o próprio objeto.
* Função de atribuir qualitativamente o uso de interfaces associadas ao objeto
* ou recuperação de proxies, delegadores ou interceptadores do objeto.
*
* @return mixed o próprio objeto ou seu proxy.
*/
public function getAlter();
}
| true |
74b4dac34cb9eaa8617da21cbac6f4861ad1260f | PHP | sahiljain2497/Infocom-Web | /app/Http/Controllers/Admin/CircleController.php | UTF-8 | 2,707 | 2.5625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Circle;
use Validator;
class CircleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$circle = Circle::paginate(10);
return view('admin.circle.index')->withCircles($circle);
}
/**
* 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)
{
$v = Validator::make($request->all(),[
'circle' => 'required'
]);
if($v->fails()){
return redirect()->route('circle.index')->withErrors($v);
}
else{
Circle::forceCreate(['region' => $request->circle]);
return redirect()->route('circle.index')->with('success-message','CIRCLE CREATED SUCCESSFULLY');
}
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$data = Circle::where('id','=',$id)->first();
return view('admin.circle.edit')->withData($data);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$v = Validator::make($request->all(),[
'circle' => 'required'
]);
if($v->fails()){
return redirect()->route('circle.edit',$id)->withErrors($v);
}
else{
Circle::where('id','=',$id)->update(['region' => $request->circle]);
return redirect()->route('circle.edit',$id)->with('update-message','CIRCLE EDITED SUCCESSFULLY');
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Circle::where('id',$id)->delete();
return redirect()->route('circle.index')->with('delete-message','CIRCLE DELETED SUCCESSFULLY');
}
}
| true |
b1b1e074a168570e99ad5b136b4bffb6c0b77301 | PHP | longnh299/book-management-php-it4409 | /php/update-data.php | UTF-8 | 576 | 2.53125 | 3 | [] | no_license | <?php
include "connection.php";
session_start();
if(isset($_POST["submit"])){
$id=$_POST["id"];
$name=$_POST["name"];
$publisher=$_POST["publisher"];
$price=$_POST["price"];
$sql="UPDATE books SET name='{$name}',publisher='{$publisher}',price={$price} WHERE id={$id}";
$run_sql=mysqli_query($conn,$sql);
if($run_sql){
$_SESSION["success"]="Data Update Successfully";
header("location:../index.php");
}else{
$_SESSION["error"]="Data Not Update Successfully";
header("location:../edit-data.php");
}
}
?> | true |
97731293d331f9a4e12421ad2cfa0abb81415a04 | PHP | joliveroizquierdo/Blog_PDO | /index.php | UTF-8 | 570 | 2.5625 | 3 | [] | no_license | <?php
/*require_once 'modelos/usuarioModelo.php';
$objetoUsuario = new usuarios();
$datos = $objetoUsuario->listarUsuarios();
foreach($datos as $dato){
echo $dato['nombres'];
echo '<br>';
}*/
//Enrutado de la aplicacion
if(!empty($_GET["accion"])){
$accion=$_GET["accion"];
}else{
$accion="index";
}
if(is_file("controladores/".$accion."Controlador.php")){
require_once("controladores/".$accion."Controlador.php");
}else{
require_once("controladores/errorControlador.php");
}
?>
| true |
2f54d08d41df9bc05353de60efec4e0f1f1b716a | PHP | Oktopost/DeepQueue | /src/DeepQueue/Exceptions/DecoratorNotExistsException.php | UTF-8 | 223 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace DeepQueue\Exceptions;
class DecoratorNotExistsException extends GenericException
{
public function __construct($className)
{
parent::__construct(2, "Queue decorator $className does not exists!");
}
} | true |
273be4ff9a1249fa0bcf278592d5865e3e98fed3 | PHP | phpcfdi/sat-catalogos | /src/CFDI40/RegimenFiscal.php | UTF-8 | 824 | 2.875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
declare(strict_types=1);
namespace PhpCfdi\SatCatalogos\CFDI40;
use PhpCfdi\SatCatalogos\Common\AbstractEntryIdentifiable;
class RegimenFiscal extends AbstractEntryIdentifiable
{
/** @var bool */
private $aplicaFisica;
/** @var bool */
private $aplicaMoral;
public function __construct(
string $id,
string $texto,
bool $aplicaFisica,
bool $aplicaMoral,
int $vigenteDesde,
int $vigenteHasta
) {
parent::__construct($id, $texto, $vigenteDesde, $vigenteHasta);
$this->aplicaFisica = $aplicaFisica;
$this->aplicaMoral = $aplicaMoral;
}
public function aplicaFisica(): bool
{
return $this->aplicaFisica;
}
public function aplicaMoral(): bool
{
return $this->aplicaMoral;
}
}
| true |
9d5e6aa26c55f4210fe6ebb9235156fce4e403fe | PHP | WaiMaungMaung/PhotoMarathon-1 | /app/View/Components/Helper.php | UTF-8 | 504 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
function getCMPID($old_cmp){
$return_id ="";
if($old_cmp != null){
$divided_id = preg_split("/(,?\s+)|((?<=[a-z])(?=\d))|((?<=\d)(?=[a-z]))/i", $old_cmp);
$increment_value = $divided_id[1]+1;
$increment_id = str_pad($increment_value,4,"0",STR_PAD_LEFT);
// $arr = array($divided_id[0], $increment_id);
$return_id = $divided_id[0].$increment_id;
}
else {
$return_id = "CPM0001";
}
return $return_id;
} | true |
01c315480a727ff8478234c1c484e0cbcb986537 | PHP | niravkothari91/bq | /app/Http/Middleware/GenerateMenus.php | UTF-8 | 1,451 | 2.671875 | 3 | [] | no_license | <?php
namespace App\Http\Middleware;
use App\Category;
use App\Subcategory;
use Closure;
class GenerateMenus
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$parentCategories = Category::all();
if($parentCategories != null && $parentCategories->count() > 0) {
\Menu::make('MyNavBar', function ($menu) use ($parentCategories) {
foreach($parentCategories as $category_item) {
$parent = $menu->add($category_item->name, ['url' => '#']);
$subcategories = Subcategory::byParentId($category_item->id)->get();
foreach($subcategories as $subcategory) {
$subcatItem = $parent->add($subcategory->name, ['url' => route('shop.index', ['subcategory' => $subcategory->slug])]);
/*$prodCategories = Productcategory::byParentId($subcategory->id)->get();
foreach($prodCategories as $prodCategory) {
$subcatItem->add($prodCategory->name, ['url' => '#']);
}*/
}
}
});
} else {
dd("Menu Items not found. Please make sure the seeders ran properly");
}
return $next($request);
}
}
| true |
2ceb8e6f49482cddef080d68e5a7aef7b0810507 | PHP | gluck59/TestWork-1207199 | /app/Http/Controllers/ListController.php | UTF-8 | 1,272 | 2.671875 | 3 | [] | no_license | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Item;
class ListController extends Controller
{
/**
* return all records
* @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
*/
public function index()
{
$items = Item::all();
return view('list')->with('items', $items);
}
/**
* create record
* @param Request $request
* @return string
*/
public function create(Request $request)
{
$item = new Item;
$item->item = $request->text;
$item->save();
return 'created';
}
/**
* delete record
* @param Request $request
* @return string
*/
public function delete(Request $request)
{
// Item::where('id',$request->id)->delete();
//return $request->all();
$item = Item::find($request->id);
$item->delete();
return "deleted";
}
/**
* update a record
* @param Request $request
* @return array
*/
public function update(Request $request)
{
$item = Item::find($request->id);
$item->item = $request->value;
$item->save();
return $request->all();
}
}
| true |
4e64188854050b89246c0dbae1dd906f91777f36 | PHP | blackdragon610/moneq-dev | /app/Libs/PushClass.php | UTF-8 | 6,444 | 2.65625 | 3 | [] | no_license | <?php
namespace App\Libs;
use App\Models\PushType;
use App\Models\User;
use App\Models\UserToken;
use Illuminate\Support\Facades\Auth;
use LaravelFCM\Facades\FCM;
use LaravelFCM\Message\OptionsBuilder;
use LaravelFCM\Message\PayloadDataBuilder;
use LaravelFCM\Message\PayloadNotificationBuilder;
/*
* Pushの共通処理
*/
class PushClass{
public UserToken $UserToken;
public User $User;
public PushType $PushType;
public bool $isNow = true;
function __construct(UserToken $UserToken, User $User, PushType $PushType)
{
$this->UserToken = $UserToken;
$this->User = $User;
$this->PushType = $PushType;
}
/**
* デバイストークンの設定
* @param int $token トークン
* @param string $os os
*/
public function setToken(string $token, string $userToken, string $os)
{
$UserToken = clone $this->UserToken;
if (!$this->getToken(Auth::user()->id, $token)->first())
{
$UserToken->user_id = Auth::user()->id;
$UserToken->token = $token;
$UserToken->os = $os;
$UserToken->user_token = $userToken;
$UserToken->save();
}
}
/**
* デバイストークンの取得
* @param int $userId ユーザーのID
* @param string $token トークンを指定する場合
* @return UserToken
*/
public function getToken(int $userId, string $token=""){
$UserToken = clone $this->UserToken;
$UserToken = $UserToken->where("user_id", $userId);
if ($token){
$UserToken = $UserToken->where("token", $token);
}
return $UserToken;
}
/**
* デバイストークンの削除
* @param string $deviceToken
* @param string $os
*/
public function deleteToken($deviceToken)
{
$UserToken = clone $this->UserToken;
$tokens = $UserToken
//->where("os", $os)
->where("token", $deviceToken)
->get();
if ($tokens)
{
//トークンの削除
foreach ($tokens as $token)
{
$token->delete();
}
}
}
/**
* チャットのプッシュ
* @param int $detailId
* @param int $userId
* @param int $userIdFrom
* @param $serial
* @param array $input
* @return int
* @throws \LaravelFCM\Message\Exceptions\InvalidOptionsException
*/
public function sendChat(array $userIds, string $title, string $body, array $datas, int $chatId, int $detailId)
{
\Log::info($userIds);
if (!isset($datas["mode"])){
$datas["mode"] = "chat";
}
$datas["id"] = $chatId;
$datas["detailId"] = $detailId;
foreach ($userIds as $userId){
$user = $this->User->find($userId);
$PushType = app("PushType");
$PushType->saveEntry("chat", $userId, $detailId, $chatId);
if ($user){
//該当ユーザーの取得
$this->sendUser(
$user,
$title,
$body,
$datas,
);
}
}
}
/**
* 該当ユーザーにプッシュ通知を行い送信ユーザー数を返す
* @param object $User ユーザーのモデル
* @param string $title タイトル
* @param string $message メッセージ
* @param array $datas その他送付データ
* @return int 送信ユーザー数
* @throws \LaravelFCM\Message\Exceptions\InvalidOptionsException
*/
public function sendUser(object $User, string $title, string $message, $datas = []) : int
{
$number = 0;
$datas["title"] = $title;
$datas["body"] = $message;
if (count($User->tokens)){
foreach ($User->tokens as $token)
{
if ($token->token){
if ($this->isNow){
$this->sendPush($token->token, $title,$message, $User->id, $datas);
}
}
}
if (!$this->isNow){
$this->Push->saveEntry($title,$message, $User->id, $datas);
}
$number++;
}
return $number;
}
/**
* プッシュの送信
* @param string $token
* @param string $title タイトル
* @param string $message 内容
* @param int $userId ユーザーのID
* @param array $datas その他データ
* @throws \LaravelFCM\Message\Exceptions\InvalidOptionsException
*/
public function sendPush(string $token, string $title, string $message, int $userId, $datas = [])
{
$optionBuilder = new OptionsBuilder();
$optionBuilder->setTimeToLive(60*20);
$notificationBuilder = new PayloadNotificationBuilder($title);
$notificationBuilder->setBody($message)
->setSound("receive.caf")
//->setSound("receive")
//->setSound("https://buttobi.new-challenge.jp/receive.caf")
//->setIcon("https://s.yimg.jp/c/logo/f/2.0/news_r_34_2x.png")
->setBadge($this->getBadgeAll($userId));
//dd(file_get_contents(dirname(__FILE__) . "/../Front/Sound/receive.mp3"));
$dataBuilder = new PayloadDataBuilder();
//$datas["notification_foreground"] = "true";
//$dataBuilder->addData(["data" => $datas]);
$dataBuilder->addData(["notification_android_sound" => "receive", "notification_foreground" => "true", "data" => $datas]);
$option = $optionBuilder->build();
$notification = $notificationBuilder->build();
$data = $dataBuilder->build();
$downstreamResponse = FCM::sendTo($token, $option, $notification, $data);
$downstreamResponse->numberSuccess();
$downstreamResponse->numberFailure();
$downstreamResponse->numberModification();
$downstreamResponse->tokensToDelete();
$downstreamResponse->tokensToModify();
$downstreamResponse->tokensToRetry();
$downstreamResponse->tokensWithError();
}
public function getBadgeAll(int $userId)
{
$PushType = clone $this->PushType;
$badge = $PushType->getBadge($userId);
return $badge;
}
}
| true |
1808b29c3497acb9490aad85587823169b65799c | PHP | abrahamrkj/Drupal-8-CTA-Button-Field-module | /src/Plugin/Field/FieldType/CtaButton.php | UTF-8 | 2,065 | 2.734375 | 3 | [] | no_license | <?php
namespace Drupal\cta_button\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldStorageDefinitionInterface as StorageDefinition;
/**
* Plugin implementation of the 'cta_button' field type.
*
* @FieldType(
* id = "CtaButton",
* label = @Translation("CTA Button"),
* description = @Translation("Stores an Call To Action Button"),
* category = @Translation("Custom"),
* default_widget = "CtaButtonDefaultWidget",
* default_formatter = "CtaButtonDefaultFormatter"
* )
*/
class CtaButton extends FieldItemBase {
/**
* CTA Button Field type properties definition.
*
* Inside this method we define all the fields (properties) that our
* custom field type will have.
*
* Here there is a list of allowed property types: https://goo.gl/sIBBgO
*/
public static function propertyDefinitions(StorageDefinition $storage) {
$properties = [];
$properties['cta_text'] = DataDefinition::create('string')
->setLabel(t('CTA text'));
$properties['cta_link'] = DataDefinition::create('string')
->setLabel(t('CTA Link'));
return $properties;
}
/**
* CTA Button Field type schema definition.
*
* Inside this method we defines the database schema used to store data for
* our field type.
*
* Here there is a list of allowed column types: https://goo.gl/YY3G7s
*/
public static function schema(StorageDefinition $storage) {
$columns = [];
$columns['cta_text'] = [
'type' => 'char',
'length' => 255,
];
$columns['cta_link'] = [
'type' => 'char',
'length' => 255,
];
return [
'columns' => $columns,
'indexes' => [],
];
}
/**
* Define when the CTA Button field is empty.
*
* This method is important and used internally by Drupal.
*/
public function isEmpty() {
$isEmpty =
empty($this->get('cta_text')->getValue()) &&
empty($this->get('cta_link')->getValue());
return $isEmpty;
}
}
| true |
800273a09254e764ddd36a39954a9a748dd43bef | PHP | Catrisa/minimal-mvc-framework | /mvc/Controller.php | UTF-8 | 1,024 | 2.96875 | 3 | [] | no_license | <?php
namespace Mvc;
/**
* Base class for controllers.
*/
abstract class Controller {
protected $request;
/**
* Create a new controller and store the incoming request data.
*/
public function __construct($request) {
$this->request = $request;
}
/**
* Fallback method for rendering views directly from a template.
*
* This method allows for returning output directly from a view
* template, without the need to implement the
* ``<viewname>View()`` method in the Controller.
*/
public function __call($view_name, $arguments) {
$class_name = get_class($this);
$view = View::factory($class_name, $view_name);
try {
$view->render();
} catch (\InvalidArgumentException $err) {
// view template file does not exist
Application::handleError(404);
}
}
}
| true |
4448114f16069c13752aaa92c577114bbd2c95f0 | PHP | ashinpaugh/classplan-platform | /src/Entity/Course.php | UTF-8 | 4,206 | 2.734375 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use ForceUTF8\Encoding;
use JMS\Serializer\Annotation as Serializer;
/**
* @ORM\Entity()
* @ORM\Table(name="course", indexes={
* @ORM\Index(name="idx_number", columns={"number"})
* })
*/
class Course extends AbstractEntity
{
/**
* @ORM\ManyToOne(targetEntity="Subject", inversedBy="courses", cascade={"persist"})
* @Serializer\Exclude()
*
* @var Subject
*/
protected $subject;
/**
* @ORM\OneToMany(targetEntity="Section", mappedBy="course")
* @Serializer\Exclude()
*
* @var Section[]
*/
protected $sections;
/**
* @ORM\Id()
* @ORM\Column(name="id", type="bigint")
* @ORM\GeneratedValue(strategy="AUTO")
* @Serializer\Groups(groups={"course", "course_full"})
*
* @var Integer
*/
protected $id;
/**
* @ORM\Column(type="integer")
* @Serializer\Groups(groups={"course", "course_full"})
*
* @var Integer
*/
protected $number;
/**
* @ORM\Column(type="string")
* @Serializer\Groups(groups={"course", "course_full"})
*
* @var string
*/
protected $name;
/**
* @ORM\Column(type="string", nullable=true, unique=false)
* @Serializer\Groups(groups={"course", "course_full"})
*
* @var string
*/
protected $level;
/**
* Course constructor.
*
* @param Subject $subject
* @param integer $number
*/
public function __construct(Subject $subject, $number)
{
$this->setNumber($number);
$this->subject = $subject;
$this->sections = new ArrayCollection();
}
/**
* @Serializer\VirtualProperty(name="subject")
* @Serializer\Groups(groups={"course", "course_full"})
* @Serializer\Type("integer")
*
* @return int
*/
public function getSubjectId(): int
{
return $this->subject->getId();
}
/**
* @Serializer\VirtualProperty(name="sections")
* @Serializer\Groups(groups={"course_full"})
* @Serializer\Type("array<integer>")
*
* @return array
*/
public function getSectionIds(): array
{
$collection = $this->sections->map(function (Section $section) {
return $section->getId();
});
return $collection->toArray();
}
/**
* @return Section[]
*/
public function getSections()
{
return $this->sections;
}
/**
* @return mixed
*/
public function getNumber()
{
return $this->number;
}
/**
* @return Subject
*/
public function getSubject()
{
return $this->subject;
}
/**
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* @return string
*/
public function getLevel()
{
return $this->level;
}
/**
* @param int $number
*
* @return Course
*/
public function setNumber($number)
{
$this->number = Encoding::toUTF8($number);
return $this;
}
/**
* @param Subject $subject
*
* @return Course
*/
public function setSubject(Subject $subject)
{
$this->subject = $subject;
$subject->addCourse($this);
return $this;
}
/**
* @param string $name
*
* @return Course
*/
public function setName($name)
{
$this->name = Encoding::toUTF8($name);
return $this;
}
/**
* @param string $level
*
* @return Course
*/
public function setLevel($level)
{
$this->level = $level;
return $this;
}
/**
* @param Section $event
*
* @return $this
*/
public function addSection(Section $event)
{
$this->sections->add($event);
return $this;
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
}
| true |
40d22a4c6ecf86ebe638b09d97432be48f7eeac0 | PHP | Cancer-Expert-Now/prismic-client | /src/Document.php | UTF-8 | 1,306 | 2.6875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Prismic;
use DateTimeInterface;
use Prismic\Document\Fragment\DocumentLink;
use Prismic\Value\DocumentData;
use Prismic\Value\Translation;
interface Document
{
/** The document unique identifier */
public function id(): string;
/**
* The unique user document identifier (Unique within a language and a type)
*
* It is possible for the uid to be null
*/
public function uid(): ?string;
/** The document type */
public function type(): string;
/** @return string[] */
public function tags(): iterable;
/** the document language code such as "en-gb" */
public function lang(): string;
/** The date the document was first published */
public function firstPublished(): DateTimeInterface;
/** The last time the document was changed */
public function lastPublished(): DateTimeInterface;
/** @return Translation[] */
public function translations(): iterable;
/**
* Convenience method to return a link to this document that is suitable for passing to a {@link LinkResolver}
*/
public function asLink(): DocumentLink;
/**
* Return the value object containing all of the document content fragments
*/
public function data(): DocumentData;
}
| true |
6600dbb65f6792c156c9c5c825ab3c0b62e138c2 | PHP | techstunts/drivesforfree | /f3/dff/modules/storageprovider/models/storageabstract.php | UTF-8 | 426 | 2.8125 | 3 | [] | no_license | <?php
namespace storageprovider\models;
abstract class storageabstract{
protected $_provider;
public function __call($name, $arguments) {
if(method_exists($this->_provider, $name)){
return call_user_func_array(array($this->_provider, $name), $arguments);
}
throw new \Exception('Given method ' . $name . ' doesn\'t exist in class ' . get_class($this->_provider));
}
}
| true |
42dfd1703d7d54431a5110fa9e75bcbabbcb83c4 | PHP | criscosg/LogbookREST | /src/EasyScrumREST/UserBundle/Event/UserEvent.php | UTF-8 | 443 | 2.53125 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace EasyScrumREST\UserBundle\Event;
use EasyScrumREST\UserBundle\Entity\RecoverPassword;
use Symfony\Component\EventDispatcher\Event;
class UserEvent extends Event
{
private $recover;
public function __construct(RecoverPassword $recover)
{
$this->recover = $recover;
}
/**
* @return RecoverPassword $recover
*/
public function getRecover()
{
return $this->recover;
}
} | true |
f3f3d109a0594b06a724fbeba2c25e93f661aea7 | PHP | jswebschmiede/doc.php | /lib/wiki.class.php | UTF-8 | 2,466 | 2.921875 | 3 | [
"WTFPL"
] | permissive | <?php
class Wiki{
public static function makeLink($array,$num=null){
$link=ROOT_FILE;
if(defined(HTACCESS)&&HTACCESS){
if(is_numeric($num)){
$link.=".".$array->getPathTo($num);
}else{
$link.=$array;
}
}else{
if(is_numeric($num)){
$link.="?";
for($i=0;$i<$num;$i++){
$opt=$array->getPath($i);
$link.=$i."=".$opt[$i]."&";
}
}else{
$link.="?";
$obj=$array->getPath();
for($i=0;$i<count($obj);$i++){
$link.=$i."=".$obj[$i]."&";
}
if($array->getType()==1)$link.="file=".$array->getName().$array->getFileType();
elseif($array->getType()==0)$link.=$i."=".$array->getName();
}
}
return $link;
}
private static function loadFolder($path){
$dir=scandir($path->getFullString(true));
//sort the array for aAbB...
natcasesort($dir);
//write new ordered array
$dir=array_values($dir);
$folderArray=array();
for($i=2;$i<count($dir);$i++){
array_push($folderArray, new File($path->getPath(),$dir[$i]));
}
return $folderArray;
}
public static function loadObj($path){
if($path){
$pathStr=$path->getPathString().$path->getName();
$pathType=$path->getType();
if($pathType==0){
//is directory
return static::loadFolder($path);
}elseif($pathType==1){
//is file
if($path->getTypeString()=="unknown" || $path->needToReadFile()){
//Read file if type = file
return $path->getContent();
}else{
return null;
}
}else{
Notification::Error($pathStr." not found");
}
}
}
private static function checkPush($array,$i){
//check if $_GET[$i] exists and isn't empty
if(isset($_GET[$i]) && !empty($_GET[$i])){
if(strpos($_GET[$i],"..")===false){
array_push($array, $_GET[$i]);
return $array;
}else{
Notification::Error('Using ".." is not allowed.');
}
}
}
public static function parseGET(){
$path=array();
if(isset($_GET['0']) && !isset($_GET['file'])){
//is directory
$arrLength=count($_GET);
for($i=0;$i<$arrLength;$i++){
$path=static::checkPush($path,$i);
}
$path=new File($path,"");
}elseif(isset($_GET['file'])){
//is file
$arrLength=count($_GET);
if($arrLength>=1){
for($i=0;$i<$arrLength-1;$i++){
$path=static::checkPush($path,$i);
}
}
$path=new File($path,$_GET['file']);
}else{
$path=new File("","");
}
return $path;
}
}
?> | true |
ba4aac826cd721bf8cac9aa4e1d4aa5b44d42d53 | PHP | nobody5607/srr | /common/models/Contents.php | UTF-8 | 1,764 | 2.75 | 3 | [] | no_license | <?php
namespace common\models;
use Yii;
/**
* This is the model class for table "tbl_contents".
*
* @property int $id
* @property string $name
* @property string $ description
* @property int $section_id tbl_section
* @property int $rstat
* @property int $public ห้อง public, private
* @property string $content_date
* @property string $create_date
* @property int $user_create
*/
class Contents extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'tbl_contents';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['name','thumn_image'], 'required'],
[['id', 'section_id', 'rstat', 'public', 'user_create','forder'], 'integer'],
[['description'], 'string'],
[['content_date', 'create_date','thumn_image'], 'safe'],
[['name'], 'string', 'max' => 255],
[['id'], 'unique'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'id' => Yii::t('section', 'ID'),
'name' => Yii::t('section', 'Name'),
'description' => Yii::t('section', 'Description'),
'section_id' => Yii::t('section', ' tbl_section'),
'rstat' => Yii::t('section', 'Rstat'),
'public' => Yii::t('section', 'Section Public'),
'content_date' => Yii::t('section', 'Content Date'),
'create_date' => Yii::t('section', 'Create Date'),
'user_create' => Yii::t('section', 'User Create'),
];
}
public function getSections()
{
return $this->hasOne(Sections::class, ['id' => 'section_id']);
}
}
| true |
db02f9446a750dc7c529bdaad4ceb92917246c3a | PHP | mibexx/php-time-tracking | /src/Mibexx/TimeTracking/TimeTrackingFacadeInterface.php | UTF-8 | 356 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Mibexx\TimeTracking;
interface TimeTrackingFacadeInterface
{
/**
* @param string $name
*/
public function track(string $name): void;
/**
* @param string $name
*/
public function stop(): void;
/**
* @return array
*/
public function getTrackings(): array;
}
| true |
b520821211a9120bed2839fffeb13e5926144a72 | PHP | bakasajoshua/performance | /app/Exports/SurgeFullExport.php | UTF-8 | 1,623 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Exports;
use DB;
use App\SurgeColumn;
use App\SurgeColumnView;
use App\Lookup;
class SurgeFullExport extends BaseExport
{
protected $week;
protected $modalities;
protected $gender_id;
protected $ages;
function __construct($week, $modality)
{
parent::__construct();
$this->week = $week;
$columns = SurgeColumnView::where(['modality_id' => $modality->id])->get();
$this->sql = "countyname as County, Subcounty, facilitycode AS `MFL Code`, partnername AS Partner, name AS `Facility`, start_date, end_date";
foreach ($columns as $column) {
$alias = $column->alias_name;
$alias = str_replace('GBV - ', '', $alias);
$this->sql .= ", `{$column->column_name}` AS `{$alias}`";
}
}
public function headings() : array
{
$row = DB::table('d_surge')
->join('view_facilities', 'view_facilities.id', '=', 'd_surge.facility')
->join('weeks', 'weeks.id', '=', 'd_surge.week_id')
->selectRaw($this->sql)
// ->where(['week_number' => 5])
->whereRaw(Lookup::get_active_partner_query('2020-01-01'))
->first();
return collect($row)->keys()->all();
}
public function query()
{
return DB::table('d_surge')
->join('view_facilities', 'view_facilities.id', '=', 'd_surge.facility')
->join('weeks', 'weeks.id', '=', 'd_surge.week_id')
->selectRaw($this->sql)
->where(['funding_agency_id' => 1, 'is_surge' => 1, 'week_id' => $this->week->id ])
->whereRaw(Lookup::get_active_partner_query('2020-01-01'))
->groupBy('d_surge.facility')
// ->orderBy('name', 'asc');
->orderBy('d_surge.facility', 'asc');
}
}
| true |
bf10acba355ede19bb32cc4a49c7207d58f574c3 | PHP | cleverage/CleverAgeSyliusColissimoPlugin | /src/Model/Shipping/Letter/Addressee.php | UTF-8 | 1,591 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace CleverAge\SyliusColissimoPlugin\Model\Shipping\Letter;
class Addressee extends BaseAddress
{
private string $lastName;
private string $firstName;
private ?string $mobileNumber = null;
private ?string $email = null;
public function getLastName(): string
{
return $this->lastName;
}
public function setLastName(string $lastName): Addressee
{
$this->lastName = $lastName;
return $this;
}
public function getFirstName(): string
{
return $this->firstName;
}
public function setFirstName(string $firstName): Addressee
{
$this->firstName = $firstName;
return $this;
}
public function getMobileNumber(): ?string
{
return $this->mobileNumber;
}
public function setMobileNumber(?string $mobileNumber): Addressee
{
$this->mobileNumber = $mobileNumber;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): Addressee
{
$this->email = $email;
return $this;
}
public function toArray(): array
{
$base = [
'lastName' => $this->getLastName(),
'firstName' => $this->getFirstName(),
];
if ($mobileNumber = $this->getMobileNumber()) {
$base['mobileNumber'] = $mobileNumber;
}
if ($email = $this->getEmail()) {
$base['email'] = $email;
}
return array_merge($base, parent::toArray());
}
}
| true |
90fd2237f29523da17b2d7662c91e6a9b78baebc | PHP | Elya92/library | /admin.php | UTF-8 | 4,726 | 2.65625 | 3 | [] | no_license | <?php
//форма добавления книги и кнопки перехода на страницу удаления книг
$cntnt = "
<form method=\"post\" enctype=\"multipart/form-data\" action=\"admin.php\">
<br><br>
Введите автора:
<br>
<input type=\"text\" name=\"atr\" size=\"30\">
<br><br>
Введите название книги:
<br>
<input type=\"text\" name=\"bk\" size=\"40\">
<br><br>
Выберите жанр книги:
<br>
<input type=\"radio\" name=\"gnr\" value=\"1\" checked>
Классика
<br>
<input type=\"radio\" name=\"gnr\" value=\"2\" checked>
Детектив
<br>
<input type=\"radio\" name=\"gnr\" value=\"3\" checked>
Поэзия
<br><br>
<input type=\"file\" name=\"img\" accept=\"image/jpeg\">
<br><br>
<input type=\"submit\" name=\"add\" value=\"Добавить\">
</form>
<form method=\"post\" action=\"delete.php\">
<br><br>
<input type=\"submit\" name=\"del\" value=\"Перейти на страницу удаления книг\">
</form>
";
//если введен пароль, а не случайно пользователь нашел эту страницу
if (isset($_POST["oka"]) AND $_POST["oka"]){
$title = "Страница администратора"; //задаем название страницы
$pswd = htmlentities($_POST["pswd"]); //введенный пароль преобразуем для защиты от взлома
$file_pswd = fopen("password.txt", "r"); //открываем файл с паролем
$data = file("password.txt"); //считываем пароль
if (preg_match("/^$pswd$/", $data[0])){ //проверяем правильность пароля
$content = $cntnt; //если пароль верный, выводим форму
}
else{ //иначе пишем об ошибке
$content = "
<br><br><br><br>
<h1 align=\"center\">
Ошибка! Введите верный пароль или перейдите на другую страницу!
</h1>
";
}
include('shablon.php');
fclose($file_pswd); //закрываем файл с паролем
}
//если добавлена книга
if (isset($_POST["add"]) AND $_POST["add"]){
$title = "Страница администратора"; //задаем название страницы
//проверка, были ли введены нужные данные
if ($_POST["atr"] != "" && $_POST["bk"] != "" && $_POST["gnr"] != ""){
$autor = htmlentities($_POST["atr"]); //преобразуем введенные данные для защиты от взлома
$name = htmlentities($_POST["bk"]); //преобразуем введенные данные для защиты от взлома
$g = htmlentities($_POST["gnr"]); //преобразуем введенные данные для защиты от взлома
$f_bks = fopen ("books.txt", "a"); //открываем файл со списком книг для добавления новой книги
$data = file("books.txt"); //считываем все данные из файла построчно
$i = count($data); //считаем количество строк
preg_match_all("/^\d+/", $data[$i-1], $num); //находим номер последней книги
$n = $num[0][0] + 1; //увеличиваем найденный номер на 1
$book = "\r\n".$n.". ".$g." \"".$name."\" ".$autor; //инициализируем информацию о добавленной книге
fwrite($f_bks, $book); //записываем информацию в файл
//сохраняем фотографию обложки книги
copy($_FILES["img"]["tmp_name"],
"D:/USR/www/Biblio/images/books/$n.jpg");
//и выводим сообщение об успешном добавлении
$content = "
<h2>
Книга успешно добавлена.
</h2>
";
//и повторно форму добавления и кнопку перехода на страницу удаления книг
$content .= $cntnt;
}
else { //иначе выводим сообщение об ошибке
$content = "
<h2>
Ошибка! Книга не была добавлена!
</h2>
";
//и повторно форму добавления и кнопку перехода на страницу удаления книг
$content .= $cntnt;
}
include('shablon.php');
fclose($f_bks); //закрываем файл книг
}
?> | true |
8bc3d9ea030ab5bab64ce6447cc340e831fdc515 | PHP | GrigoryGerasimov/laravel-weather | /src/Objects/Marine/Marine.php | UTF-8 | 2,325 | 2.78125 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace GrigoryGerasimov\Weather\Objects\Marine;
use GrigoryGerasimov\Weather\Contracts\WeatherCollection\WeatherMarineInterface;
use GrigoryGerasimov\Weather\Objects\Forecast\{ForecastCommon, ForecastDay, ForecastAstro};
use Illuminate\Support\Collection;
final readonly class Marine implements WeatherMarineInterface
{
/**
* @param \stdClass $forecastMarineItem
*/
public function __construct(
private \stdClass $forecastMarineItem
) {}
/**
* @return ForecastCommon|null
*/
public function common(): ?ForecastCommon
{
return isset($this->forecastMarineItem->date) && isset($this->forecastMarineItem->date_epoch) ? new ForecastCommon($this->forecastMarineItem) : null;
}
/**
* @return ForecastDay|null
*/
public function day(): ?ForecastDay
{
return isset($this->forecastMarineItem->day) ? new ForecastDay($this->forecastMarineItem) : null;
}
/**
* @return ForecastAstro|null
*/
public function astro(): ?ForecastAstro
{
return isset($this->forecastItem->astro) ? new ForecastAstro($this->forecastMarineItem) : null;
}
/**
* @return Collection<MarineHour>|null
*/
public function hour(): ?Collection
{
$collection['marine_hours'] = [];
foreach($this->forecastMarineItem->hour as $forecastMarineHour) {
if (!isset($forecastMarineHour)) {
return null;
}
$collection['marine_hours'][] = new MarineHour($forecastMarineHour);
}
return collect($collection['marine_hours']);
}
/**
* @return Collection<MarineTide>|null
*/
public function tides(): ?Collection
{
if (!isset($this->forecastMarineItem->day->tides)) {
return null;
}
$tidesArray = $this->forecastMarineItem->day->tides;
$collection['marine_tides'] = [];
foreach($tidesArray as $forecastMarineTideObject) {
if (!isset($forecastMarineTideObject->tide)) {
return null;
}
$collection['marine_tides'][] = collect($forecastMarineTideObject->tide)->mapInto(MarineTide::class);;
}
return collect($collection['marine_tides'])->flatten();
}
} | true |
238d1a1b6f33ea314f94db9dd8e9caeacf620925 | PHP | exxxar/crypto-core-package | /src/middleware/XApiVersionMiddleware.php | UTF-8 | 952 | 2.625 | 3 | [] | no_license | <?php
namespace Cryptolib\CryptoCore\Middleware;
use Closure;
use Illuminate\Http\Request;
class XApiVersionMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next, $version)
{
if (!$request->hasHeader("X-API-VERSION"))
return response()->json((object)[
"code" => 415,
"detail" => "Need Api version",
"title" => "Подключение к маршруту"
]);
if ($request->header("X-API-VERSION") != $version)
return response()->json((object)[
"code" => 415,
"detail" => "Bad Api version, required $version",
"title" => "Подключение к маршруту"
]);
return $next($request);
}
}
| true |
2352ee6c735cdea92379ccdb3fe9ce7ca0766e56 | PHP | FlyingWings/helpful-tools | /commands/ssh.php | UTF-8 | 6,395 | 2.671875 | 3 | [] | no_license | <?php
/**
* 搭建本地隧道到目标地址
*/
function cli_build_ssh_direct(){
$arguments = [
"alexfu.cc",
"root"
];
$name = ["addr", "user"];
//获取命令行参数
$argu_new = func_get_args()[0];
foreach($arguments as $key=>$value){
if($key == count($argu_new)){
break;
}
$arguments[$key] = $argu_new[$key];
}
foreach($arguments as $key=>$value){
$arguments[$name[$key]] = $value;
unset($arguments[$key]);
}
$user = posix_getpwuid(posix_geteuid())['name'];
if($user == "root"){
throw new Exception("Please DO NOT run in root mode");
}
if(!is_dir(ROOT. DIRECTORY_SEPARATOR. "data/ssh")){
mkdir(ROOT. DIRECTORY_SEPARATOR. "data/ssh");
}
//找到本地.ssh目录 && 远程.ssh目录(默认远程为Linux)
if(PHP_OS == "Linux"){
//MacOS
$local_ssh_dir = "/home/{$user}/.ssh";
}else if(PHP_OS == "Darwin"){
$local_ssh_dir = "/Users/{$user}/.ssh";
}else{
throw new Exception("OS not supported");
}
//默认远端为Linux
if($arguments["user"] == "root"){
$remote_ssh_dir = "/{$arguments["user"]}/.ssh";
}else{
$remote_ssh_dir = "/home/{$arguments["user"]}/.ssh";
}
$key_file = ROOT. "/data/ssh/id_rsa_".$arguments["addr"];
//本地未保存该密钥时,生成密钥对,并继续
if(!file_exists($key_file)){
exec(sprintf("ssh-keygen -f %s -N ''", $key_file));
$temppath =ROOT."/data/ssh/".$arguments["addr"]."_TEMP";
mkdir($temppath);
//SCP from remote
exec(sprintf("scp %s@%s:%s/authorized_keys %s", $arguments["user"], $arguments["addr"], $remote_ssh_dir, $temppath));
$content = file_get_contents($temppath. "/authorized_keys");
$public_key = file_get_contents(
ROOT. "/data/ssh/id_rsa_".$arguments["addr"].".pub");
//SCP back to remote
if(strpos($content, $public_key) ===0 || strpos($content, $public_key) > 0){
//Do nothing
}else{
file_put_contents($temppath. "/authorized_keys", $public_key, FILE_APPEND);
exec(sprintf("scp %s/authorized_keys %s@%s:%s/authorized_keys ", $temppath, $arguments["user"], $arguments["addr"], $remote_ssh_dir));
}
$key_file = ROOT. "/data/ssh/id_rsa_".$arguments["addr"];
printf("Key File Generated\n");
}else{
$key_file = ROOT. "/data/ssh/id_rsa_".$arguments["addr"];
printf("Key File Name Existed\n");
}
$auth = sprintf("Host %s\n\tHostName %s\n\tUser %s\n\tIdentityFile %s\n\n", $arguments["addr"], $arguments["addr"], $arguments["user"], $key_file);
$configs = @file_get_contents($local_ssh_dir."/config");
if(gettype(strpos($configs, $auth)) == "boolean"){
file_put_contents($local_ssh_dir."/config", $auth, FILE_APPEND);
}
}
/**
* SSH通道
* 地址|远程端口|远程用户名
*/
function cli_build_ssh_transfer(){
$arguments = [
"alexfu.cc",
"2222",
"22",
"root"
];
//获取命令行参数
$argu_new = func_get_args()[0];
foreach($arguments as $key=>$value){
if($key == count($argu_new)){
break;
}
$arguments[$key] = $argu_new[$key];
}
$name = ["addr", "port", 'port_local', "user"];
foreach($arguments as $key=>$value){
$arguments[$name[$key]] = $value;
unset($arguments[$key]);
}
$user = posix_getpwuid(posix_geteuid())['name'];
if($user == "root"){
throw new Exception("Please DO NOT run in root mode");
}
if(!is_dir(ROOT. DIRECTORY_SEPARATOR. "data/ssh")){
mkdir(ROOT. DIRECTORY_SEPARATOR. "data/ssh");
}
$temppath =ROOT."/data/ssh/".$arguments["addr"]."_TEMP";
if(!is_dir($temppath)){
mkdir($temppath);
}
//找到本地.ssh目录 && 远程.ssh目录(默认Linux和MacOS)
if(PHP_OS == "Linux"){
//Linuxvi
$local_ssh_dir = "/home/{$user}/.ssh";
}else if(PHP_OS == "Darwin"){
$local_ssh_dir = "/Users/{$user}/.ssh";
}else{
throw new Exception("OS not supported");
}
if($arguments["user"] == "root"){
$remote_ssh_dir = "/{$arguments["user"]}/.ssh";
}else{
$remote_ssh_dir = "/home/{$arguments["user"]}/.ssh";
}
$key_file = ROOT. "/data/ssh/id_rsa_".$arguments["addr"];
if(!file_exists($key_file)){
throw new Exception(sprintf("Key File not exists, please run command 'php cli.php build ssh direct %s", implode(" ",$arguments)));
}
//从服务器上复制ssh_hosts.json的信息
exec(sprintf("scp -i %s %s@%s:%s %s",$key_file, $arguments['user'], $arguments['addr'], SSH_HOSTS_FILE, $temppath));
if(file_exists($temppath. "/ssh_hosts.json")){
$temp = array_filter(explode("\n", file_get_contents($temppath. "/ssh_hosts.json")));
}else{
$temp = [];
}
$map = [];
if(!empty($temp)){
foreach($temp as $item){
$t = explode("\t", $item);
$map[$t[0]] = ["addr"=>$t[1], "user"=>$t[2]];
}
}
$judge_flag = sprintf("%d:127.0.0.1:%d", $arguments['port'], $arguments['port_local']);
$shell_status = array_filter(explode("\n", shell_exec(sprintf("ps -ef | grep ssh | grep '%s'", $judge_flag))));
if((isset($map[$arguments['port']]) && $map[$arguments['port']]['addr'] != gethostname()) || count($shell_status) >1 ){
throw new Exception(sprintf("PORT %d IN USED FOR %s\n", $arguments['port'], implode(":",$map[$arguments['port']])));
}else{
$map[$arguments['port']] = ['addr'=>gethostname(), 'user'=>$user];
}
foreach($map as $k=>$v){
$content[] = implode("\t", [$k, implode("\t", $v)]);
}
// dd($content);
file_put_contents($temppath. "/ssh_hosts.json", implode("\n", $content));
exec(sprintf("scp -i %s %s/ssh_hosts.json %s@%s:%s ",$key_file, $temppath, $arguments['user'], $arguments['addr'], SSH_HOSTS_FILE));
try{
printf("PORT LISTEN FOR %s:%s\n", $arguments['addr'], $arguments['port']);
exec(sprintf("ssh -i %s -N -f -R %d:127.0.0.1:%d %s -l %s", $key_file, $arguments['port'], $arguments['port_local'], $arguments['addr'], $arguments['user']));
}catch (Exception $e){
printf("%s\n", $e->getMessage());
}
} | true |
2f3758e876e627afeb52981f70b90b3b09e857a5 | PHP | MonsterSunFuck/agency | /get.php | UTF-8 | 861 | 2.5625 | 3 | [] | no_license | <?php
//Списко стран - городов
require('list.php');
//Принимаем POST данные
$type = $_POST["type"];
$size = intval($_POST["size"]);
$act = $_POST["act"];
//Получения списка размеров типов рекламы
$dimensions = mysql_fetch_array(mysql_query("SELECT * FROM dimensions"));
switch($act){
//Cтавим страну и возвращаем города
case "get_size":
$all_size = '<option value="0">Выберите размер</option>';
foreach($dimensions as $dimension)
if($dimension["type_advertising"] == $type)
$all_sizes .= '<option value="'.$dimension['id'].'">'.$dimension["width"].'x'.$dimension["height"].'</option>';
echo $all_sizes;
exit();
break;
//Cтавим город
case "set_size":
setcookie("size", $size, time()+3600);
exit();
break;
}
?> | true |
ff3f32da052d4f8aea2b9cced8ebbd3d31cd29e8 | PHP | gho999/silver-giggle | /customer/functions/functions.php | UTF-8 | 8,501 | 2.78125 | 3 | [] | no_license | <?php
$con = mysqli_connect("localhost","root","","project");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//getting the user ip address
function getIp() {
$ip = $_SERVER['REMOTE_ADDR'];
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
return $ip;
}
//creating hte shopping cart
function cart(){
if(isset($_GET['add_cart'])){
global $con;
$ip = getIp();
$painting_id=$_GET['add_cart'];
$check_painting = "select * from cart where ip_add='$ip' AND painting_id='$painting_id'";
$run_check = mysqli_query($con, $check_painting);
if(mysqli_num_rows($run_check)>0)
{
echo "";
}
else{
$insert_painting = "insert into cart(painting_id,ip_add) values ('$painting_id','$ip')";
$run_painting = mysqli_query($con,$insert_painting);
echo "<script>window.open('index.php','_self')</script>";
}
}
}
// getting the total added items
function total_paintings(){
if(isset($_GET['add_cart'])){
global $con;
$ip=getIp();
$get_paintings = "select * from cart where ip_add='$ip'";
$run_paintings = mysqli_query($con, $get_paintings);
$count_paintings =mysqli_num_rows($run_paintings);
}
else{
global $con;
$ip=getIp();
$get_paintings = "select * from cart where ip_add='$ip'";
$run_paintings = mysqli_query($con, $get_paintings);
$count_paintings =mysqli_num_rows($run_paintings);
}
echo $count_paintings;
}
//getting the total price of the items in the cart
function total_price(){
$total = 0;
global $con;
$ip=getIp();
$sel_price = "select * from cart where ip_add='$ip'";
$run_price = mysqli_query($con,$sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$painting_id = $p_price['painting_id'];
$painting_price = "select * from painting where painting_id='$painting_id'";
$run_painting_price = mysqli_query($con,$painting_price);
while($pp_price = mysqli_fetch_array($run_painting_price)){
$painting_price = array($pp_price['painting_price']);
$values = array_sum($painting_price);
$total += $values;
}
}
echo "$".$total;
}
//other one
function total_prices(){
$total = 0;
global $con;
$ip=getIp();
$sel_price = "select * from cart where ip_add='$ip'";
$run_price = mysqli_query($con,$sel_price);
while($p_price=mysqli_fetch_array($run_price)){
$painting_id = $p_price['painting_id'];
$painting_price = "select * from painting where painting_id='$painting_id'";
$run_painting_price = mysqli_query($con,$painting_price);
while($pp_price = mysqli_fetch_array($run_painting_price)){
$painting_price = array($pp_price['painting_price']);
$values = array_sum($painting_price);
$total += $values;
}
}
return $total;
}
/*if(!$con)
echo "not connect";*/
//getting the categories
function getCats(){
global $con;
$get_cats= "select * from categories";
$run_cats= mysqli_query($con,$get_cats);
while ($row_cats=mysqli_fetch_array($run_cats)){
$cat_id= $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<li><a href='index.php?cat=$cat_id'>$cat_title</a></li>";
}
}
//getting the galleries
function getGalleries(){
global $con;
$get_galleries= "select * from galleries";
$run_galleries= mysqli_query($con,$get_galleries);
while ($row_galleries=mysqli_fetch_array($run_galleries)){
$gallery_id= $row_galleries['gallery_id'];
$gallery_name = $row_galleries['gallery_name'];
$gallery_location = $row_galleries['location'];
echo "<li><a href='index.php?gallery=$gallery_id'>$gallery_name</a></li>";
}
}
function getPaintings(){
if(!isset($_GET['cat'])){
if(!isset($_GET['gallery'])){
global $con;
$get_painting = "select * from painting order by RAND() LIMIT 0,6";
$run_painting = mysqli_query($con,$get_painting);
while($row_painting=mysqli_fetch_array($run_painting)){
$painting_id = $row_painting['painting_id'];
$painting_cat = $row_painting['painting_cat'];
$painting_artistid = $row_painting['artist_id'];
$painting_title = $row_painting['painting_title'];
$painting_price = $row_painting['painting_price'];
$painting_galleryid = $row_painting['gallery_id'];
// $painting_desc = $row_painting['painting_desc'];
$painting_image = $row_painting['painting_image'];
$painting_date = $row_painting['painting_displaydate'];
echo "
<div id='single_painting'>
<h3>$painting_title</h3>
<img src='admin_area/paintingimages/$painting_image' width='180' height='180' />
<p><b>Price: $ $painting_price</b></p>
<a href='details.php?painting_id=$painting_id' style='float:left;'>Details</a>
<a href='index.php?add_cart=$painting_id'><button style='float:right'>Add to cart </button></a>
</div>
";
}
}
}
}
function getCatPaintings(){
if(isset($_GET['cat'])){
$cat_id=$_GET['cat'];
global $con;
$get_cat_painting = "select * from painting where painting_cat='$cat_id'";
$run_cat_painting = mysqli_query($con,$get_cat_painting);
$count_cats=mysqli_num_rows($run_cat_painting);
if($count_cats==0)
{
echo "<h4 style='padding:20px;'>There is no painting in this category</h4>";
}
while($row_cat_painting=mysqli_fetch_array($run_cat_painting)){
$painting_id = $row_cat_painting['painting_id'];
$painting_cat = $row_cat_painting['painting_cat'];
$painting_artistid = $row_cat_painting['artist_id'];
$painting_title = $row_cat_painting['painting_title'];
$painting_price = $row_cat_painting['painting_price'];
$painting_galleryid = $row_cat_painting['gallery_id'];
// $painting_desc = $row_cat_painting['painting_desc'];
$painting_image = $row_cat_painting['painting_image'];
$painting_date = $row_cat_painting['painting_displaydate'];
echo "
<div id='single_painting'>
<h3>$painting_title</h3>
<img src='admin_area/paintingimages/$painting_image' width='180' height='180' />
<p><b>$ $painting_price</b></p>
<a href='details.php?painting_id=$painting_id' style='float:left;'>Details</a>
<a href='index.php?painting_id=$painting_id'><button style='float:right'>Add to cart </button></a>
</div>
";
}
}
}
function getGalPaintings(){
if(isset($_GET['gallery'])){
$gallery_id=$_GET['gallery'];
global $con;
$get_gal_painting = "select * from painting where gallery_id='$gallery_id'";
$run_gal_painting = mysqli_query($con,$get_gal_painting);
$count_gals=mysqli_num_rows($run_gal_painting);
if($count_gals==0)
{
echo "<h4 style='padding:20px;'>There is no painting in this gallery</h4>";
}
while($row_gal_painting=mysqli_fetch_array($run_gal_painting)){
$painting_id = $row_gal_painting['painting_id'];
$painting_cat = $row_gal_painting['painting_cat'];
$painting_artistid = $row_gal_painting['artist_id'];
$painting_title = $row_gal_painting['painting_title'];
$painting_price = $row_gal_painting['painting_price'];
$painting_galleryid = $row_gal_painting['gallery_id'];
// $painting_desc = $row_cat_painting['painting_desc'];
$painting_image = $row_gal_painting['painting_image'];
$painting_date = $row_gal_painting['painting_displaydate'];
echo "
<div id='single_painting'>
<h3>$painting_title</h3>
<img src='admin_area/paintingimages/$painting_image' width='180' height='180' />
<p><b>$ $painting_price</b></p>
<a href='details.php?painting_id=$painting_id' style='float:left;'>Details</a>
<a href='index.php?painting_id=$painting_id'><button style='float:right'>Add to cart </button></a>
</div>
";
}
}
}
?> | true |
fae65065f2108c47287c1c00d6c65447f440878e | PHP | shutrit/swift-mailer | /individual_addressed_emails.php | UTF-8 | 1,569 | 2.609375 | 3 | [] | no_license | <?php
require_once'includes/config.php';
//config.php has the email addresses for $recipients
$recipients = [
$testing=>'Test Account 1',
$test2,
$test3=>'Test Account 3',
$secret
];
try {
//prepare email
$message = Swift_Message::newInstance()
->setSubject('FARBRENGEN/commemorating ג Tammuz')
->setFrom($from)
->setBody('test multiple');
// create the transport use smtp of your hosting account
$transport = Swift_SmtpTransport::newInstance($smtp_server,465, 'ssl')
->setUsername($username)
->setPassword($password);
$mailer = Swift_Mailer::newInstance($transport);
$sent = 0;
$failures = [];
//send individual emails
foreach($recipients as $key=> $value) {
// ensure numeric key
if(is_int($key)) {
$message->setTo($value);
} else {
$message->setTo([$key=> $value]);
}
$sent += $mailer->send($message,$failures);
}
if($sent) {
echo"number of emails send : $sent<br>";
}
if($failures) {
echo "could not send to the following addresses:<br>";
foreach($failures as $failure) {
echo $failure;
}
}
}
catch (Exception $e) {
echo $e->getMessage();
}
| true |
55cdf136342a8af1507025df15eda6eb28b1ba9f | PHP | max-gryshin/parts-processing | /src/DataFixtures/ToolFixtures.php | UTF-8 | 1,448 | 2.671875 | 3 | [] | no_license | <?php
namespace App\DataFixtures;
use App\Entity\Tool;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Persistence\ObjectManager;
class ToolFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$tool = null;
foreach (static::getInfo() as $item) {
$tool = $this->createTool($item[0], $item[1], $item[2]);
$manager->persist($tool);
$this->addReference("tool_$item[3]", $tool);
}
$manager->flush();
}
private function createTool(
$name,
$status,
$type
): Tool
{
return (new Tool())
->setName($name)
->setStatus($status)
->setType($type)
;
}
private static function getInfo(): array
{
return [
['Молоток', 1, 1, 1],
['Пласкогубцы', 1, 2, 2],
['Отвертка -', 1, 3, 3],
['Лом', 1, 4, 4],
['Линейка', 1, 5, 5],
['Держатель', 1, 6, 6],
['Тиски', 1, 7, 7],
['Отвертка +', 1, 3, 8],
['Напильник 1', 1, 8, 9],
['Напильник 2', 1, 8, 10],
['Напильник 3', 1, 8, 11],
['Напильник 4', 1, 8, 12],
['Напильник 5', 1, 8, 13],
['Кувалда', 1, 9, 14],
];
}
}
| true |
4d78fb584c014f47b3a3eed7589495b64e64dd1d | PHP | mottor/events | /src/Events/EventBus.php | UTF-8 | 6,392 | 2.875 | 3 | [] | no_license | <?php
namespace Mottor\Events;
/**
* Class EventBus
* @package Mottor\Events
*/
class EventBus
{
/**
* @var string путь к файл с указанием самого файла
*/
protected $logFileName = 'event.log';
/** @var array */
protected $eventListeners = [];
/**
* @param string $fileName
*/
public function setLogFileName($fileName) {
$this->logFileName = $fileName;
}
/**
* @return string
*/
public function getLogFileName() {
return $this->logFileName;
}
/**
* @param string $eventName
* @return array
*/
public function getListenersForEvent($eventName) {
return $this->hasListenersForEvent($eventName) ? $this->eventListeners[$eventName] : [];
}
/**
* @param string $eventName
* @param mixed $listener
*/
public function addListener($eventName, $listener) {
if (!$this->hasListenersForEvent($eventName)) {
$this->eventListeners[$eventName] = [];
}
$this->eventListeners[$eventName][] = $listener;
}
/**
* @param string $eventName
* @return bool
*/
public function hasListenersForEvent($eventName) {
return array_key_exists($eventName, $this->eventListeners) && count($this->eventListeners[$eventName]) > 0;
}
/**
* @param mixed $listener
* @return array
*/
public function prepareListener($listener) {
$preparedListener = [
'handler' => [],
'isAsync' => false,
'log' => false,
];
if (is_array($listener) && array_key_exists('handler', $listener)) {
$preparedListener['handler'] = $listener['handler'];
$preparedListener['isAsync'] = array_key_exists('isAsync', $listener) ? $listener['isAsync'] : $preparedListener['isAsync'];
$preparedListener['log'] = array_key_exists('log', $listener) ? $listener['log'] : $preparedListener['log'];
} else {
$preparedListener['handler'] = $listener;
}
if (is_string($preparedListener['handler'])
&& class_exists($preparedListener['handler'])
&& is_subclass_of($preparedListener['handler'], EventListenerInterface::class)
) {
$handler = $preparedListener['handler'];
if ($preparedListener['isAsync']) {
// Для асинхронных обработчиков будем опрерировать названием классов.
// Обработчик асинхронных событий будет создавать экземпляр объекта самостоятельно.
// (здесь ничего не делаем)
} else {
// В случае синхронного вызова, необходимо создать объект для работы функции call_user_func.
// Если в метод call_user_func передать название класса с методом, он будет вызывать метод как статичный.
// В нашем случае, обработчик должен быть объектом для вызова метода handle.
$handler = new $handler();
}
$preparedListener['handler'] = [$handler, 'handle'];
}
return $preparedListener;
}
/**
* @param string $eventName
* @param array $data
*/
public function trigger($eventName, array $data = []) {
$logList = [];
$listenerList = $this->getListenersForEvent($eventName);
foreach ($listenerList as $index => $listener) {
$log = [
'event_name' => $eventName,
'data' => $data,
'listenerIndex' => $index,
];
try {
$listener = $this->prepareListener($listener);
$log['isAsync'] = $listener['isAsync'];
if ($listener['isAsync']) {
$log['result'] = $this->executeHandlerAsync($listener['handler'], $data);
} else {
$log['result'] = $this->executeHandlerNow($listener['handler'], $data);
}
if ($listener['log']) {
$logList[] = $log;
}
} catch (\Exception $e) {
$log['error'] = [
'code' => $e->getCode(),
'message' => $e->getMessage(),
];
$logList[] = $log;
}
}
$this->writeLog($logList);
}
/**
* @param mixed $listener
* @param array $data
* @return string
*/
public function executeHandlerAsync($listener, array $data) {
// todo
return "";
}
/**
* @param mixed $handler
* @param array $data
* @return bool|string
* @throws \Exception
*/
public function executeHandlerNow($handler, array $data = []) {
if (!is_callable($handler)) {
throw new \Exception("Handler is not callable", 5730);
}
$result = false;
try {
ob_start();
$result = call_user_func($handler, $data);
} finally {
ob_end_clean();
}
return $result;
}
/**
* @param array $log
*/
public function writeLog(array $log) {
try {
if (0 == count($log)) {
return;
}
$log = json_encode($log);
file_put_contents($this->logFileName, "{$log}\n\n", FILE_APPEND);
} catch (\Exception $e) {
// пустой, так как нет необходимости
}
}
public function clearLog() {
if (file_exists($this->logFileName)) {
unlink($this->logFileName);
}
}
/**
* @param string $eventName
*/
public function clearListenersForEvent($eventName) {
$this->eventListeners[$eventName] = [];
}
/**
* @return string
*/
public function getLogContents() {
if (!file_exists($this->logFileName)) {
return "";
}
return (string) file_get_contents($this->logFileName);
}
}
| true |
d214060bea583c64aec58551f0b4ce9f59b2a4dd | PHP | FoolCode/asagi-toolkit | /fuuka-to-asagi-migration-tool/resources/parameters.php | UTF-8 | 3,193 | 3.21875 | 3 | [] | no_license | <?php
if(PHP_SAPI != 'cli') {
die('This file must be accessed via command line.');
}
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - S�o Paulo - Brazil
* diego.m.rodrigues [at] gmail [dot] com
* May/2005
**********************************************/
class arg_parser
{
var $argc;
var $argv;
var $parsed;
var $force_this;
function arg_parser($force_this="") {
global $argc, $argv;
$this->argc = $argc;
$this->argv = $argv;
$this->parsed = array();
array_push($this->parsed, array($this->argv[0]));
if (!empty($force_this)) {
if (is_array($force_this)) {
$this->force_this = $force_this;
}
}
//Sending parameters to $parsed
if ($this->argc > 1) {
for ($i = 1; $i < $this->argc; $i++) {
//We only have passed -xxxx
if (substr($this->argv[$i],0,1) == "-") {
//Se temos -xxxx xxxx
if ( $this->argc > ($i+1) ) {
if (substr($this->argv[$i+1],0,1) != "-") {
array_push($this->parsed, array($this->argv[$i], $this->argv[$i+1]));
$i++;
continue;
}
}
}
//We have passed -xxxxx1 xxxxx2
array_push($this->parsed, array($this->argv[$i]) );
}
}
//Testing if all necessary parameters have been passed
$this->force();
}
//Testing if one parameter have benn passed
function passed($argumento) {
for($i = 0; $i < $this->argc; $i++) {
if (isset($this->parsed[$i][0]) && $this->parsed[$i][0] == $argumento) {
return $i;
}
}
return 0;
}
//Testing if you have passed a estra argument, -xxxx1 xxxxx2
function full_passed($argumento) {
$findArg = $this->passed($argumento);
if ($findArg) {
if (count($this->parsed[$findArg]) > 1) {
return $findArg;
}
}
return 0;
}
//Returns xxxxx2 at a " -xxxx1 xxxxx2" call
function get_full_passed($argumento) {
$findArg = $this->full_passed($argumento);
if ($findArg) {
return $this->parsed[$findArg][1];
}
return;
}
//Necessary parameters to script
function force() {
if (is_array($this->force_this)) {
for($i=0 ; $i< count($this->force_this) ; $i++) {
if ($this->force_this[$i][1] == "SIMPLE" && !$this->passed($this->force_this[$i][0])) {
die("\n\nMissing " . $this->force_this[$i][0] . "\n\n");
}
if ($this->force_this[$i][1] == "FULL" && !$this->full_passed($this->force_this[$i][0])) {
die("\n\nMissing " . $this->force_this[$i][0] ." <arg>\n\n");
}
}
}
}
}
| true |
0098d2011a44c23a0c6098f9ac2db1b1212e5787 | PHP | geodesicsolutions-community/geocore-community | /src/classes/PEAR/PayPal/Type/ExecuteCheckoutOperationsRequestDetailsType.php | UTF-8 | 2,528 | 2.6875 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
/**
* @package PayPal
*/
/**
* Make sure our parent class is defined.
*/
require_once 'PayPal/Type/XSDSimpleType.php';
/**
* ExecuteCheckoutOperationsRequestDetailsType
*
* @package PayPal
*/
class ExecuteCheckoutOperationsRequestDetailsType extends XSDSimpleType
{
/**
* On your first invocation of ExecuteCheckoutOperationsRequest, the value of this
* token is returned by ExecuteCheckoutOperationsResponse.
*/
var $Token;
/**
* All the Data required to initiate the checkout session is passed in this
* element.
*/
var $SetDataRequest;
/**
* If auto authorization is required, this should be passed in with IsRequested set
* to yes.
*/
var $AuthorizationRequest;
function ExecuteCheckoutOperationsRequestDetailsType()
{
parent::XSDSimpleType();
$this->_namespace = 'urn:ebay:apis:eBLBaseComponents';
$this->_elements = array_merge($this->_elements,
array (
'Token' =>
array (
'required' => false,
'type' => 'ExpressCheckoutTokenType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'SetDataRequest' =>
array (
'required' => true,
'type' => 'SetDataRequestType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
'AuthorizationRequest' =>
array (
'required' => false,
'type' => 'AuthorizationRequestType',
'namespace' => 'urn:ebay:apis:eBLBaseComponents',
),
));
}
function getToken()
{
return $this->Token;
}
function setToken($Token, $charset = 'iso-8859-1')
{
$this->Token = $Token;
$this->_elements['Token']['charset'] = $charset;
}
function getSetDataRequest()
{
return $this->SetDataRequest;
}
function setSetDataRequest($SetDataRequest, $charset = 'iso-8859-1')
{
$this->SetDataRequest = $SetDataRequest;
$this->_elements['SetDataRequest']['charset'] = $charset;
}
function getAuthorizationRequest()
{
return $this->AuthorizationRequest;
}
function setAuthorizationRequest($AuthorizationRequest, $charset = 'iso-8859-1')
{
$this->AuthorizationRequest = $AuthorizationRequest;
$this->_elements['AuthorizationRequest']['charset'] = $charset;
}
}
| true |
e4ba9f0d7999fbadc4d228fb44ad6943af6c8020 | PHP | cier-centro/edu-unica | /service/BaseJornadaUnicaMerge.php | UTF-8 | 1,459 | 2.765625 | 3 | [] | no_license | <?php
class BaseJornadaUnicaMerge {
/**
* @type Reader
* @type Level
* @type Word
*/
protected $reader;
protected $baseJornadaUnica;
public function setReader($reader) {
$this->reader = $reader;
}
public function setBaseMide($baseJornadaUnica) {
$this->baseJornadaUnica = $baseJornadaUnica;
}
public function getArrayAllEntitiesToBuildJson() {
$entitiesArray = $this->baseJornadaUnica->getArrayAllEntities();
$dataArray = array();
foreach ($entitiesArray as $i => $entities) {
$dataArray[$i]['departamento'] = $entities['departamento'];
$dataArray[$i]['etc'] = $entities['etc'];
$dataArray[$i]['establecimientosEducativos'] = $entities['establecimientosEducativos'];
$dataArray[$i]['sedesEducativas'] = $entities['sedesEducativas'];
$dataArray[$i]['cupos'] = $entities['cupos'];
$dataArray[$i]['matriculas'] = $entities['matriculas'];
$dataArray[$i]['recursosPAE'] = $entities['recursosPAE'];
$dataArray[$i]['totalMatricula'] = $entities['totalMatricula'];
$dataArray[$i]['materialEntregado'] = $entities['materialEntregado'];
$dataArray[$i]['coordenadaX'] = $entities['coordenadaX'];
$dataArray[$i]['coordenadaY'] = $entities['coordenadaY'];
}
return $dataArray;
}
}
| true |
dc2a073d3ae839ae311740ed2dd5a5770befb7fc | PHP | meratroksin/emotion | /libs/ProjectOxfordEmotion.php | UTF-8 | 899 | 2.5625 | 3 | [] | no_license | <?php
require_once 'HTTP/Request2.php';
class ProjectOxfordEmotion
{
protected $data;
protected $emotion;
protected $headers = [
'Content-Type' => 'application/json',
'Ocp-Apim-Subscription-Key' => '7f3bc9352a584d06b3f681a5d2b93112',
];
public function __construct($data)
{
$this->emotion = new HTTP_Request2(PROJECTOXFORD_EMOTION);
$this->data = json_decode('{"url": " ' . $data . ' "}');
}
public function requestEmotion()
{
$this->emotion->setHeader($this->headers);
$this->emotion->setMethod(HTTP_Request2::METHOD_POST);
$this->emotion->setBody(json_encode($this->data));
try
{
$response = $this->emotion->send();
return json_decode($response->getBody(), true);
}
catch (HttpException $ex)
{
return $ex;
}
}
}
| true |
1aca41001a34015d284608b192f14540b47f6b6c | PHP | albertcht/notion-ai | /src/Concerns/HasPrompts.php | UTF-8 | 5,348 | 3.046875 | 3 | [
"MIT"
] | permissive | <?php
namespace AlbertCht\NotionAi\Concerns;
use AlbertCht\NotionAi\Enums\Languages;
use AlbertCht\NotionAi\Enums\PromptTypes;
use AlbertCht\NotionAi\Enums\Tones;
use AlbertCht\NotionAi\Exceptions\InvalidEnumException;
use AlbertCht\NotionAi\Exceptions\InvalidPromptException;
trait HasPrompts
{
protected array $customPromptTypes = [
PromptTypes::HELP_ME_WRITE,
PromptTypes::HELP_ME_EDIT,
PromptTypes::HELP_ME_DRAFT,
PromptTypes::CONTINUE_WRITING,
PromptTypes::TRANSLATE,
PromptTypes::CHANGE_TONE,
];
public function writeWithPrompt(string $promptType, string $selectedText, string $pageTitle = ''): ?string
{
$this->validatePromptType($promptType);
return $this->sendRequest([
'type' => $promptType,
'pageTitle' => $pageTitle,
'selectedText' => $selectedText,
]);
}
public function continueWriting(string $previousContent, string $pageTitle = '', string $restContent = ''): ?string
{
return $this->sendRequest([
'type' => PromptTypes::CONTINUE_WRITING,
'pageTitle' => $pageTitle,
'previousContent' => $previousContent,
'restContent' => $restContent,
]);
}
public function helpMeEdit(string $prompt, string $selectedText, string $pageTitle = ''): ?string
{
return $this->sendRequest([
'type' => PromptTypes::HELP_ME_EDIT,
'prompt' => $prompt,
'pageTitle' => $pageTitle,
'selectedText' => $selectedText,
]);
}
public function helpMeWrite(string $prompt, string $previousContent = '', string $pageTitle = '', string $restContent = ''): ?string
{
return $this->sendRequest([
'type' => PromptTypes::HELP_ME_WRITE,
'prompt' => $prompt,
'pageTitle' => $pageTitle,
'previousContent' => $previousContent,
'restContent' => $restContent,
]);
}
public function helpMeDraft(string $prompt, string $previousContent = '', string $pageTitle = '', string $restContent = ''): ?string
{
return $this->sendRequest([
'type' => PromptTypes::HELP_ME_DRAFT,
'prompt' => $prompt,
'pageTitle' => $pageTitle,
'previousContent' => $previousContent,
'restContent' => $restContent,
]);
}
public function translate(string $text, string $language): ?string
{
$this->validateEnums(Languages::class, $language);
return $this->sendRequest([
'type' => PromptTypes::TRANSLATE,
'text' => $text,
'language' => $language,
]);
}
public function changeTone(string $text, string $tone): ?string
{
$this->validateEnums(Tones::class, $tone);
return $this->sendRequest([
'type' => PromptTypes::CHANGE_TONE,
'text' => $text,
'tone' => $tone,
]);
}
public function summarize(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::SUMMARIZE, $selectedText, $pageTitle);
}
public function improveWriting(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::IMPROVE_WRITING, $selectedText, $pageTitle);
}
public function fixSpellingGrammar(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::FIX_SPELLING_GRAMMAR, $selectedText, $pageTitle);
}
public function explainThis(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::EXPLAIN_THIS, $selectedText, $pageTitle);
}
public function makeLonger(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::MAKE_LONGER, $selectedText, $pageTitle);
}
public function makeShorter(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::MAKE_SHORTER, $selectedText, $pageTitle);
}
public function findActionItems(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::FIND_ACTION_ITEMS, $selectedText, $pageTitle);
}
public function simplifyLanguage(string $selectedText, string $pageTitle = ''): ?string
{
return $this->writeWithPrompt(PromptTypes::SIMPLIFY_LANGUAGE, $selectedText, $pageTitle);
}
protected function validatePromptType(string $promptType): void
{
$promptTypes = array_diff(
PromptTypes::getValues(),
$this->customPromptTypes
);
if (! in_array($promptType, $promptTypes)) {
throw new InvalidPromptException("Invalid prompt type `{$promptType}`, only: " . implode(',', $promptTypes) . ' are suppored.');
}
}
protected function validateEnums(string $class, string $enum, array $suppported = []): void
{
$supported = $suppported ?: $class::getValues();
if (! in_array($enum, $supported)) {
throw new InvalidEnumException("Invalid value `{$enum}`, only: " . implode(', ', $supported) . ' are suppored.');
}
}
}
| true |
6ed97cca33bb1dd3331498a8a588be6439ed8e85 | PHP | fjmn2001/laravel-onboarding | /src/SaleOrder/Application/DeleteSaleOrderUseCase.php | UTF-8 | 455 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Src\SaleOrder\Application;
use Src\SaleOrder\Domain\Contracts\SaleOrderRepositoryContract;
use Shared\Domain\ValueObject\Id;
final class DeleteSaleOrderUseCase
{
private $repository;
public function __construct(SaleOrderRepositoryContract $repository)
{
$this->repository = $repository;
}
public function __invoke(int $saleOrderId): void
{
$id = new Id($saleOrderId);
$saleOrder = $this->repository->delete($id);
}
}
?> | true |
47fb6afbf76518d0e4c27c8191ccdcf9676c543f | PHP | Time-travelers/php-test | /data_structure/tree_link.php | UTF-8 | 4,210 | 3.203125 | 3 | [] | no_license | <?php
/*
*@author:xu.weishuai
*@Time:2019/10/30 15:51
*/
/*
* 8(0)
* 7(1) 9(2)
* 5(3) 6(4) 1(5) 2(6)
*
* */
/*
* 类 node
* 属性 pre leftNode rightNode index data
* 类 tree
* 属性 size r_root
*
* */
class node{
// public $pre;
public $leftNode;
public $rightNode;
public $index;
public $data;
public function __construct($data,$index=0,$pre=null,$leftNode=null,$rightNode=null)
{
$this->data=$data;
$this->index=$index;
}
// 筛选节点
public function search($index){
if($this->index==$index){
return $this;
}
if($this->leftNode!=null){
if($this->leftNode->index==$index){
return $this->leftNode;
}
$temp=$this->leftNode->search($index);
// ---------------需要判断一下否则直接返回 会报错-----------------------------
if($temp!=null){
return $temp;
}
}
if($this->rightNode!=null){
if($this->rightNode->index==$index){
return $this->rightNode;
}
$temp= $this->rightNode->search($index);
// ---------------需要判断一下否则直接返回 会报错-----------------------------
if($temp!=null){
return $temp;
}
}
return null;
}
/**
* preTraverse 前序遍历
* @author:xu.weishuai
* @Time:2019/10/30 18:33
*/
public function preTraverse(){
if($this->leftNode!=null){
// echo $this->leftNode->data;
$this->leftNode->preTraverse();
}
echo $this->data;
if($this->rightNode!=null){
// echo $this->rightNode->data;
$this->rightNode->preTraverse();
}
}
public function inTraverse(){
echo $this->data;
if($this->leftNode!=null){
$this->leftNode->inTraverse();
}
if($this->rightNode!=null){
$this->rightNode->inTraverse();
}
}
public function afterTraverse(){
if($this->leftNode!=null){
$this->leftNode->afterTraverse();
}
if($this->rightNode!=null){
$this->rightNode->afterTraverse();
}
echo $this->data;
}
}
class Tree{
public $r_root;
public function __construct($node)
{
$this->r_root=$node;
}
// 添加 筛选节点
public function search($index){
return $this->r_root->search($index);
}
public function add($index,$type,$data){
$indexNode=$this->r_root->search($index);
if(!$indexNode){
return false;
}
if($type==0){
$index=2*$indexNode->index+1;
$node=new node($data,$index);
$indexNode->leftNode=$node;
return true;
}
if($type==1){
$index=2*$indexNode->index+2;
$node=new node($data,$index);
$indexNode->rightNode=$node;
return true;
}
return false;
}
// 树遍历 前序 中序 后续
public function preTraverse(){
$this->r_root->preTraverse();
}
public function inTraverse(){
$this->r_root->inTraverse();
}
public function afterTraverse(){
$this->r_root->afterTraverse();
}
}
$root_node=new node(8);
$tree=new Tree($root_node);
var_dump($tree->search(0)->data);
/*
* 8(0)
* 7(1) 9(2)
* 5(3) 6(4) 1(5) 2(6)
*
* */
$tree->add(0,0,7);
$tree->add(0,1,9);
$tree->add(1,0,5);
$tree->add(1,1,6);
$tree->add(2,1,2);
$tree->add(2,0,1);
//var_dump($tree->search(1)->leftNode);
var_dump($tree->search(4)->data);
//var_dump($tree->search(2)->leftNode);
//var_dump($tree->search(5));
//var_dump($tree);
//$tree->search(5) ;
$tree->preTraverse();
echo "\n";
$tree->inTraverse();
echo "\n";
$tree->afterTraverse(); | true |
35c6414961512454db528617cbe4578c1d0febf2 | PHP | Jbru95/BummerPHP | /lib/LoginController.php | UTF-8 | 923 | 2.828125 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Mingkai
* Date: 2018/4/3
* Time: 15:29
*/
namespace Bummer;
class LoginController{
public function __construct(Site $site, array &$session, array $post)
{
$users = new Users($site);
$email = strip_tags($post['email']);
$password = strip_tags($post['password']);
$user = $users->login($email, $password);
$session[User::SESSION_NAME] = $user;
$root = $site->getRoot();
if ($user === null) {
$this->redirect = "$root/login.php?e";
$session['ERROR'] = "Invalid Login Credentials";
}
else {
$this->redirect = "$root/";
$_SESSION["inTurn"] = false;
}
}
/**
* @return mixed
*/
public function getRedirect()
{
return $this->redirect;
}
private $redirect; ///< Page we will redirect the user to.
} | true |
27b039f874e9c734cf0d77b1fbe583a19e204ecf | PHP | gdbots/common-php | /tests/Common/Util/DateUtilsTest.php | UTF-8 | 1,620 | 2.671875 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace Gdbots\Tests\Common;
use Gdbots\Common\Util\DateUtils;
class DateUtilsTest extends \PHPUnit_Framework_TestCase
{
public function testUtcZuluWithMicroseconds()
{
$expected = '2012-12-14T20:24:01.123456Z';
$date = \DateTime::createFromFormat(DateUtils::ISO8601_ZULU, $expected);
$actual = $date->format(DateUtils::ISO8601_ZULU);
$this->assertSame($expected, $actual);
}
public function testISO8601WithMicroseconds()
{
$expected = '2012-12-14T20:24:01.123456+00:00';
$date = \DateTime::createFromFormat(DateUtils::ISO8601, $expected);
$actual = $date->format(DateUtils::ISO8601);
$this->assertSame($expected, $actual);
}
public function testIsValidISO8601Date()
{
$this->assertTrue(DateUtils::isValidISO8601Date('2012-12-14T20:24:01.123456+00:00'));
$this->assertTrue(DateUtils::isValidISO8601Date('2012-12-14T20:24:01+00:00'));
$this->assertTrue(DateUtils::isValidISO8601Date('2012-12-14T20:24:01.123456Z'));
$this->assertTrue(DateUtils::isValidISO8601Date('2012-12-14T20:24:01Z'));
$this->assertTrue(DateUtils::isValidISO8601Date('2012-12-14T20:24:01.123456'));
$this->assertFalse(DateUtils::isValidISO8601Date('2012-12-14T20:24:01.123456+00:00AA'));
$this->assertFalse(DateUtils::isValidISO8601Date('2012-12-14T20:24:0100:00'));
$this->assertFalse(DateUtils::isValidISO8601Date('cats'));
$this->assertFalse(DateUtils::isValidISO8601Date('-1 day'));
$this->assertFalse(DateUtils::isValidISO8601Date('1234567890'));
}
}
| true |
54ede549fb8a4565930c25543dbf771a8838568a | PHP | augustincharly/Business-case-back | /src/Controller/LoginController.php | UTF-8 | 1,889 | 2.5625 | 3 | [] | no_license | <?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
class LoginController extends AbstractController
{
/**
* @param Request $request
* @Route("/login", name="login")
*/
public function login(Request $request, SerializerInterface $serializer, UserRepository $userRepository)
{
if ($request->isMethod("post")) {
$data = $request->getContent();
if (!empty($data)) {
$data = json_decode($data, true);
$user = $userRepository->findOneBy(["username" => $data["username"]]);
if ($data["username"] && $data["password"]) {
if (!$user) {
return new JsonResponse("User not found", 500, ['Content-Type:' => 'application/json'], false);
} else if ($user->getPassword() !== hash("sha256", $data["password"])) {
return new JsonResponse("Wrong password", 500, ['Content-Type:' => 'application/json'], false);
} else {
return new JsonResponse(["username" => $user->getUsername(), "roles" => $user->getRoles(), "api_token" => $user->getApiToken()], 200, ['Content-Type:' => 'application/json'], false);
}
} else {
return new JsonResponse("Error, wrong formated", 500, ['Content-Type:' => 'application/json'], false);
}
} else {
return new JsonResponse("Error, wrong formated", 500, ['Content-Type:' => 'application/json'], false);
}
}
}
}
| true |
54ee256b3ae24322ba0299a23bd1d961ac46ea73 | PHP | zx648383079/PHP-ZoDream | /Module/Disk/Domain/Repositories/StatisticsRepository.php | UTF-8 | 700 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace Module\Disk\Domain\Repositories;
use Module\Disk\Domain\Model\FileModel;
use Module\Disk\Domain\Model\ServerModel;
final class StatisticsRepository {
public static function subtotal(): array {
$todayStart = strtotime(date('Y-m-d 00:00:00'));
$server_count = ServerModel::query()->count();
$online_count = $server_count > 0 ? ServerModel::query()->where('status', 1)->count() : 0;
$file_count = FileModel::query()->count();
$today_count = $file_count > 0 ? FileModel::where('created_at', '>=', $todayStart)->count() : 0;
return compact('server_count', 'online_count', 'today_count', 'file_count');
}
} | true |
0cb76715278f8ce4b05ced39464462783555b544 | PHP | fidransky/letters | /pluginy/clanky/frontend/archive.php | UTF-8 | 2,400 | 2.5625 | 3 | [] | no_license | <?php
$first = true;
$odd = true;
foreach ($articles as $i => $article) {
$article["meta"]["permalink"] = $lrs["address"]."/".$article["alias"];
$article["meta"]["cas"] = date($datetime_format, strtotime($article["cas"]));
if (!empty($article["kategorie"])) {
include_once (PLUGINS_DIR."clanky/scripts/list.php");
$article["meta"]["kategorie"] = "<a href=\"kategorie/".$article["kategorie"]."\">".category_real_name($article["kategorie"])."</a>";
}
else
$article["meta"]["kategorie"] = "–";
$article["meta"]["tagy"] = (empty($article["tagy"]) ? "–" : $article["tagy"]);
$article["meta"]["pocet_slov"] = count(explode(" ", $article["text"]));
include_plugins("meta", array(), $article);
$meta = $article["meta"];
unset($article["meta"]);
// speciální CSS třídy
$class = null;
if ($first === true) { // první článek
$class .= "first ";
$first = false;
}
if ($odd === true) { // lichý článek
$class .= "odd ";
$odd = false;
}
else {
$class .= "even ";
$odd = true;
}
// text
if (!empty($article["heslo"]) and !check_user2("clanky_s_heslem") and !isSet($_SESSION["clanek_".$article["alias"]."_pristup"]))
$article["text"] = "<p class=\"error\">".__("Tento článek je přístupný pouze s heslem.")."</p><form method=\"post\" action=\"".$permalink."\" class=\"locked-article\"><input type=\"password\" name=\"password\" size=\"15\" title=\"".__("zadejte heslo pro přístup")."\" class=\"input\"><input type=\"submit\" value=\"".__("Pokračovat")."\"></form>";
else {
include_plugins("text editor", array("action" => "modify"), $article);
$text = null;
if ($preview_type == "words") {
foreach (explode(" ", $article["text"]) as $index => $word) {
if ($index == $preview_count) break;
$text .= $word." ";
}
if ($preview_count < count(explode(" ", $text))) $text .= "…";
$article["text"] = $text;
}
elseif ($preview_type == "paragraphs") {
foreach (explode("</p>", $article["text"]) as $index => $paragraph) {
if ($index == $preview_count) break;
$text .= $paragraph."</p>";
}
$article["text"] = $text;
}
}
// zobrazení
if (file_exists($template["path"]."category.php")) include ($template["path"]."category.php");
else var_dump($article);
}
?> | true |
1dd0dc80b0c873e48478c877973995f6bd81f6df | PHP | hanh01/hanh2101 | /PHP/Session3/snippet7.php | UTF-8 | 302 | 3.328125 | 3 | [] | no_license | <?php
namespace aptech;
class Boston{
function say(){
echo "Boston\n";
}
}
class NewYork{
function say(){
echo "NewYork\n";
}
}
function foo1()
{
echo "This is foo1() \n";
}
function foo2()
{
echo "This is foo2()\n";
}
?>
| true |
6ca6dfcd92d66d8940d76afac001ecd771c4d4ea | PHP | hige-itapps/Grant_Management_System | /server/Application.php | UTF-8 | 2,818 | 2.984375 | 3 | [] | no_license | <?php
/* Holds information for an application; these fields should be mostly self-explanatory, they mirror the fields in the database. */
class Application{
public $id; // id of application (INT)
public $broncoNetID; // applicant's broncoNetID (STRING)
public $dateSubmitted; // date submitted (DATE)
public $nextCycle; // true=submitted for next cycle, false=current (BOOLEAN)
public $name; // (STRING)
public $email; // (STRING)
public $department; // (STRING)
public $deptChairEmail; // (STRING)
public $travelFrom; // (DATE)
public $travelTo; // (DATE)
public $activityFrom; // (DATE)
public $activityTo; // (DATE)
public $title; // title of activity (STRING)
public $destination; // (STRING)
public $amountRequested; // (DECIMAL)
public $purpose1; // is research (BOOLEAN)
public $purpose2; // is conference (BOOLEAN)
public $purpose3; // is creative activity (BOOLEAN)
public $purpose4; // is other event text (STRING)
public $otherFunding; // (STRING)
public $proposalSummary; // (STRING)
public $goal1; // (BOOLEAN)
public $goal2; // (BOOLEAN)
public $goal3; // (BOOLEAN)
public $goal4; // (BOOLEAN)
public $deptChairApproval; // (STRING)
public $amountAwarded; // (DECIMAL)
public $status; // approved, denied, on hold, pending, etc. (STRING)
public $budget; // (ARRAY of budget items), must be received separately
/*Constructor(for everything except budget); just pass in the application array received from the database call*/
public function __construct($appInfo) {
$this->id = $appInfo[0];
$this->broncoNetID = $appInfo[1];
$this->dateSubmitted = $appInfo[2];
$this->nextCycle = $appInfo[3];
$this->name = $appInfo[4];
$this->email = $appInfo[5];
$this->department = $appInfo[6];
$this->deptChairEmail = $appInfo[7];
$this->travelFrom = $appInfo[8];
$this->travelTo = $appInfo[9];
$this->activityFrom = $appInfo[10];
$this->activityTo = $appInfo[11];
$this->title = $appInfo[12];
$this->destination = $appInfo[13];
$this->amountRequested = $appInfo[14];
$this->purpose1 = $appInfo[15];
$this->purpose2 = $appInfo[16];
$this->purpose3 = $appInfo[17];
$this->purpose4 = $appInfo[18];
$this->otherFunding = $appInfo[19];
$this->proposalSummary = $appInfo[20];
$this->goal1 = $appInfo[21];
$this->goal2 = $appInfo[22];
$this->goal3 = $appInfo[23];
$this->goal4 = $appInfo[24];
$this->deptChairApproval = $appInfo[25];
$this->amountAwarded = $appInfo[26];
$this->status = $appInfo[27];
}
}
?> | true |
1e58e8d2b6c95de5e57433bcbaeb732fe2e91a18 | PHP | zhuxxx/important | /common/model/touch/register.model.php | UTF-8 | 5,993 | 2.671875 | 3 | [] | no_license | <?php
/**
*新用户注册
*/
class registerModel extends model
{
public function __construct() {
parent::__construct(C('db_default'), 'customer_contact');
}
/*
* 用户注册
* @access public
* @param array $param 用户信息(mobile,password)
* @return bool
*/
public function register($param=array()){
//手机号检查
if(!empty($param['mobile'])){
if(!is_mobile($param['mobile'])){
return array('err'=>1,'msg'=>'您的手机号码格式不正确');
}
if(!$this->_usrUnique('mobile',$param['mobile'])){
return array('err'=>1,'msg'=>'手机号已存在');
}
}
//密码检查
if(strlen($param['password'])<8){
return array('err'=>1,'msg'=>'密码长度应为(8-20位)');
}
$user=$param;
if(empty($user['salt'])){
$user['salt']=randstr(6);
$user['password']=$this->_genPassword($param['password'].$user['salt']);
}
if(empty($user['last_ip'])){
$user['last_ip']=get_ip();
$user['last_login']=CORE_TIME;
$user['visit_count']=1;
$user['chanel']=3;
}
//加入数据库
$result=$this->model('customer_contact')->add($user);
if(empty($result)){
return array('err'=>1,'msg'=>'数据操作失败:'.$this->getDBError());
}else{
return array('err'=>0,'msg'=>'数据操作成功!');
}
}
/*
* 用户密码重置(找回密码)
* @access public
* @param array $param 用户信息(mobile,password)
* @return bool
*/
public function findpwd($param=array()){
if(!empty($param['mobile'])){
if(!is_mobile($param['mobile'])){
return array('err'=>1,'msg'=>'您的手机号码格式不正确');
}
//只有手机号存在的时候才会密码重置
$user=$param;
if(!$this->_usrUnique('mobile',$param['mobile'])){
$user['salt']=randstr(6);
$user['password']=$this->_genPassword($param['password'].$user['salt']);
}
//更新数据库
$result=$this->model('customer_contact')->where('mobile='.$param['mobile'])->update($user);
if(empty($result)){
return array('err'=>1,'msg'=>'数据操作失败:'.$this->getDBError());
}else{
return array('err'=>0,'msg'=>'数据操作成功!');
}
}
}
/*
* 检查唯一性
* @param string $name 检查类型
* @param string $value 检查值
* @return bool(true唯一)
*/
private function _usrUnique($name='mobile',$value='',$user_id=0){
$where = "$name='$value'";
if($user_id){
$where .= " and user_id !='$user_id'";
}
$exist=$this->model('customer_contact')->select('user_id')->where($where)->getOne();
return $exist>0 ? false : true;
}
/*
* 生成加密密码
* @param string $password 明文密码
* @return string 密文密码
*/
private function _genPassword($string=''){
return md5('rs.'.$string.'.sr');
}
/**
*用户密码重置时检验用户名是否存在,只有存在时才调用短信验证
*/
public function isLegal($param=array()){
if(!empty($param['mobile'])){
//手机号检查
if(!is_mobile($param['mobile'])){
return array('err'=>1,'msg'=>'您的手机号码格式不正确');
}
//密码检查
if(strlen($param['password'])<8){
return array('err'=>1,'msg'=>'密码长度应为(8-20位)');
}
//只有手机号存在的时候才会密码重置
if($this->_usrUnique('mobile',$param['mobile'])){
return array('err'=>1,'msg'=>'手机号码不存在!');
}
}
}
/**
*用户登录信息验证
*/
public function login($username, $password, $vcode){
//用户名或密码是否为空
if(empty($username) || empty($password)){
return array('err'=>1,'msg'=>'用户名或密码不能为空!');
}
//检查验证码
if(!chkVcode('regcode',$vcode)){
$this->_loginError(0, $username, 1, '验证码不正确,请重新输入!', 3);
return array('err'=>1,'msg'=>'验证码不正确,请重新输入!');
}
//手机号匹配用户信息
$info = $this->model('customer_contact')->where('mobile='.$username)->getRow();
if(empty($info)){
$this->_loginError(0, $username, 2, '没有该用户信息,请注册!', 3);
return array('err'=>1,'msg'=>'没有该用户信息,请注册!');
}else{
$password = $this->_getLoginPassword(array('mobile'=>$username,'password'=>$password));//检查密码是否正确
if($password != trim($info['password'])){
//判断账号是否锁定
if($info['login_unlock_time'] > CORE_TIME){
$this->_loginError($info['user_id'], $username, 3, '您的账号已被锁定,请稍候再试!', 3);
return array('err'=>1,'msg'=>'您的账号已被锁定,请稍候再试');
}
//记录密码输入的次数
$_data = array();
$_data['login_fail_count'] = $info['login_fail_count'] >= 5 ? 1 : $info['login_fail_count']+1;
$msg = '密码不正确,连续输错5次将被锁定';
if($_data['login_fail_count'] == 5){
$_data['login_unlock_time'] = CORE_TIME + 14400;
$msg = '已输错5次密码,账号将锁定4小时';
}
$this->model('customer_contact')->where('user_id='.$info['user_id'])->update($_data);
$this->_loginError($info['user_id'], $username, 4, $msg, 3);
return array('err'=>1,'msg'=>$msg,'user'=>$info);
}
}
}
/**
*用户登录密码验证
*/
private function _getLoginPassword($param=array()){
//获取对应用户的额密码盐
$salt = $this->model('customer_contact')->select('salt')->where('mobile='.$param['mobile'])->getOne();
return $this->_genPassword($param['password'].$salt);
}
/**
*用户登录错误日志
*/
private function _loginError($user_id=0,$mobile='',$err_code=1,$remark='',$chanel=3){
$_login=array(
'user_id'=>$user_id,
'mobile'=>$mobile,
'err_code'=>$err_code,
'remark'=>$remark,
'input_time'=>CORE_TIME,
'ip'=>get_ip(),
'chanel'=>$chanel,
);
return $this->model('log_login_err')->add($_login);
}
} | true |
0d101ea51d4730c81b16451b10e8ab717dba811f | PHP | vali4ka/admin | /classes/Colors.php | UTF-8 | 1,533 | 2.859375 | 3 | [] | no_license | <?php
class Colors implements ICRUD_IMG{
private $db;
public function __construct($db){
$this -> db = $db;
}
public function add(IItem $item){
$sql = '
INSERT INTO colors (products_id, colors, images, promo)
VALUES (
"'.$item -> products_id.'",
"'.$item -> colors.'",
"'.$item -> images.'",
"'.$item -> promo.'"
)';
mysqli_query($this -> db, $sql);
}
public function delete($id){
$sql ='
DELETE FROM colors
WHERE id ='.$id;
mysqli_query($this->db, $sql);
}
public function colors_images($id){
$sql = '
SELECT colors.colors, colors.images, products.name, colors.products_id, colors.id
FROM products
INNER JOIN colors ON products.id = colors.products_id
WHERE products.id = '.$id;
$res = mysqli_query($this -> db, $sql);
return mysqli_fetch_assoc($res);
}
public function get_images($id){
$sql = '
SELECT colors.images, colors.colors, products.name, colors.id, colors.promo
FROM products
INNER JOIN colors ON products.id = colors.products_id
WHERE products.id ='.$id;
return mysqli_query($this -> db, $sql);
}
public function images_count(){
$sql ='
SELECT COUNT(colors.id) as cnt
FROM products
LEFT JOIN colors ON products.id = colors.products_id
GROUP BY products.id
';
$res = mysqli_query($this -> db, $sql) or die(mysqli_error($this ->db));
$result = array();
while ($row = mysqli_fetch_assoc($res)) {
$result[] = $row;
}
return $result;
}
}
?> | true |
74e860af18a0ee774b5fbb488d8e437b5d01edcc | PHP | cueBlog-Club/config | /src/Config.php | UTF-8 | 909 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace CuePhp\Config;
use CuePhp\Config\ConfigRepository;
use CuePhp\Config\Exception\LoaderException;
use CuePhp\Config\Loader\File\FileLoaderInterface;
class Config extends ConfigRepository
{
public function __construct($values, $parser = null)
{
$this->loadFromFile($values, $parser);
parent::__construct($this->data);
}
public static function load($values, $parser = null)
{
return new static($values, $parser);
}
protected function getDefaults(): array
{
return [];
}
protected function loadFromFile(string $path, FileLoaderInterface $loader = null)
{
if ($loader === null) {
throw new LoaderException('loader handler not be missing');
} else {
$this->data = array_replace_recursive($this->data, $loader->loadFromFile($path));
}
}
}
| true |
6d2f704e2535247347128b5edf2d24d9062d7f8e | PHP | andreyrork/jarcash | /classes/Filter/Encrypt/Cookie.php | UTF-8 | 1,447 | 2.53125 | 3 | [] | no_license | <?php
class Filter_Encrypt_Cookie implements Zend_Filter_Encrypt_Interface
{
/**
* Encrypts $value with the defined settings
*
* @param string $value Data to encrypt
* @return string The encrypted data
*/
public function encrypt($value)
{
$chain = new Zend_Filter();
$subnet = new Filter_Encrypt(new Filter_Encrypt_Environment_Subnet());
$chain->addFilter($subnet);
$userAgent = new Filter_Encrypt(new Filter_Encrypt_Environment_UserAgent());
$chain->addFilter($userAgent);
$options = Config::getInstance()->crypt;
$crypt = new Zend_Filter_Encrypt($options->toArray());
$chain->addFilter($crypt);
$filtered = $chain->filter($value);
return base64_encode($filtered);
}
/**
* Decrypts $value with the defined settings
*
* @param string $value Data to decrypt
* @return string The decrypted data
*/
public function decrypt($value)
{
$value = base64_decode($value);
$options = Config::getInstance()->crypt;
$crypt = new Zend_Filter_Decrypt($options->toArray());
$chain = new Zend_Filter();
$chain->addFilter($crypt);
$userAgent = new Filter_Decrypt(new Filter_Encrypt_Environment_UserAgent());
$chain->addFilter($userAgent);
$subnet = new Filter_Decrypt(new Filter_Encrypt_Environment_Subnet());
$chain->addFilter($subnet);
$filtered = $chain->filter($value);
$filtered = trim($filtered);
return $filtered;
}
} | true |
efe28bb9f37950c1a70751f547b82c2a89731c01 | PHP | Lavaei/Raman-Framework | /View/Helper/Rate.php | UTF-8 | 7,597 | 2.671875 | 3 | [] | no_license | <?php
/**
* Implement the jqxRating
*
* @author Mostafa Lavaei <lavaei@ramansoft.co>
* @version 1.0
*/
class Raman_View_Helper_Rate
{
/**
* Html tag name. it will generate automatically
* @var string
*/
protected $TagName;
/**
* Scripts dependencies
* @var array
*/
protected $Dependencies;
/**
* Path to jqwidgets library
* @var string
*/
protected $JQwidgetsPath;
/**
* The primary key in database
* @var integer
*/
protected $PrimaryKey;
/**
* Ajax url
* @var string
*/
protected $Url;
/**
* A floating point number between 0 and 5
* @var float
*/
protected $Value;
/**
* The minimum authentication level required for rating
* @var string
*/
protected $MinimumAuthenticationLevel;
/**
* Path to the login page
* @var string
*/
protected $LoginPage;
/**
* Path to the signup page
* @var string
*/
protected $SignupPage;
/**
* Get SignupPage's value
* @return SignupPage's value
* @see Raman_View_Helper_Rate::$SignupPage
*/
public function getSignupPage()
{
return $this->SignupPage;
}
/**
* Set SignupPage's value
* @param string $SignupPage
* @see Raman_View_Helper_Rate::$SignupPage
*/
public function setSignupPage($value)
{
$this->SignupPage = $value;
}
/**
* Get LoginPage's value
* @return LoginPage's value
* @see Raman_View_Helper_Rate::$LoginPage
*/
public function getLoginPage()
{
return $this->LoginPage;
}
/**
* Set LoginPage's value
* @param string $LoginPage
* @see Raman_View_Helper_Rate::$LoginPage
*/
public function setLoginPage($value)
{
$this->LoginPage = $value;
}
/**
* Get MinimumAuthenticationLevel's value
* @return MinimumAuthenticationLevel's value
*/
public function getMinimumAuthenticationLevel()
{
return $this->MinimumAuthenticationLevel;
}
/**
* Set MinimumAuthenticationLevel's value
* @param string $MinimumAuthenticationLevel
*/
public function setMinimumAuthenticationLevel($value)
{
$this->MinimumAuthenticationLevel = $value;
}
/**
* Get Value's value
* @return Value's value
*/
public function getValue()
{
return $this->Value;
}
/**
* Set Value's value
* @param float $Value
*/
public function setValue($value)
{
$this->Value = $value;
}
/**
* Get Url's value
* @return Url's value
*/
public function getUrl()
{
return $this->Url;
}
/**
* Set Url's value
* @param string $Url
*/
public function setUrl($value)
{
$this->Url = $value;
}
/**
* Get PrimaryKey's value
* @return PrimaryKey's value
*/
public function getPrimaryKey()
{
return $this->PrimaryKey;
}
/**
* Set PrimaryKey's value
* @param integer $PrimaryKey
*/
public function setPrimaryKey($value)
{
$this->PrimaryKey = $value;
}
/**
* Get JQwidgetsPath's value
* @return JQwidgetsPath's value
*/
public function getJQwidgetsPath()
{
return $this->JQwidgetsPath;
}
/**
* Set JQwidgetsPath's value
* @param string $JQwidgetsPath
*/
public function setJQwidgetsPath($value)
{
$this->JQwidgetsPath = $value;
}
/**
* Get Dependencies's value
* @return Dependencies's value
*/
public function getDependencies()
{
return $this->Dependencies;
}
/**
* Set Dependencies's value
* @param string $Dependencies
*/
public function setDependencies($value)
{
$this->Dependencies = $value;
}
/**
* Get TagName's value
* @return TagName's value
*/
public function getTagName()
{
return $this->TagName;
}
/**
* Set TagName's value
* @param string $TagName
*/
public function setTagName($value)
{
$this->TagName = $value;
}
public function __construct(array $initData=array())
{
foreach ($initData as $attr=>$value)
$this->$attr = $value;
if(!isset($this->MinimumAuthenticationLevel))
$this->setMinimumAuthenticationLevel(AUTH_LEVEL_USER_VERIFIED);
if(!isset($this->Dependencies))
{
$this->setDependencies(array(
'jqx.base.css',
'jqx.arctic.css',
'jqxcore.js',
'jqxrating.js'
));
}
if(!isset($this->TagName))
$this->setTagName('Raman_Rate_' . date("isu", time()));
if(!isset($this->LoginPage))
$this->setLoginPage(ROOT_URL . 'users/index/login');
if(!isset($this->SignupPage))
$this->setSignupPage(ROOT_URL . 'users/index/signup');
if(!isset($this->JQwidgetsPath))
$this->setJQwidgetsPath(ROOT_URL . '/libPlugins/jqwidgets');
}
/**
* @param array $data
*/
public function render()
{
$tagName = $this->getTagName();
// load scripts
$return .= "<script>" . $this->getScripts() . "</script>";
// create html
$return .= "<div id=\"$tagName\"></div>";
return $return;
}
public function getScripts()
{
$authSes = new Zend_Session_Namespace('authentication');
$dialog = new Raman_View_Helper_Dialog();
$primary = $this->getPrimaryKey();
$url = $this->getUrl();
$value = $this->getValue();
$minAuthLvl = $this->getMinimumAuthenticationLevel();
$tagName = $this->getTagName();
$loginPage = $this->getLoginPage();
$signupPage = $this->getSignupPage();
$userId = (int) $authSes->userId;
$authLevel = (int) $authSes->authLevel;
$dialog->setTemplate(Raman_View_Helper_Dialog::DIALOG_TEMPLATE_DANGER);
$dialog->setTitle('Login Required');
$dialog->setContent("You don't have permission to rate. Please <a href='$signupPage'>create an account</a> or <a href='$loginPage'>login</a> if you have ");
$showLoginRequiredError = $dialog->getScripts();
// load scripts
$return = "$(document).ready(function(){ " . $this->generateDependencies("var userId = $userId;$('#$tagName').jqxRating({ value:$value, theme: 'classic', height:24});$('#$tagName').on('change', function (event) {if($authLevel < $minAuthLvl){ $showLoginRequiredError }else{ $.post('$url',{request:'rate', value:event.value, primary:'$primary'},function(data){});}}); $('#$tagName').css({'display':'inline-block'}); ") . "});";
return $return;
}
public function generateDependencies($callback)
{
$JQwidgetsPath = $this->getJQwidgetsPath();
$scriptsPath = array();
$stylesPath = array();
$extPattern = "@^.*\.([^.]*)$@";
foreach ($this->getDependencies() as $depend)
{
preg_match($extPattern, $depend, $matches);
$extention = $matches[1];
switch($extention)
{
case 'js':
$scriptsPath[] = "$JQwidgetsPath/$depend";
break;
case 'css':
$stylesPath[] = "$JQwidgetsPath\/styles\/$depend";
break;
}
}
$scripts = $this->loadJavascripts($scriptsPath, $callback);
$styles = $this->loadStyles($stylesPath);
Zend_Registry::set('loadedScripts', $loadedScripts);
return "$styles $scripts" ;
}
protected function loadJavascripts(array $paths, $callback)
{
if(sizeof($paths) == 0)
return;
$currentPath = array_pop($paths);
if(sizeof($paths) > 0)
$nextScript = $this->loadJavascripts($paths, $callback);
else
$nextScript = $callback;
return "$.getScript('$currentPath', function(data, textStatus, jqxhr){ $nextScript }); ";
}
protected function loadStyles(array $paths)
{
if(sizeof($paths) == 0)
return;
$currentPath = array_pop($paths);
if(sizeof($paths) > 0)
$callback = $this->loadStyles($paths);
return "$('<link>').appendTo('head').attr({type : 'text\/css', rel : 'stylesheet'}).attr('href', '$currentPath'); $callback";
}
} | true |
4c77e34e74c2f51df1184b4449d47af74a606f66 | PHP | PhyrusFramework/framework | /phpcli/modules/watcher.php | UTF-8 | 5,141 | 2.78125 | 3 | [] | no_license | <?php
class CLI_Watcher extends CLI_Module {
public function command_create() {
if (sizeof($this->params) == 0) {
echo "\nWatcher name not specified.\n";
return;
}
$name = $this->params[0];
$folder = Path::root() . '/' . Definitions::get('watcher');
create_folder($folder);
$file = "$folder/$name.php";
$content = "<?php\n\nreturn [\n\t'interval' => 60,\n\t'run' => function() {\n\t\t// Do something.\n\t}\n];";
file_put_contents($file, $content);
echo "\nWatcher created.\n";
}
public function command_status() {
$file = Path::root() . '/watcher';
if (!file_exists($file)) {
echo "\nWatcher directory does not exist.\n";
return;
}
$file .= '/pid.lock';
if (!file_exists($file)) {
echo "\nWatcher not running.\n";
return;
}
echo "Watcher is running on process " . file_get_contents($file);
}
public function command_start() {
$file = Path::root() . '/watcher';
if (!file_exists($file)) {
mkdir($file);
}
$file .= '/pid.lock';
if (file_exists($file)) {
echo "\nWatcher already running.\n";
return;
}
$pid = getmypid();
file_put_contents($file, $pid);
echo "\nWatcher running on process $pid\n";
$this->startLoop();
unlink($file);
}
private function gcd($nums) {
if (sizeof($nums) < 2) {
if (sizeof($nums) == 1) return $nums[0];
return 0;
}
if (sizeof($nums) == 2) {
$a = $nums[0];
$b = $nums[1];
if ($b == 0)
return $a;
return $this->gcd([$b, $a % $b]);
}
return $this->gcd($nums[0], $this->gcd(array_slice($nums, 1, sizeof($nums) - 1)));
}
private function startLoop() {
$interval = 1;
$count = 0;
$prev_last_modified = '0000-00-00 00:00:00';
$last_modified = '0000-00-00 00:00:00';
while(true) {
$files = Folder::instance(Path::root() . '/watcher')->subfiles('php');
if (sizeof($files) == 0) {
echo "\nNo watchers active.\n";
return;
}
$watchers = [];
$intervals = [];
foreach($files as $f) {
$w = include($f);
if (!is_array($w)) {
continue;
}
if (!isset($w['interval'])) {
continue;
}
if (!is_numeric($w['interval'])) {
continue;
}
if (!isset($w['run'])) {
continue;
}
$mod = File::instance($f)->modification_date();
if ($mod > $last_modified) {
$last_modified = $mod;
}
$watchers[] = $w;
$intervals[] = $w['interval'];
}
if ($last_modified != $prev_last_modified) {
$interval = $this->gcd($intervals);
$prev_last_modified = $last_modified;
}
if ($count > 0) {
foreach($watchers as $watcher) {
$i = $watcher['interval'];
if (floor($count / $i) == $count / $i) {
$watcher['run']();
}
}
}
if ($interval < 1) {
echo "\nWatcher interval ($interval) too small, stopping process.\n";
break;
}
sleep($interval);
$count += $interval;
}
}
public function command_stop() {
$file = Path::root() . '/watcher';
if (!file_exists($file)) {
echo "\nWatcher not running.\n";
return;
}
$file .= '/pid.lock';
if (!file_exists($file)) {
echo "\nWatcher not running.\n";
return;
}
$pid = file_get_contents($file);
$pid = intval($pid);
if ($pid == 0) {
echo "\nInvalid Watcher process.\n";
return;
}
if (detectOS() == 'windows') {
shell_exec("taskkill /F /PID $pid");
} else {
shell_exec("kill $pid");
}
unlink($file);
echo "\nWatcher stopped\n";
return;
}
public function command_restart() {
$this->command_stop();
$this->command_start();
}
public function help() {?>
The Watcher command is used to run or stop the watcher process.
- create <name>
Create a new watcher script.
- status
Check whether the process is running or not.
- start
Start the process.
- restart
Stop the process if running and start it again.
- stop <key>
Stop the process if running.
<?php }
} | true |
ec9dc60a9483d79999cb3c1668d83b8cf130a3f1 | PHP | yishengjiang99/PhotoRewards-Backend | /tools/trends/web/search.php | UTF-8 | 2,113 | 2.625 | 3 | [] | no_license | <?php
session_start();
include('header.php');
include('searchform.php');
include('../share/config.php');
include('../share/MySqlUtil.php');
if (isset($_GET['keyword']) && isset($_GET['date']) && isset($_GET['total'])) {
$mySqlUtil = new MySqlUtil();
$keyword = $_GET['keyword'];
$date = $_GET['date'];
$total = $_GET['total'];
if (isset($_SESSION['sort'])) {
if (isset($_GET['sort']) && isset($_GET['col'])) {
$_SESSION['sort'] = $mySqlUtil->secureVar($_GET['sort'], 'str');
if ($_SESSION['sort'] == 'asc') {
$_SESSION['sort'] = 'desc';
} else {
$_SESSION['sort'] = 'asc';
}
$_SESSION['col'] = $mySqlUtil->secureVar($_GET['col'], 'str');
if ($_SESSION['col'] != 'keyword' && $_SESSION['col'] != 'date' &&
$_SESSION['col'] != 'total') {
$_SESSION['col'] = 'keyword';
}
}
} else {
$_SESSION['sort'] = 'asc';
$_SESSION['col'] = 'keyword';
}
$trends = $mySqlUtil->searchTrends($keyword, $date, $total,
$_SESSION['sort'], $_SESSION['col']);
if (!empty($trends)) { ?>
<table cellpadding="2" cellspacing="1" border="0" align="center" width="65%">
<tr class="caption">
<?php $url = 'search.php?keyword=' . $keyword . '&date=' . $date .
'&total=' . $total . '&sort=' . $_SESSION['sort'] . '&col='; ?>
<th><a href="<?php echo($url . 'keyword') ?>">Keyword</a></th>
<th widht="100px"><a href="<?php echo($url . 'date') ?>">Date</a></th>
<th widht="100px"><a href="<?php echo($url . 'total') ?>">Total</a></th>
</tr>
<?php
foreach ($trends as $trend) {
echo('<tr><td>' . $trend['keyword'] . '</td><td align="center">' .
$trend['date'] . '</td><td align="center">' . $trend['total'] .
'</td></tr>');
}
?></table><?php
} else {
?><p><strong>Not founded</strong></p><?php
}
}
?>
<?php include('footer.php'); ?> | true |
fd68d9f90324b0e56fd7ff7f1f5664b17ea8ac14 | PHP | lqllife/tp5 | /application/common.php | UTF-8 | 1,468 | 3.125 | 3 | [
"Apache-2.0"
] | permissive | <?php
/**
* print_r()函数优化
*
* @param $str
*/
function p($str){
echo '<div style="border: 1px solid bisque;border-bottom-color:red;border-right-color:red;color:green;background-color: bisque;"><pre>';
print_r($str);
echo '</pre></div>';
}
/**
* var_dump()函数优化
* @param $str
*/
function v($str){
echo '<div style="border: 1px solid bisque;border-bottom-color:red;border-right-color:red;color:green;background-color: bisque;"><pre>';
var_dump($str);
echo '</pre></div>';
}
/**
* dump()函数优化
* @param $str
*/
function d($str){
echo '<div style="border: 1px solid bisque;border-bottom-color:red;border-right-color:red;color:green;background-color: bisque;"><pre>';
dump($str);
echo '</pre></div>';
}
/**
* 打印最近使用的SQL语句
* @param $model
*/
function ps($model){
$re = $model -> getLastSql();
p($re);
}
/**
* 生成订单号
* @return string
*/
function make_orderId(){
$mic = explode(".",(microtime()));
$mictime = $mic[1];
$midtime = explode ( " ", $mictime);
$reftime = $midtime[0]; //取微秒
$time = date("YmdHis",time()); //取年月日时分 //取年月日时分秒
$sdcustomno = $time.$reftime.rand(10,99); //订单在商户系统中的流水号 商户信息+日期+随机数
return $sdcustomno;
} | true |
37f52a8b2da504ce324bf69538656870274e192b | PHP | Chatter-Laravel/core | /src/Models/Discussion.php | UTF-8 | 2,986 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace Chatter\Core\Models;
use Str;
use Auth;
use Chatter\Core\Models\Post;
use Chatter\Core\Traits\TimeAgo;
use Chatter\Core\Models\Category;
use Chatter\Core\Traits\Reactionable;
use Illuminate\Database\Eloquent\Model;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Discussion extends Model implements DiscussionInterface
{
use SoftDeletes, Sluggable, HasFactory, Reactionable, TimeAgo;
public $timestamps = true;
protected $table = 'chatter_discussions';
protected $fillable = ['title', 'category_id', 'color', 'last_reply_at'];
protected $dates = ['deleted_at', 'last_reply_at'];
public function user()
{
return $this->belongsTo(config('chatter.user.namespace'));
}
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
public function posts()
{
return $this->hasMany(Post::class, 'discussion_id');
}
public function users()
{
return $this->belongsToMany(config('chatter.user.namespace'), 'chatter_user_discussion', 'discussion_id', 'user_id');
}
/**
* Returns the post counts without the
* first one because is the discussion
* itself.
*
* @return int
*/
public function postsCount()
{
$count = $this->posts()->count();
return $count > 0 ? $count - 1 : 0;
}
/**
* Sets the body attribute
*
* @param string $value
* @return void
*/
public function setBodyAttribute($value)
{
$this->attributes['body'] = resolve('purifier')->clean($value);
}
/**
* Returs the body attribute
*
* @return string
*/
public function getBodyAttribute()
{
$post = $this->posts()->oldest()->first();
if (null !== $post) {
return Str::words(str_replace(array("\t", "\r", "\n"), '', strip_tags($post->body)), 30);
}
}
/**
* Returns true if the discussion was answered
*
* @return bool
*/
public function getAnsweredAttribute()
{
return $this->postsCount() > 0;
}
/**
* Returns the number of answers the discussion got
*
* @return int
*/
public function getAnswersAttribute()
{
return $this->postsCount();
}
/**
* Returns the last reply of the discussion
*
* @return PostInterface|null
*/
public function getLastReplayAttribute()
{
if ($this->answered) {
return $this->posts()->latest()->first();
}
return null;
}
/**
* Return the sluggable configuration array for this model.
*
* @return array
*/
public function sluggable(): array
{
return [
'slug' => [
'source' => 'title'
]
];
}
}
| true |
58a874f0e1cf76ccc1d2411d0df770f635b43852 | PHP | charles-owen/site-cl | /src/Site/ViewAux.php | UTF-8 | 2,081 | 3.09375 | 3 | [
"MIT"
] | permissive | <?php
/**
* @file
* @brief Abstract base class for auxiliary views.
*/
namespace CL\Site;
/**
* Abstract base class for auxiliary views.
*
* An auxiliary view class is a view that is used by another page view class.
* A view is for a page. An auxiliary view is for some component used by the
* page.
*
* @cond
* @property \CL\Site\View view
* @endcond
*/
abstract class ViewAux {
/**
* Property get magic method
* @param string $property Property name
* @return mixed
*/
public function __get($property) {
switch($property) {
case 'view':
return $this->view;
default:
return PropertyHelper::Error($property);
}
}
/**
* Property set magic method
* @param string $property Property name
* @param mixed $value Value to set
*/
public function __set($property, $value) {
switch($property) {
case 'view':
$this->view = $value;
$this->install($this->view);
break;
case 'script':
$this->script .= $value;
break;
default:
PropertyHelper::Error($property);
break;
}
}
/**
* Called when this auxiliary view is installed in a view
* @param View $view View we are installing into
*/
protected function install(View $view) {
$this->view = $view;
}
/**
* If a file exists, require it as a function and apply to
* this auxiliary view.
*
* Example:
*
* @param Site $site Site object
* @param string $file File relative to decor directory.
*/
public function decorApply(Site $site, $file) {
$path = $site->rootDir . '/' . $site->decor . '/' . $file;
if(file_exists($path)) {
$function = require($path);
if(is_callable($function)) {
$function($this);
}
}
}
/**
* Get content necessary for the head section of the HTML
* @return string HTML for content that needs to be added to the heading
*/
public function head() {
return '';
}
protected $view = null; ///< View we are attached to
} | true |
a8c839a11f12e9bf70e06c76fa8742b2bb906095 | PHP | waqarjan333/dhqhospital | /application/controllers/Profile.php | UTF-8 | 4,108 | 2.515625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Profile extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Profiles');
}
public function user_profile($id)
{
if(isset($_POST['save']))
{
$fname = $this->input->post('fname');
$lname = $this->input->post('lname');
$email = $this->input->post('email');
$phone = $this->input->post('phone');
// Change Password code
$current_pass = $this->input->post('current_pass');
if($current_pass != null)
{
$check = $this->db->select('password')->from('user')->where(array('password'=>md5($current_pass), 'id'=>$id))->get();
$count = $check->num_rows();
if(!($count > 0))
{
$this->session->set_flashdata('error', 'You Enter Wrong Password, Please Try again!! Or Contact Admin');
redirect('Profile/user_profile/'.$id);
}
else
{
$new_pass = $this->input->post('new_pass');
$again_new_pass = $this->input->post('again_new_pass');
if($new_pass == $again_new_pass)
{
$array = array(
'f_name'=>$fname,
'l_name'=>$lname,
'password'=>md5($new_pass),
'email' => $email,
'contact'=>$phone,
);
}
else
{
$this->session->set_flashdata('error', 'New Password & Confirm New Password Did Not Match With Each Other, TRY AGAIN !!!');
redirect('Profile/user_profile/'.$id);
}
}
}
else
{
$array = array(
'f_name'=>$fname,
'l_name'=>$lname,
'email' => $email,
'contact'=>$phone,
);
}
$page_data['record'] = $this->db->where('id', $id);
$page_data['record'] = $this->db->update('user', $array);
$page_data['id']=$id;
$page_data['page_name'] = 'show-profile';
$this->load->view('index', $page_data);
$this->session->set_flashdata('message', 'Profile Update Successfully');
redirect('Profile/user_profile/'.$id);
}
else
{
$query = $this->db->query("select * from user where id=".$id);
$page_data['record'] = $query->result_array();
$page_data['id']=$id;
$page_data['page_name1'] = 'show-profile';
$page_data['page_name'] = 'show-profile';
$this->load->view('index', $page_data);
}
}
public function system_settings()
{
if(isset($_POST['save']))
{
// $this->load->library('upload');
$config = array(
'upload_path' => './images',
'allowed_types' => "gif|jpg|png|jpeg|pdf"
);
$this->load->library('upload', $config);
$this->upload->initialize($config);
$hname = $this->input->post('hname');
$address = $this->input->post('address');
if($this->upload->do_upload('logo'))
{
$data = $this->upload->data();
$image_path = base_url("images/" . $data['raw_name'] . $data['file_ext']);
// echo $image_path; exit;
$array = array(
'name'=>$hname,
'address'=>$address,
'logo'=>$image_path
);
$save=$this->db->insert('hospital_info',$array);
if($save)
{
$this->session->set_flashdata('message', 'Hospital Informations Successfully Saved');
redirect('Profile/system_settings/');
}
else{
$this->session->set_flashdata('message', 'Error Occured During Image Uploading');
redirect('Profile/system_settings/');
}
}
else{
$page_data['upload_error']=$this->upload->display_errors();
$page_data['page_name1'] = 'settings';
$page_data['page_name'] = 'settings';
$this->load->view('index',$page_data);
}
}
else{
$page_data['page_name1'] = 'settings';
$page_data['page_name'] = 'settings';
$this->load->view('index',$page_data);
}
}
public function delete_info($id)
{
$this->db->where('id',$id);
$result =$this->db->delete('hospital_info');
if($result)
{
$this->session->set_flashdata('message', 'Informations Deleted Successfully');
redirect('Profile/system_settings');
}
else
{
$this->session->set_flashdata('message', 'Error While Deleting Informations');
redirect('Profile/system_settings');
}
}
}
| true |
237d6e0274a4787ae43d596bb732f186f2bd12a1 | PHP | EdisonLabs/janrain_capture | /includes/janrain_capture.widget.inc | UTF-8 | 18,094 | 2.703125 | 3 | [] | no_license | <?php
/**
* @file
* Widget-related functions
*/
/**
* Check if the screens are hosted remotely
*/
function _janrain_capture_widget_is_remote_screens() {
$screenPath = variable_get('janrain_capture_screens_folder', NULL);
return (strpos($screenPath, 'http') === 0);
}
/**
* Update the local cache of remote JTL and Event files aka "Screens".
*/
function janrain_capture_widget_update_remote_screens() {
// wtb oop or enums
static $allowedScreens = array('signin', 'edit-profile', 'public-profile', 'forgot', 'verify');
static $allowedTypes = array('js', 'html');
$cacheDir = JANRAIN_CAPTURE_WIDGET_SCREEN_CACHE_DIR;
// make sure cache directory is ready for files
if (!file_prepare_directory($cacheDir, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
// cache dir failure, notify and bail
watchdog('janrain_capture',
'Failed to create screen cache directory: %directory',
array('%directory' => $cacheDir),
WATCHDOG_ERROR);
return;
}
// hook cron shouldn't run this but lets sanity check anyway
if (!_janrain_capture_widget_is_remote_screens()) {
return;
}
$screenSourceDir = variable_get('janrain_capture_screens_folder');
$sourcePathTemplate = '%s%s.%s';
$destPathTemplate = '%s/%s.%s';
// grab each file
foreach ($allowedScreens as &$name) {
foreach ($allowedTypes as &$ext) {
$screenSource = sprintf($sourcePathTemplate, $screenSourceDir, $name, $ext);
$screenDest = sprintf($destPathTemplate, $cacheDir, $name, $ext);
$response = drupal_http_request($screenSource);
if ($response->code != 200) {
// notify there was an issue, but try to get the other files
watchdog('janrain_capture', $response->error, array(), WATCHDOG_ERROR);
continue;
}
// use unmanaged since remote source is always authoritative
$success = file_unmanaged_save_data($response->data, $screenDest, FILE_EXISTS_REPLACE);
if (FALSE === $success) {
// failed to save a file that was succesfully downloaded
watchdog('janrain_capture', "Failed to write %screenDest", array('screenDest' => $screenDest), WATCHDOG_ERROR);
}
}
}
}
/**
* Get the contents of a JTL or events file
* @param string screenName
* The type of screen (signin, forgot, etc...)
* @param string fileType
* 'html' for JTL or 'js' for events
* @return string
* return empty string on error conditions, otherwise returns the JTL or javascript content of the file.
*/
function _janrain_capture_widget_get_screen($screenName, $fileType) {
global $base_url;
// wtb oop
static $allowedScreens = array('signin', 'edit-profile', 'public-profile', 'forgot', 'verify');
static $allowedTypes = array('js', 'html');
// sanity check that it's a valid screen request
if (!(in_array($screenName, $allowedScreens) && in_array($fileType, $allowedTypes))) {
// no such screen exists, return empty string.
return '';
}
// check for screens module
if (module_exists('janrain_capture_screens')) {
$fileName = sprintf('%s.%s', $screenName, $fileType);
// proceed with screens module
if (!in_array($fileName, _janrain_capture_get_screens())) {
return '';
}
if ($screen_file = _janrain_capture_get_screen_file($fileName)) {
return file_get_contents($screen_file);
}
return '';
}
// screen name and type are valid get the content
if (_janrain_capture_widget_is_remote_screens()) {
// files are remote so pull from local cache (updated by _janrain_capture_widget_update_screens();
$fileName = sprintf('%s/%s.%s', JANRAIN_CAPTURE_WIDGET_SCREEN_CACHE_DIR, $screenName, $fileType);
}
else {
$screenPath = variable_get('janrain_capture_screens_folder', 'file:///sites/all/themes/janrain-capture-screens/');
if (strpos($screenPath, 'file:///', 0) === 0) {
// files are local, usually in sites/all/themes
$fileName = sprintf('%s%s%s.%s', DRUPAL_ROOT, str_replace('file://', '', $screenPath), $screenName, $fileType);
}
else {
// invalid screens folder setting
$fileName = sprintf('%s/janrain-capture-screens/%s.%s', drupal_get_path('module', 'janrain_capture'), $screenName, $fileType);
}
}
if (!is_readable($fileName)) {
// let everyone know there was a problem with the file, but don't kill the site.
drupal_set_message("Unable to read $fileName", 'error');
return '';
}
// file exists and is readable, return the contents.
return file_get_contents($fileName);
}
/**
* Adds widget JS settings to the page.
*/
function janrain_capture_widget_add_settings($settings = array()) {
// Widget settings
$janrain_capture_main = variable_get('janrain_capture_main2', array());
$janrain_capture_main = array_merge($janrain_capture_main, variable_get('janrain_capture_ui2', array()));
$janrain_capture_optional = variable_get('janrain_capture_federate2', array());
$janrain_capture_optional = array_merge($janrain_capture_optional, variable_get('janrain_capture_backplane2', array()));
if (!empty($janrain_capture_optional['capture_sso_address'])) {
$settings['janrainCapture']['sso_address'] = $janrain_capture_optional['capture_sso_address'];
}
if (isset($janrain_capture_optional['backplane_enabled'])
&& !empty($janrain_capture_optional['backplane_bus_name'])) {
$settings['janrainCapture']['backplane_enabled'] = $janrain_capture_optional['backplane_enabled'];
$settings['janrainCapture']['backplane_bus_name'] = $janrain_capture_optional['backplane_bus_name'];
}
// Add settings array into a JS variable
drupal_add_js($settings, array('type' => 'setting', 'every_page' => TRUE, 'preprocess' => FALSE, 'weight' => 0, 'scope' => 'header',));
}
/**
* Adds widget JS scripts to the page.
*/
function janrain_capture_widget_add_scripts() {
global $base_url;
// File scripts
drupal_add_js(drupal_get_path('module', 'janrain_capture') . '/janrain_capture.js', array(
'type' => 'file',
'every_page' => TRUE,
'weight' => 1,
'preprocess' => FALSE,
'scope' => 'header',));
$widget = array(
'#type' => 'markup',
'#prefix' => '<script type="text/javascript">',
'#suffix' => '</script>',
'#markup' => janrain_capture_widget_js(),
'#weight' => 3,
);
$capture_client = array(
'#type' => 'markup',
'#prefix' => '<script type="text/javascript" src="https://d7v0k4dt27zlp.cloudfront.net/assets/capture_client.js">',
'#suffix' => '</script>',
'#markup' => '',
'#weight' => 2,
);
$capture_js = array(
'#type' => 'markup',
'#prefix' => '<script type="text/javascript" src="'. $base_url . '/' . drupal_get_path('module', 'janrain_capture') . '/janrain_capture.js">',
'#suffix' => '</script>',
'#markup' => '',
'#weight' => 1,
);
drupal_add_html_head($widget, 'janrain_capture_widget_js');
drupal_add_html_head($capture_client, 'janrain_capture_client_js');
}
/**
* Returns Capture widget js.
*/
function janrain_capture_widget_js() {
global $base_url;
global $base_path;
global $language;
$janrain_settings = variable_get('janrain_capture_fields2', array());
$janrain_settings = array_merge($janrain_settings, variable_get('janrain_capture_main2', array()));
$janrain_settings = array_merge($janrain_settings, variable_get('janrain_capture_ui2', array()));
$janrain_settings = array_merge($janrain_settings, variable_get('janrain_capture_federate2', array()));
$janrain_settings = array_merge($janrain_settings, variable_get('janrain_capture_backplane2', array()));
$janrain_settings = array_merge($janrain_settings, variable_get('janrain_capture_engage2', array()));
// module
$settings["plex.moduleVersion"] = JANRAIN_CAPTURE_MODULE_VERSION;
// capture
$settings["capture.redirectUri"] = url('janrain_capture/oauth', array('absolute' => TRUE));
$settings["capture.appId"] = $janrain_settings['capture_app_id'];
$settings["capture.clientId"] = $janrain_settings['capture_client_id'];
$settings["capture.responseType"] = "code";
$settings["capture.captureServer"] = $janrain_settings['capture_address'];
$settings["capture.loadJsUrl"] = $janrain_settings['load_js'];
$share_settings = variable_get('janrain_capture_share', array());
if (isset($share_settings["enabled"]) && $share_settings["enabled"]) {
$settings["packages"] = '["login","capture","share"]';
}
else {
$settings["packages"] = '["login","capture"]';
}
// engage
$settings["appUrl"] = $janrain_settings['engage_address'];
if (!empty($janrain_settings['engage_providers'])) {
$provider_names = explode(',', $janrain_settings['engage_providers']);
if ($provider_names) {
$settings["providers"] = json_encode($provider_names);
}
}
// federate
$settings["capture.federate"] = $janrain_settings['capture_sso_enabled'];
$settings["capture.federateServer"] = 'https://' . $janrain_settings['capture_sso_address'];
$settings["capture.federateXdReceiver"] = $base_url . base_path() . drupal_get_path('module', 'janrain_capture') . '/xdcomm.html';
$settings["capture.federateLogoutUri"] = url('janrain_capture/simple_logout', array('absolute' => TRUE));
$settings["capture.federateSegment"] = isset($janrain_settings['capture_sso_segment_name']) ? $janrain_settings['capture_sso_segment_name'] : '';
if (isset($janrain_settings['capture_sso_supported_segment_names'])) {
$segment_names = explode(',', $janrain_settings['capture_sso_supported_segment_names']);
if ($segment_names) {
$settings["capture.federateSupportedSegments"] = json_encode($segment_names);
}
}
// backplane
$settings["capture.backplane"] = $janrain_settings['backplane_enabled'];
$settings["capture.backplaneServerBaseUrl"] = isset($janrain_settings['backplane_server_base_url']) ? $janrain_settings['backplane_server_base_url'] : '';
$settings["capture.backplaneBusName"] = $janrain_settings['backplane_bus_name'];
$settings["capture.backplaneVersion"] = $janrain_settings['backplane_version'];
// miscellaneous
$settings["capture.language"] = $language->language;
$settings["mobileFriendly"] = empty($janrain_settings['mobile_friendly']) ? FALSE : (bool) $janrain_settings['mobile_friendly'];
if (module_exists('janrain_capture_screens')) {
$settings["capture.stylesheets"] = "'" . file_create_url(_janrain_capture_get_screen_file('stylesheets/styles.css')) . "'";
if ($mobile_stylesheet = _janrain_capture_get_screen_file('stylesheets/mobile-styles.css')) {
$settings["capture.mobileStylesheets"] = "'" . file_create_url($mobile_stylesheet) . "'";
}
if ($ie_stylesheet = _janrain_capture_get_screen_file('stylesheets/ie-styles.css')) {
$settings["capture.conditionalIEStylesheets"] = "'" . file_create_url($ie_stylesheet) . "'";
}
}
else {
$folder_url = variable_get('janrain_capture_screens_folder', 'file:///sites/all/themes/janrain-capture-screens/');
// If path is local, search for user agent-specific stylesheets in the file system.
if (strpos($folder_url, 'file:///', 0) === 0) {
// Example of $folder_url: file:///sites/all/themes/janrain-capture-screens/
$web_path = str_replace('file://', '', $folder_url);
// Example of $web_path: /sites/all/themes/janrain-capture-screens/
$fs_path = DRUPAL_ROOT . $web_path;
// Example of $fs_path: /var/www/d7/sites/all/themes/janrain-capture-screens/
$web_url = $base_url . $web_path;
$base_stylesheet_path = "'{$web_url}stylesheets/janrain.css'";
$mobile_stylesheet_path = "'{$web_url}stylesheets/janrain_mobile.css'";
$ie_stylesheet_path = "'{$web_url}stylesheets/janrain_ie.css'";
$settings["capture.stylesheets"] = $base_stylesheet_path;
$settings["capture.mobileStylesheets"] = $mobile_stylesheet_path;
$settings["capture.conditionalIEStylesheets"] = $ie_stylesheet_path;
}
else {
// Remote stylesheets
$settings["capture.stylesheets"] = "'{$folder_url}stylesheets/janrain.css'";
$settings["capture.mobileStylesheets"] = "'{$folder_url}stylesheets/janrain_mobile.css'";
$settings["capture.conditionalIEStylesheets"] = "'{$folder_url}stylesheets/janrain_ie.css'";
}
// Log a warning if directories are setup properly but no stylesheets were found
if (!count($settings["capture.stylesheets"]) && !count($settings["capture.mobileStylesheets"]) && !count($settings["capture.conditionalIEStylesheets"])) {
watchdog('janrain_capture',
'No stylesheets were found in the screens folder (@path). Please check the Janrain Capture module settings.',
array('@path' => $fs_path ?: $folder_url),
WATCHDOG_WARNING,
l(t('Janrain Capture module settings'), 'admin/config/people/janrain_capture'));
}
}
$output = <<<EOD
function janrainSignOut(){
janrain.capture.ui.endCaptureSession();
}
(function() {
if (typeof window.janrain !== 'object') window.janrain = {};
window.janrain.plex = {};
window.janrain.settings = {};
window.janrain.settings.capture = {};
// module settings
janrain.plex.moduleVersion = '{$settings["plex.moduleVersion"]}';
// capture settings
janrain.settings.capture.redirectUri = '{$settings["capture.redirectUri"]}';
janrain.settings.capture.appId= '{$settings["capture.appId"]}';
janrain.settings.capture.clientId = '{$settings["capture.clientId"]}';
janrain.settings.capture.responseType = '{$settings["capture.responseType"]}';
janrain.settings.capture.captureServer = '{$settings["capture.captureServer"]}';
janrain.settings.capture.registerFlow = 'socialRegistration';
janrain.settings.packages = {$settings['packages']};
janrain.settings.capture.setProfileCookie = true;
janrain.settings.capture.keepProfileCookieAfterLogout = true;
janrain.settings.capture.setProfileData = true;
janrain.settings.capture.federateEnableSafari = true;
// styles
janrain.settings.capture.stylesheets = [{$settings["capture.stylesheets"]}];\n
EOD;
// mobile styles
if (isset($settings["capture.mobileStylesheets"]) && $settings["capture.mobileStylesheets"] != '') {
$output .= "janrain.settings.capture.mobileStylesheets = [{$settings['capture.mobileStylesheets']}];\n";
}
//IE styles
if (isset($settings["capture.conditionalIEStylesheets"]) && $settings["capture.conditionalIEStylesheets"] != '') {
$output .= "janrain.settings.capture.conditionalIEStylesheets = [{$settings['capture.conditionalIEStylesheets']}];\n";
}
// captcha
$output .= "janrain.settings.capture.recaptchaPublicKey = '6LeVKb4SAAAAAGv-hg5i6gtiOV4XrLuCDsJOnYoP';\n";
$output .= <<<EOD
// engage settings
janrain.settings.appUrl = '{$settings["appUrl"]}';
janrain.settings.tokenAction = 'event';\n
EOD;
if (isset($settings["providers"])){
$output .= "janrain.settings.providers = {$settings["providers"]}";
}
// Backplane
if ($settings["capture.backplane"]) {
$output .= <<<EOD
// backplane settings
janrain.settings.capture.backplane = '{$settings["capture.backplane"]}';
janrain.settings.capture.backplaneBusName = '{$settings["capture.backplaneBusName"]}';
janrain.settings.capture.backplaneVersion = '{$settings["capture.backplaneVersion"]}';\n
EOD;
if ($settings['capture.backplaneServerBaseUrl']) {
$output .= "janrain.settings.capture.backplaneServerBaseUrl = 'https://{$settings['capture.backplaneServerBaseUrl']}';\n";
}
}
if ($settings["capture.federate"]) {
$output .= <<<EOD
// federate settings
janrain.settings.capture.federate = '{$settings["capture.federate"]}';
janrain.settings.capture.federateServer = '{$settings["capture.federateServer"]}';
janrain.settings.capture.federateXdReceiver = '{$settings["capture.federateXdReceiver"]}';
janrain.settings.capture.federateLogoutUri = '{$settings["capture.federateLogoutUri"]}';\n
EOD;
if (isset($settings["capture.federateSegment"])) {
$output .= "janrain.settings.capture.federateSegment = '{$settings["capture.federateSegment"]}';\n";
}
if (isset($settings["capture.federateSupportedSegments"])) {
$output .= "janrain.settings.capture.federateSupportedSegments = {$settings["capture.federateSupportedSegments"]};\n";
}
}
if ($settings["capture.language"]) {
$output .= "janrain.settings.language = '{$settings["capture.language"]}';\n";
}
if ($settings["mobileFriendly"]) {
global $base_root;
$current_url = $base_root . request_uri();
$_SESSION['janrain_capture_redirect_uri'] = $current_url;
$output .=
"\n// mobile-specific settings
janrain.settings.tokenAction = 'url';
janrain.settings.popup = false;
janrain.settings.tokenUrl = janrain.settings.capture.captureServer;
janrain.settings.capture.redirectUri = '{$current_url}';
janrain.settings.capture.redirectFlow = true;\n";
}
else {
if (isset($_SESSION['janrain_capture_redirect_uri'])) {
unset($_SESSION['janrain_capture_redirect_uri']);
}
}
if (!isset($_SESSION['janrain_capture_access_token'])) {
$api = new JanrainCaptureApi();
$api->refreshAccessToken();
}
$access_token = "var access_token = '";
$access_token .= isset($_SESSION['janrain_capture_access_token']) ? $_SESSION['janrain_capture_access_token'] : "";
$access_token .= "';";
$output .= <<<EOD
function isReady() { janrain.ready = true; };
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", isReady, false);
} else {
window.attachEvent('onload', isReady);
}
var e = document.createElement('script');
e.type = 'text/javascript';
e.id = 'janrainAuthWidget';
var url = document.location.protocol === 'https:' ? 'https://' : 'http://';
url += '{$settings["capture.loadJsUrl"]}';
e.src = url;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(e, s);
})();
{$access_token}
EOD;
return $output;
}
| true |
cf7443b67f67c4576b87f11bf7c02aeeef539383 | PHP | yiisolutions/yii2-last-lesson | /models/Group.php | UTF-8 | 1,489 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "group".
*
* @property integer $id
* @property string $name
* @property integer $teacher_id
*
* @property Teacher $teacher
* @property Lesson[] $lessons
*/
class Group extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'group';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'teacher_id'], 'required'],
[['teacher_id'], 'integer'],
[['name'], 'string', 'max' => 255],
[['teacher_id'], 'exist', 'skipOnError' => true, 'targetClass' => Teacher::className(), 'targetAttribute' => ['teacher_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'teacher_id' => 'Teacher ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getTeacher()
{
return $this->hasOne(Teacher::className(), ['id' => 'teacher_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getLessons()
{
return $this->hasMany(Lesson::className(), ['group_id' => 'id']);
}
/**
* Return group name
*
* @return string
*/
public function __toString()
{
return $this->name;
}
}
| true |
9e5975996384dade7359b6cb5c38248d0ceb9872 | PHP | farestakorabt/carrousel | /firstDay/7.2_exos.php | UTF-8 | 1,077 | 3.296875 | 3 | [] | no_license | <?php
// function continuer() {
// $i = 0;
// while(true)
// {
// $reponse = readline("Voulez vous continuer ? \n");
// if($reponse === "non")
// {
// echo "salut !";
// return false;
// } else {
// $i++;
// if($i == 2)
// {
// echo "Vous etes tenace ! \n";
// } elseif($i == 3)
// {
// echo "Vous etes collant ! \n";
// }
// }
// }
// };
// continuer();
function continuer() {
$i = 0;
$reponse = readline("Voulez vous continuer ? \n");
if($reponse === "non")
{
return false;
} elseif ($reponse === "oui")
{
$i++;
} else {
echo "Vous avez mal répondu \n";
}
if($i == 2){
echo "Vous etes tenace ! \n";
}
if($i == 3){
echo "Vous etes collant ! \n";
}
if($i == 4){
echo "Vous etes tenace ! \n";
}
}
continuer(); | true |
7b5aa72414a05ec1ec5e5b21cf9b37d33b3823ab | PHP | SrirangaDigital/tattvaloka | /php/get-parts.php | UTF-8 | 1,273 | 2.65625 | 3 | [] | no_license | <?php
include("connect.php");
require_once("common.php");
if(isset($_GET['volume'])){$volume = $_GET['volume'];}else{$volume = '';}
if(!(isValidVolume($volume)))
{
exit(1);
}
$query = "select distinct part,month,year from article where volume='$volume' order by part";
$result = $db->query($query);
$num_rows = $result ? $result->num_rows : 0;
echo '<div id="issueHolder" class="issueHolder"><div class="issue">';
if($num_rows > 0)
{
$isFirst = 1;
while($row = $result->fetch_assoc())
{
$part = $row['part'];
$dpart = preg_replace("/^0/", "", $part);
$dpart = preg_replace("/\-0/", "-", $dpart);
echo (($row['month'] == '01') && ($isFirst == 0)) ? '<div class="deLimiter">|</div>' : '';
$monthdetails = getMonth($row['month']) . ", " . $row['year'];
$monthdetails = preg_replace('/^,/', '', $monthdetails);
if($row['part'] == '99')
{
echo '<div class="aIssue"><a href="toc.php?vol=' . $volume . '&part=' . $row['part'] . '" title=Special Issue>Special Issue</a></div>';
}
else
{
echo '<div class="aIssue"><a href="toc.php?vol=' . $volume . '&part=' . $row['part'] . '" title="'. $monthdetails .'">Issue ' . $dpart . '</a></div>';
}
$isFirst = 0;
}
}
echo '</div></div>';
if($result){$result->free();}
$db->close();
?>
| true |
189ef5ee8e88fdaf872ceb1054e2e4207483015c | PHP | wenz/core | /tests/lib/ConfigTest.php | UTF-8 | 11,337 | 2.671875 | 3 | [
"GPL-3.0-or-later",
"BSD-3-Clause",
"GPL-1.0-or-later",
"AGPL-3.0-or-later",
"MIT",
"AGPL-3.0-only"
] | permissive | <?php
/**
* Copyright (c) 2013 Bart Visscher <bartv@thisnet.nl>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
namespace Test;
use Symfony\Component\EventDispatcher\GenericEvent;
/**
* Class ConfigTest
*
* @group DB
* @package Test
*/
class ConfigTest extends TestCase {
const TESTCONTENT = '<?php $CONFIG=array("foo"=>"bar", "beers" => array("Appenzeller", "Guinness", "Kölsch"), "alcohol_free" => false);';
/** @var array */
private $initialConfig = ['foo' => 'bar', 'beers' => ['Appenzeller', 'Guinness', 'Kölsch'], 'alcohol_free' => false];
/** @var string */
private $configFile;
/** @var \OC\Config */
private $config;
/** @var string */
private $randomTmpDir;
protected function setUp(): void {
parent::setUp();
$this->randomTmpDir = \OC::$server->getTempManager()->getTemporaryFolder();
$this->configFile = $this->randomTmpDir.'testconfig.php';
\file_put_contents($this->configFile, self::TESTCONTENT);
$this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php');
}
protected function tearDown(): void {
\unlink($this->configFile);
parent::tearDown();
}
public function testGetKeys() {
$expectedConfig = ['foo', 'beers', 'alcohol_free'];
$this->assertSame($expectedConfig, $this->config->getKeys());
}
public function testGetValue() {
$this->assertSame('bar', $this->config->getValue('foo'));
$this->assertNull($this->config->getValue('bar'));
$this->assertSame('moo', $this->config->getValue('bar', 'moo'));
$this->assertFalse($this->config->getValue('alcohol_free', 'someBogusValue'));
$this->assertSame(['Appenzeller', 'Guinness', 'Kölsch'], $this->config->getValue('beers', 'someBogusValue'));
$this->assertSame(['Appenzeller', 'Guinness', 'Kölsch'], $this->config->getValue('beers'));
}
public function testGetValueReturnsEnvironmentValueIfSet() {
$this->assertEquals('bar', $this->config->getValue('foo'));
try {
\putenv('OC_foo=baz');
$this->assertEquals('baz', $this->config->getValue('foo'));
} finally {
// Always remove the env var, otherwise it will effect later tests
\putenv('OC_foo');
}
}
public function testSetValue() {
$this->config->setValue('foo', 'moo');
$expectedConfig = $this->initialConfig;
$expectedConfig['foo'] = 'moo';
$this->checkConfigMatchesExpected($expectedConfig);
$expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
" 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
$this->assertStringEqualsFile($this->configFile, $expected);
$calledBeforeSetValue = [];
$calledAfterSetValue = [];
\OC::$server->getEventDispatcher()->addListener('config.beforesetvalue',
function (GenericEvent $event) use (&$calledBeforeSetValue) {
$calledBeforeSetValue[] = 'config.beforesetvalue';
$calledBeforeSetValue[] = $event;
});
\OC::$server->getEventDispatcher()->addListener('config.aftersetvalue',
function (GenericEvent $event) use (&$calledAfterSetValue) {
$calledAfterSetValue[] = 'config.aftersetvalue';
$calledAfterSetValue[] = $event;
});
$this->config->setValue('bar', 'red');
$this->config->setValue('apps', ['files', 'gallery']);
$expectedConfig['bar'] = 'red';
$expectedConfig['apps'] = ['files', 'gallery'];
$this->checkConfigMatchesExpected($expectedConfig);
$this->assertInstanceOf(GenericEvent::class, $calledBeforeSetValue[1]);
$this->assertInstanceOf(GenericEvent::class, $calledAfterSetValue[1]);
$this->assertEquals('config.beforesetvalue', $calledBeforeSetValue[0]);
$this->assertEquals('config.aftersetvalue', $calledAfterSetValue[0]);
$this->assertArrayHasKey('key', $calledBeforeSetValue[1]);
$this->assertArrayHasKey('value', $calledBeforeSetValue[1]);
$this->assertArrayHasKey('key', $calledAfterSetValue[1]);
$this->assertArrayHasKey('value', $calledAfterSetValue[1]);
$this->assertArrayHasKey('update', $calledAfterSetValue[1]);
$this->assertArrayHasKey('oldvalue', $calledAfterSetValue[1]);
$expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
" 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'bar' => 'red',\n 'apps' => \n " .
" array (\n 0 => 'files',\n 1 => 'gallery',\n ),\n);\n";
$this->assertStringEqualsFile($this->configFile, $expected);
}
public function testSetValues() {
$this->assertStringEqualsFile($this->configFile, self::TESTCONTENT);
// Changing configs to existing values and deleting non-existing once
// should not rewrite the config.php
$this->config->setValues([
'foo' => 'bar',
'not_exists' => null,
]);
$this->checkConfigMatchesExpected($this->initialConfig);
$this->assertStringEqualsFile($this->configFile, self::TESTCONTENT);
$calledBeforeUpdate = [];
\OC::$server->getEventDispatcher()->addListener('config.beforesetvalue',
function (GenericEvent $event) use (&$calledBeforeUpdate) {
$calledBeforeUpdate[] = 'config.beforesetvalue';
$calledBeforeUpdate[] = $event;
});
$calledAfterUpdate = [];
\OC::$server->getEventDispatcher()->addListener('config.aftersetvalue',
function (GenericEvent $event) use (&$calledAfterUpdate) {
$calledAfterUpdate[] = 'config.aftersetvalue';
$calledAfterUpdate[] = $event;
});
$this->config->setValues([
'foo' => 'moo',
'alcohol_free' => null,
]);
$expectedConfig = $this->initialConfig;
$expectedConfig['foo'] = 'moo';
unset($expectedConfig['alcohol_free']);
$this->checkConfigMatchesExpected($expectedConfig);
$this->assertInstanceOf(GenericEvent::class, $calledBeforeUpdate[1]);
$this->assertInstanceOf(GenericEvent::class, $calledAfterUpdate[1]);
$this->assertEquals('config.beforesetvalue', $calledBeforeUpdate[0]);
$this->assertEquals('config.aftersetvalue', $calledAfterUpdate[0]);
$this->assertArrayHasKey('key', $calledBeforeUpdate[1]);
$this->assertEquals('foo', $calledBeforeUpdate[1]->getArgument('key'));
$this->assertArrayHasKey('value', $calledBeforeUpdate[1]);
$this->assertEquals('moo', $calledBeforeUpdate[1]->getArgument('value'));
$this->assertArrayHasKey('key', $calledAfterUpdate[1]);
$this->assertEquals('foo', $calledAfterUpdate[1]->getArgument('key'));
$this->assertArrayHasKey('value', $calledAfterUpdate[1]);
$this->assertEquals('moo', $calledAfterUpdate[1]->getArgument('value'));
$this->assertArrayHasKey('update', $calledAfterUpdate[1]);
$this->assertTrue($calledAfterUpdate[1]->getArgument('update'));
$this->assertArrayHasKey('oldvalue', $calledAfterUpdate[1]);
$this->assertEquals('bar', $calledAfterUpdate[1]->getArgument('oldvalue'));
$expected = "<?php\n\$CONFIG = array (\n 'foo' => 'moo',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
" 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n);\n";
$this->assertStringEqualsFile($this->configFile, $expected);
$calledBeforeDelete = [];
\OC::$server->getEventDispatcher()->addListener('config.beforedeletevalue',
function (GenericEvent $event) use (&$calledBeforeDelete) {
$calledBeforeDelete[] = 'config.beforedeletevalue';
$calledBeforeDelete[] = $event;
});
$calledAfterDelete = [];
\OC::$server->getEventDispatcher()->addListener('config.afterdeletevalue',
function (GenericEvent $event) use (&$calledAfterDelete) {
$calledAfterDelete[] = 'config.afterdeletevalue';
$calledAfterDelete[] = $event;
});
$this->config->setValues([
'foo' => null
]);
$this->assertInstanceOf(GenericEvent::class, $calledBeforeDelete[1]);
$this->assertInstanceOf(GenericEvent::class, $calledAfterDelete[1]);
$this->assertEquals('config.beforedeletevalue', $calledBeforeDelete[0]);
$this->assertEquals('config.afterdeletevalue', $calledAfterDelete[0]);
$this->assertArrayHasKey('key', $calledBeforeDelete[1]);
$this->assertEquals('foo', $calledBeforeDelete[1]->getArgument('key'));
$this->assertArrayHasKey('value', $calledBeforeDelete[1]);
$this->assertNull($calledBeforeDelete[1]->getArgument('value'));
$this->assertArrayHasKey('key', $calledAfterDelete[1]);
$this->assertEquals('foo', $calledAfterDelete[1]->getArgument('key'));
$this->assertArrayHasKey('value', $calledAfterDelete[1]);
$this->assertEquals('moo', $calledAfterDelete[1]->getArgument('value'));
}
public function testDeleteKey() {
$calledBeforeDeleteValue = [];
$calledAfterDeleteValue = [];
\OC::$server->getEventDispatcher()->addListener('config.beforedeletevalue',
function (GenericEvent $event) use (&$calledBeforeDeleteValue) {
$calledBeforeDeleteValue[] = 'config.beforedeletevalue';
$calledBeforeDeleteValue[] = $event;
});
\OC::$server->getEventDispatcher()->addListener('config.afterdeletevalue',
function (GenericEvent $event) use (&$calledAfterDeleteValue) {
$calledAfterDeleteValue[] = 'config.afterdeletevalue';
$calledAfterDeleteValue[] = $event;
});
$this->config->deleteKey('foo');
$expectedConfig = $this->initialConfig;
unset($expectedConfig['foo']);
$this->checkConfigMatchesExpected($expectedConfig);
$this->assertInstanceOf(GenericEvent::class, $calledBeforeDeleteValue[1]);
$this->assertInstanceOf(GenericEvent::class, $calledBeforeDeleteValue[1]);
$this->assertEquals('config.beforedeletevalue', $calledBeforeDeleteValue[0]);
$this->assertEquals('config.afterdeletevalue', $calledAfterDeleteValue[0]);
$this->assertArrayHasKey('key', $calledBeforeDeleteValue[1]);
$this->assertArrayHasKey('key', $calledAfterDeleteValue[1]);
$expected = "<?php\n\$CONFIG = array (\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
" 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n);\n";
$this->assertStringEqualsFile($this->configFile, $expected);
}
public function testConfigMerge() {
// Create additional config
$additionalConfig = '<?php $CONFIG=array("php53"=>"totallyOutdated");';
$additionalConfigPath = $this->randomTmpDir.'additionalConfig.testconfig.php';
\file_put_contents($additionalConfigPath, $additionalConfig);
// Reinstantiate the config to force a read-in of the additional configs
$this->config = new \OC\Config($this->randomTmpDir, 'testconfig.php');
// Ensure that the config value can be read and the config has not been modified
$this->assertSame('totallyOutdated', $this->config->getValue('php53', 'bogusValue'));
$this->assertStringEqualsFile($this->configFile, self::TESTCONTENT);
// Write a new value to the config
$this->config->setValue('CoolWebsites', ['demo.owncloud.org', 'owncloud.org', 'owncloud.com']);
$expected = "<?php\n\$CONFIG = array (\n 'foo' => 'bar',\n 'beers' => \n array (\n 0 => 'Appenzeller',\n " .
" 1 => 'Guinness',\n 2 => 'Kölsch',\n ),\n 'alcohol_free' => false,\n 'php53' => 'totallyOutdated',\n 'CoolWebsites' => \n array (\n " .
" 0 => 'demo.owncloud.org',\n 1 => 'owncloud.org',\n 2 => 'owncloud.com',\n ),\n);\n";
$this->assertStringEqualsFile($this->configFile, $expected);
// Cleanup
\unlink($additionalConfigPath);
}
private function checkConfigMatchesExpected($expectedConfig) {
foreach ($expectedConfig as $key => $value) {
$this->assertEquals($value, $this->config->getValue($key));
}
}
}
| true |
3ceab9b36f47035f80d8b39fb1fbd1736739b227 | PHP | deniskoronets/ZNU-Diploma | /app/Models/DatedLesson.php | UTF-8 | 715 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class DatedLesson extends Model {
protected $table = 'dated_lessons';
public $timestamps = false;
protected $fillable = [
'user_id', 'faculty_id', 'group_id',
'lesson_type_id', 'discipline_id',
'year', 'semester', 'date_of',
];
public function discipline() {
return $this->belongsTo(Discipline::class, 'discipline_id', 'id');
}
public function faculty() {
return $this->belongsTo(Faculty::class, 'faculty_id', 'id');
}
public function group() {
return $this->belongsTo(FacultyGroup::class, 'group_id', 'id');
}
public function lessonType() {
return $this->belongsTo(LessonType::class, 'lesson_type_id', 'id');
}
}
| true |
8a9ae759c6a95292a9be5f054de8a8105dbdb5df | PHP | salyus2/curso-php | /php7/declaraciones-tipo-escalar.php | UTF-8 | 460 | 3.90625 | 4 | [] | no_license | <?php
//Las declaraciones de tipo escalar se trata de un sistema para evitar que se pasen valores inadecuados a nuestras funciones
function cuadrado(int $numero){
return $numero * $numero;
}
$numero = '2';
echo 'El cuadrado de ' . $numero . ' es ' . cuadrado($numero);
//declare(strict_types=1);
function cuadrado2(int $numero2)
{
return $numero2 * $numero2;
}
$numero2 = 2;
echo 'El cuadrado de ' . $numero2 . ' es ' . cuadrado2($numero2); | true |
4f1f180fce7a1444b982d79806a4594f3500cdf3 | PHP | Moebiuxz/JardinMVC | /model/Usuario.php | UTF-8 | 252 | 3.125 | 3 | [] | no_license | <?php
class Usuario
{
public $rut;
public $nombre;
public $apellido;
public function __construct($rut, $nombre, $apellido)
{
$this->rut = $rut;
$this->nombre = $nombre;
$this->apellido = $apellido;
}
} | true |
691dbead71bd6ef85b2233f8123b004e2688e59e | PHP | algo13/php-eaw | /src/mb_eaw_wrap.function.php | UTF-8 | 1,235 | 2.90625 | 3 | [
"MIT"
] | permissive | <?php
/**
* mb_eaw_wrap.function.php
*
* Copyright (c) 2015 algo13
*
* This software is released under the MIT License.
* http://opensource.org/licenses/mit-license.php
*/
if (!function_exists('mb_eaw_strwidth')) {
require_once dirname(__FILE__).'/mb_eaw_strwidth.function.php';
}
// string mb_wrap( string $str, int $width = 75, string $break = "\n", string $encoding = mb_internal_encoding())
function mb_eaw_wrap($string, $width = 75, $break = "\n", $table = null, $encoding = null)
{
if (func_num_args() < 5) {
$encoding = mb_internal_encoding();
}
$len = mb_strlen($string, $encoding);
if ($len === false) {
return false;
}
$line = '';
$lineLen = 0;
$retval = '';
for ($start = 0; $start < $len; ++$start) {
$char = mb_substr($string, $start, 1, $encoding);
$charwidth = mb_eaw_strwidth($char, $table, $encoding);
if (($lineLen + $charwidth) <= $width) {
$line .= $char;
$lineLen += $charwidth;
} else {
$retval .= $line.$break;
$line = $char;
$lineLen = $charwidth;
}
}
if ($line !== '') {
return $retval.$line.$break;
}
return $retval;
}
| true |
cadecd44d00fc19345c44fcedf1eeef7425f998e | PHP | exesser/cms-bundle | /Dashboard/Model/Grid/Row.php | UTF-8 | 3,984 | 2.71875 | 3 | [] | no_license | <?php
namespace ExEss\Bundle\CmsBundle\Dashboard\Model\Grid;
use ExEss\Bundle\CmsBundle\Dashboard\Model\Grid;
use ExEss\Bundle\CmsBundle\Dashboard\Model\StripEmptyOnEncodeTrait;
class Row implements \JsonSerializable
{
use StripEmptyOnEncodeTrait;
public const TYPE_EMBEDDED_GUIDANCE = 'embeddedGuidance';
private ?string $size = null;
private ?bool $hasMargin = null;
private ?string $type = null;
private ?string $panelKey = null;
private Row\Options $options;
private array $cssClasses = [];
private array $children = [];
private ?Grid $grid = null;
/**
* @throws \InvalidArgumentException In case the argument contains unsupported options.
*/
public function __construct(array $source)
{
$options = $source['options'] ?? [];
$this->setOptions(new Row\Options($options));
unset($source['options']);
if (($children = $source['children'] ?? false) !== false && \is_array($children)) {
foreach ($children as $child) {
$this->addChild(new Row($child));
}
unset($source['children']);
}
if (($size = $source['size'] ?? false) !== false) {
$this->setSize($size);
unset($source['size']);
}
if (($panelKey = $source['panelKey'] ?? false) !== false) {
$this->setPanelKey($panelKey);
unset($source['panelKey']);
}
if (($hasMargin = $source['hasMargin'] ?? null) !== null) {
$this->setHasMargin($hasMargin);
unset($source['hasMargin']);
}
if (($type = $source['type'] ?? false) && \is_string($type)) {
$this->setType($type);
unset($source['type']);
}
if (($cssClasses = $source['cssClasses'] ?? false) !== false) {
$this->setCssClasses($cssClasses);
unset($source['cssClasses']);
}
if (($grid = $source['grid'] ?? false) !== false && \is_array($grid)) {
$this->setGrid(new Grid($grid));
unset($source['grid']);
}
if (\count($source)) {
throw new \InvalidArgumentException(\sprintf(
'Unsupported row options: %s',
\implode(', ', \array_keys($source))
));
}
}
public function setSize(string $size): Row
{
$this->size = $size;
return $this;
}
public function getSize(): ?string
{
return $this->size;
}
public function setHasMargin(bool $hasMargin): Row
{
$this->hasMargin = $hasMargin;
return $this;
}
public function isHasMargin(): ?bool
{
return $this->hasMargin;
}
public function setType(string $type): Row
{
$this->type = $type;
return $this;
}
public function getType(): ?string
{
return $this->type;
}
public function setPanelKey(string $panelKey): Row
{
$this->panelKey = $panelKey;
return $this;
}
public function getPanelKey(): ?string
{
return $this->panelKey;
}
public function setCssClasses(array $cssClasses): Row
{
$this->cssClasses = $cssClasses;
return $this;
}
public function getCssClasses(): array
{
return $this->cssClasses;
}
public function setOptions(Row\Options $options): Row
{
$this->options = $options;
return $this;
}
public function getOptions(): Row\Options
{
return $this->options;
}
public function addChild(Row $row): Row
{
$this->children[] = $row;
return $this;
}
public function getChildren(): array
{
return $this->children;
}
public function setGrid(Grid $grid): Row
{
$this->grid = $grid;
return $this;
}
public function getGrid(): ?Grid
{
return $this->grid;
}
}
| true |
12e64e65c7b9df87a87db809efb204bdfb3eb07e | PHP | pleminh/magento2-blog-product | /Model/Article/Rss.php | UTF-8 | 1,388 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Gemtoo\Blog\Model\Article;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\UrlInterface;
use Magento\Store\Model\StoreManagerInterface;
class Rss
{
/**
* @var \Magento\Framework\App\Config\ScopeConfigInterface
*/
protected $scopeConfig;
protected $urlBuilder;
protected $storeManager;
/**
* @param UrlInterface $urlBuilder
* @param ScopeConfigInterface $scopeConfig
* @param StoreManagerInterface $storeManager
*/
public function __construct(
UrlInterface $urlBuilder,
ScopeConfigInterface $scopeConfig,
StoreManagerInterface $storeManager
)
{
$this->urlBuilder = $urlBuilder;
$this->scopeConfig = $scopeConfig;
$this->storeManager = $storeManager;
}
/**
* @return bool
*/
public function isRssEnabled()
{
return
$this->scopeConfig->getValue('rss/config/active', ScopeInterface::SCOPE_STORE) &&
$this->scopeConfig->getValue('gemtoo_blog/article/rss', ScopeInterface::SCOPE_STORE);
}
/**
* @return string
*/
public function getRssLink()
{
return $this->urlBuilder->getUrl(
'gemtoo_blog/article/rss',
['store' => $this->storeManager->getStore()->getId()]
);
}
}
| true |
b23326f1b37b354db184109e4ad88b5d9867618c | PHP | ederius/oficinajuridica | /php/sql.php | UTF-8 | 3,083 | 2.71875 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Eder
* Date: 30/04/2015
* Time: 4:51 PM
*/
class Sql
{
private $host ="localhost";
private $usuario ="root";
private $contrasena ="";
private $db ="db_juridica";
public function __construct(){
$this->conexion();
}
public function conexion(){
$query=mysql_connect($this->host,$this->usuario,$this->contrasena);
$base=mysql_select_db($this->db);
if(!$query){
echo "no se pudo comunicar con el servidor";
}else if(!$base){
echo "no se encontro la base de datos";
}
}
public function mostrarUsuarios(){
$sql=' SELECT * FROM administradores';
$consulta=mysql_query($sql);
return $consulta;
}
public function datosUsuarios($var){
$sql=' SELECT * FROM administradores WHERE idusuario='.$var.'';
$consulta=mysql_query($sql);
return $consulta;
}
public function actualizarUsuario($n,$u,$c,$e,$r,$id)
{
if($_SESSION['contrasena']==$c) {
$insert = mysql_query("UPDATE administradores SET nombre_completo='" . $n . "', nombre_usuario='" . $u . "',
email='" . $e . "', contrasena='" . $c . "', roll='" . $r . "' WHERE idusuario= " . $id . " ")
or die(mysql_error());
}else{
$insert = mysql_query("UPDATE administradores SET nombre_completo='" . $n . "', nombre_usuario='" . $u . "',
email='" . $e . "', contrasena='" . md5($c) . "', roll='" . $r . "' WHERE idusuario= " . $id . " ")
or die(mysql_error());
}
if (!$insert) {
echo "<div class='alert alert-danger'>Error Actualizar!</div>";
} else {
echo '<div class="alert alert-success" role="alert">Actualización Exitosa!</div>';
}
}
public function eliminarUsuario($id){
$insert = mysql_query("DELETE FROM administradores WHERE idusuario= " . $id . " ")
or die(mysql_error());
if (!$insert) {
echo "<div class='alert alert-danger'>Error Actualizar!</div>";
} else {
echo '<div class="alert alert-success" role="alert">Actualización Exitosa!</div>';
}
}
public function registroClase($n){
$insert = mysql_query("INSERT INTO dmo_clase VALUES ('', '".$n."') ")
or die(mysql_error());
if (!$insert) {
echo "<div class='alert alert-danger'>Error Actualizar!</div>";
} else {
echo '<div class="alert alert-success" role="alert">Actualización Exitosa!</div>';
}
}
public function registroPeticion($n){
$insert = mysql_query("INSERT INTO dmo_peticion VALUES ('', '".$n."') ")
or die(mysql_error());
if (!$insert) {
echo "<div class='alert alert-danger'>Error Actualizar!</div>";
} else {
echo '<div class="alert alert-success" role="alert">Actualización Exitosa!</div>';
}
}
} | true |
95e7671d6c4968d4898afb47eb9704e9d926a7c3 | PHP | kovalevich/hyip | /application/views/helpers/Getparams.php | UTF-8 | 1,331 | 2.59375 | 3 | [] | no_license | <?php
/**
*
* @author kovalevich
* @version
*/
require_once 'Zend/View/Interface.php';
/**
* Nicetime helper
*
* @uses viewHelper Zend_View_Helper
*/
class Zend_View_Helper_Getparams
{
/**
*
* @var Zend_View_Interface
*/
public $view;
/**
*/
public function getparams ()
{
$params = array();
if(Zend_Registry::isRegistered('_GET')) {
foreach(Zend_Registry::get('_GET') as $param => $value)
{
if($param == 'brand') $params[] = 'brand='.$value;
if($param == 'model') $params[] = 'model='.$value;
if($param == 'generation') $params[] = 'generation='.$value;
if($param == 'price') $params[] = 'price='.$value;
if($param == 'year') $params[] = 'year='.$value;
if($param == 'engine') $params[] = 'engine='.$value;
if($param == 'volume') $params[] = 'volume='.$value;
if($param == 'transmission') $params[] = 'transmission='.$value;
}
}
return count($params) ? '?' . implode('&', $params) : '';
}
/**
* Sets the view field
*
* @param $view Zend_View_Interface
*/
public function setView (Zend_View_Interface $view)
{
$this->view = $view;
}
}
| true |
cc48577bcf06c92d7c3a0772f3f3f5e8d6683d60 | PHP | OlesKashchenko/Jarboe | /src/Yaro/Jarboe/Fields/Subactions/AbstractSubaction.php | UTF-8 | 400 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace Yaro\Jarboe\Fields\Subactions;
abstract class AbstractSubaction
{
protected $attributes;
public function __construct($attributes)
{
$this->attributes = $attributes;
} // end __construct
public function getAttribute($ident)
{
return isset($this->attributes[$ident]) ? $this->attributes[$ident] : false;
} // end getAttribute
} | true |
9cc98deadeb3f23460fc1c2afa6f573ff2a7313d | PHP | rahulyhg/Atriya- | /admin/application/Mailer.class.php | UTF-8 | 2,693 | 2.90625 | 3 | [] | no_license | <?php
require ("class.phpmailer.php");
class Mailer {
function Mailer() {
//session_start();
}
function sendMail($to, $from, $subject, $message, $path, $file_name) {
$host = $_SERVER['HTTP_HOST'];
if( strpos( $host, "flexihire.co.in" ) !== false ) {
$toArr = explode(",", $to);
$to = $toArr[0];
$mail = new PHPMailer();
$mail -> IsSMTP();
// telling the class to use SMTP
$mail -> Host = "mail.flexihire.co.in";
// SMTP server
$mail -> Port = 25;
$mail -> SMTPAuth = true;
$mail -> Username = "donot-reply@flexihire.co.in";
$mail -> Password = "&J{cr8GwTJZ9";
$mail -> From = $from;
$mail -> FromName = "FLEXIHIRE";
// $mail->AddAddress($hodEmail[0]["emailid"]);
$mail -> AddAddress($to);
for ($i = 1; $i < count($toArr); $i++) {
$mail -> AddCC($toArr[$i]);
}
$mail -> IsHTML(true);
if ($path != "") {
$mail -> addStringAttachment(file_get_contents($path), $file_name);
}
$mail -> Subject = $subject;
$mail -> Body = stripslashes($message);
//$mail->Send();
if (!$mail -> Send()) {
//echo "Mailer Error: " . $mail->ErrorInfo;
} else {
//echo "Message sent!";
}
}
}
function sendMailWithAttachment($to, $from, $subject, $message, $path, $file_name,$attchement) {
$host = $_SERVER['HTTP_HOST'];
//if( strpos( $host, "flexihire.co.in" ) !== false ) {
$toArr = explode(",", $to);
$to = $toArr[0];
$mail = new PHPMailer();
$mail -> IsSMTP();
// telling the class to use SMTP
$mail -> Host = "mail.flexihire.co.in";
// SMTP server
$mail -> Port = 25;
$mail -> SMTPAuth = true;
$mail -> Username = "donot-reply@flexihire.co.in";
$mail -> Password = "&J{cr8GwTJZ9";
$mail -> From = $from;
$mail -> FromName = "FLEXIHIRE";
// $mail->AddAddress($hodEmail[0]["emailid"]);
$mail -> AddAddress($to);
for ($i = 1; $i < count($toArr); $i++) {
$mail -> AddCC($toArr[$i]);
}
$mail -> IsHTML(true);
if ($path != "") {
$mail -> addStringAttachment(file_get_contents($path), $file_name);
}
$mail -> Subject = $subject;
$mail -> Body = stripslashes($message);
for($i=0;$i<count($attchement);$i++){
$mail->AddAttachment($attchement[$i]);
}
//$mail->Send();
if (!$mail -> Send()) {
// echo "Mailer Error: " . $mail->ErrorInfo;
} else {
//echo "Message sent!";
}
//}
}
}
| true |
2e69666ffcfa8f4d42142d810d48c15f5a10f8bc | PHP | imochon7/aplicacion_discos | /proyecto/clases/ControllerGato.php | UTF-8 | 3,833 | 2.6875 | 3 | [] | no_license | <?php
class ControllerGato extends Controller {
function viewinsert(Gato $gato = null) {
$error="";
if($gato === null){
$gato = new Gato();
}else{
$error="Se ha producido un error";
}
$nombre = $gato->getNombre();
$raza = $gato->getRaza();
$color = $gato->getColor();
$form = <<<ABC
$error<br>
<form action="index.php">
<input type='text' value="$nombre" name='nombre' required placeholder='nombre' /><br/>
<input type='text' value="$raza" name='raza' placeholder='raza' /><br/>
<input type='text' value="$color" name='color' placeholder='color' /><br/>
<input type='hidden' name='ruta' value='gato' />
<input type='hidden' name='accion' value='doinsert' />
<input type='submit' value='alta' /><br/>
</form>
ABC;
$this->getModel()->addData('form',$form);
}
function doinsert(){
$gato = new Gato();
$gato->read();
if($gato->isValid()){
$r = $this->getModel()->insertGato($gato);
header('Location: index.php?ruta=gato&accion=viewList&op=insert&r=' .r);
exit();
}else{
$this->viewinsert($gato);
}
}
function viewlist(){
$lista=$this->getModel()->getList();
$datoFinal = <<<DEF
<script>
var confirmarBorrar = function(evento) {
var objeto = evento.target;
var r = confirm('¿Borrar?');
if (r) {
} else {
evento.preventDefault();
}
}
var a = document.getElementsByClassName('borrar');
for (var i = 0; i < a.length; i++) {
a[i].addEventListener('click', confirmarBorrar, false);
}
</script>
DEF;
$dato ='';
foreach($lista as $gato){
$dato .= $gato;
$dato .= '<a class="borrar" href="index.php?ruta=gato&accion=delete&id=' . $gato->getId() . '">borrar este gato</a> ';
$dato .= '<a href="index.php?ruta=gato&accion=viewedit&id=' . $gato->getId() . '">editar este gato</a>';
$dato .= '<br>';
}
$dato .= $datoFinal;
$dato .= '<a href="index.php?ruta=gato&accion=viewinsert">Insertar</a>';
$this->getModel()->addData('lista', $dato);
}
function dodelete(){
$id = Request::read('id');
$r = $this->getModel()->deleteGato($id);
header('Location: index.php?ruta=gato&accion=viewList&op=delete&r=' .r);
exit();
}
function viewedit(){
$id = Request::read('id');
$gato = $this->getModel()->getGato('id');
$nombre = $gato->getNombre();
$raza = $gato->getRaza();
$color = $gato->getColor();
$form = <<<ABC
$error<br>
<form action="index.php">
<input type='text' value='$nombre' name='nombre' required placeholder='nombre' /><br/>
<input type='text' value='$raza' name='raza' placeholder='raza' /><br/>
<input type='text' value='$color' name='color' placeholder='color' /><br/>
<input type='hidden' value='$id' name='id'/><br/>
<input type='hidden' name='ruta' value='gato' />
<input type='hidden' name='accion' value='doedit' />
<input type='submit' value='edicion' /><br/>
</form>
ABC;
$this->getModel()->addData('form', $form);
}
function doedit(){
$gato = new Gato();
$gato->read();
//$gato->setId(Request::read('id'));
$r = $this->getModel()->editGato($gato);
header('Location: index.php?ruta=gato&accion=viewlist&op=edit&r=' . $r);
exit();
}
} | true |
60751587112d2ebd9e88750cc841b2f8ab5e9bd8 | PHP | foxer-zt/mousehole | /source/Mouse/Stats.php | UTF-8 | 1,343 | 3.609375 | 4 | [] | no_license | <?php
namespace Irishdash\Mouse;
class Stats
{
/**
* @var int
*/
protected $hp;
/**
* @var int
*/
protected $strength;
/**
* @var int
*/
protected $baseDamage;
/**
* @var Stats
*/
protected static $_instance;
/**
* Damage multiplier
*/
const MULT = 1.3;
/**
* @constructor
*/
private function __construct()
{
$this->hp = 10;
$this->strength = 1;
}
/**
*
*/
private function __clone()
{
//
}
/**
* Get Stats singleton
*
* @return Stats
*/
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Change stats
*
* @param string $stat
* @param int $value
* @param bool $inc
* @return void
*/
public function changeStat($stat, $value = 1, $inc = true)
{
if (isset($this->$stat)) {
$inc == false ? $this->$stat -= $value : $this->$stat += $value;
}
}
/**
* Calculate damage according to stats.
*
* @return float
*/
public function getBaseDamage()
{
return floor(self::MULT * $this->strength);
}
} | true |
0d053574bb055baa984aeb7e009822d85fe90908 | PHP | hubertj6/Projekt-WM | /model/KolekcjaAktualnosci.php | UTF-8 | 537 | 2.65625 | 3 | [] | no_license | <?php
class KolekcjaAktualnosci extends Aktualnosci{
var $TablicaAktualnosci;
public function __construct(){
$this->TablicaAktualnosci = array();
}
function dodaj($aktualnosci){
$this->TablicaAktualnosci[] = $aktualnosci;
}
function usun($aktualnosci){
$n = 0;
while($this->TablicaAktualnosci.count >= $n){
if($this->TablicaAktualnosci[n] == $aktualnosci){
$this->TablicaAktualnosci[n].delete;
break;
}
}
}
}
?> | true |
2a4124b03b1931edba675cc5885c5e29cc7f6f19 | PHP | mmuniraju4444/loan | /app/Repositories/LoanRepaymentRepository.php | UTF-8 | 3,143 | 2.625 | 3 | [] | no_license | <?php
namespace App\Repositories;
use App\Http\Resources\LoanRepayment\LoanRepayment as LoanRepaymentJson;
use App\Http\Resources\LoanRepayment\LoanRepaymentIndex;
use App\Interfaces\ILoanRepository;
use App\Models\LoanApplication;
use App\Models\LoanRepayment;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
class LoanRepaymentRepository
{
/**
* @var null
*/
protected $loanModel;
/**
* @var LoanRepository
*/
protected $loanRepo;
/**
* LoanRepaymentRepository constructor.
*/
public function __construct()
{
$this->loanModel = null;
$this->loanRepo = app(ILoanRepository::class);
}
/**
* @param string $uuid
* @param array $request
* @return LoanRepaymentIndex|null
*/
public function getAll(string $uuid, array $request): ?LoanRepaymentIndex
{
return new LoanRepaymentIndex(LoanRepayment::where('loan_application_id', LoanApplication::getId($uuid))->get());
}
/**
* @throws Exception
*/
public function save(string $uuid, array $request): LoanRepaymentJson|JsonResponse|null
{
$this->loanModel = $this->loanRepo->getModel($uuid);
// Check if the Loan is Fully Paid
if ($this->loanModel->is_fully_paid) {
$amount = Arr::get($request, 'amount', $this->loanModel->emi);
// Check if the payment amount is more the balance
if ($amount > $this->loanModel->total_balance_amount) {
throw new \Exception('Loan EMI cant be more than ' . $this->loanModel->total_balance_amount);
}
$request['loan_application_id'] = $this->loanModel->uuid;
$request['amount'] = $amount;
return new LoanRepaymentJson($this->saveOrUpdatePage($request));
}
throw new \Exception('Loan EMI Fully Paid');
}
/**
* @param array $attributes
* @return LoanApplication
* @throws Exception
*/
protected function saveOrUpdatePage(array $attributes): LoanRepayment
{
DB::beginTransaction();
try {
$model = LoanRepayment::updateOrCreate(
[
'uuid' => Arr::get($attributes, 'uuid')
],
[
'loan_application_id' => LoanApplication::getId($attributes['loan_application_id']),
'amount' => Arr::get($attributes, 'amount')
]);
DB::commit();
return $model;
} catch (Exception $ex) {
DB::rollBack();
throw $ex;
}
}
/**
* @param string $uuid
* @return LoanRepaymentJson|null
*/
public function get(string $uuid): ?LoanRepaymentJson
{
$model = $this->getModel($uuid);
return new LoanRepaymentJson($model);
}
/**
* @param string $uuid
* @return LoanRepayment|null
*/
protected function getModel(string $uuid, array $with = []): ?LoanRepayment
{
return LoanRepayment::getModel($uuid, $with);
}
}
| true |
77700408f27919e632adf2e3afa65573d54b1177 | PHP | justupgrade/random-shop | /www/classes/Picture.php | UTF-8 | 3,031 | 3.390625 | 3 | [] | no_license | <?php
class Picture extends DBObject {
private $id;
private $path;
private $itemID;
static protected $table = 'pictures';
//WHAT DO I NEED THIS FOR? FOR CLARITY? Single responsibility principle
protected function __construct($id,$path,$itemID){
$this->id=$id;
$this->path = $path;
$this->itemID = $itemID;
}
static protected function CreateFromArray($data) {
return new Picture($data['id'], $data['path'], $data['item_id']);
}
static public function Create() {
trigger_error("CANNOT CREATE PICTURE WITHOUT DATA; CALL Picture::Upload(...)!");
}
//save to db ? private ?
static protected function CreatePicture($itemID, $path) {
//validate path? how?
$columns = array('path', 'item_id');
$values = array($path, $itemID);
if(($id = parent::Create($columns, $values))) {
return new Picture($id,$path,$itemID);
}
return null;
}
//load from db :: ALL PICTURES FOR SPECYFIED ITEM
static public function Load($itemID) {
return parent::LoadArray($itemID);
}
//what to update? picture itself? path to picture?
static public function Update($picture) {
//do not allow to update for now...
trigger_error('Picture can not be updated!');
}
/* DELETE FORM DB + DELETE FILE FROM DRIVE!!!
* why the ... is this static? super() is static...
* */
static public function Delete($picture) {
if(parent::Delete($picture->getID()) === 1) {
//keep directory structure? for now yes...
if(unlink($picture->getPath())) return 1;
}
return 0;
}
//------------------ methods --------------------
//watermark? description? other effects?
public function edit() {
}
public function download() {
//what for? what to download? =D binary data or what?
}
public function save() { //save edited? save, so admin can restore?
}
public function changePath($newPath) {
//move file... why would someone move file?
//is new path valid?
//moved successfully? -> saveToDb!!!
}
//------------------ PICTURES ----------------------
static public function Upload($name, $file, $item){
$hashed_name = md5($name);
$begining = substr($hashed_name, 0, 2);
$ending = substr($hashed_name, strlen($hashed_name)-2, 2);
$structure = $_SERVER['DOCUMENT_ROOT'].'/uploads/' . $item->getCategoryID() . '/';
$structure .= date("Y") . '/' . date("m") . '/' . date("d") . '/';
$structure .= $begining.$ending . '/';
if(!is_dir($structure)) mkdir($structure,0777,true);
if(!move_uploaded_file($file, $structure.$name)) return null;
//uploaded? -> create
return self::CreatePicture($item->getID(), $structure.$name);
}
//----------------- GET / SET --------------------
public function getID() { return $this->id; }
public function getItemID() { return $this->itemID; }
public function getPath() { return $this->path; }
public function setPath($new) { $this->path = $new; } //LET THIS TO EXIST? move file while called?
}
?> | true |
39031d65a522b131e5047705d723a2f73fdcd595 | PHP | n0bisuke/Taxshare | /app/vendors/nikeplusphp_3_1_1.php | UTF-8 | 8,039 | 3.21875 | 3 | [] | no_license | <?php
/**
* A PHP class that makes it easy to get your data from the Nike+ service
*
* NikePlusPHP v3.x requires PHP 5 with SimpleXML and cURL.
* To get started you will need your Nike account information.
*
* @author Charanjit Chana
* @link http://nikeplusphp.org
* @version 3.1.1
*/
class NikePlusPHP {
/**
* public variables
*/
public $idErrorMessage = 'The login details you supplied are incorrect.', $feedErrorMessage = 'There was an error fetching the feed from the Nike servers.';
/**
* private variables
*/
private $userId, $cookie, $body, $profile;
/**
* __construct()
* Called when you initiate the class and keeps a cookie that allows you to keep authenticating
* against the Nike+ website.
*
* @param string $username your Nike username, should be an email address
* @param string $password your Nike password
*/
public function __construct($username, $password) {
$this->login($username, $password);
$this->checkUserId();
$this->getProfile();
}
/**
* login()
* Called by __construct and performs the actual login action.
*
* @param string $username
* @param string $password
*
* @return string
*/
private function login($username, $password) {
$url = 'https://secure-nikerunning.nike.com/services/profileService?_plus=true';
$loginDetails = 'action=login&login='.urlencode($username).'&password='.$password;
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_POSTFIELDS, $loginDetails);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
$noDoubleBreaks = str_replace(array("\n\r\n\r", "\r\n\r\n", "\n\n", "\r\r", "\n\n\n\n", "\r\r\r\r"), '||', $data);
$sections = explode('||', $noDoubleBreaks);
$headerSections = explode('Set-Cookie: ', $sections[0]);
$this->body = $sections[1].'';
for($i=1; $i<=4; $i++) {
$allheaders[] = @str_replace(array("\n\r", "\r\n", "\r", "\n\n", "\r\r"), "", $headerSections[$i]);
}
foreach($allheaders as $h) {
$exploded[] = explode('; ', $h);
}
foreach($exploded as $e) {
$string[] = $e[0];
}
$header = implode(';', $string);
if($contents = @simplexml_load_string($this->body)) {
$this->userId = (integer) $contents->profile->id;
} else {
throw new ErrorException('The XML feed could not be read.');
}
$this->cookie = $header;
}
/**
* cookieValue()
* Available for debugging purposes. Using this function in your code can make your
* cookie values publicly available
*
* @return string
*/
public function cookieValue() {
return $this->cookie;
}
/**
* checkUserId()
* Check that the userId exists and is the correct type
*
* @return true
*/
private function checkUserId() {
if(!$this->userId || gettype($this->userId) != 'integer') {
throw new ErrorException($this->idErrorMessage);
}
return true;
}
/**
* getNikePlusFile()
* Gets the contents of a file from the Nike+ service,
*
* @param string $filePath the path to the file that needs to be read
*
* @return object
*/
private function getNikePlusFile($filePath) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, $this->cookie);
curl_setopt($ch, CURLOPT_URL, $filePath);
$data = curl_exec($ch);
curl_close($ch);
if($content = @simplexml_load_string($data)) {
return $content;
} else {
throw new ErrorException('The XML feed could not be read.');
}
}
/**
* profile()
* Get the profile of the current user
*
* @return object
*/
private function getProfile() {
if(!$this->profile = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/get_user_data.jsp?_plus=true')) {
throw new Exception($this->feedErrorMessage);
}
}
/**
* profile()
* Get the profile of the current user
*
* @return object
*/
public function profile() {
return $this->profile;
}
/**
* getRuns()
* Get ALL run data for the current user
*
* @return object
*/
public function getRuns() {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/run_list.jsp?_plus=true')) {
throw new ErrorException($this->feedErrorMessage);
}
return $data->runList;
}
/**
* getRun()
* Get the data for a single run
*
* @param int|string $runId the numeric ID of the run to retrieve
*
* @return object
*/
public function getRun($runId) {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/get_run.jsp?_plus=true&id='.$runId)) {
throw new Exception($this->feedErrorMessage);
}
return $data;
}
/**
* getMostRecentRunId()
* Get the id for a the latest run
*
* @return int the numeric ID of the last run
*/
public function getMostRecentRunId() {
return (float) $this->profile->mostRecentRun->attributes()->id;
}
/**
* getPersonalRecords()
* Get the personal records for the current user
*
* @return object
*/
public function getPersonalRecords() {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/personal_records.jsp?_plus=true')) {
throw new Exception($this->feedErrorMessage);
}
return $data;
}
/**
* getGoals()
* Get the goals set for the current user
*
* @return object
*/
public function getGoals() {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/goal_list.jsp?_plus=true')) {
throw new Exception($this->feedErrorMessage);
}
return $data;
}
/**
* getCompleteGoals()
* Get the completed goals for the current user
*
* @return object
*/
public function getCompletedGoals() {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/app/completed_goal_list.jsp?_plus=true')) {
throw new Exception($this->feedErrorMessage);
}
return $data;
}
/**
* getUserEvents()
* Get a list of events for the current user
*
* @return object
*/
public function getUserEvents() {
if(!$data = $this->getNikePlusFile('http://nikerunning.nike.com/nikeplus/v2/services/userevent/get_user_events.jsp?_plus=true')) {
throw new Exception($this->feedErrorMessage);
}
return $data;
}
/**
* getTotalDistance()
* Get the total distance covered by the current user
*
* @return float|string
*/
public function getTotalDistance() {
return (float) $this->profile->userTotals->totalDistance;
}
/**
* getTotalTime()
* Get the total amount of time spent running by the current user
*
* @return float|string
*/
public function getTotalTime() {
return (float) $this->profile->userTotals->totalDuration;
}
/**
* getTotalCalories()
* Get the total number of calories burned by the current user
*
* @return float|string
*/
public function getTotalCalories() {
return (float) $this->profile->userTotals->totalCalories;
}
/**
* getNumberOfRuns()
* Get the total number of runs made by the current user
*
* @return float|string
*/
public function getNumberOfRuns() {
return (float) $this->profile->userTotals->totalRuns;
}
/**
* toMiles()
* Convert a value from Km in to miles
*
* @param float|string $distance
*
* @return int
*/
public function toMiles($distance) {
return number_format(((float) $distance * 0.621371192), 2, '.', ',');
}
} | true |
a7b84dd699069c8dbe650d94beffe39ea825ba2f | PHP | packaged/rwd | /src/Country/Countries/JPCountry.php | UTF-8 | 540 | 2.578125 | 3 | [] | no_license | <?php
namespace Packaged\Rwd\Country\Countries;
use Packaged\Rwd\Country\CountryInterface;
class JPCountry implements CountryInterface
{
public function getName()
{
return 'Japan';
}
public function getIso2()
{
return 'JP';
}
public function getIso3()
{
return 'JPN';
}
public function getWmo()
{
return 'JP';
}
public function getNumericCode()
{
return 392;
}
public function getDialPrefix()
{
return 81;
}
public function getCurrencyCode()
{
return 'JPY';
}
}
| true |
3d2d6500cb3fa3c5bec1c1b76c02b317bf8a9c76 | PHP | anlutro/laravel-4-core | /src/Eloquent/RelationshipQueryJoiner.php | UTF-8 | 4,702 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
/**
* Laravel 4 Core
*
* @author Andreas Lutro <anlutro@gmail.com>
* @license http://opensource.org/licenses/MIT
* @package l4-core
*/
namespace anlutro\Core\Eloquent;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Relations\Relation;
/**
* Utility class for joining related tables in Eloquent.
*
* (new RelationshipQueryJoiner($eloquentQuery))
* ->join('relation');
*/
class RelationshipQueryJoiner
{
/**
* The query builder.
*
* @var \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder
*/
protected $query;
/**
* The model.
*
* @var \Illuminate\Database\Eloquent\Model
*/
protected $model;
/**
* This array keeps track of currently joined relationships to try and
* prevent overlapping joins.
*
* @var array
*/
protected $joined = [];
public function __construct(Builder $query)
{
$this->query = $query;
$this->model = $query->getModel();
}
/**
* Join one or multiple relations onto the query.
*
* @param string|array $relations Single string or array of strings with
* the name of the relation(s) that should be joined onto the query.
* @param string $type The join type - left, inner etc
*
* @return static
*/
public function join($relations, $type = 'left')
{
foreach ((array) $relations as $relation) {
if (in_array($relation, $this->joined)) {
continue;
}
if (strpos($relation, '.') !== false) {
$this->joinNested($relation, $type);
} else {
$this->joined[] = $relation;
$relation = $this->getRelation($this->model, $relation);
$this->joinRelation($relation, $type);
}
}
$this->checkQuerySelects();
// @todo resarch when/if group by's are necessary
// $this->checkQueryGroupBy();
return $this;
}
/**
* @param Model $model
* @param string $name
*
* @return Relation
* @throws \InvalidArgumentException
*/
protected function getRelation($model, $name)
{
if (!method_exists($model, $name)) {
$class = get_class($model);
throw new \InvalidArgumentException("$class has no relation $name");
}
return $model->$name();
}
protected function joinNested($relation, $type)
{
$segments = explode('.', $relation);
$model = $this->model;
$current = '';
foreach ($segments as $segment) {
$current = $current ? "$current.$segment" : $segment;
$relation = $this->getRelation($model, $segment);
if (!in_array($current, $this->joined)) {
$this->joinRelation($relation, $type);
}
$model = $relation->getRelated();
}
}
protected function checkQuerySelects()
{
$selects = $this->query->getQuery()->columns;
$tableSelect = $this->model->getTable().'.*';
if (empty($selects) || !in_array($tableSelect, $selects)) {
$this->query->addSelect($tableSelect);
}
}
protected function checkQueryGroupBy()
{
$groups = $this->query->getQuery()->groups;
$keyGroup = $this->model->getQualifiedKeyName();
if (empty($groups) || !in_array($keyGroup, $groups)) {
$this->query->groupBy($keyGroup);
}
}
protected function joinRelation(Relation $relation, $type)
{
if ($relation instanceof Relations\BelongsToMany) {
$this->joinManyToManyRelation($relation, $type);
} else if ($relation instanceof Relations\HasOneOrMany) {
$this->joinHasRelation($relation, $type);
} else if ($relation instanceof Relations\BelongsTo) {
$this->joinBelongsToRelation($relation, $type);
}
}
protected function joinHasRelation(Relations\HasOneOrMany $relation, $type)
{
$table = $relation->getRelated()->getTable();
$foreignKey = $relation->getForeignKey();
$localKey = $relation->getQualifiedParentKeyName();
$this->query->join($table, $foreignKey, '=', $localKey, $type);
}
protected function joinBelongsToRelation(Relations\BelongsTo $relation, $type)
{
$table = $relation->getRelated()->getTable();
$foreignKey = $relation->getQualifiedForeignKey();
$localKey = $relation->getQualifiedOtherKeyName();
$this->query->join($table, $foreignKey, '=', $localKey, $type);
}
protected function joinManyToManyRelation(Relations\BelongsToMany $relation, $type)
{
$pivotTable = $relation->getTable();
// $relation->getQualifiedParentKeyName() is protected
$parentKey = $relation->getParent()->getQualifiedKeyName();
$localKey = $relation->getOtherKey();
$this->query->join($pivotTable, $localKey, '=', $parentKey, $type);
$related = $relation->getRelated();
$foreignKey = $relation->getForeignKey();
$relatedTable = $related->getTable();
$relatedKey = $related->getQualifiedKeyName();
$this->query->join($relatedTable, $foreignKey, '=', $relatedKey, $type);
}
}
| true |
e96e97e0bb201ff940751873c2c0ffd5d0a29d46 | PHP | sophpie/modular-cd | /module/Repository/src/Repository/Model/RepositoryInterface.php | UTF-8 | 172 | 2.859375 | 3 | [] | no_license | <?php
namespace Repository\Model;
interface RepositoryInterface
{
/**
* Get repository name
*
* @return string
*/
public function getName();
} | true |
911b5b4c6db6be0d82a0eb015abfb8926934e655 | PHP | dr-matt-smith/hdip_web3_test_2017_SOLUTION | /src/model/Book.php | UTF-8 | 2,066 | 3.34375 | 3 | [] | no_license | <?php
namespace Itb\Model;
/**
* Class Book to represent book objects
* @package Itb\Model;
*/
class Book
{
/**
* isbn of book (unique primary KEY)
*
* example:
* <code>
* 1234
* </code>
* @var integer
*/
private $id;
/**
* title of book
*
* example:
* <code>
* The Return of Sherlock Holmes
* </code>
*
* @var string
*/
private $title;
/**
* path to cover image
*
* example:
* <code>
* holmes_return.jpg
* </code>
* @var string
*/
private $image;
/**
* total number of pages (including Index)
*
* example:
* <code>
* 20
* </code>
* @var int
*/
private $numPages;
/**
* set ISBN
*
* example usage:
*
* <code>
* $book->setId(1234);
* </code>
* @param integer $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* get the ISBN
*
* example usage:
*
* <code>
* $isbn = $b->getId();
* </code>
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* get the title
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* get the image path
* @return string
*/
public function getImage()
{
return $this->image;
}
/**
* get the total number of pages
* @return int
*/
public function getNumPages()
{
return $this->numPages;
}
/**
* set the book title
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* set the image path
* @param string $image
*/
public function setImage($image)
{
$this->image = $image;
}
/**
* @param int $numPages
*/
public function setNumPages(int $numPages)
{
$this->numPages = $numPages;
}
} | true |