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
e302059cb93720d045854cedad247b82cabc62ae
PHP
casahugo/battlegame
/src/Collection/RoundCollection.php
UTF-8
1,779
2.90625
3
[]
no_license
<?php declare(strict_types=1); namespace App\Collection; use App\Player; use App\Round; class RoundCollection extends \NoRewindIterator { private PlayerCollection $players; private const DEFAULT_RESULT = 0; /** @var array<string, int> */ private array $results = []; public function __construct(PlayerCollection $players) { $this->players = $players; $this->results = \array_fill_keys($this->players->getPlayerIds(), static::DEFAULT_RESULT); $iterator = new \MultipleIterator(); foreach ($this->players as $player) { $iterator->attachIterator($player->getCards()); } parent::__construct($iterator); } /** @return Round[] */ public function getArrayCopy(): array { return \iterator_to_array($this, false); } public function current(): Round { $round = new Round(new CardCollection(parent::current())); $winnerId = $round->getWinnerId(); if (\is_null($winnerId)) { return $round; } if (\array_key_exists($winnerId, $this->results)) { $this->results[$winnerId]++; } return $round; } public function getWinner(): ?Player { if ($this->getInnerIterator()->valid()) { \iterator_to_array($this, false); } if (\is_null($this->findWinnerId())) { return null; } return $this->players->getPlayer($this->findWinnerId()); } private function findWinnerId(): ?string { $values = array_count_values($this->results); $max = \max($this->results); if ($values[$max] > 1) { return null; } return array_flip($this->results)[$max]; } }
true
81867da5a44d60038787375c5a01d8e461c557ef
PHP
ccorlatti/AlCentavo
/library/dao/generated/BaseTransactioncomment.php
UTF-8
1,160
2.59375
3
[]
no_license
<?php /** * BaseTransactioncomment * * This class is member of the DAO layer. * * @author Claudio Corlatti <corlatti@gmail.com> * $Id$ */ abstract class BaseTransactioncomment extends Doctrine_Record { public function setTableDefinition() { $this->setTableName('transactioncomment'); $this->hasColumn('id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true, 'autoincrement' => true)); $this->hasColumn('idUser', 'integer', 4, array('type' => 'integer', 'length' => 4, 'notnull' => true)); $this->hasColumn('idTransaction', 'integer', 4, array('type' => 'integer', 'length' => 4, 'notnull' => true)); $this->hasColumn('content', 'string', 500, array('type' => 'string')); } public function setUp() { $this->actAs('Timestampable'); $this->actAs('SoftDelete'); $this->hasOne('User', array('local' => 'idUser', 'foreign' => 'id')); $this->hasOne('Transaction', array('local' => 'idTransaction', 'foreign' => 'id')); } } ?>
true
e8e97594b03304899534898d8dda3f21c87a6d69
PHP
darthmanwe/addrgen
/php/addrgen.php
UTF-8
6,739
2.9375
3
[ "MIT" ]
permissive
<?php /** * Copyright (c) 2012 Matyas Danter * Copyright (c) 2012 Chris Savery * Copyright (c) 2013 Pavol Rusnak * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ class Curve { public function __construct($prime, $a, $b) { $this->a = $a; $this->b = $b; $this->prime = $prime; } public function contains($x, $y) { return !gmp_cmp(gmp_mod(gmp_sub(gmp_pow($y, 2), gmp_add(gmp_add(gmp_pow($x, 3), gmp_mul($this->a, $x)), $this->b)), $this->prime), 0); } public static function cmp(Curve $cp1, Curve $cp2) { return gmp_cmp($cp1->a, $cp2->a) || gmp_cmp($cp1->b, $cp2->b) || gmp_cmp($cp1->prime, $cp2->prime); } } class Point { const INFINITY = 'infinity'; public function __construct(Curve $curve, $x, $y, $order = null) { $this->curve = $curve; $this->x = $x; $this->y = $y; $this->order = $order; if (isset($this->curve) && ($this->curve instanceof Curve)) { if (!$this->curve->contains($this->x, $this->y)) { throw new ErrorException('Curve does not contain point'); } if ($this->order != null) { if (self::cmp(self::mul($order, $this), self::INFINITY) != 0) { throw new ErrorException('Self*Order must equal infinity'); } } } } public static function cmp($p1, $p2) { if (!($p1 instanceof Point)) { if (($p2 instanceof Point)) return 1; if (!($p2 instanceof Point)) return 0; } if (!($p2 instanceof Point)) { if (($p1 instanceof Point)) return 1; if (!($p1 instanceof Point)) return 0; } return gmp_cmp($p1->x, $p2->x) || gmp_cmp($p1->y, $p2->y) || Curve::cmp($p1->curve, $p2->curve); } public static function add($p1, $p2) { if (self::cmp($p2, self::INFINITY) == 0 && ($p1 instanceof Point)) { return $p1; } if (self::cmp($p1, self::INFINITY) == 0 && ($p2 instanceof Point)) { return $p2; } if (self::cmp($p1, self::INFINITY) == 0 && self::cmp($p2, self::INFINITY) == 0) { return self::INFINITY; } if (Curve::cmp($p1->curve, $p2->curve) == 0) { if (gmp_cmp($p1->x, $p2->x) == 0) { if (gmp_mod(gmp_add($p1->y, $p2->y), $p1->curve->prime) == 0) { return self::INFINITY; } else { return self::double($p1); } } $p = $p1->curve->prime; $l = gmp_mul(gmp_sub($p2->y, $p1->y), gmp_invert(gmp_sub($p2->x, $p1->x), $p)); $x3 = gmp_mod(gmp_sub(gmp_sub(gmp_pow($l, 2), $p1->x), $p2->x), $p); $y3 = gmp_mod(gmp_sub(gmp_mul($l, gmp_sub($p1->x, $x3)), $p1->y), $p); return new Point($p1->curve, $x3, $y3); } else { throw new ErrorException('Elliptic curves do not match'); } } public static function mul($x2, Point $p1) { $e = $x2; if (self::cmp($p1, self::INFINITY) == 0) { return self::INFINITY; } if ($p1->order != null) { $e = gmp_mod($e, $p1->order); } if (gmp_cmp($e, 0) == 0) { return self::INFINITY; } if (gmp_cmp($e, 0) > 0) { $e3 = gmp_mul(3, $e); $negative_self = new Point($p1->curve, $p1->x, gmp_neg($p1->y), $p1->order); $i = gmp_div(self::leftmost_bit($e3), 2); $result = $p1; while (gmp_cmp($i, 1) > 0) { $result = self::double($result); if (gmp_cmp(gmp_and($e3, $i), 0) != 0 && gmp_cmp(gmp_and($e, $i), 0) == 0) { $result = self::add($result, $p1); } if (gmp_cmp(gmp_and($e3, $i), 0) == 0 && gmp_cmp(gmp_and($e, $i), 0) != 0) { $result = self::add($result, $negative_self); } $i = gmp_div($i, 2); } return $result; } } public static function leftmost_bit($x) { if (gmp_cmp($x, 0) > 0) { $result = 1; while (gmp_cmp($result, $x) <= 0) { $result = gmp_mul(2, $result); } return gmp_div($result, 2); } } public static function double(Point $p1) { $p = $p1->curve->prime; $a = $p1->curve->a; $inverse = gmp_invert(gmp_mul(2, $p1->y), $p); $three_x2 = gmp_mul(3, gmp_pow($p1->x, 2)); $l = gmp_mod(gmp_mul(gmp_add($three_x2, $a), $inverse), $p); $x3 = gmp_mod(gmp_sub(gmp_pow($l, 2), gmp_mul(2, $p1->x)), $p); $y3 = gmp_mod(gmp_sub(gmp_mul($l, gmp_sub($p1->x, $x3)), $p1->y), $p); if (gmp_cmp(0, $y3) > 0) $y3 = gmp_add($p, $y3); return new Point($p1->curve, $x3, $y3); } } function addr_from_mpk($mpk, $index, $change = false) { // create the ecc curve $_p = gmp_init('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F', 16); $_r = gmp_init('FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141', 16); $_b = gmp_init('0000000000000000000000000000000000000000000000000000000000000007', 16); $_Gx = gmp_init('79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798', 16); $_Gy = gmp_init('483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8', 16); $curve = new Curve($_p, 0, $_b); $gen = new Point($curve, $_Gx, $_Gy, $_r); // prepare the input values $x = gmp_init(substr($mpk, 0, 64), 16); $y = gmp_init(substr($mpk, 64, 64), 16); $branch = $change ? 1 : 0; $z = gmp_init(hash('sha256', hash('sha256', "$index:$branch:" . pack('H*', $mpk), TRUE)), 16); // generate the new public key based off master and sequence points $pt = Point::add(new Point($curve, $x, $y), Point::mul($z, $gen)); $keystr = pack('H*', '04' . str_pad(gmp_strval($pt->x, 16), 64, '0', STR_PAD_LEFT) . str_pad(gmp_strval($pt->y, 16), 64, '0', STR_PAD_LEFT)); $vh160 = '00' . hash('ripemd160', hash('sha256', $keystr, TRUE)); $addr = $vh160 . substr(hash('sha256', hash('sha256', pack('H*', $vh160), TRUE)), 0, 8); $num = gmp_strval(gmp_init($addr, 16), 58); $num = strtr($num, '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv', '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); $pad = ''; $n = 0; while ($addr[$n] == '0' && $addr[$n+1] == '0') { $pad .= '1'; $n += 2; } return $pad . $num; } ?>
true
1552449c379f15f66003f952b395f3e9f7864a40
PHP
scottsousa/pmpro-social-locker
/pmpro-social-locker/pmpro-social-locker.php
UTF-8
2,808
2.828125
3
[]
no_license
<?php /** * Plugin Name: PMPro Social Locker * Description: Integrate PMPro with the Social Locker plugin from OnePress (http://wordpress.org/support/plugin/social-locker). The goal is to give a user a free membership if they interact with Social Locker. * Version: 0.1 * Author URI: http://www.slocumstudio.com/ * Author: Scott Sousa (Slocum Studio), Stranger Studios */ // Constants define( 'PMPROSL_FREE_LEVEL_ID', 2 ); define( 'PMPROSL_MEMBERSHIP_PERIOD_DAYS', 7 ); /** * This function hooks into the AJAX action of Social Locker when a click is tracked. We're using it to set a cookie * so that we can verify if a user has access to the site. * * Note: They are not using check_ajax_referer(), and there is no nonce set, therefore we cannot check here either. */ add_action( 'wp_ajax_sociallocker_tracking', 'pmprosl_sociallocker_tracking', 1 ); add_action( 'wp_ajax_nopriv_sociallocker_tracking', 'pmprosl_sociallocker_tracking', 1 ); function pmprosl_sociallocker_tracking() { // First make sure we have a valid post ID if ( ! ( int ) $_POST['targetId'] ) exit; // Next make sure the "sender" is valid if ( empty( $_POST['sender'] ) || ! in_array( $_POST['sender'], array( 'button', 'timer', 'cross' ) ) ) exit; // Next make sure the "senderName" is valid if ( empty( $_POST['senderName'] ) ) exit; // Finally, make sure we haven't already set the cookie if( isset( $_COOKIE['pmprosl_has_access_flag'] ) && ! $_COOKIE['pmprosl_has_access_flag'] ) exit; // Passed all validation checks, lets set the cookies setcookie( 'pmprosl_has_access', PMPROSL_FREE_LEVEL_ID, ( time() + ( 60 * 60 * 24 * PMPROSL_MEMBERSHIP_PERIOD_DAYS ) ), COOKIEPATH, COOKIE_DOMAIN, false ); // has_access cookie (expires in PMPROSL_MEMBERSHIP_PERIOD_DAYS days) setcookie( 'pmprosl_has_access_flag', true, ( time() + ( 60 * 60 * 24 * 10 * 365 ) ), COOKIEPATH, COOKIE_DOMAIN, false ); // has_access flag cookie used to verify if a user already had access once (expires in 10 years; i.e. never) return; // We're returning here because we know Social Locker's hook is coming up next } /** * This function determines if the pmprosl_has_access cookie is set and verifies if the user should have access. */ add_filter( 'pmpro_has_membership_access_filter', 'pmprosl_pmpro_has_membership_access_filter', 10, 4 ); function pmprosl_pmpro_has_membership_access_filter( $hasaccess, $post, $user, $post_membership_levels ) { // If the flag is set if ( isset( $_COOKIE['pmprosl_has_access'] ) && $_COOKIE['pmprosl_has_access'] ) // Loop through post levels foreach ( $post_membership_levels as $level ) // If the cookie matches one of the post levels, give them access if ( ( int ) $_COOKIE['pmprosl_has_access'] == $level->id ) { $hasaccess = true; break; } return $hasaccess; }
true
f9f5b9bd9079546adebae2f63b45c4a5fa9a46d8
PHP
VinceLim68/auto
/test/test.php
UTF-8
4,686
2.875
3
[]
no_license
<?php $mysqli = new mysqli('localhost', 'root', '', 'property_info'); header("Content-type:text/html;charset=utf-8"); $maxnum = 50; //每页记录条数 $query1 = "SELECT COUNT(*) AS totalrows FROM for_sale_property "; $result1 = $mysqli->query($query1) or die($mysqli->error); $row1 = $result1->fetch_assoc(); $totalRows1 = $row1['totalrows']; //数据集总条数 $totalpages = ceil($totalRows1/$maxnum);//分页总数 if(!isset($_GET['page']) || !intval($_GET['page']) || $_GET['page'] > $totalpages) $page = 1; //对3种出错进行处理 //在url参数page不存在时,page不为10进制数时,page大于可分页数时,默认为1 else $page = $_GET['page']; $startnum = ($page - 1)*$maxnum; //从数据集第$startnum条开始读取记录,这里的数据集是从0开始的 $query = "SELECT * FROM for_sale_property LIMIT $startnum,$maxnum";//选择出符合要求的数据 从$startnum条数据开始,选出$maxnum行 $result = $mysqli->query($query) or die($mysqli->error); $row = $result->fetch_assoc(); ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=uft-8"> <title>分页示例</title> <script language="JavaScript" type="text/JavaScript"> <!-- function MM_jumpMenu(targ,selObj,restore){ //v3.0 eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'"); if (restore) selObj.selectedIndex=0; } //--> </script> <style type="text/css"> a{text-decoration:none;} a:hover{text-decoration:underline} table{font-size:12px;} .tb{background-color:#73BB95} .tr{background-color:#FFFFFF} .scrolldiv{height:200px;overflow-y:scroll; } </style> </head> <body> <div class="scrolldiv"> <table width="90%" border="0" align="center" cellpadding="0" cellspacing="1" class="tb"> <tr> <td height="24"><div align="left">id</div></td> <td height="24"><div align="left">概述</div></td> <td height="24"><div align="left">单价</div></td> </tr> <?php if($totalRows1) {//记录集不为空显示 do { ?> <tr class="tr"> <td height="24"><div align="center"><?php echo $row['id'];?></div></td> <td height="24"><div align="center"><?php echo $row['title'];?></div></td> <td height="24"><div align="center"><?php echo $row['price'];?></div></td> </tr> <?php }while($row = $result->fetch_assoc());?> </table> </div> <table width="95%" border="0" align="center" cellpadding="10" cellspacing="0"> <tr><form name="form1"> <td height="27" align="center"> <?php echo "共计<font color=\"#ff0000\">$totalRows1</font>条记录"; echo "<font color=\"#ff0000\">".$page."</font>"."/".$totalpages."页 "; //实现 << < 1 2 3 4 5> >> 样式的分页链接<div > $pre = $page - 1;//上一页 $next = $page + 1;//下一页 $maxpages = 4;//处理分页时 << < 1 2 3 4 > >>显示4页 $pagepre = 1;//如果当前页面是4,还要显示前$pagepre页,如<< < 3 /4/ 5 6 > >> 把第3页显示出来 if($page != 1) { echo "<a href='".$_SERVER['PHP_SELF']."'><<</a> "; echo "<a href='".$_SERVER['PHP_SELF'].'?page='.$pre."'><</a> "; } if($maxpages>=$totalpages){ //如果总记录不足以显示4页 $pgstart = 1;$pgend = $totalpages;//就不所以的页面打印处理 }elseif(($page-$pagepre-1+$maxpages)>$totalpages){//就好像总页数是6,当前是5,则要把之前的3 4页显示出来,而不仅仅是4 $pgstart = $totalpages - $maxpages + 1;$pgend = $totalpages; }else{ $pgstart=(($page<=$pagepre)?1:($page-$pagepre));//当前页面是1时,只会是1 2 3 4 > >>而不会是 0 1 2 3 > >> $pgend=(($pgstart==1)?$maxpages:($pgstart+$maxpages-1)); } for($pg=$pgstart;$pg<=$pgend;$pg++){ //跳转菜单 if($pg == $page){ echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pg\"><font color=\"#ff0000\">$pg</font></a> "; } else { echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$pg\">$pg</a> "; } } if($page != $totalpages){ echo "<a href='".$_SERVER['PHP_SELF'].'?page='.$next."'>></a> "; echo "<a href='".$_SERVER['PHP_SELF'].'?page='.$totalpages."'>>></a> "; } ?> <select name="menu1" onChange="MM_jumpMenu('parent',this,0)"> <option value="">选择</option> <?php for($pg1=1;$pg1<=$totalpages;$pg1++) { echo "<option value=\"".$_SERVER['PHP_SELF']."?page=$pg1\">".$pg1."</option>"; }?> </select> </td></form> </tr> </table> <?php } else {//记录集为空时显示?> <table> <tr class="tr"> <td height="24"><div align="center">没有任何记录</div></td> </tr> </table> <?php }?> </body> </html> <?php $result1->free_result(); $result->free_result(); //mysql_free_result($result); ?>
true
b275d519aab225cc2feabf47088bf68033385894
PHP
SoleSS/yii2-quiz
/models/QuizTest.php
UTF-8
1,945
2.546875
3
[]
no_license
<?php namespace soless\quiz\models; use Yii; use yii\db\Expression; use yii\helpers\ArrayHelper; /** * This is the model class for table "quiz_test". * * @property int $id * @property string $title Наименование * @property string|null $description Описание * @property string|null $questions_list Список вопросов * @property int|null $solve_time Время для завершения теста * * @property QuizResult[] $quizResults * @property User[] $users * @property-read array $resultDates */ class QuizTest extends base\QuizTest { const QUESTION_STATUS_DISABLED = 0; const QUESTION_STATUS_ENABLED = 1; const DEFAULT_SOLVE_TIME = 0; public function getQuestionsList () { $ids = []; foreach ($this->questions_list as $item) { if ($item['status'] == static::QUESTION_STATUS_ENABLED) { $ids[] = $item['question_id']; } } return $ids; } public function getQuestions () { return QuizQuestion::find() ->where(['id' => $this->questionsList]) ->all(); } /** * @return \yii\db\ActiveQuery */ public function getQuizResults() { return $this->hasMany(QuizResult::className(), ['quiz_test_id' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getUsers() { return $this->hasMany(User::className(), ['id' => 'user_id'])->viaTable('quiz_result', ['quiz_test_id' => 'id']); } public static function asArray() { return \yii\helpers\ArrayHelper::map(static::find()->select(['id', 'title'])->asArray()->all(), 'id', 'title'); } public function getResultDates() { return QuizResult::find() ->select(new Expression("DATE(created_at)")) ->distinct() ->where(['quiz_test_id' => $this->id]) ->column(); } }
true
4451f34701a110eb24bc5af96a24a86296e96562
PHP
Diegoni/mutual
/respuestabuscarsaldo.php
UTF-8
6,820
2.78125
3
[]
no_license
<?php include_once("menu.php"); ?> <!-------------------------------------------------------------------- ---------------------------------------------------------------------- Cuerpo de la pagina ---------------------------------------------------------------------- ---------------------------------------------------------------------> <div class="span9"> <?php /*-------------------------------------------------------------------- ---------------------------------------------------------------------- Primer paso busco los clientes ---------------------------------------------------------------------- --------------------------------------------------------------------*/ if (isset($_POST['buscar']) && !isset($_POST['conciliar'])) { //asigno las variables $cliente = $_POST['cliente']; //echo "Buscado: ".$cliente; $query="SELECT * FROM `clientes` where dni LIKE '%".$cliente."%' OR nombre LIKE '%".$cliente."%' OR apellido LIKE '%".$cliente."%' ORDER BY apellido ASC"; $result=mysql_query($query); mysql_query("SET NAMES 'utf8'"); $numero_filas = mysql_num_rows($result); //si no hay registros que coincidan con la busqueda se informa al usuario mediante un cartel if($numero_filas==0){ echo '<h4>No hay registros que coincidan con los datos ingresados</h4><a class="btn btn-danger" href="buscar.php?bandera=1">Volver</a>'; }else{ //muestra la cantidad de registros que trajo la consulta echo "$numero_filas Registros\n"; echo '<br>'; echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post" name="form1">'; //Del boton conciliar echo '<table class="table table-striped">'; //Titulos de la tabla echo '<tr class="info">'; echo '<td></td>'; echo '<td>DNI</td>'; echo '<td>Nombre</td>'; echo '<td>Apellido</td>'; echo '<td>Tel</td>'; echo '<td>Direccion</td>'; echo '<td>ID</td>'; echo '<td></td>'; echo '</tr>'; //muestro todos los clientes que cohinciden con el filtro aplicado while ($rows = mysql_fetch_array($result)) { echo '<tr>'; echo '<td><input type="radio" onclick="document.form1.conciliar.disabled=false;" value="'.$rows['idclientes'] . '" name="radio" size="1"></td>'; echo '<td>' . $rows['dni'] . '</td>'; echo '<td>' . $rows['nombre'] . '</td>'; echo '<td>' . $rows['apellido'] . '</td>'; echo '<td>' . $rows['telefono'] . '</td>'; echo '<td>' . $rows['Direccion'] . '</td>'; echo '<td>' . $rows['idclientes'] . '</td>';?> <td><a href="#" title="Permite editar al cliente" onClick="abrirVentana('edit_cliente.php?id=<?echo $rows['idclientes'];?>')"><i class="icon-edit-sign"></i></a></td> <? echo '</tr>'; } echo '</table>'; //fin de la tabla, mando la el id del cliente seleccionado echo '<input type="submit" class="btn" name="conciliar" value="Buscar" id="conciliar" disabled>'; echo '<input type="hidden" name="busqueda" value="'.$cliente.'">'; echo '</form>'; } } /*-------------------------------------------------------------------- ---------------------------------------------------------------------- Segundo paso Seleccion de usuarios a conciliar ---------------------------------------------------------------------- --------------------------------------------------------------------*/ //opcion que permite ingresar a esta segunda parte del codigo else if (isset($_POST['conciliar'])) { $idsel=$_POST['radio']; $busqueda=$_POST['busqueda']; //Busco el usuario a mantener $query="SELECT * FROM `clientes` WHERE idclientes='".$idsel."' "; $cliente=mysql_query($query) or die(mysql_error()); //Guardo el DNI del cliente seleccionado en una variable para usarla mas adelante while ($clientes = mysql_fetch_array($cliente)){ $dni=$clientes['dni']; $nombre=$clientes['nombre']; $apellido=$clientes['apellido']; } //Busco dentro de las facturas aquellas que pertenescan al cliente $query="SELECT * FROM `factura` WHERE idclien='".$idsel."' AND anulada='--N--' ORDER BY idfactura ASC"; mysql_query("SET NAMES 'utf8'"); $result=mysql_query($query); //Titulos de la tabla echo "<h3>Facturas de ".$apellido." - ".$nombre.": <a href='#' class='show_hide' title='ver detalle'><i class='icon-chevron-sign-down'></i></a></h3><br><br>"; //recorro el arraw de las facturas while ($rows = mysql_fetch_array($result)) { echo '<table class="table table-striped">'; echo '<tr class="info">'; echo '<td><strong>Factura</strong></td>'; echo '<td>' . $rows['numerofactura'] . '</td>'; echo '<td><strong>Fecha</strong></td>'; echo '<td>' . $rows['fecha'] . '</td>'; echo '</tr>'; echo '</table>'; //cominenzo de la tabla de detalle factura echo "<div class='slidingDiv'>"; echo '<table class="table table-striped table-hover">'; echo '<tr class="warning">'; echo '<td>Concepto</td>'; echo '<td>Monto</td>'; echo '<td>Forma de $</td>'; echo '</tr>'; //asigno el id de la factura a un variable, y con esta consulto dentro de la tabla detalle los registros que sean de la factura $idfactura=$rows['idfactura']; $query="SELECT * FROM `detalle` WHERE idfactura=".$idfactura." ORDER BY iddetalle ASC"; mysql_query("SET NAMES 'utf8'"); $detalle=mysql_query($query); //recorro el arraw de los detalles de la factura while ($detalles = mysql_fetch_array($detalle)) { echo '<tr>'; echo '<td>' . $detalles['nombreconcepto'] . '</td>'; echo '<td>$ ' . $detalles['monto'] . '</td>'; echo '<td>' . $detalles['formapago'] . '</td>'; $subtotal=$detalles['monto']+$subtotal; echo '</tr>'; } echo '<tr>'; echo '<td><strong> Suma total </strong></td>'; echo '<td title="Total de la factura ' . $rows['numerofactura'] . '"><strong>$ ' . $subtotal . '</strong></td>'; $total=$total+$subtotal;//total acumulado de las facturas echo '<td title="El acumulado suma los totales de las facturas">acum: $ ' . $total . ' </td>'; $subtotal=0;//subtotal reiniciado para comenzar un nuevo bucle, con una nueva factura echo '</tr>'; echo '</table>'; echo '</div>'; echo '<br>'; } echo '<br>'; echo '<br>'; echo '<hr>'; //Busco en la tabla clientes, clientes que tengan el mismo dni que el seleccionado $query="SELECT * FROM `clientes` where dni='".$dni."' "; //echo $query; mysql_query("SET NAMES 'utf8'"); $result=mysql_query($query); $numero_filas = mysql_num_rows($result); //si me trajo registros es porque la tabla contiene registros que cohincidan con el dni, muestro cartel y envio datos para colocar en el formulario if($numero_filas>1){ echo "<h4>Hay clientes con el mismo dni: <a class='btn btn-danger' href='buscar.php?bandera=1&dato=".$dni."'>Conciliarlos</a></h4>"; } } ?> </div><!-- cierra clase span9--> </div><!-- cierra clase row--> <?php include_once("footer.php"); ?>
true
c14476bff10fd213bffca6a15b14fa6df9e40e8f
PHP
bryly27/codingDojoAssignments
/projects/eCommerce/application/controllers/wall.php
UTF-8
4,018
2.5625
3
[]
no_license
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Wall extends CI_Controller { public function index() { $this->load->library('form_validation'); $this->load->view('main'); // $this->session->sess_destroy(); } //---------------------registering--------------------------- public function register() { if($this->input->post('action') == 'register') { $this->load->model('user'); //---------form validation--------- $this->load->library('form_validation'); $this->form_validation->set_rules('first_name', 'FirstName', 'trim|required|min_length[2]'); $this->form_validation->set_rules('last_name', 'LastName', 'trim|required|min_length[2]'); $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]'); $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[8]|matches[confirm_password]'); $this->form_validation->set_rules('confirm_password', 'Password Confirmation', 'trim|required'); if ($this->form_validation->run() === FALSE) { $this->load->view('main'); } else { $user_details = array( "first_name" => $this->input->post('first_name'), "last_name" => $this->input->post('last_name'), "email" => $this->input->post('email'), "password" => md5($this->input->post('password')) ); $add_user = $this->user->add_user($user_details); redirect('/'); } } } //-----------------------login-------------------------- public function login() { $this->load->library('form_validation'); $this->form_validation->set_rules("email","Email","required|valid_email"); // if(empty($this->input->post('email') || $this->input->post('password'))) // { // echo 'Please enter login information'; // } // else // { if($this->input->post('action') == 'login') { $this->load->model('user'); $email = $this->input->post('email'); $password = md5($this->input->post('password')); $user = $this->user->get_user($email); $this->session->set_userdata('userInfo', $user); // if($email == $user['email'] && $password == $user['password']) if ($user && $user['password']==$password) { $this->session->set_userdata('log', TRUE); redirect('/wall/home'); // $this->load->model('user'); // $messages['message'] = $this->user->get_messages(); // $this->load->view('success', $messages); } else { // echo 'the information you entered is wrong'; $this->session->set_userdata('log', FALSE); // redirect('/'); echo 'Please enter valid credentials'; $this->load->view('main'); } } // } } //------------------------home-------------------- public function home() { if($this->session->userdata('log') == TRUE) { $this->load->model('user'); $messages['userInfo'] = $this->session->userdata('userInfo'); $messages['message'] = $this->user->get_messages(); $messages['comment'] = $this->user->get_comments(); // $message['commentPost'] = $this->user->get_comments($userInfo['id']); // var_dump($messages); // die(); $this->load->view('success', $messages); } else { redirect('/'); } } //----------------adding message------------------- public function addMessage() { $this->load->model('user'); $messageInfo = array( "message" => $this->input->post('message'), "user_id" => $this->input->post('action'), ); $this->user->add_message($messageInfo); redirect('wall/home'); } //----------------adding comment--------------------- public function addComment() { $this->load->model('user'); $commentInfo = array( "comment" => $this->input->post('comment'), "messages_id" => $this->input->post('commentAction'), "user_id" => $this->input->post('commentAction2'), ); $this->user->add_comment($commentInfo); redirect('wall/home'); } //--------------------log off---------------------- public function logoff() { $this->session->sess_destroy(); redirect('/'); } }
true
7d2d4139f53f5bfca35db893d6d57b4f46ffeecc
PHP
llamani/cdp
/api/src/Entity/Project.php
UTF-8
5,454
2.609375
3
[]
no_license
<?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\ProjectRepository") * @ORM\Table(name="projects") */ class Project { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $name; /** * @ORM\Column(type="text") */ private $description; /** * @ORM\Column(type="datetime") */ private $created_at; /** * @ORM\OneToMany(targetEntity="App\Entity\Issue", mappedBy="project", orphanRemoval=true) */ private $issues; /** * @ORM\OneToMany(targetEntity="App\Entity\Test", mappedBy="project", orphanRemoval=true) */ private $tests; /** * @ORM\OneToMany(targetEntity="App\Entity\Sprint", mappedBy="project", orphanRemoval=true) */ private $sprints; /** * @ORM\OneToMany(targetEntity="App\Entity\UserProjectRelation", mappedBy="project", orphanRemoval=true) */ private $userProjectRelations; public function __construct() { $this->issues = new ArrayCollection(); $this->tests = new ArrayCollection(); $this->sprints = new ArrayCollection(); $this->userProjectRelations = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getDescription(): ?string { return $this->description; } public function setDescription(string $description): self { $this->description = $description; return $this; } public function getCreatedAt(): ?\DateTimeInterface { return $this->created_at; } public function setCreatedAt(\DateTimeInterface $created_at): self { $this->created_at = $created_at; return $this; } /** * @return Collection|Issue[] */ public function getIssues(): Collection { return $this->issues; } public function addIssue(Issue $issue): self { if (!$this->issues->contains($issue)) { $this->issues[] = $issue; $issue->setProject($this); } return $this; } public function removeIssue(Issue $issue): self { if ($this->issues->contains($issue)) { $this->issues->removeElement($issue); // set the owning side to null (unless already changed) if ($issue->getProject() === $this) { $issue->setProject(null); } } return $this; } /** * @return Collection|Test[] */ public function getTests(): Collection { return $this->tests; } public function addTest(Test $test): self { if (!$this->tests->contains($test)) { $this->tests[] = $test; $test->setProject($this); } return $this; } public function removeTest(Test $test): self { if ($this->tests->contains($test)) { $this->tests->removeElement($test); // set the owning side to null (unless already changed) if ($test->getProject() === $this) { $test->setProject(null); } } return $this; } /** * @return Collection|Sprint[] */ public function getSprints(): Collection { return $this->sprints; } public function addSprint(Sprint $sprint): self { if (!$this->sprints->contains($sprint)) { $this->sprints[] = $sprint; $sprint->setProject($this); } return $this; } public function removeSprint(Sprint $sprint): self { if ($this->sprints->contains($sprint)) { $this->sprints->removeElement($sprint); // set the owning side to null (unless already changed) if ($sprint->getProject() === $this) { $sprint->setProject(null); } } return $this; } /** * @return Collection|UserProjectRelation[] */ public function getUserProjectRelations(): Collection { return $this->userProjectRelations; } public function addUserProjectRelation(UserProjectRelation $userProjectRelation): self { if (!$this->userProjectRelations->contains($userProjectRelation)) { $this->userProjectRelations[] = $userProjectRelation; $userProjectRelation->setProject($this); } return $this; } public function removeUserProjectRelation(UserProjectRelation $userProjectRelation): self { if ($this->userProjectRelations->contains($userProjectRelation)) { $this->userProjectRelations->removeElement($userProjectRelation); // set the owning side to null (unless already changed) if ($userProjectRelation->getProject() === $this) { $userProjectRelation->setProject(null); } } return $this; } public function __toString() { return $this->getName(); } }
true
795b2c3768b50857729b739118bead2197ede5c2
PHP
alifrio75/pg-schedule
/frontend/models/Atlet.php
UTF-8
2,421
2.625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "atlet". * * @property int $id * @property string $name * @property int $country * @property string $avatar * @property string $birthday * @property string $gender * @property int $umur * * @property Countries $country0 * @property PertandinganJadwal[] $pertandinganJadwals * @property PertandinganJadwal[] $pertandinganJadwals0 */ class Atlet extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'atlet'; } /** * @inheritdoc */ public function rules() { return [ [['country', 'umur'], 'integer'], [['birthday', 'gender'], 'required'], [['birthday', 'avatar'], 'safe'], [['gender'], 'string'], [['name'], 'string', 'max' => 255], [['avatar'], 'string', 'max' => 255], [['name'], 'unique'], [['country'], 'exist', 'skipOnError' => true, 'targetClass' => Countries::className(), 'targetAttribute' => ['country' => 'id']], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Name', 'country' => 'Country', 'avatar' => 'Avatar', 'birthday' => 'Birthday', 'gender' => 'Gender', 'umur' => 'Umur', ]; } /** * @return \yii\db\ActiveQuery */ public function getCountry0() { return $this->hasOne(Countries::className(), ['id' => 'country']); } /** * @return \yii\db\ActiveQuery */ public function getPertandinganJadwals() { return $this->hasMany(PertandinganJadwal::className(), ['home' => 'id']); } /** * @return \yii\db\ActiveQuery */ public function getPertandinganJadwals0() { return $this->hasMany(PertandinganJadwal::className(), ['opponent' => 'id']); } public function getPreview1() { if (!empty($this->avatar)) { $image = \yii\helpers\Html::img($this->avatar, []); } else { $image = \yii\helpers\Html::img(Yii::$app->urlManager->baseUrl.'/uploads/default.png', []); } // enclose in a container if you wish with appropriate styles return ($image == null) ? null : \yii\helpers\Html::tag('div', $image); } }
true
4b606eb1abd7b134d4470d8ffee17836a4cdbb62
PHP
SamihaTahsin1/studentmanagement
/application/controllers/Admin.php
UTF-8
5,157
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Admin extends CI_Controller { public function __construct() { parent::__construct(); if (!$this->session->userdata('user_id')) { return redirect(base_url()); } } public function dashboard() { $this->load->model('queries'); $schoolUsers = $this->queries->viewAllschools(); $this->load->view('dashboard', ['schoolUsers' => $schoolUsers]); } public function addschool() { $this->load->view('addschool'); } public function createschool() { $this->form_validation->set_rules('schoolname','school Name', 'required'); $this->form_validation->set_rules('branch','Branch Name', 'required'); if ($this->form_validation->run()) { $data = $this->input->post(); $this->load->model('queries'); if ($this->queries->insertschool($data)) { $this->session->set_flashdata('message', 'school Added Successfully'); } else { $this->session->set_flashdata('message', 'Failed To Add!'); } return redirect('admin/dashboard'); } else { $this->addschool(); } } public function addStudent() { $this->load->model('queries'); $schools = $this->queries->getschools(); $this->load->view('addStudent', ['schools'=>$schools]); } public function createStudent() { $this->form_validation->set_rules('studentname','Student Name', 'required'); $this->form_validation->set_rules('school_id','school Name', 'required'); $this->form_validation->set_rules('email','Email', 'required'); $this->form_validation->set_rules('gender','Gender', 'required'); $this->form_validation->set_rules('course','Course', 'required'); if ($this->form_validation->run()) { $data = $this->input->post(); $this->load->model('queries'); if ($this->queries->insertStudent($data)) { $this->session->set_flashdata('message', 'Student Added Successfully'); } else { $this->session->set_flashdata('message', 'Failed To Add!'); } return redirect('admin/addStudent'); } else { $this->addStudent(); } } public function viewstudents($school_id) { $this->load->model('queries'); $students = $this->queries->getStudents($school_id); $this->load->view('viewStudents', ['students' => $students]); } public function editStudent($student_id) { $this->load->model('queries'); $schools = $this->queries->getschools(); $studentInfo = $this->queries->getStudentRecord($student_id); $this->load->view('editStudent', ['schools' => $schools, 'studentInfo' => $studentInfo]); } public function addModerator() { $this->load->model('queries'); $schools = $this->queries->getschools(); $roles = $this->queries->getRoles(); // echo "<pre>"; // print_r($schools); // echo "</pre>"; // exit(); $this->load->view('addModerator', ['schools' => $schools, 'roles' => $roles]); } public function createModerator() { $this->form_validation->set_rules('username','Username', 'required'); $this->form_validation->set_rules('school_id','school Name', 'required'); $this->form_validation->set_rules('email','Email', 'required'); $this->form_validation->set_rules('gender','Gender', 'required'); $this->form_validation->set_rules('role_id','Role', 'required'); $this->form_validation->set_rules('password','Password', 'required'); $this->form_validation->set_rules('confpwd','Password Confirmation', 'required'); if ($this->form_validation->run()) { $data = $this->input->post(); $data['password'] = sha1($this->input->post('password')); $data['confpwd'] = sha1($this->input->post('confpwd')); $this->load->model('queries'); if ($this->queries->insertModerator($data)) { $this->session->set_flashdata('message', 'Moderator Added Successfully'); } else { $this->session->set_flashdata('message', 'Failed To Add!'); } return redirect('admin/dashboard'); } else { $this->addModerator(); } } public function modifystudent($id) { $this->form_validation->set_rules('studentname','Student Name', 'required'); $this->form_validation->set_rules('school_id','school Name', 'required'); $this->form_validation->set_rules('email','Email', 'required'); $this->form_validation->set_rules('gender','Gender', 'required'); $this->form_validation->set_rules('course','Course', 'required'); if ($this->form_validation->run()) { $data = $this->input->post(); $this->load->model('queries'); if ($this->queries->updateStudent($data, $id)) { $this->session->set_flashdata('message', 'Student Updated Successfully'); } else { $this->session->set_flashdata('message', 'Failed To Update!'); } redirect($_SERVER['HTTP_REFERER']); // return redirect('admin/addStudent'); } else { $this->editStudent(); } } public function deletestudent($id) { $this->load->model('queries'); if($this->queries->removeStudent($id)) { return redirect('admin/dashboard'); } else { return redirect('admin/dashboard'); } } public function moderator() { $this->load->model('queries'); $moderator = $this->queries->viewAllschools(); $this->load->view('viewModerator', ['moderator'=>$moderator]); } }
true
9ae9b74006c87d3ab5db02854bdd188a9e2b121e
PHP
Ferreira17dtr/SistRedeslogin1
/filmes_edit.php
UTF-8
1,737
2.765625
3
[]
no_license
<?php if($_SERVER['REQUEST_METHOD']=="GET"){ if (isset($_GET['filme']) && is_numeric($_GET['filme'])) { $idFilme = $_GET['filme']; $con = new mysqli ("localhost","root","","filmes"); if ($con->connect_errno!=0) { echo "<h1>Ocorreu um erro no acesso à base de dados. <br>" .$con->conect_error. "</h1>"; exit(); } $sql = "Select * from filmes where id_filme=?"; $stm = $con->prepare($sql); if($stm!=false) { $stm->bind_param("i",$idFilme); $stm->execute(); $res=$stm->get_result(); $livro = $res->fetch_assoc(); $stm->close(); } ?> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Editar filme</title> </head> <body> <h1>Editar filmes</h1> <form action="filmes_update.php" method="post"> <label>ID filme</label><input type="text" name="idFilme" required value ="<?php echo$livro['id_filme'];?>"><br> <label>Titulo</label><input type="text" name="titulo" required value ="<?php echo$livro['titulo'];?>"><br> <label>Sinopse</label><input type="text" name="sinopse" value ="<?php echo$livro['sinopse'];?>"><br> <label>Quantidade</label><input type="text" name="quantidade" value ="<?php echo$livro['quantidade'];?>"><br> <label>Idioma</label><input type="numeric" name="idioma" required value ="<?php echo$livro['idioma'];?>"><br> <label>Data lançamento</label><input type="date" name="data_lancamento" value ="<?php echo$livro['data_lancamento'];?>"><br> <input type="submit" name="enviar"><br> </form> </body> </html> <?php } else { echo ('<h1>Houve um erro ao processar o pedido. <br> Dentro de segundos será reencaminhado!</h1>'); header("refresh=2;url=index.php"); } }
true
c3aafb4e2cf7b1f8c0ec7d580180a288476de8ff
PHP
winatawelly/skripsi
/code/datasetGenerator/createJson/createDatasetJson.php
UTF-8
10,448
2.625
3
[]
no_license
<?php $data = file_get_contents("../dataset/datafile/season14-15/season_stats.json"); $data1 = file_get_contents("../dataset/datafile/season15-16/season_stats.json"); $data2 = file_get_contents("../dataset/datafile/season16-17/season_stats.json"); #$dataValid = file_get_contents("dataset/datafile/season17-18/season_stats.json"); //$data = file_get_contents("dataset/test.json"); $data = json_decode($data,true); $data1 = json_decode($data1,true); $data2 = json_decode($data2,true); #$dataValid = json_decode($dataValid,true); $fInput = array(); $fOutput = array(); $readCount = 0; $jsonObj = array(); echo "Reading file..."; foreach($data as $key => $values){ /* if($readCount == 50){ break; } */ $input = array(); $output = array(); $readCount++; foreach($values as $key2 => $values2){ //echo "<br><br>"; foreach($values2 as $key3 => $values3){ if($key3 == 'team_details'){ foreach($values3 as $key4 => $values4){ if($key4 == 'team_rating'){ //team name and team rating //echo $key4." = ".$values4."<br>"; //array_push($input,$values4/10); } } } if($key3 == 'aggregate_stats'){ $noGoal = false; foreach($values3 as $key4 => $values4){ if($key4 == 'goals'){ //goal(s) scored //echo $key4." = ".$values4."<br>"; array_push($output,(int)$values4); $noGoal = true; } } if($noGoal == false){ array_push($output,0); } //echo "<br>"; } if($key3 == 'Player_stats'){ foreach($values3 as $key4 => $values4){ //player name //echo $key4."<br>"; foreach($values4 as $key5 => $values5){ if($key5 == 'player_details'){ //player name, position, and rating foreach($values5 as $key6 => $values6){ if($key6 == 'player_position_info' || $key6 == 'player_rating' ){ if($values6 == 'Sub'){ break; }else if($key6 == 'player_rating'){ array_push($input,$values6/10); } //echo $key6.' = '.$values6.'<br>'; } } //echo "<br>"; } } } } } } /* echo "<br>"; $input_str = ''; for($i = 0 ; $i < count($input) ; $i++){ if($i == 0){ $input_str = $input_str.'['; } $input_str = $input_str.$input[$i].', '; if($i == count($input)-1){ $input_str = $input_str.']'; } } echo $input_str; */ array_push($jsonObj,array('input' => $input , 'output' => $output)); //array_push($fInput,$input); //array_push($fOutput,$output); } foreach($data1 as $key => $values){ /* if($readCount == 50){ break; } */ $input = array(); $output = array(); $readCount++; foreach($values as $key2 => $values2){ //echo "<br><br>"; foreach($values2 as $key3 => $values3){ if($key3 == 'team_details'){ foreach($values3 as $key4 => $values4){ if($key4 == 'team_rating'){ //team name and team rating //echo $key4." = ".$values4."<br>"; //array_push($input,$values4/10); } } } if($key3 == 'aggregate_stats'){ $noGoal = false; foreach($values3 as $key4 => $values4){ if($key4 == 'goals'){ //goal(s) scored //echo $key4." = ".$values4."<br>"; array_push($output,(int)$values4); $noGoal = true; } } if($noGoal == false){ array_push($output,0); } //echo "<br>"; } if($key3 == 'Player_stats'){ foreach($values3 as $key4 => $values4){ //player name //echo $key4."<br>"; foreach($values4 as $key5 => $values5){ if($key5 == 'player_details'){ //player name, position, and rating foreach($values5 as $key6 => $values6){ if($key6 == 'player_position_info' || $key6 == 'player_rating' ){ if($values6 == 'Sub'){ break; }else if($key6 == 'player_rating'){ array_push($input,$values6/10); } //echo $key6.' = '.$values6.'<br>'; } } //echo "<br>"; } } } } } } /* echo "<br>"; $input_str = ''; for($i = 0 ; $i < count($input) ; $i++){ if($i == 0){ $input_str = $input_str.'['; } $input_str = $input_str.$input[$i].', '; if($i == count($input)-1){ $input_str = $input_str.']'; } } echo $input_str; */ array_push($jsonObj,array('input' => $input , 'output' => $output)); //array_push($fInput,$input); //array_push($fOutput,$output); } foreach($data2 as $key => $values){ /* if($readCount == 50){ break; } */ $input = array(); $output = array(); $readCount++; foreach($values as $key2 => $values2){ //echo "<br><br>"; foreach($values2 as $key3 => $values3){ if($key3 == 'team_details'){ foreach($values3 as $key4 => $values4){ if($key4 == 'team_rating'){ //team name and team rating //echo $key4." = ".$values4."<br>"; //array_push($input,$values4/10); } } } if($key3 == 'aggregate_stats'){ $noGoal = false; foreach($values3 as $key4 => $values4){ if($key4 == 'goals'){ //goal(s) scored //echo $key4." = ".$values4."<br>"; array_push($output,(int)$values4); $noGoal = true; } } if($noGoal == false){ array_push($output,0); } //echo "<br>"; } if($key3 == 'Player_stats'){ foreach($values3 as $key4 => $values4){ //player name //echo $key4."<br>"; foreach($values4 as $key5 => $values5){ if($key5 == 'player_details'){ //player name, position, and rating foreach($values5 as $key6 => $values6){ if($key6 == 'player_position_info' || $key6 == 'player_rating' ){ if($values6 == 'Sub'){ break; }else if($key6 == 'player_rating'){ array_push($input,$values6/10); } //echo $key6.' = '.$values6.'<br>'; } } //echo "<br>"; } } } } } } /* echo "<br>"; $input_str = ''; for($i = 0 ; $i < count($input) ; $i++){ if($i == 0){ $input_str = $input_str.'['; } $input_str = $input_str.$input[$i].', '; if($i == count($input)-1){ $input_str = $input_str.']'; } } echo $input_str; */ array_push($jsonObj,array('input' => $input , 'output' => $output)); //array_push($fInput,$input); //array_push($fOutput,$output); } //print("<pre>".print_r($fInput,true)."</pre>"); //print("<pre>".print_r($fOutput,true)."</pre>"); // $input_str = '['; // $inputCount = 0; // $outputCount = 0; // foreach($fInput as $key => $values){ // $inputCount++; // $input_str = $input_str.'('; // foreach($values as $key2 => $values2){ // $input_str = $input_str.$values2.', '; // } // $input_str = $input_str.'),'; // } // $input_str = $input_str.']'; // $output_str = '['; // foreach($fOutput as $key => $values){ // $outputCount++; // $output_str = $output_str.'('; // foreach($values as $key2 => $values2){ // $output_str = $output_str.$values2.', '; // } // $output_str = $output_str.'),'; // } // $output_str = $output_str.']'; $myfile = fopen("inputTestPlayerOnly.json", "w") or die("Unable to open file!"); fwrite($myfile,json_encode($jsonObj)) // fwrite($myfile, $input_str); // $myfile = fopen("OutputTest.txt", "w") or die("Unable to open file!"); // fwrite($myfile, $output_str); // echo "<br>Done!"; // echo $inputCount."<br>"; // echo $outputCount."<br>"; // echo json_encode($jsonObj) //echo $input_str."<br>"; //echo $output_str; ?>
true
cb02e00a691c1061afcf56b21cc5d625450912db
PHP
MiguelKersch/php-morning
/guttentag.php
UTF-8
875
2.734375
3
[]
no_license
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php $offset = strtotime("1 hours"); date_default_timezone_get('Europe/Amsterdam'); echo "The time is " . date("h:i", $offset); $ochtend = date("6:00"); $middag = date("12:00"); $avond = date("18:00"); $nacht = date("0:00"); $tijd = date("h:i", $offset); if( $tijd >= $ochtend && $tijd <= $middag ){ echo '<body style="background-image: url(morning.png); ">'; }elseif($tijd >= $middag && $tijd <= $avond){ echo '<body style="background-image: url(afternoon.png); ">'; }elseif($tijd >= $avond && $tijd > $nacht){ echo '<body style="background-image: url(evening.png); ">'; }elseif($tijd >= $nacht && $tijd <= $ochtend){ echo '<body style="background-image: url(night.png); ">'; } ?> <style type="text/css"> </style> </body> </html>
true
d175f3728d4aa13b16c072b6453c091642b34d0d
PHP
Apurva-tech/IWP-CSE3002
/Lab-DA-3/Q6/Q6.php
UTF-8
387
2.84375
3
[]
no_license
<?php $total_count = 0; if(isset($_COOKIE['count'])){ $total_count = $_COOKIE['count']; $total_count ++; } if(isset($_COOKIE['last_visit'])){ $last_visit = $_COOKIE['last_visit']; } setcookie('count', $total_count); setcookie('last_visit', date("H:i:s")); if($total_count == 0){ echo "Welcome! We are glad to see you here."; } else { echo "This is your visit number ".$total_count; } ?>
true
a1ba740e41201e4545176933b6fbce2d15559029
PHP
kktsvetkov/asido.kaloyan.info
/examples/resize/example_05.phps
UTF-8
1,491
2.890625
3
[]
no_license
<?php /** * Resize Example #05 * * This example shows the `passepartout` resize which resizes the image * proportionally, but the result has the proportions of the provided width and * height with the blank areas filled with the provided color. In the case we are * resizing a 640x480 image by making it fit inside a square frame 300x300 and * using a nice green color as background. If the color argument is omitted, then * "white" is used to fill the blank areas. This is very handy when you want all * the resulting images to fit inside some frame without stretching them if the * proportions of the image and the frame do not match * * @package Acido * @subpackage Acido.Examples.Resize */ ///////////////////////////////////////////////////////////////////////////// /** * Include the main Asido class */ include('./../../class.asido.php'); /** * Set the correct driver: this depends on your local environment */ Asido::Driver('gd'); /** * Create an Asido_Image object and provide the name of the source * image, and the name with which you want to save the file */ $i1 = Asido::Image('example.png', 'result_05.png'); /** * Resize the image by putting it inside a square frame (300x300) with `rgb(177,77,37)` as background. */ Asido::Frame($i1, 300, 300, Asido::Color(39, 107, 20)); /** * Save the result */ $i1->Save(ASIDO_OVERWRITE_ENABLED); ///////////////////////////////////////////////////////////////////////////// ?>
true
7aabbf7910e00a8074605224676c3db9b337e614
PHP
atlcurling/tkt
/tkt0.1/bargraph.php
UTF-8
882
3.234375
3
[]
no_license
<?php function barfrag($col, $wid = 16) { echo "<span style='border: black 1px solid; background-color: $col; padding: 0 {$wid}px 0 0;'></span>"; } function bargraph($x, $xcol, $n = 0, $ncol = "", $wid = 16) { if ($n == 0) $n = $x; if ($ncol == "") $ncol = $xcol; echo "<span style='border: black 1px solid'>"; for ($i = 0; $i < $x; $i ++) barfrag($xcol, $wid); for ($i = $x; $i < $n; $i ++) barfrag($ncol, $wid); echo "</span>\n"; } function bargraph2($x1, $x1col, $x2 = 0, $x2col = "", $n = 0, $ncol = "", $wid = 16) { if ($x2col == "") $x2col = $x1col; if ($n == 0) $n = $x1 + $x2; if ($ncol == "") $ncol = $x1col; echo "<span style='border: black 1px solid'>"; for ($i = 0; $i < $x1; $i ++) barfrag($x1col, $wid); for ($i = $x1; $i < $x1 + $x2; $i ++) barfrag($x2col, $wid); for ($i = $x1 + $x2; $i < $n; $i ++) barfrag($ncol, $wid); echo "</span>\n"; } ?>
true
1883e34a7686a6b1687407c7a8acf31f2e55a055
PHP
jakflo/astromen_symfony
/src/Forms/DataObjects/AstromanAdd.php
UTF-8
2,876
2.84375
3
[ "MIT" ]
permissive
<?php namespace App\Forms\DataObjects; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Length; use App\Forms\MyConstraints\CzDate; use Symfony\Component\Validator\Constraints\IsTrue; use Symfony\Component\Validator\Mapping\ClassMetadata; use App\Entity\Models\AstromenModel; use App\Entity\Models\Db_wrap; use App\Utils\DateTools; class AstromanAdd { protected $fName; protected $lName; protected $dob; protected $skill; /** * * @var Db_wrap */ protected $db; public function __construct(Db_wrap $db) { $this->db = $db; } public function getFName() { return $this->fName; } public function getLName() { return $this->lName; } public function getDob() { return $this->dob; } public function getSkill() { return $this->skill; } public function setFName($fName) { $this->fName = $fName; } public function setLName($lName) { $this->lName = $lName; } public function setDob($dob) { $this->dob = $dob; } public function setSkill($skill) { $this->skill = $skill; } public function getFullName() { return trim("{$this->fName} {$this->lName}"); } public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('fName', new NotBlank(['message' => 'Zadejte jméno'])); $metadata->addPropertyConstraint('fName', new Length(['max' => 20, 'maxMessage' => 'Jméno může mít nanejvýš 20 znaků'])); $metadata->addPropertyConstraint('lName', new NotBlank(['message' => 'Zadejte příjmení'])); $metadata->addPropertyConstraint('lName', new Length(['max' => 20, 'maxMessage' => 'Příjmení může mít nanejvýš 20 znaků'])); $metadata->addPropertyConstraint('dob', new NotBlank(['message' => 'Zadejte datum narození'])); $metadata->addPropertyConstraint('dob', new CzDate(['message' => 'Neplatné datum narození'])); $metadata->addPropertyConstraint('skill', new NotBlank(['message' => 'Zadejte dovednost'])); $metadata->addPropertyConstraint('skill', new Length(['max' => 45, 'maxMessage' => 'Dovednost může mít nanejvýš 45 znaků'])); $metadata->addGetterConstraint('nameNotUsedYet', new IsTrue(['message' => 'Tento astronaut již existuje'])); } public function isNameNotUsedYet() { $dateTools = new DateTools; if (empty($this->fName) or empty($this->lName) or empty($this->dob) or !$dateTools->checkCzDate($this->dob)) { return true; } $model = new AstromenModel($this->db); return !$model->isNameExists($this->fName, $this->lName, $this->dob); } }
true
7c61207b0aeba54096b3b26b157650ac486f8eeb
PHP
roelti/rentalshop
/product_pdf.php
UTF-8
1,155
2.671875
3
[]
no_license
<?php // ------------- Pdf File Attachment Function ------------- \\ # Adds a pdf download section to the description of a single product page function show_product_pdf($content){ // Only for single product pages (woocommerce) if (is_product()){ global $post; $custom_content = ""; if(isset($post->_pdf_id)){ $pdfs = get_children( array ( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'application/pdf', 'orderby' => 'ID', 'order' => 'ASC' )); if (!empty($pdfs)) { $custom_content = __("<p><strong><u>Downloads</u></strong></p>", "rentalshop"); $custom_content.= "<p>"; foreach ( $pdfs as $attachment_id => $attachment ) { $custom_content.='<a href="' . $attachment->guid . '" target="_blank"><i class="fa fa-file-pdf-o" aria-hidden="true"></i> ' . $attachment->post_title . '</a><br>'; } $custom_content.= "</p>"; $content.= $custom_content; } } } return $content; } ?>
true
939f08870b2bbc8e249346d0d0a4ecf041c1fa02
PHP
jel-massih/APISearch
/inc/processRequest.php
UTF-8
1,635
2.59375
3
[]
no_license
<?php include_once('flaggedKeywords.php'); include_once('twilioHandler.php'); include_once('sendGridHandler.php'); include_once('mongoHandler.php'); if($_GET['q'] == null) { return;} $query = $_GET['q']; $keywordSearchVersion = preg_replace('/".*?"/', "", $query); $file = file_get_contents('http://access.alchemyapi.com/calls/text/TextGetRankedKeywords?apikey=fda1e7725193cdb5de390bda841f5152fa746f0d&outputMode=json&text='.urlencode($keywordSearchVersion)); $d_file = json_decode($file); $keywords = array(); foreach($d_file->keywords as $keyword) { $keyword->text = strtolower($keyword->text); array_push($keywords, $keyword->text); } foreach($flags as $flag) { $flag = strtolower($flag); if(stripos($keywordSearchVersion,$flag) !== false) { array_push($keywords, $flag); } } $output = getOutput($query, $keywords); if($output == "") { $output = "Could not Understand your Request! Please Rephrase!"; } echo($output); function getOutput($query, $keywords) { global $twilio, $sendgrid, $record, $emailRecieved, $mongo, $rdio; if (count(array_intersect($keywords, $record)) > 0) { return processTwilioRecording($query, $keywords); } if(count(array_intersect($keywords, $emailRecieved)) > 0) { return processEmailRecieved($query, $keywords); } foreach($keywords as $keyword) { if(in_array($keyword, $rdio)) { return processRdio($query, $keywords); } if(in_array($keyword, $twilio)) { return processTwilio($query, $keywords); } if(in_array($keyword, $sendgrid)) { return processSendGrid($query, $keywords); } if(in_array($keyword, $mongo)) { return processMongo($query, $keywords); } } return ""; } ?>
true
be986c30461839fabbc66938dea29872a229ce6a
PHP
RodriGerometta/CursoWeb
/php/clase 2/ejercicio 2.php
UTF-8
654
3.671875
4
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Ejercicio 2</title> </head> <body> <?php //punto a) $resultado = (min (15, -150, 60, 10, -5, 200)); echo ("El menor valor de la lista es: $resultado <br>" ); //punto b) if ($resultado < 0){ echo ("El valor absoluto es: " .(abs ($resultado))); } ?> </body> </html>
true
fae6147a6c3b9f3cbd74cdae019ab245024adaff
PHP
CodeaciousAU/phplib-security
/src/Session/SessionStore.php
UTF-8
1,718
2.765625
3
[]
no_license
<?php /** * @author Glenn Schmidt <glenn@codeacious.com> */ namespace Codeacious\Security\Session; use Codeacious\Security\Authentication\Assertion; use Codeacious\Security\User; use Laminas\Session\Container; /** * Provides functionality for setting or clearing the current web session user. The session user is * persisted across requests by storing it in a Laminas\Session container. */ class SessionStore extends AssertionStore { /** * @var Container */ private $container; /** * @param Container $container */ public function __construct(Container $container) { $this->container = $container; } /** * Set the logged-in user for the current session. * * @param User|null $user Pass null to clear the session user * @param User|null $realUser If not null, this starts a session whereby $realUser is * impersonating $user. Not applicable if $user is null. * @return void */ public function setSessionUser(User $user = null, User $realUser = null) { parent::setSessionUser($user, $realUser); //Generate a new session ID, in accordance with good security practice $this->container->getManager()->regenerateId(); } /** * @return Assertion|null */ public function getAssertion() { if (!is_array($this->container['assertion'])) return null; return new Assertion($this->container['assertion']); } /** * @param Assertion|null $assertion * @return void */ protected function persistAssertion(Assertion $assertion = null) { $this->container['assertion'] = $assertion ? $assertion->getArrayCopy() : null; } }
true
8992becde75306dae42be2db5827f2d73c04d1e8
PHP
veebayerr/Inventory_Mgmt
/PHP Source Code/payment_report.php
UTF-8
3,500
2.84375
3
[]
no_license
<?php $servername = 'localhost'; //dont chanage $username = 'php'; //username for the application $password = 'dnFRr196rsSK7s0i'; //login credentials php has access to insert and select $dbname = 'joomla'; //should never need to be changed $userId = "Null"; //passed from joomla to this application $storeNo = "Null"; // passed from joomla to this application $conn = new mysqli($servername,$username,$password,$dbname); //sql functions mysqli if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); //establish connection with sql database } if(isset($_GET['storeNo'])){ $storeNo = $_GET['storeNo']; //gets the store no passed from joomla }//end storeno if(isset($_GET['userId'])){ $userId = $_GET['userId']; //gets the employee id passed from joomla }//end userid echo("<html><h1>Sales Report</h1>"); //html consturct //$sql = "SELECT sum(payment_ammount) FROM `payment` WHERE payment_date >= '2016-11-09' and payment_date <= '2016-11-11' and payment_type = 'cash'"; //$result = $conn->query($sql); //complicated sql statement if(isset($_POST['Submit'])){ echo(" <form action='' method='post'> <input type='date' name='start_date' value = '{$_POST['start_date']}'>: Start Date<br> <input type='date' name='end_date' value = '{$_POST['end_date']}'>: End Date<br> <input type = 'submit' name = 'Submit' value ='Run'> </form> <br><br>"); $sql = "SELECT sum(payment_ammount) FROM `payment` WHERE payment_date >= '{$_POST['start_date']}' and payment_date <= '{$_POST['end_date']}' and store_no = {$storeNo} and payment_type = 'cash'"; $cash = $conn->query($sql); $sql = "SELECT sum(payment_ammount) FROM `payment` WHERE payment_date >= '{$_POST['start_date']}' and payment_date <= '{$_POST['end_date']}' and store_no = {$storeNo} and payment_type = 'credit'"; $credit = $conn->query($sql); $sql = "SELECT sum(payment_ammount) FROM `payment` WHERE payment_date >= '{$_POST['start_date']}' and payment_date <= '{$_POST['end_date']}' and store_no = {$storeNo} and payment_type = 'check'"; $check = $conn->query($sql); $cashval = 0; $paid_total = 0; $sql = "SELECT sum(`price_before_tax`) FROM `transaction` WHERE `store_no` ='{$storeNo}' and `transaction_date` <='{$_POST['end_date']}' and `transaction_date` >='{$_POST['start_date']}'"; $tval = $conn->query($sql); while ($row = $cash->fetch_assoc()) { $cashval = $row['sum(payment_ammount)']; } while ($row = $credit->fetch_assoc()) { $creditval = $row['sum(payment_ammount)']; } while ($row = $check->fetch_assoc()) { $checkval = $row['sum(payment_ammount)']; } while ($row = $tval->fetch_assoc()) { $paid_total = $row['sum(`price_before_tax`)']; } $change = ($cashval + $creditval + $checkval) - $paid_total; echo("$".$cashval." in sales paid with cash.<br>"); echo("$".$creditval." in sales paid with credit.<br>"); echo("$".$checkval." in sales paid with check.<br>"); echo("$".($cashval + $creditval + $checkval)." total sales.<br>"); echo("$". $change . " total change given out.<br>"); echo("$". $paid_total . " profit made.<br>"); }else{ echo(" <form action='' method='post'> <input type='date' name='start_date'>: Start Date<br> <input type='date' name='end_date'>: End Date<br> <input type = 'submit' name = 'Submit' value ='Run'> </form> "); } echo("</table></html>");//html closer $conn->close(); //sql closer ?>
true
e9caf21aa8302ea49f28849bd6ecf1328dff0c12
PHP
bishopj88/LaraGab
/src/Traits/EngagePostTrait.php
UTF-8
2,227
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace BishopJ88\LaraGab\Traits; use Exception; Trait EngagePostTrait { /** * Upvotes given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function postUpvote( $parameters = ['postID' => ''] ) { return $this->post('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/upvote'); } /** * Removes the upvote for given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function removeUpvote( $parameters = ['postID' => ''] ) { return $this->delete('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/upvote'); } /** * Removes the downvote for given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function removeDownvote( $parameters = ['postID' => ''] ) { return $this->delete('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/downvote'); } /** * Downvotes given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function postDownvote( $parameters = ['postID' => ''] ) { return $this->post('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/downvote'); } /** * Reposts given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function postRepost( $parameters = ['postID' => ''] ) { return $this->post('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/repost'); } /** * Remove repost record for given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function removeRepost( $parameters = ['postID' => ''] ) { return $this->delete('https://api.gab.com/v1.0/posts/' .$parameters['postID']. '/repost'); } /** * Returns the details of given post. * * @param array $parameters postID ~ Post ID * * @return string Returns JSON. */ public function getPostDetails( $parameters = ['postID' => ''] ) { return $this->get('https://api.gab.com/v1.0/posts/' .$parameters['postID']); } }
true
1ee2999b1d3708ad4dfb575ed737fcc97a9ba3a9
PHP
AlekefromKz/PHP-GlobalCare
/insurance_types/additional/errors/start-end.php
UTF-8
424
3.125
3
[]
no_license
<?php if($StartDate == ''){ $errors[] = 'Enter start date!';} if($EndDate == ''){ $errors[] = 'Enter end date!';} if($StartDate < date("Y-m-d")){$errors[] = 'Start date can not be earlier than today!!!';} if($StartDate > $EndDate){$errors[] = 'Start date can not be earlier than end date!';} if($StartDate > 2030-01-01 or $EndDate > 2030-01-01){$errors[] = 'Dates have to be earlier than 2030-01-10';} ?>
true
aafa619b051f9ee6b4c879089be2927f18929685
PHP
preetyverma20/Web-Development-Course
/Web Development/MySQL/viewdata.php
UTF-8
347
2.703125
3
[]
no_license
<?php include_once 'connect.php'; $query = "select * from `users` where id>4 order by name desc limit 3"; $result = mysqli_query($con,$query); if(mysqli_num_rows($result)!=0){ while($row = mysqli_fetch_array($result)){ echo $row["id"]." ".$row["name"]." ".$row["age"]." ".$row["qualification"]."<br>"; } }else{ echo "Khali hai"; } ?>
true
9bd2ee8b0ff3ef3a5774179026b164035ee7afe5
PHP
cmooreitrs/monitor-ninja
/modules/reports/libraries/Sla_options.php
UTF-8
4,068
2.78125
3
[ "BSD-3-Clause" ]
permissive
<?php defined('SYSPATH') OR die('No direct access allowed.'); /** * Report options for SLA reports */ class Sla_options extends Report_options { public static $type = 'sla'; static function discover_options($input = false) { # not using $_REQUEST, because that includes weird, scary session vars if (!empty($input)) { $report_info = $input; } else if (!empty($_POST)) { $report_info = $_POST; } else { $report_info = $_GET; } if(isset($report_info['report_period'], $report_info['start_year'], $report_info['start_month'], $report_info['end_year'], $report_info['end_month']) && $report_info['report_period'] == 'custom' && strval($report_info['start_year']) !== "" && strval($report_info['start_month']) !== "" && strval($report_info['end_year']) !== "" && strval($report_info['end_month']) !== "" ) { $report_info['start_time'] = mktime(0, 0, 0, $report_info['start_month'], 1, $report_info['start_year']); $report_info['end_time'] = mktime(0, 0, -1, $report_info['end_month'] + 1, 1, $report_info['end_year']); unset( $report_info['start_year'], $report_info['end_year'], $report_info['start_month'], $report_info['end_month'] ); } return $report_info; } public function setup_properties() { parent::setup_properties(); // Warning! months is 1-indexed $this->properties['months'] = array('type' => 'array', 'default' => false); $this->properties['report_period'] = array('type' => 'enum', 'default' => 'thisyear', 'options' => array( "thisyear" => _('This year'), "lastyear" => _('Last year'), "lastmonth" => _('Last month'), "last3months" => _('Last 3 months'), "last6months" => _('Last 6 months'), "lastquarter" => _('Last quarter'), "last12months" => _('Last 12 months'), 'custom' => _('Custom') )); if(ninja::has_module('synergy')) { $this->properties['include_synergy_events'] = array( 'type' => 'bool', 'default' => false, 'description' => 'Include BSM events' ); } } /** * Validated/assure that we have an array with 12 elements indexed from 1 * to 12, one for each month. Move the values from the param into a new * array that has 0.0 as the default value if none is provided with the * param. * * @param array $months * * @return array */ private static function validate_months($months) { $res = array(); if (!is_array($months)) $months = array(); for ($i = 1; $i <= 12; $i++) { $res[$i] = 0.0; if (isset($months[$i])) { $res[$i] = $months[$i]; } } return $res; } public function set($name, $value) { if ($name == 'months') { $value = static::validate_months($value); } $resp = parent::set($name, $value); if ($resp === false && preg_match('/^month/', trim($name))) { $id = (int)str_replace('month_', '', $name); if (trim($value) == '') return; // adjust locales to our format $value = str_replace(',', '.', $value); // values are percentages if ($value>100) { $value = 100; } elseif($value < 0) { $value = 0; } $this->options['months'][$id] = (float)$value; return true; } return $resp; } protected function calculate_time($report_period) { $res = parent::calculate_time($report_period); if ($res && isset($this->options['start_time']) && isset($this->options['end_time'])) { $this->options['months'] = static::validate_months($this['months']); } return $res; } protected function load_options($id) { $opts = parent::load_options($id); if (!$opts) return false; foreach (array('start_time', 'end_time', 'report_period') as $k) { if (isset($opts[$k])) $this->set($k, $opts[$k]); } $this->calculate_time($this['report_period']); /** * The months array is indexed from 1 instead of 0 so make a new array * with index from 1 to 12 with the SLA values from the db and fill the * rest of the array with 0.0. */ $array_result = $opts['months'] + array_fill(1, 12, 0.0); ksort($array_result); $opts['months'] = $array_result; return $opts; } }
true
483e6f71ce6c043e1904218e808ec64331fd2565
PHP
rossriley/php-scalar-objects
/tests/StringHandlerTest.php
UTF-8
1,787
2.84375
3
[]
no_license
<?php namespace Spl\Scalars\Tests; class StringHandlerTest extends \PHPUnit_Framework_TestCase { public function setup() { } public function testCapitalize() { $str = "hello world"; $this->assertEquals($str->capitalize(), "Hello World"); } public function testCaseCompare() { $str = "hello world"; $this->assertEquals($str->caseCompare("Hello World"), 0); } public function testHash() { $str = "testing"; $this->assertEquals($str->hash()->length(), 60 ); } public function testLength() { $str = "testing"; $this->assertEquals($str->length(),7); } public function testLower() { $str = "Hello World"; $this->assertEquals($str->lower(), "hello world"); } public function testPadLeft() { $str = "Hello World"; $this->assertEquals($str->padLeft(12), " Hello World"); $this->assertEquals($str->padLeft(12, "-"), "-Hello World"); } public function testPadRight() { $str = "Hello World"; $this->assertEquals($str->padRight(12), "Hello World "); $this->assertEquals($str->padRight(12, "-"), "Hello World-"); } public function testRepeat() { $str = "testing"; $this->assertEquals($str->repeat(3), "testingtestingtesting"); } public function testReverse() { $str = "testing"; $this->assertEquals($str->reverse(), "gnitset"); } public function testTrims() { $str = " testing "; $this->assertEquals($str->trim(), "testing"); $this->assertEquals($str->trimRight(), " testing"); $this->assertEquals($str->trimLeft(), "testing "); $str = "testing"; $this->assertEquals($str->trim("ing"), "test"); } public function testUpper() { $str = "Hello World"; $this->assertEquals($str->upper(), "HELLO WORLD"); } }
true
edb2a7e9887d17424652fd71807469bb260d5807
PHP
aldocf/ta_survey
/model/Responden.php
UTF-8
1,894
2.71875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: ACF * Date: 16/02/2018 * Time: 10:36 */ class Responden { private $id_responden; private $jabatan; private $nama_perusahaan; private $id_user; private $pendidikan; private $lamaBekerja; /** * @return mixed */ public function getIdResponden() { return $this->id_responden; } /** * @param mixed $id_responden */ public function setIdResponden($id_responden) { $this->id_responden = $id_responden; } /** * @return mixed */ public function getJabatan() { return $this->jabatan; } /** * @param mixed $jabatan */ public function setJabatan($jabatan) { $this->jabatan = $jabatan; } /** * @return mixed */ public function getNamaPerusahaan() { return $this->nama_perusahaan; } /** * @param mixed $nama_perusahaan */ public function setNamaPerusahaan($nama_perusahaan) { $this->nama_perusahaan = $nama_perusahaan; } /** * @return mixed */ public function getIdUser() { return $this->id_user; } /** * @param mixed $id_user */ public function setIdUser($id_user) { $this->id_user = $id_user; } /** * @return mixed */ public function getPendidikan() { return $this->pendidikan; } /** * @param mixed $pendidikan */ public function setPendidikan($pendidikan): void { $this->pendidikan = $pendidikan; } /** * @return mixed */ public function getLamaBekerja() { return $this->lamaBekerja; } /** * @param mixed $lamaBekerja */ public function setLamaBekerja($lamaBekerja): void { $this->lamaBekerja = $lamaBekerja; } }
true
e8ddeda32499544aa6b7494cfa9cc506f61025a1
PHP
nagnit4enko/example
/App/Core/View.php
UTF-8
1,427
2.859375
3
[]
no_license
<?php namespace App\Core; class View { public $user = []; public $property = [ 'header' => true ]; function __construct($user){ $this->user = $user; } function render($content_view, $template_view = null, $data = null) { $theme = ($template_view ? $template_view : $content_view); // Если есть такой шаблон то обробатываем и выводим if (file_exists(ROOT .'/App/Views/'.$theme)) { if(is_array($data)) { extract($data); } ob_start(); require_once ROOT .'/App/Views/'.$theme; return ob_get_clean(); } else { throw new \App\Exceptions\TemplateExeption('Отсутсвует шаблон '.$theme); } } function renderJSON($json){ $result = json_encode($json); header('content-type: application/json; charset=utf-8'); header('Connection: close'); header("Content-Length: ".mb_strlen($result)); header("Content-Encoding: none"); header("Accept-Ranges: bytes"); exit($result); } function setTitle($title){ $this->setProperty('title', $title); } function setProperty($key, $value) { $this->property[$key] = $value; } function getProperty($key) { if (isset($this->property[$key])) { return $this->property[$key]; } return ''; } function getTitle(){ return $this->property['title']; } }
true
525a39cec3808d3b6bd8e25fbe23092c6eb8d8fd
PHP
rheehot/countryside-partner-laravel
/app/Http/Controllers/OpenApiChatController.php
UTF-8
2,938
2.71875
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Exceptions\MeteoException; use App\Services\OpenApiChatService; use GuzzleHttp\Client as HttpClient; use Illuminate\Http\Request; use Validator; use Exception; /** * Class OpenApiChatController * @package App\Http\Controllers */ class OpenApiChatController extends Controller { /** @var HttpClient */ private $httpClient; /** * @var OpenApiChatService */ private $openApiChatService; /** * OpenApiChatController constructor. * @param HttpClient $httpClient * @param OpenApiChatService $openApiChatService */ public function __construct(HttpClient $httpClient, OpenApiChatService $openApiChatService) { $this->httpClient = $httpClient; $this->openApiChatService = $openApiChatService; } /** * @return array * @throws MeteoException */ protected function intro() : array { $url = $this->openApiChatService->getIntroUrl(); $response = $this->httpClient->get($url); $responseDecode = json_decode($response->getBody(), true); if ($responseDecode['status'] === "OK") { $result['text'] = preg_replace( "/\..\/../", "http://www.okdab.kr/episAutoAnswerApi", $responseDecode['result']['message']['text'] ); return $result; } else { throw new MeteoException(300); } } /** * @return array * @throws MeteoException */ protected function createRoom() : array { $url = $this->openApiChatService->getCreateRoomUrl(); $response = $this->httpClient->get($url); $responseDecode = json_decode($response->getBody(), true); if ($responseDecode['status'] === "OK") { $result['roomId'] = $responseDecode['result']['roomId']; return $result; } else { throw new MeteoException(300); } } /** * @param Request $request * @return array * @throws MeteoException */ protected function sendMessage(Request $request) : array { $data = $request->all(); $validator = Validator::make($data, [ 'roomId' => 'required|max:20', 'msg' => 'required|max:4000', ]); if ($validator->fails()) { throw new MeteoException(101, $validator->errors()); } $url = $this->openApiChatService->getSendMessageUrl( $data['roomId'], $data['msg'], ); $response = $this->httpClient->get($url); $responseDecode = json_decode($response->getBody(), true); try{ $result['result'] = $responseDecode['serverResult']['message']['text']; return $result; }catch (Exception $e){ throw new MeteoException(300, $e->getMessage()); } } }
true
117e7abe5d79bc8520180247384711fb074a2394
PHP
MuZiShark/utilities
/php/http/get_headerArray.php
UTF-8
522
2.796875
3
[]
no_license
<?php $url = 'http://www.baidu.com/'; $headerArray = get_headers($url, 1); //var_dump($headerArray); // 将数组序列化后写入文件中 $file = 'headerArray.txt'; file_put_contents($file, serialize($headerArray)); $headerArray2 = unserialize(file_get_contents($file)); //var_dump($headerArray2); // 从文件中反序列化得到数组 $handle = fopen($file, 'r'); $headerArray3 = unserialize(fread($handle, filesize($file))); fclose($handle); //var_dump($headerArray3); echo 'Game Over'; ?>
true
975056dcac8a4d469be1b82900888ae685d0e1f6
PHP
mirea-fcyb-2015/ratings
/rating/discForm.php
UTF-8
2,489
2.640625
3
[]
no_license
<?php include_once'../utils.php'; printHeader(); //---------------------------------------------------------------------------------------------------------------------- $dbconnect = pg_connect("host=localhost dbname=ratings user=postgres password=123456") or die('Could not connect: ' . pg_last_error()); //---------------------------------------------------------------------------------------------------------------------- $teachers = pg_query("SELECT last_name, first_name, middle_name, id FROM teachers") or die('Ошибка запроса: ' . pg_last_error()); $teachers = pg_fetch_all($teachers); $groups = pg_query("SELECT id, name FROM groups"); $groups = pg_fetch_all($groups); //---------------------------------------------------------------------------------------------------------------------- ?> <html> <table> <tr><td> <form action='addDisc.php' method="post"> <table> <tr> <td><h2>Добавить данные о дисциплине</h2></td> </tr> <tr> <td>Название:</td> <td> <input style='width:250px' type='text' name='discName'></input> </td> </tr> <tr> <td>Преподаватель:</td> <td> <select id="teacher" style='width:250px' name="discTeacher"> <option value=''></option> <?php foreach ($teachers as $t) { echo "<option value=".$t['id'].">".$t['last_name']."&nbsp;".$t['first_name']."&nbsp;".$t['middle_name']."</option>"; } ?> </select> </td> </tr> <tr> <td>Группы:</td> <td> <table> <?php foreach ($groups as $n=>$g) { echo "<tr><td><input type='checkbox' name='discGroup[$n]' value=".$g['id'].">".$g['name']."</td></tr>"; if (isset($_POST['discGroup'])) echo $_POST['discGroup']; } ?> </table> </td> </tr> </table> <button type='submit'>Добавить</button> </form> </td></tr> <tr><td> <form action='editDiscForm.php' method="post"> <button type='submit'>Назад</button> </form> </td></tr> </table> </html> <?php //---------------------------------------------------------------------------------------------------------------------- pg_close($dbconnect); //---------------------------------------------------------------------------------------------------------------------- printFooter(); ?>
true
1f1638eec09acfcd3ab8eed405d8ea5752cc8ce2
PHP
ARCANEDEV/php-html
/src/Elements/Link.php
UTF-8
1,462
3.171875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Arcanedev\Html\Elements; /** * Class Link * * @author ARCANEDEV <arcanedev.maroc@gmail.com> */ class Link extends HtmlElement { /* ----------------------------------------------------------------- | Properties | ----------------------------------------------------------------- */ /** @var string */ protected $tag = 'link'; /* ----------------------------------------------------------------- | Main Methods | ----------------------------------------------------------------- */ /** * Set the href url. * * @param string $href * * @return $this */ public function href($href) { return $this->attribute('href', $href); } /** * Set the rel value. * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types * * @param string $value * * @return $this */ public function rel($value) { return $this->attribute('rel', $value); } /** * Set the rel as stylesheet. * * @param string $href * * @return $this */ public function stylesheet($href) { return $this->rel('stylesheet')->href($href); } /** * Set the rel as icon. * * @param string $href * * @return $this */ public function icon($href) { return $this->rel('icon')->href($href); } }
true
0947c05fd78b955895bf297059297bb8f39498c6
PHP
oazist/ComSecureCTF
/include/logout.inc.php
UTF-8
726
2.625
3
[]
no_license
<?php // Start session session_start(); // Include required functions file require_once('loginfunction.inc.php'); // If not logged in, redirect to login screen // If logged in, unset session variable and display logged-out message if (check_login_status() == false) { // Redirect to redirect('../login.html'); }else{ // Kill session variables unset($_SESSION['logged_in']); unset($_SESSION['username']); // Destroy session session_destroy(); } ?> <!DOCTYPE html> <html lang="en"> <head> </head> <body> <p>You have successfully logged out</p> <p><a href="../login.html">Click Here</a> if you want to log in again</p> </body> </html>
true
9814509945fff40b2c584bcab437b3cdb0c969c5
PHP
nguyenhoang24695/myEdu
/app/Models/ExternalSource.php
UTF-8
2,326
2.53125
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: hocvt * Date: 11/18/15 * Time: 08:04 */ namespace App\Models; use App\Core\MyStorage; use Illuminate\Database\Eloquent\Model; /** * App\Models\ExternalSource * * @property integer $id * @property integer $course_content_id * @property integer $user_id * @property string $title * @property string $source_type * @property string $content * @property string $data_disk * @property string $data_path * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at * @property-read \App\Models\User $user * @property-read \App\Models\CourseContent $course_content * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereId($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereCourseContentId($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereUserId($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereTitle($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereSourceType($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereContent($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereDataDisk($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereDataPath($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereCreatedAt($value) * @method static \Illuminate\Database\Query\Builder|\App\Models\ExternalSource whereUpdatedAt($value) * @mixin \Eloquent */ class ExternalSource extends Model{ protected $table = 'external_sources'; public function user() { return $this->belongsTo(User::class, 'user_id'); } public function course_content(){ return $this->belongsTo(CourseContent::class, 'course_content_id'); } public function delete(){ $return = parent::delete(); if($return && $this->data_path){ try{ MyStorage::getDisk($this->data_disk)->delete($this->data_path); }catch (\Exception $ex){ \Log::error($ex->getMessage()); } } return $return; } }
true
45bbb4655c8eb51965ca898044debb60cff78ce4
PHP
shun989/Mang-Ham-PHP
/MyExcercise/index.php
UTF-8
3,589
2.5625
3
[]
no_license
<?php $customerList = array( "1" => array("ten" => "Lộc văn Khôi", "ngaysinh" => "1995/11/11", "diachi" => "Lạng sơn", "anh" => "image/khoi.jpeg"), "2" => array("ten" => "Nguyễn văn Trọng", "ngaysinh" => "2001/12/03", "diachi" => "Lào cai", "anh" => "image/trong.jpeg"), "3" => array("ten" => "Trần đức Duy", "ngaysinh" => "2001/03/01", "diachi" => "Việt trì, Phú thọ.", "anh" => "image/duy.jpeg"), "4" => array("ten" => "Đoàn hồng Quân", "ngaysinh" => "1998/12/28", "diachi" => "Việt trì, Phú thọ", "anh" => "image/quan.jpeg"), "5" => array("ten" => "Nguyễn hương Lan", "ngaysinh" => "1996/05/05", "diachi" => "Hà Nội", "anh" => "image/lan.jpeg"), ); function searchByDate($customers, $from_date, $to_date) { if (empty($from_date) && empty($to_date)) { return $customers; } $filtered_customers = []; foreach ($customers as $customer) { if (!empty($from_date) && (strtotime($customer['ngaysinh']) < strtotime($from_date))) continue; if (!empty($to_date) && (strtotime($customer['ngaysinh']) > strtotime($to_date))) continue; $filtered_customers[] = $customer; } return $filtered_customers; } ?> <?php $from_date = NULL; $to_date = NULL; if ($_SERVER["REQUEST_METHOD"] == "POST") { $from_date = $_POST["from"]; $to_date = $_POST["to"]; } $filtered_customers = searchByDate($customerList, $from_date, $to_date); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> table { border-collapse: collapse; width: 100%; } th, td { padding: 8px; text-align: left; border-bottom: 1px solid chartreuse; } img { width: 60px; } div { width: 50%; border: 1px solid lightgray; } div input { margin: 10px 10px; height: 25px; } </style> <body> <table border="0"> <caption><h1 style="color: blue">Danh sách khách hàng.</h1></caption> <form action="" method="post"> <div> From:<input id="from" type="text" name="from" placeholder="yyyy/mm/dd" value="<?php echo isset($from_date) ? $from_date : ''; ?>"> To:<input id="to" type="text" name="to" placeholder="yyyy/mm/dd" value="<?php echo isset($from_date) ? $from_date : ''; ?>"> <button id="submit" type="submit">Search</button> </div> </form> <tr> <th>STT</th> <th>Tên</th> <th>Ngày sinh</th> <th>Địa chỉ</th> <th>Ảnh</th> </tr> <?php if (count($filtered_customers) === 0): ?> <tr> <td colspan="5" class="message">Không tìm thấy khách hàng nào</td> </tr> <?php endif; ?> <?php foreach ($filtered_customers as $index => $customer): ?> <tr> <td><?php echo $index + 1; ?></td> <td><?php echo $customer['ten']; ?></td> <td><?php echo $customer['ngaysinh']; ?></td> <td><?php echo $customer['diachi']; ?></td> <td> <div class="profile"><img src="<?php echo $customer['anh']; ?>"/></div> </td> </tr> <?php endforeach; ?> </table> </body> </html>
true
10b5da8cdd535e904ddd89b9370b52de54bfd68e
PHP
nazmulpcc/runner
/src/Compilers/JavaCompiler.php
UTF-8
901
2.71875
3
[]
no_license
<?php namespace nazmulpcc\Compilers; use nazmulpcc\Traits\HasVersions; /** * Java compiler class */ class JavaCompiler extends BaseCompiler { use HasVersions; public function __construct($code, $object = false) { $object = $object ? : dirname($code). "/Main.class"; parent::__construct($code, $object); $this->memory(4096); // set memory for java vm } public function getCompileCommand() { return "{$this->getVersionedCompiler('compiler')} {$this->codePath} 2>&1"; } public function getRunCommand() { return $this->isolate("-p --run {$this->getVersionedCompiler('runner')} Main"); } public static function getCompilerVersions() { return [ 'java8' => [ 'compiler' => '/usr/lib/jvm/java-8-openjdk-amd64/bin/javac', 'runner' => '/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java' ] ]; } protected function getDefaultCompiler() { return 'java8'; } }
true
5eccfabd7aad11cae5b75de69be01e345ea9e751
PHP
surajnair04/Cycling_safety
/public_html/create_account.php
UTF-8
1,371
2.625
3
[]
no_license
<?php session_start(); $email = $_POST["Email"]; $pwd = $_POST["Password"]; $username = $_POST["userName"]; $experience = $_POST["experienceLevel"]; //echo 'email: '.$email.'<br/>'; //echo 'pwd: '.$pwd.'<br/>'; //echo 'option: '.$experience.'<br/>'; $db_name = "cyclings_vid1"; $con=mysqli_connect("localhost","cyclings_jiahui","@2n54a=@]ZQ4", $db_name); $crypt_pwd = crypt($pwd, "st"); if(mysqli_connect_errno()) { echo"failed to connect to mysql:".mysqli_connect_error(); } else // echo "connected!"; $table_name = "Users"; $sql="INSERT INTO ".$table_name." (Email, Password, experienceLevel, userName) VALUES ('".$email."', '".$crypt_pwd."', '".$experience."', '".$username."')"; // echo "<br>sql=".$sql; if (mysqli_query($con,$sql)) { $_SESSION["username"] = $username; //Store the username and user_id in session variable $sql="SELECT * FROM Users WHERE userName= '$username' AND password= '$crypt_pwd'"; $result = $con->query($sql); $row = $result->fetch_assoc(); $_SESSION["user_id"] = $row["userid"]; header("Location: http://cyclingsafety.umd.edu/rate-vid.html"); /* Redirect browser */ exit(); } else { echo "Error creating table: " . mysqli_error($con); } ?>
true
5df0a688134cb833306331dfba1ce7531f7d012f
PHP
dehero/fastred
/modules/locale.php
UTF-8
9,502
2.578125
3
[ "MIT" ]
permissive
<?php if (!defined('LOCALE_DEFAULT')) { define('LOCALE_DEFAULT', 'en-US'); } if (!defined('LOCALE_LIBRARY_PATH')) { define('LOCALE_LIBRARY_PATH', __DIR__ . '/../locales/'); } $__LOCALE_LIBRARIES = array(); if (!function_exists('locale')) { function locale($value = null) { static $locale = LOCALE_DEFAULT; if (!is_null($value)) { $locale = $value; } return $locale; } } if (!function_exists('localeDatetimeToStr')) { function localeDatetimeToStr($datetime, $key = '-dd-mm-yyyy-hh-ii-ss') { fastredRequire('arr', 'datetime', 'int', 'var'); $args = []; $obj = datetimeObj($datetime); $arr = arrFromStr($key, '-'); $dayPrecending = false; foreach($arr as $value) { switch ($value) { case 'd': case 'day': $args[] = (integer)$obj->day; $dayPrecending = true; break; case 'dd': $args[] = intToStr($obj->day, 2); $dayPrecending = true; break; case 'h': case 'hour': $args[] = (integer)$obj->hour; break; case 'hh': $args[] = intToStr($obj->hour, 2); break; case 'i': case 'minute': $args[] = (integer)$obj->minute; break; case 'ii': $args[] = intToStr($obj->minute, 2); break; case 'm': $args[] = (integer)$obj->month; break; case 'mm': $args[] = intToStr($obj->month, 2); break; case 'mon': case 'month': $args[] = localeGetStr('-' . $value . '-' . $obj->month, $dayPrecending ? 2 : 1); $dayPrecending = false; break; case 's': $args[] = (integer)$obj->second; break; case 'ss': case 'second': $args[] = intToStr($obj->second, 2); break; case 'wd': case 'wkd': case 'weekday': $args[] = localeGetStr('-' . $value . '-' . datetimeGetWeekday($datetime)); break; case 'yyyy': $args[] = intToStr($obj->month, 4); break; case 'y': case 'year': $args[] = (integer)$obj->year; break; } } $result = localeGetStr($key, $args); return empty($result) ? arrToStr($args, ' ') : $result; } } if (!function_exists('localeGetFirstWeekDay')) { function localeGetFirstWeekDay() { return (integer)localeGetStr('-weekday-first'); } } if (!function_exists('localeGetStrObj')) { function localeGetStrObj() { fastredRequire('cache'); $locale = locale(); return cache('localeGetStrObj?' . $locale, function() use($locale) { global $__LOCALE_LIBRARIES; fastredRequire('obj'); $result = obj(); $pathCount = count($__LOCALE_LIBRARIES); for ($i = 0; $i < $pathCount; $i++) { $filename = $__LOCALE_LIBRARIES[$i] . '/' . $locale . '.json'; //print_r($result); objMerge($result, objFromJsonFile($filename)); } return $result; }); } } if (!function_exists('localeGetStr')) { function localeGetStr($key, $args = null, $pluralInt = null) { $values = localeGetStrObj(); if (isset($values->{$key})) { $str = $values->{$key}; } if (is_numeric($args)) $pluralInt = $args; if (is_numeric($pluralInt)) { $str = localeIntGetPlural($pluralInt, $str); } if (!is_null($args)) { fastredRequire('str'); $str = strGetFormatted($str, $args); } return !empty($str) ? $str : $key; } } if (!function_exists('localeFloatToStr')) { function localeFloatToStr($float, $precision = 2) { $float = (float)$float; return number_format($float, $precision, localeGetStr('-decimal-point'), localeGetStr('-thousands-separator') ); } } if (!function_exists('localeLibrary')) { function localeLibrary($path) { global $__LOCALE_LIBRARIES; $__LOCALE_LIBRARIES[] = realpath($path); } } if (!function_exists('localeIntGetPlural')) { function localeIntGetPlural($int, $forms) { fastredRequire('str'); $forms = explode('|', $forms); $rules = [ 'en' => 0, 'af' => 0, 'an' => 0, 'anp' => 0, 'as' => 0, 'ast' => 0, 'az' => 0, 'bg' => 0, 'bn' => 0, 'brx' => 0, 'ca' => 0, 'da' => 0, 'de' => 0, 'doi' => 0, 'el' => 0, 'eo' => 0, 'es' => 0, 'es-ar' => 0, 'et' => 0, 'eu' => 0, 'ff' => 0, 'fi' => 0, 'fo' => 0, 'fur' => 0, 'fy' => 0, 'gl' => 0, 'gu' => 0, 'ha' => 0, 'he' => 0, 'hi' => 0, 'hne' => 0, 'hu' => 0, 'hy' => 0, 'ia' => 0, 'it' => 0, 'kk' => 0, 'kl' => 0, 'kn' => 0, 'ku' => 0, 'ky' => 0, 'lb' => 0, 'mai' => 0, 'ml' => 0, 'mn' => 0, 'mni' => 0, 'mr' => 0, 'nah' => 0, 'nap' => 0, 'nb' => 0, 'ne' => 0, 'nl' => 0, 'nn' => 0, 'no' => 0, 'nso' => 0, 'or' => 0, 'pa' => 0, 'pap' => 0, 'pms' => 0, 'ps' => 0, 'pt' => 0, 'rm' => 0, 'rw' => 0, 'sat' => 0, 'sco' => 0, 'sd' => 0, 'se' => 0, 'si' => 0, 'so' => 0, 'son' => 0, 'sq' => 0, 'sv' => 0, 'sw' => 0, 'ta' => 0, 'te' => 0, 'tk' => 0, 'ur' => 0, 'yo' => 0, 'ach' => 1, 'ak' => 1, 'am' => 1, 'arn' => 1, 'br' => 1, 'fa' => 1, 'fil' => 1, 'fr' => 1, 'gun' => 1, 'ln' => 1, 'mfe' => 1, 'mg' => 1, 'mi' => 1, 'oc' => 1, 'pt-br' => 1, 'tg' => 1, 'ti' => 1, 'tr' => 1, 'uz' => 1, 'wa' => 1, 'zh' => 2, 'ay' => 2, 'bo' => 2, 'cgg' => 2, 'dz' => 2, 'id' => 2, 'ja' => 2, 'jbo' => 2, 'ka' => 2, 'km' => 2, 'ko' => 2, 'lo' => 2, 'ms' => 2, 'my' => 2, 'sah' => 2, 'su' => 2, 'th' => 2, 'tt' => 2, 'ug' => 2, 'vi' => 2, 'wo' => 2, 'ru' => 3, 'uk' => 3, 'be' => 3, 'bs' => 3, 'hr' => 3, 'sr' => 3, 'cs' => 4, 'sk' => 4, 'ar' => 5, 'csb' => 6, 'cy' => 7, 'ga' => 8, 'gd' => 9, 'is' => 10, 'jv' => 11, 'kw' => 12, 'lt' => 13, 'lv' => 14, 'me' => 15, 'mk' => 16, 'mnk' => 17, 'mt' => 18, 'pl' => 19, 'ro' => 20, 'sl' => 21 ]; $n = abs((integer)$int); $language = strToLowerCase(strGetReplaced(locale(), '_', '-')); if ($language !== 'es-ar' && $language !== 'pt-br') { $language = explode('-', $language)[0]; } $rule = (integer)$rules[$language]; $index = 0; if (count($forms) > 0) { switch ($rule) { case 0: $index = (integer)($n != 1); break; case 1: $index = (integer)($n > 1); break; case 2: $index = 0; break; case 3: $index = ($n % 10 == 1 && $n % 100 != 11) ? 0 : (($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2); break; case 4: $index = ($n == 1) ? 0 : (($n >= 2 && $n <= 4) ? 1 : 2); break; case 5: $index = ($n == 0) ? 0 : (($n == 1) ? 1 : (($n == 2) ? 2 : (($n % 100 >= 3 && $n % 100 <= 10) ? 3 : (($n % 100 >= 11) ? 4 : 5)))); break; case 6: $index = ($n == 1) ? 0 : (($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2); break; case 7: $index = ($n == 1) ? 0 : (($n == 2) ? 1 : (($n != 8 && $n != 11) ? 2 : 3)); break; case 8: $index = ($n == 1) ? 0 : (($n == 2) ? 1 : (($n > 2 && $n < 7) ? 2 : (($n > 6 && $n < 11) ? 3 : 4))); break; case 9: $index = ($n == 1 || $n == 11) ? 0 : (($n == 2 || $n == 12) ? 1 : (($n > 2 && $n < 20) ? 2 : 3)); break; case 10: $index = (integer)($n % 10 != 1 || $n % 100 == 11); break; case 11: $index = (integer)($n != 0); break; case 12: $index = ($n == 1) ? 0 : (($n == 2) ? 1 : (($n == 3) ? 2 : 3)); break; case 13: $index = ($n % 10 == 1 && $n % 100 != 11) ? 0 : (($n % 10 >= 2 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2); break; case 14: $index = ($n % 10 == 1 && $n % 100 != 11) ? 0 : (($n != 0) ? 1 : 2); break; case 15: $index = ($n % 10 == 1 && $n % 100 != 11) ? 0 : (($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2); break; case 16: $index = ($n == 1 || $n % 10 == 1) ? 0 : 1; break; case 17: $index = ($n == 0) ? 0 : (($n == 1) ? 1 : 2); break; case 18: $index = ($n == 1) ? 0 : (($n == 0 || ($n % 100 > 1 && $n % 100 < 11)) ? 1 : (($n % 100 > 10 && $n % 100 < 20) ? 2 : 3)); break; case 19: $index = ($n == 1) ? 0 : (($n % 10 >= 2 && $n % 10 <= 4 && ($n % 100 < 10 || $n % 100 >= 20)) ? 1 : 2); break; case 20: $index = ($n == 1) ? 0 : (($n == 0 || ($n % 100 > 0 && $n % 100 < 20)) ? 1 : 2); break; case 21: $index = ($n % 100 == 1) ? 0 : (($n % 100 == 2) ? 1 : (($n % 100 == 3 || $n % 100 == 4) ? 2 : 3)); break; } if ($index >= count($forms)) { $index = 0; } } return $forms[$index]; } } localeLibrary(LOCALE_LIBRARY_PATH);
true
f3d312220ade920ac01370779a2f42f2e524021c
PHP
lightools/bitbang-http-logger
/src/BitbangLogger/Formatters/IFormatter.php
UTF-8
392
2.75
3
[ "MIT" ]
permissive
<?php namespace Lightools\BitbangLogger\Formatters; use Bitbang\Http\Message; /** * @author Jan Nedbal */ interface IFormatter { /** * @param Message $message HTTP request or response * @return bool */ public function canFormat(Message $message); /** * @param string|array $body HTTP body * @return string */ public function format($body); }
true
1e5e571786aa3dee6faaeae7cc68a08ad7568e72
PHP
vedmant/laravel-shortcodes
/src/helpers.php
UTF-8
294
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php use Illuminate\Support\HtmlString; if (! function_exists('shortcodes')) { /** * Render shortcodes. * * @param string $string * @return string|HtmlString */ function shortcodes($string) { return app('shortcodes')->render($string); } }
true
2dff4416d2f9c5b0ed42f496eb4f07225baaf048
PHP
paysera/lib-php-cs-fixer-config
/src/Fixer/PhpBasic/CodeStyle/ClassNamingFixer.php
UTF-8
6,161
2.59375
3
[]
no_license
<?php declare(strict_types=1); namespace Paysera\PhpCsFixerConfig\Fixer\PhpBasic\CodeStyle; use PhpCsFixer\AbstractFixer; use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverRootless; use PhpCsFixer\FixerConfiguration\FixerOptionBuilder; use PhpCsFixer\FixerDefinition\CodeSample; use PhpCsFixer\FixerDefinition\FixerDefinition; use PhpCsFixer\Tokenizer\Token; use PhpCsFixer\Tokenizer\Tokens; use SplFileInfo; final class ClassNamingFixer extends AbstractFixer { const CONVENTION = 'PhpBasic convention 2.5.2: For services suffix has to represent the job of that service'; const SERVICE = 'Service'; private $validServiceSuffixes; private $invalidSuffixes; public function __construct() { parent::__construct(); $this->validServiceSuffixes = [ 'Registry', 'Factory', 'Client', 'Plugin', 'Proxy', 'Interface', 'Repository', ]; $this->invalidSuffixes = [ 'Service', ]; } public function getDefinition() { return new FixerDefinition( ' We use nouns for class names. For services we use some suffix to represent the job of that service, usually *er: manager normalizer provider updater controller registry resolver We do not use service as a suffix, as this does not represent anything (for example PageService). We use object names only for entities, not for services (for example Page). ', [ new CodeSample(' <?php class SampleService { } '), ] ); } public function getName() { return 'Paysera/php_basic_code_style_class_naming'; } public function isRisky() { // Paysera Recommendation return true; } public function isCandidate(Tokens $tokens) { return $tokens->isTokenKindFound(T_CLASS); } public function configure(array $configuration = null) { parent::configure($configuration); if ($this->configuration['service_suffixes'] === true) { return; } if (isset($this->configuration['service_suffixes']['valid'])) { $this->validServiceSuffixes = $this->configuration['service_suffixes']['valid']; } if (isset($this->configuration['service_suffixes']['invalid'])) { $this->invalidSuffixes = $this->configuration['service_suffixes']['invalid']; } } protected function createConfigurationDefinition() { $suffixes = new FixerOptionBuilder( 'service_suffixes', 'Set valid and invalid suffixes for Class names.' ); $suffixes = $suffixes ->setAllowedTypes(['array', 'bool']) ->getOption() ; return new FixerConfigurationResolverRootless('service_suffixes', [$suffixes], $this->getName()); } protected function applyFix(SplFileInfo $file, Tokens $tokens) { $classNamespace = null; $valid = true; foreach ($tokens as $key => $token) { if ($token->isGivenKind(T_NAMESPACE)) { $semicolonIndex = $tokens->getNextTokenOfKind($key, [';']); if ($tokens[$semicolonIndex - 1]->isGivenKind(T_STRING)) { $classNamespace = $tokens[$semicolonIndex - 1]->getContent(); } } if (!$token->isGivenKind(T_CLASS)) { continue; } $classNameIndex = $tokens->getNextMeaningfulToken($key); if (!$tokens[$classNameIndex]->isGivenKind(T_STRING)) { continue; } $previousTokenIndex = $tokens->getPrevMeaningfulToken($key); if (strpos($tokens[$key - 1]->getContent(), "\n") !== false) { $newLineIndex = $key - 1; } elseif ( $tokens[$previousTokenIndex]->isGivenKind([T_ABSTRACT, T_FINAL]) && strpos($tokens[$previousTokenIndex - 1]->getContent(), "\n") !== false ) { $newLineIndex = $previousTokenIndex - 1; } $className = $tokens[$classNameIndex]->getContent(); if ($classNamespace !== null) { $valid = $this->isClassNameValid($className, $classNamespace); } if (!$valid && isset($newLineIndex)) { $this->insertComment($tokens, $newLineIndex, $className); } } } /** * @param int $className * @param string $classNamespace * @return bool */ private function isClassNameValid($className, $classNamespace) { if ($classNamespace === self::SERVICE) { if (preg_match('#\w+(er\b|or\b)#', $className)) { return true; } foreach ($this->validServiceSuffixes as $validServiceSuffix) { if (preg_match('#' . $validServiceSuffix . '\b#', $className)) { return true; } } foreach ($this->invalidSuffixes as $invalidSuffix) { if (preg_match('#' . $invalidSuffix . '\b#', $className)) { return false; } } return false; } return true; } /** * @param Tokens $tokens * @param int $insertIndex * @param string $className */ private function insertComment(Tokens $tokens, $insertIndex, $className) { $comment = '// TODO: "' . $className . '" - ' . self::CONVENTION; if (!$tokens[$tokens->getPrevNonWhitespace($insertIndex)]->isGivenKind(T_COMMENT)) { $tokens->insertAt($insertIndex + 1, new Token([T_WHITESPACE, $tokens[$insertIndex]->getContent()])); $tokens->insertAt($insertIndex + 1, new Token([T_COMMENT, $comment])); } } }
true
444d23a2abaae3e6e1ab50c85fc87ad03f30cea2
PHP
BibakBangTeam/Spammer
/spamer.php
UTF-8
2,379
2.515625
3
[]
no_license
<?php define('API_KEY','303323571:AAFeY2yE2Q8LL5aA7VKpV4ELIB_NsFN8xRE'); /* created by DR.RASMUS && @DR_RASMUS && @VIZARD_TM */ //----######------ function makereq($method,$datas=[]){ $url = "https://api.telegram.org/bot".API_KEY."/".$method; $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($datas)); $res = curl_exec($ch); if(curl_error($ch)){ var_dump(curl_error($ch)); }else{ return json_decode($res); } } //##############=--API_REQ function apiRequest($method, $parameters) { if (!is_string($method)) { error_log("Method name must be a string\n"); return false; } if (!$parameters) { $parameters = array(); } else if (!is_array($parameters)) { error_log("Parameters must be an array\n"); return false; } foreach ($parameters as $key => &$val) { // encoding to JSON array parameters, for example reply_markup if (!is_numeric($val) && !is_string($val)) { $val = json_encode($val); } } $url = "https://api.telegram.org/bot".API_KEY."/".$method.'?'.http_build_query($parameters); $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($handle, CURLOPT_TIMEOUT, 60); return exec_curl_request($handle); } //----######------ //--------- $update = json_decode(file_get_contents('php://input')); var_dump($update); //========= $chat_id = $update->message->chat->id; $textmessage = isset($update->message->text)?$update->message->text:''; if (strpos($textmessage , "/spam" ) !== false ) { $text = str_replace("/spam","",$textmessage); if ($text != "") { $textt = explode(" ",$text); if ($textt['2'] != "" && $textt['1'] != "") { $t = $textt['1']; $te = $textt['2']; for($y=1;$y<=$t;$y++){ makereq('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"$te", ]); } } } } if ($textmessage == "/start"){ makereq('sendmessage',[ 'chat_id'=>$chat_id, 'text'=>"سلام به این اسپمر خوش اومدی منو توی گروهات اد کن و از دستور زیر استفاده کن /spam TEDAD MATN TEDAD:تعداد پیام ارسالی MATN:متن مورد نظر مثال: /spam 50 @VIZARD_TM", ]); } /* created by DR.RASMUS && @DR_RASMUS && @VIZARD_TM */ ?>
true
66aed05279b60aad27f6ec05d401d54fa73a7d9b
PHP
rohanraghuwanshi/PHP_Login-and-Register
/dbconnect.php
UTF-8
374
2.71875
3
[]
no_license
<?php $ds = "mysql:host=localhost;dbname=Student"; $username = "root"; $password = ""; try{ $GLOBALS['db'] = new PDO($ds, $username, $password); $db -> setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ $error_message = $e->getMessage(); echo $error_message; exit(); } ?>
true
056a1edcd61caf0ef1a742928ddcd3c2c33dbf0b
PHP
Suylo/Sharing-Pictures
/app/models/User.php
UTF-8
2,881
3.171875
3
[]
no_license
<?php namespace App\models; class User { /** * @var int - User ID - IMPORTANT in order to identificate user. */ private $userID; private $picturesCollection; /** * @vars - Identification IRL user */ private $firstName; private $lastName; private $address; private $postalCode; private $birthDate; /** * @vars - Identification Virtual user */ private $userEmail; private $userPasswd; private $creationDate; /** * User constructor. * @param $UserID - ID of user which allows to identify user * @param $FirstName - First name, e.g. "John" * @param $LastName - Last name, e.g. "Doe" * @param $Address - The location of user, e.g. "69 rue de la République" * @param $PostalCode - Postal code e.g. "75000" * @param $BirthDate - Birth date of user, e.g. "2000-01-01" * @param $UserEmail - Email, e.g. "example.1@gmail.com" * @param $UserPasswd - Password of user, it encrypted * @param $CreationDate - Creation date of the account of user, e.g. "2021-04-08" */ public function __construct($UserID, $FirstName, $LastName, $Address, $PostalCode, $BirthDate, $UserEmail, $UserPasswd, $CreationDate, $picturesCollection) { $this->userID = $UserID; $this->firstName = $FirstName; $this->lastName = $LastName; $this->address = $Address; $this->postalCode = $PostalCode; $this->birthDate = $BirthDate; $this->userEmail = $UserEmail; $this->userPasswd = $UserPasswd; $this->creationDate = $CreationDate; $this->picturesCollection = $picturesCollection; } /** * @return int */ public function getUserID() { return $this->userID; } /** * @return String */ public function getFirstName() { return $this->firstName; } /** * @return String */ public function getLastName() { return $this->lastName; } /** * @return String */ public function getAddress() { return $this->address; } /** * @return String */ public function getPostalCode() { return $this->postalCode; } /** * @return String */ public function getBirthDate() { return $this->birthDate; } /** * @return String */ public function getUserEmail() { return $this->userEmail; } /** * @return String */ public function getUserPasswd() { return $this->userPasswd; } /** * @return String */ public function getCreationDate() { return $this->creationDate; } /** * @return mixed */ public function getPicturesCollection() { return $this->picturesCollection; } }
true
954fd07b19964f5f98fd903ac362bedb208049ea
PHP
imneha/apart_api
/app/Commands/Acl/AddRoleModulePermission.php
UTF-8
881
2.65625
3
[ "MIT" ]
permissive
<?php namespace ApartmentApi\Commands\Acl; use ApartmentApi\Models\AclRoleResourcePermission; use Api\Commands\CreateCommand; class AddRoleModulePermission extends CreateCommand { protected $permission; protected $aclRole; protected $rules = [ ]; public function __construct($request, $permission, $aclRole) { $this->permission = $permission; $this->aclRole = $aclRole; parent::__construct($request); } /** * Execute the command. * * @return void */ public function handle(AclRoleResourcePermission $roleResourcePermission) { return $roleResourcePermission ->permission() ->associate($this->permission) ->role() ->associate($this->aclRole) ->save(); } }
true
8f15e7b46c2546f8b109dc4fc285edd023c151ad
PHP
xboston/phalcon-code
/codes/1.2.0/api/Phalcon_Mvc_Model/Phalcon_Mvc_Model-379.php
UTF-8
328
2.859375
3
[]
no_license
<?php //What is the maximum robot id? $id = Robots::maximum(array( 'column' => 'id' )); echo "The maximum robot id is: " , $id , "\n"; //What is the maximum id of mechanical robots? $sum = Robots::maximum(array( "type='mechanical'" , 'column' => 'id' )); echo "The maximum robot id of mechanical robots is " , $id , "\n";
true
130a8b664f85103559f05fe69d77d3dda5ff889e
PHP
juhimulchandani/Content-Management-System
/classes/Posts.class.php
UTF-8
6,814
3.046875
3
[]
no_license
<?php class Posts{ private $table = "posts"; private $post_author; private $post_id; private $post_category_id; private $post_title; private $post_body; private $post_tags; private $post_author_id; private $post_status; private $post_date; private $post_image; private $created_at; private $updated_at; private $conn; public function __construct($conn){ $this->conn=$conn; } function readAllPosts(){ $sql = "SELECT * FROM {$this->table}"; $statement = $this->conn->prepare($sql); $statement->execute(); $result=$statement->fetchAll(); return $result; } function readPost($post_id){ $sql="SELECT * FROM {$this->table} WHERE post_id={$post_id}"; $statement=$this->conn->prepare($sql); $statement->execute(); //$result will hold the fetched result from db which is in the form of assoc array. $result=$statement->fetch(PDO::FETCH_ASSOC); //$keys now will hold all the key set i.e. the column names from the db i.e key in assoc arrays and their values will be fetched one by one in follwg for loop. $keys=array_keys($result); for($i=0;$i<count($keys);$i++){ $this->{$keys[$i]}=$result[$keys[$i]]; } // followg was method fetching value of each column of db one by one but it was replaced by for loop above. // $this->post_id=$result['post_id']; // $this->post_body=$result['post_body']; // $this->post_author_id=$result['post_author_id']; // $this->post_image=$result['post_image']; // $this->post_date=$result['post_date']; // $this->post_tags=$result['post_tags']; // $this->post_status=$result['post_status']; // $this->post_title=$result['post_title']; // $this->post_category_id=$result['post_category_id']; $this->post_author = $this->getAuthorName($this->post_author_id); } function readAllPostsOfCategory($category_id){ $sql="SELECT * FROM {$this->table} WHERE post_category_id={$category_id}"; $statement=$this->conn->prepare($sql); $statement->execute(); $result=$statement->fetchAll(); return $result; } function readAllPostsBySearch($keywords){ $sql="SELECT posts.post_id, posts.post_category_id, posts.post_title, posts.post_body, posts.post_tags, posts.post_author_id, posts.post_date, posts.post_image, posts.post_status, posts.created_at, posts.updated_at, CONCAT(members.member_first_name, CONCAT(\" \", members.member_last_name)) AS post_author FROM posts, members WHERE (members.member_id=posts.post_author_id) AND (members.member_first_name LIKE '%{$keywords}%' OR members.member_last_name LIKE '%{$keywords}%' OR posts.post_tags LIKE '%{$keywords}%' OR posts.post_title LIKE '%{$keywords}%' OR posts.post_body LIKE '%{$keywords}%' OR CONCAT(members.member_first_name, CONCAT(\" \", members.member_last_name)) LIKE '%{$keywords}%')"; $statement=$this->conn->prepare($sql); $statement->execute(); $result=$statement->fetchAll(); return $result; } function readAllPostsOfAuthor($post_author_id){ $sql="SEECT * FROM {$this->table} WHERE post_author_id = {$post_author_id}"; $statement=$this->conn->prepare($sql); $statement->execute(); $result=$statement->fetchAll(); return $result; } function getAuthorName($post_author_id){ $sql="SELECT member_first_name, member_last_name FROM members WHERE member_id={$post_author_id}"; $statement = $this->conn->prepare($sql); $statement->execute(); $result=$statement->fetch(); return $result['member_first_name']." ".$result['member_last_name']; } function createPost($data){ $columnString = implode(", ",array_keys($data)); $valueString = ":".implode(", :",array_keys($data)); $sql = "INSERT INTO {$this->table} ({$columnString}) VALUES ({$valueString})"; $ps=$this->conn->prepare($sql); // echo $sql; $result=$ps->execute($data); if($result){ return $this->conn->lastInsertId(); //conn provides function lastInsertId() which is used to get id of last insert made to db. }else{ return false; } } function updatePost($data, $condition){ $i=0; $columnValueSet = ""; foreach($data as $key=>$values){ $comma = ($i<count($data)-1?",":""); $columnValues.=$key."='".$values."'".$comma; $i++; } $sql="UPDATE $this->table SET $columnValueSet WHERE $condition"; $ps=$this->conn->prepare($sql); $result=$ps->execute($data); if($result){ return $ps-rowCount(); //ps provides function rowCount() which is the count of rows affected by updation. }else{ return false; } } public function setPostAsPublished($post_id){ $data = array("post_status"=>"published"); updatePost($data, "post_id={$post_id}"); } public function setPostAsDraft($post_id){ $data = array("post_status"=>"draft"); updatePost($data, "post_id={$post_id}"); } /** * @return mixed */ public function getPostAuthor() { return $this->post_author; } /** * @return mixed */ public function getPostId() { return $this->post_id; } /** * @return mixed */ public function getPostCategoryId() { return $this->post_category_id; } /** * @return mixed */ public function getPostTitle() { return $this->post_title; } /** * @return mixed */ public function getPostBody() { return $this->post_body; } /** * @return mixed */ public function getPostTags() { return $this->post_tags; } /** * @return mixed */ public function getPostAuthorId() { return $this->post_author_id; } /** * @return mixed */ public function getPostStatus() { return $this->post_status; } /** * @return mixed */ public function getPostDate() { return $this->post_date; } /** * @return mixed */ public function getPostImage() { return $this->post_image; } } // //include_once("Database.class.php"); //$db = new Database(); //$connection = $db->getConnection(); //$postObject=new Posts($connection); //$result=$postObject->readPost(1); ?>
true
2e682af25c6c6d148f3ec170be2a9d0a45987119
PHP
MohsenMohammadkhani/example-design-patterns-php
/src/structural/flyweight/Faker/UserProfile.php
UTF-8
285
3.015625
3
[ "MIT" ]
permissive
<?php namespace src\structural\flyweight\Faker; class UserProfile { private $gender; private $age; private $city; public function __construct($gender, $age, $city) { $this->gender = $gender; $this->age = $age; $this->city = $city; } }
true
1fbf9c4e57706ef5f021802abb5990342668b21b
PHP
NetassistArtem/switch_diagnostics
/Library/Session.php
UTF-8
3,018
2.6875
3
[]
no_license
<?php class Session { public static $flash_messages = array(); public static function has($key) { return isset($_SESSION[$key]); } public static function set($key, $val) { if ($key !== 'flash') { return $_SESSION[$key] = $val; } return null; } public static function hasUser($user_name) { if(self::get('user')['user'] == $user_name){ return$_SESSION['user']; } return null; } public static function get($key) { if (self::has($key)) { return $_SESSION[$key]; } return null; } public static function remove($key) { if (self::has($key)) { unset($_SESSION[$key]); } } public static function start() { session_start(); } public static function destroy() { session_destroy(); } public static function setFlash($message, $warning_class = null) { $request = new Request(); if($warning_class == $request->get('warning')){ $warning_level = 'Warning'; }elseif($warning_class == $request->get('notice')){ $warning_level = 'Notice'; }elseif($warning_class == $request->get('information')){ $warning_level = 'Information'; }else{ $warning_level = $warning_class; } self::$flash_messages[] = array( 'message' => $message, 'warning_class' => $warning_class, 'warning_level' => $warning_level ); $_SESSION['flash'] = self::$flash_messages; } public static function getFlash($account_id = null, $switch_id = null, $port_id = null, $switch_port_id = null) { $message_all = self::get('flash') ? self::get('flash') :array(); //удаление дублирующихся сообщений, если такие появятся $m = array(); foreach($message_all as $k=> $v){ $m[$k] = $v['message']; } $m = array_unique($m); $message = array(); foreach($message_all as $k=>$v){ if($m[$k]){ $message[$k] = $v; } } //завершение удаления дубликатов сообщений $errorModel = new errorModel($account_id, $switch_id, $port_id, $switch_port_id); $errorModel->writeError($message); //удалени сообщений не важных для сопорта Сообщения с пометной "Switch_SNMP_data_problem". Но в историю они записываются foreach($message as $k=> $v){ if(strpos($v['message'],'Switch_SNMP_data_problem') !== false){ unset($message[$k]); } } self::remove('flash'); return $message; } }
true
9b1938f0935ff0ec5beb4c7627f59ef57a76f0a1
PHP
aphoe/benjy-leave
/database/seeds/customer/RolesSeeder.php
UTF-8
2,038
2.5625
3
[ "MIT" ]
permissive
<?php use App\Customers\Models\Role; use App\Customers\Models\RoleDefinition; use Illuminate\Database\Seeder; class RolesSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $roles = [ [ 'name' => 'admin', 'role_name' => 'System Administrator', 'editable_permissions' => false, 'description' => 'Super user of the app. Has all rights and privileges.', ], [ 'name' => 'manager', 'role_name' => 'HR Manager', 'editable_permissions' => true, 'description' => 'Managerial staff and/or head of the Human Resource Unit for this app', ], [ 'name' => 'staff', 'role_name' => 'HR Staff', 'editable_permissions' => true, 'description' => 'Staff member and user role of the Human Resource Unit', ], [ 'name' => 'finance', 'role_name' => 'Finance Staff', 'editable_permissions' => true, 'description' => 'Functional user with finance responsibilities', ], [ 'name' => 'user', 'role_name' => 'User', 'editable_permissions' => true, 'description' => 'A user of the app, usually a member of staff of the company', ], ]; // Reset cached roles and permissions app()['cache']->forget('spatie.permission.cache'); foreach ($roles as $role){ $r = Role::create(['name' => $role['name']]); $def = new RoleDefinition(); $def->role_id = $r->id; $def->role_name = $role['role_name']; $def->description = $role['description']; $def->editable_permissions = $role['editable_permissions']; $def->save(); } } }
true
ddcf765c2edd43ae268dbc2045d387044a33a5f3
PHP
bruce1237/OA
/app/lib/contractMaker/LogoApplyContractMaker.php
UTF-8
5,195
2.578125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019-04-15 * Time: 10:10 * Used: */ namespace App\Lib\contractMaker; class LogoApplyContractMaker extends ContractMaker { protected $wordDummySealName = "image1.png"; protected $contractTemplate = 1; /** * @param int $orderId * @param array $serviceIds * @param array $orderInfo * @return string * @throws ContractException * @throws \PhpOffice\PhpWord\Exception\CopyFileException * @throws \PhpOffice\PhpWord\Exception\CreateTemporaryFileException * @throws \PhpOffice\PhpWord\Exception\Exception * Used For: */ // protected function processTemplate(int $orderId, array $serviceIds, array $orderInfo): string // { // //get word template file; // $templateFile = $this->getTemplateFile(env('LOGOAPPLY')); // $templateProcessor = new TemplateProcessor($templateFile); // //replace the dummySeal to realSeal // $realSeal = $this->replaceDummySeal(self::wordDummySealName, $orderInfo['order_firm_id']); // $templateProcessor->setImageValueC(self::wordDummySealName, $realSeal); // $cartObj = $this->getCarts($orderId, $serviceIds); // $cartDetails = $this->restructureCarts($cartObj); // $orderInfo['order_payment_method_details'] = $this->convertPaymentDetails($orderInfo['order_payment_method_details']); // $orderInfo['order_totalCHN'] = $this->toChineseNumber($cartDetails['total']); // $orderInfo['order_total'] = $cartDetails['total']; // unset($cartDetails['total']); // //find out how many records need insert to the word table // $rows = sizeof($cartDetails['name']); // //clone the Row // $templateProcessor->cloneRow('service_type', $rows); // //resture the order info CART parts // for ($i = 1; $i <= $rows; $i++) { // $orderInfo['service_name#' . $i] = $cartDetails['name'][$i - 1]; // $orderInfo['service_type#' . $i] = $cartDetails['type'][$i - 1]; // $orderInfo['service_attr#' . $i] = $cartDetails['attr'][$i - 1]; // $orderInfo['service_price#' . $i] = $cartDetails['price'][$i - 1]; // } // //assign info into word template // foreach ($orderInfo as $key => $value) { // $templateProcessor->setValue($key, $value); // } // $newFileName = storage_path("contractTemplates\\TMP" . uniqid() . ".docx"); // $templateProcessor->saveAs($newFileName); // return $newFileName; // } protected function restructureCarts($cartObj): array { $serviceName = $cartObj[0]['service_name']; $restructureArr = array(); $priceTotal = 0; foreach ($cartObj as $key => $cart) { if ($serviceName == $cart->service_name) { $priceTotal += $cart->service_price; } else { $priceTotal = 0; $serviceName = $cart->service_name; } $restructureArr[$cart->service_name][$key] = $cart; } $arr = array(); foreach ($restructureArr as $key => $value) { $value = array_values($value); $price = 0; foreach ($value as $kk => $vv) { $arr[$value[$kk]->service_category][$key]['attr'] = ''; $arr[$value[$kk]->service_category][$key]['price'] = 0; } $cate = ""; foreach ($value as $v) { $attributes = json_decode($v->service_attributes, true); foreach ($attributes as $attribute) { if ($attribute['name'] == "类别") { $cate .= $attribute['value'] . "类, "; $arr[$v->service_category][$key]['attr'] .= $attribute['value'] . "类, "; } elseif ($attribute['name'] == "注册号") { $cate .= $attribute['value'] . "类, "; $arr[$v->service_category][$key]['attr'] .= "注册号: " . $attribute['value'] . ", "; } } $price += $v->service_price; $arr[$v->service_category][$key]['price'] += $v->service_price; $arr[$v->service_category][$key]['name'] = $v->service_name; $arr[$v->service_category][$key]['type'] = $v->service_category; } } $orderDetailArray = [ 'type' => [], 'name' => [], 'attr' => [], 'price' => [], 'total' => 0, ]; $total = 0; foreach ($arr as $cart) { foreach ($cart as $item) { array_push($orderDetailArray['type'], $item['type']); array_push($orderDetailArray['name'], $item['name']); array_push($orderDetailArray['attr'], $item['attr']); array_push($orderDetailArray['price'], $item['price']); $total += $item['price']; } } $orderDetailArray['total'] = $total; return $orderDetailArray; } }
true
2dff98a7e32e07a5966670e9381753d7f4e52dd9
PHP
alexmon1989/diplinth
/app/Product.php
UTF-8
1,710
2.671875
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Product extends Model { use \Dimsav\Translatable\Translatable; public $translatedAttributes = ['title', 'description']; protected $fillable = ['in_stock', 'enabled']; /** * The relations to eager load on every query. * * @var array */ protected $with = ['heights']; public function heights() { return $this->hasMany('App\ProductHeight'); } /** * Возвращает склеенные величины возможных высот плинтуса. * * @param string $separator разделитель * @return string */ public function getSeparatedHeights($separator = '/') { $heights = $this->heights()->whereAvailable(true)->orderBy('value')->get(); $heights_arr = []; foreach ($heights as $value) { $heights_arr[] = $value->value; } $res = implode($separator, $heights_arr); if ($res) { return $res; } return '-'; } /** * Возвращает склеенные величины возможных цен плинтуса. * * @param string $separator разделитель * @return string */ public function getSeparatedPrices($separator = '/') { $prices = $this->heights()->whereAvailable(true)->orderBy('value')->get(); $prices_arr = []; foreach ($prices as $value) { $prices_arr[] = number_format($value->price, 1, ',', ' '); } $res = implode($separator, $prices_arr); if ($res) { return $res; } return '-'; } }
true
c0f1fc2eee5c81f77e14abae035efbcde2385365
PHP
nix-php-training/ads-board1
/framework/classes/Route.php
UTF-8
3,400
2.921875
3
[ "MIT" ]
permissive
<?php namespace application\classes; use application\core\Error; class Route { private $routes; private $controller; private $action; private $params = array(); public function __construct($app){ // Получаем конфигурацию из файла. $settings = Registry::get(); $this->routes = $settings['routes']; $this->controller = $settings['defaultController']; $this->action = $settings['defaultAction']; } public function parseRequest(){ if(!empty($_SERVER['REQUEST_URI'])) { return trim($_SERVER['REQUEST_URI'], '/'); } if(!empty($_SERVER['PATH_INFO'])) { return trim($_SERVER['PATH_INFO'], '/'); } if(!empty($_SERVER['QUERY_STRING'])) { return trim($_SERVER['QUERY_STRING'], '/'); } } public function getUri(){ // Получаем URI. $uri = $this->parseRequest(); if (($pos = strpos($uri, '?'))) { $uri = substr($uri, 0, $pos); } // Пытаемся применить к нему правила из конфигуации. foreach($this->routes as $pattern => $route){ // Если правило совпало. if(preg_match("~^$pattern$~", $uri)){ // Получаем внутренний путь из внешнего согласно правилу. $internalRoute = preg_replace("~^$pattern$~", $route, $uri); // Разбиваем внутренний путь на сегменты. $segments = explode('/', $internalRoute); // print_r($segments); // Первый сегмент — контроллер. $this->controller = ucfirst(array_shift($segments)).'Controller'; // Второй — действие. $this->action = array_shift($segments).'Action'; // Остальные сегменты — параметры. //print_r(count($segments)); $this->params = $segments; if(!is_callable(array($this->controller, $this->action))){ header("HTTP/1.0 404 Not Found"); return; } //$controller = new $this->controller(); // Вызываем действие контроллера с параметрами return array('controller' => $this->controller, 'action' => $this->action, 'params' => $this->params); } } if(empty($uri)) { $controllerFile = APP_PATH.'/controllers/'.$this->controller.'.php'; if(file_exists($controllerFile)){ include($controllerFile); } if(!is_callable(array($this->controller, $this->action))){ header("HTTP/1.0 404 Not Found"); return; } return array('controller' => $this->controller, 'action' => $this->action, 'params' => $this->params); } // Ничего не применилось. 404. header("HTTP/1.0 404 Not Found"); $error = new Error('Page not found'); $error->index(); die; } }
true
3fcaa1e8262eb86ee817c69eda502bec276a6a56
PHP
spujadas/exposure
/lib/Exposure/Model/ProjectWant.php
UTF-8
1,939
2.6875
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
<?php /* * This file is part of the Exposure package. * * Copyright 2013 by Sébastien Pujadas * * For the full copyright and licence information, please view the LICENCE * file that was distributed with this source code. */ namespace Exposure\Model; class ProjectWant extends Comment { protected $id = null; /** @var Project */ protected $project = null; const EXCEPTION_INVALID_PROJECT = 'invalid project'; /** @var SponsorOrganisation */ protected $sponsorOrganisation = null; const EXCEPTION_INVALID_SPONSOR_ORGANISATION = 'invalid sponsor organisation'; /** @var \DateTime */ protected $dateTime = null; const EXCEPTION_INVALID_DATE_TIME = 'invalid date time'; public function getProject() { return $this->project; } public function setProject(Project $project) { $this->project = $project; return $this->project; } public function getSponsorOrganisation() { return $this->sponsorOrganisation; } public function setSponsorOrganisation(SponsorOrganisation $sponsorOrganisation) { $this->sponsorOrganisation = $sponsorOrganisation; return $this->sponsorOrganisation; } public function getDateTime() { return $this->dateTime; } public function setDateTime(\DateTime $datetime) { $this->dateTime = $datetime; return $this->dateTime; } public function validate() { if (!is_a($this->project, 'Exposure\Model\Project')) { throw new ProjectWantException(self::EXCEPTION_INVALID_PROJECT); } if (!is_a($this->sponsorOrganisation, 'Exposure\Model\SponsorOrganisation')) { throw new ProjectWantException(self::EXCEPTION_INVALID_SPONSOR_ORGANISATION); } if (!is_a($this->dateTime, 'DateTime')) { throw new ProjectWantException(self::EXCEPTION_INVALID_DATE_TIME); } } }
true
ecc93e1b268d9e378f0944293b7deb91b54a9ebb
PHP
bjorvack/image-stacker
/src/Tests/StylesheetExporterTest.php
UTF-8
1,597
2.546875
3
[ "MIT" ]
permissive
<?php namespace Bjorvack\ImageStacker\Tests; use Bjorvack\ImageStacker\Exporters\StylesheetExporter; use Bjorvack\ImageStacker\Helpers\StringTransformer; use Bjorvack\ImageStacker\Image; use Bjorvack\ImageStacker\Stacker; class StylesheetExporterTest extends BaseTest { private $fileName; private $storagePath; public function __construct($name = null, array $data = [], $dataName = '') { parent::__construct($name, $data, $dataName); $this->fileName = dirname(__FILE__) .'/bjorvack.png'; $this->storagePath = dirname(__FILE__); } public function testCreateFromStacker() { $stacker = new Stacker('unitTest'); $image = new Image($this->fileName, 'bjorvack'); $stacker->addImage($image); StylesheetExporter::save($stacker, $this->storagePath); $packedImage = $this->storagePath.'/'.StringTransformer::slugify($stacker->getName()).'.png'; $packedCSS = $this->storagePath.'/'. StringTransformer::slugify($stacker->getName()) .'.css'; $this->assertTrue(file_exists($packedImage), $packedImage . " doesn't exist"); $this->assertTrue(file_exists($packedCSS), $packedCSS . " doesn't exist"); $css = '.unittest{display:block;background-image:url("' . $packedImage . '");}'; $css .= '.unittest-bjorvack{width:180px;height:180px;background-position:0px0px;}'; $this->assertEquals( StringTransformer::removeWhiteSpace(file_get_contents($packedCSS)), $css ); unlink($packedImage); unlink($packedCSS); } }
true
a3fcf493cbaab070740a9e870d3cd283d6affa07
PHP
c2Vuc2Vp/yumeres
/rs/catalog/index_original.php
UTF-8
22,684
2.53125
3
[ "Apache-2.0" ]
permissive
<?php $assets = '../assets/'; $vendor = '../../vendor/'; $js = '../files/js/'; $img = '../files/img/'; $css = '../files/css/'; ///////////////////////// // demarrer la session // ///////////////////////// session_start(); ////////////////////////////////////////////////////////////// // inclure le fichier de fonction et de connection à la bdd // ////////////////////////////////////////////////////////////// require_once "../../app/inc/function.php"; require_once "../../app/inc/connect.php"; if (isset($_POST['marque'])) { # code... } $art = $pdo->query("SELECT count(*) as nb FROM articles"); $arti = $art->fetch(); $Narticle = $arti['nb']; $nbre_articles_par_page = 6; $nbre_pages_max_gauche_et_droite = 2; $last_page = ceil($Narticle / $nbre_articles_par_page); if(isset($_GET['page']) && is_numeric($_GET['page'])){ $page_num = $_GET['page']; } else { $page_num = 1; } if($page_num < 1){ $page_num = 1; } else if($page_num > $last_page) { $page_num = $last_page; } $limit = 'LIMIT '.($page_num - 1) * $nbre_articles_par_page. ',' . $nbre_articles_par_page; $sql = "SELECT * FROM articles ORDER BY id DESC $limit"; $pagination = ''; if($last_page != 1){ if($page_num > 1){ $previous = $page_num - 1; $pagination .= '<li class="page-item"><a class="page-link" href="index.php?page='.$previous.'" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>'; for($i = $page_num - $nbre_pages_max_gauche_et_droite; $i < $page_num; $i++){ if($i > 0){ $pagination .= '<li class="page-item"><a class="page-link" href="index.php?page='.$i.'">'.$i.'</a></li>'; } } } $pagination .= '<li class="page-item active"><a class="page-link" href="#">'.$page_num.'<span class="sr-only">(current)</span></a></li>'; for($i = $page_num+1; $i <= $last_page; $i++){ $pagination .= '<li class="page-item"><a class="page-link" href="index.php?page='.$i.'">'.$i.'</a></li>'; if($i >= $page_num + $nbre_pages_max_gauche_et_droite){ break; } } if($page_num != $last_page){ $next = $page_num + 1; $pagination .= '<li class="page-item"><a class="page-link" aria-label="Next" href="index.php?page='.$next.'"><span aria-hidden="true">&raquo;</span></a></li>'; } } ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <meta name="description" content="Yeres, N'1 des sites de ventes en lignes"> <meta content="Yumeres, E-commerce, commerce, achat, ventes, Shop, Shopping, Afrique, Cote D'ivoire" name="keywords"> <meta content="index, follow" name="robots"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Catégorie | Yumeres - E-commerce</title> <link rel="icon" href="<?=$img?>favicon.ico"> <link rel="stylesheet" href="<?=$css?>bootstrap.css"> <link rel="stylesheet" href="<?=$css?>core-style.css"> <link rel="stylesheet" href="<?=$css?>cat.css"> <link rel="stylesheet" href="<?=$css?>nice-select.css"> <link rel="stylesheet" href="<?=$css?>shop.css"> <link rel="stylesheet" href="<?=$vendor?>mdb/mdb.min.css"> </head> <body> <div class="search-wrapper"> <div class="container vw mnc"> <div class="header-search-form"> <input id="search" onkeyup="search()" class="search form-control" placeholder="Chercher un produit" type="text"> </div> <div id="result"> </div> </div> </div> <div class="mcwr d-flex"> <?php include '../../app/inc/rs_sidebar.php'; ?> <div class="section spar d-flex"> <div class="d-none d-md-block sca"> <div class="ctnvb"> <div class="srtsct"> <h3 class="nvh">Catalogue</h3> <div class="ctp f"> <?php $categorie = $pdo->query('SELECT * FROM categories ORDER BY list_cat ASC'); while ($cat = $categorie->fetch()) { $idCat = $cat['id']; ?> <a class="cttm cth" href="#"><?=$cat['list_cat']?></a> <div class="ctp"> <?php $req = $pdo->query("SELECT * FROM sous_categories WHERE id_categories = '$idCat' ORDER BY list_cat ASC"); while ($sC = $req->fetch()) { ?> <a class="cttm" href="index.php?cat=<?=$cat['list_cat']?>&sC=<?=$sC['list_cat']?>"><?=$sC['list_cat']?></a> <?php } ?> </div> <?php } ?> </div> </div> <div class="srtsct"> <h3 class="nvh">Marque</h3> <div class="ctp f"> <?php $marques = $pdo->query('SELECT * FROM marques ORDER BY marque ASC'); while ($marque = $marques->fetch()) { ?> <div class="checkbox"> <input value="<?=$marque['marque']?>" id="<?=$marque['marque']?>" class="checkbox" name="marque" type="checkbox" onclick="onlyOne(this)"> <label for="<?=$marque['marque']?>"><?=$marque['marque']?></label> </div> <?php } ?> </div> </div> </div> </div> <div class="container-fluid"> <div id="articles"> <div class="shadow-section mt-30" id="page-title"> <ol class="bdcb"> <li class="bdcb-itm"> <a href="../acceuil/index.php" id="bdcbhm"> <svg fill="none" height="14.5" stroke="#333" stroke-width="2" viewBox="0 0 24 24" width="14" xmlns="http://www.w3.org/2000/svg"> <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path> <polyline points="9 22 9 12 15 12 15 22"></polyline> </svg> </a> </li> <?php if (!isset($_GET['cat'])) { ?> <li aria-current="page" class="bdcb-itm active"> <a href="index.php" id="bdcbhm">Catalogue</a> </li> <?php }else{ if (is_used('categories', 'list_cat', $_GET['cat'])) { ?> <li aria-current="page" class="bdcb-itm active"> <a href="index.php" id="bdcbhm">Catalogue</a> </li> <li aria-current="page" class="bdcb-itm active"> <a href="index.php?cat=<?=$_GET['cat']?>" id="bdcbhm"><?=$_GET['cat']?></a> </li> <?php }else{ ?> <li aria-current="page" class="bdcb-itm active"> <a href="index.php" id="bdcbhm">Catalogue</a> </li> <li aria-current="page" class="bdcb-itm active"> <a href="#" id="bdcbhm">Inconnu</a> </li> <?php } } if (isset($_GET['sC'])) { if (is_used('sous_categories', 'list_cat', $_GET['sC'])) { ?> <li aria-current="page" class="bdcb-itm active"><a href="index.php?sC=<?=$_GET['sC']?>" id="bdcbhm"><?=$_GET['sC']?></a></li> <?php }else{ ?> <li aria-current="page" class="bdcb-itm active"><a href="#" id="bdcbhm">Inconnu</li> <?php } } if (isset($_GET['m'])) { ?> <li aria-current="page" class="bdcb-itm active"><a href="index.php?m=<?=$_GET['m']?>" id="bdcbhm"><?=$_GET['m']?></a></li> <?php } ?> </ol> </div> <!-- <div class="shadow-section product-topbar d-xl-flex justify-content-between"> <div class="total-products"> <p>Afficher : <span id="tlpda">1-8</span> sur <span id="tlpds"><?=$Narticle?></span></p> </div> <div class="product-sorting d-flex"> <div class="sort-by-date d-flex align-items-center mr-15"> <p>Trier par : </p> <form action="#" method="get"> <select name="select" id="sortBydate"> <option value="value"> Date</option> <option value="value"> Nouveautés</option> <option value="value"> Popularités</option> </select> </form> </div> <div class="view-product d-flex align-items-center"> <p>Afficher : </p> <form action="#" method="get"> <select name="select" id="viewProduct"> <option value="value">12</option> <option value="value">24</option> <option value="value">48</option> <option value="value">96</option> </select> </form> </div> </div> </div> --> <div class="shadow-section ctpdc"> <div class="row"> <?php $articles = $pdo->query($sql); while ($Art = $articles->fetch()) { $nom = $Art['nom']; $prix = $Art['prix']; $img = $Art['img']; $id = $Art['id']; ?> <div class="col-6 col-sm-4 col-md-12 col-xl-4"> <div class="spdw"> <a class="pdlk" href="../product/index.php?id_art=<?=$id?>"> <div class="pdti"> <img src="../files/img/product-img/product1.jpg" alt=""> <img class="hvrpt" src="../files/img/product-img/product2.jpg" alt=""> </div> <div class="cprn"> <div class="itmw"> <!-- <div class="itmrt"> <div class="badge badge-primary badge-md"> 4 <span class="rtn"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512" fill="#fff" width="12" height="12"><path d="M528.1 171.5L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6zM388.6 312.3l23.7 138.4L288 385.4l-124.3 65.3 23.7-138.4-100.6-98 139-20.2 62.2-126 62.2 126 139 20.2-100.6 98z"/></svg></span> </div> </div> --> <div class="ml-auto"> <h6 class="sfbg itmprc"> <span class="lprc"><?=$prix?></span> FCFA </h6> </div> </div> <span class="itnm"><?=$nom?></span> <!-- <div class="tsvb"> <div class="tb tsic"> <div class="ic"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512" width="18" height="18" fill="currentColor"> <path d="M624 368h-16V251.9c0-19-7.7-37.5-21.1-50.9L503 117.1C489.6 103.7 471 96 452.1 96H416V56c0-30.9-25.1-56-56-56H120C89.1 0 64 25.1 64 56v40H8c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8h240c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H112V56c0-4.4 3.6-8 8-8h240c4.4 0 8 3.6 8 8v312H242.7c-16.6-28.6-47.2-48-82.7-48-17.6 0-33.8 5.1-48 13.3V288H64v128c0 53 43 96 96 96s96-43 96-96h128c0 53 43 96 96 96s96-43 96-96h48c8.8 0 16-7.2 16-16v-16c0-8.8-7.2-16-16-16zm-464 96c-26.5 0-48-21.5-48-48s21.5-48 48-48 48 21.5 48 48-21.5 48-48 48zm256-320h36.1c6.3 0 12.5 2.6 17 7l73 73H416v-80zm64 320c-26.5 0-48-21.5-48-48s21.5-48 48-48 48 21.5 48 48-21.5 48-48 48zm80-100.9c-17.2-25.9-46.6-43.1-80-43.1-24.7 0-47 9.6-64 24.9V272h144v91.1zM256 248v-16c0-4.4-3.6-8-8-8H8c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8h240c4.4 0 8-3.6 8-8zm24-56c4.4 0 8-3.6 8-8v-16c0-4.4-3.6-8-8-8H40c-4.4 0-8 3.6-8 8v16c0 4.4 3.6 8 8 8h240z"/> </svg> </div> <div class="ic grn"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="18" height="18" fill="currentColor"> <path d="M256 409.6V100l-142.9 59.5c8.4 116.2 65.2 202.6 142.9 250.1zM466.5 83.7l-192-80a48.15 48.15 0 0 0-36.9 0l-192 80C27.7 91.1 16 108.6 16 128c0 198.5 114.5 335.7 221.5 380.3 11.8 4.9 25.1 4.9 36.9 0C360.1 472.6 496 349.3 496 128c0-19.4-11.7-36.9-29.5-44.3zM256 464C158.5 423.4 64 297.3 64 128l192-80 192 80c0 173.8-98.4 297-192 336z"/> </svg> </div> <div class="ic"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" width="18" height="18" fill="currentColor"> <path d="M449.716,239.842c-0.543-7.535-7.082-13.191-14.628-12.661c-7.536,0.543-13.204,7.092-12.662,14.628c0.337,4.655,0.506,9.431,0.506,14.191c0,109.061-88.726,197.787-197.786,197.787C116.086,453.787,27.36,365.06,27.36,256S116.086,58.214,225.147,58.214c43.191,0,84.21,13.668,118.62,39.525c6.041,4.538,14.615,3.321,19.154-2.718c4.54-6.04,3.323-14.616-2.717-19.154c-39.189-29.447-85.891-45.012-135.058-45.012C101.001,30.854,0,131.855,0,256s101.001,225.145,225.147,225.145S450.292,380.146,450.292,256C450.292,250.586,450.097,245.15,449.716,239.842z"/> <path d="M496.395,61.77c-20.808-20.807-54.666-20.807-75.474,0l-197.11,197.108l-69.874-69.875c-20.808-20.807-54.666-20.807-75.474,0c-20.808,20.808-20.808,54.666,0,75.474l120.341,120.341c6.895,6.895,15.951,10.342,25.007,10.342c9.057,0,18.113-3.447,25.008-10.342l247.576-247.576C517.201,116.435,517.201,82.579,496.395,61.77z M477.049,117.897L229.472,365.475c-3.12,3.12-8.2,3.12-11.32,0L97.811,245.133c-10.141-10.141-10.141-26.64,0-36.781c5.07-5.072,11.729-7.606,18.39-7.606s13.321,2.535,18.39,7.606l71.882,71.882c4.632,4.631,10.791,7.181,17.339,7.181c6.551,0,12.71-2.551,17.341-7.182L440.268,81.116c10.138-10.141,26.64-10.141,36.781,0C487.189,91.257,487.189,107.756,477.049,117.897z"/> </svg> </div> </div> <div class="tb tsbd"> <span class="ic"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"/><path d="M3 3h18a1 1 0 0 1 1 1v16a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1zm8 5.5v7h2v-7h-2zm-.285 0H8.601l-1.497 4.113L5.607 8.5H3.493l2.611 6.964h2L10.715 8.5zm5.285 5h1.5a2.5 2.5 0 1 0 0-5H14v7h2v-2zm0-2v-1h1.5a.5.5 0 1 1 0 1H16z"/></svg> </span> <span class="ic"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path fill="none" d="M0 0h24v24H0z"/><path d="M2 19h20v2H2v-2zm9-11h2v8h-2V8zM7.965 8h2.125l-2.986 7.964h-2L2.118 8h2.125l1.861 5.113L7.965 8zM17 14v2h-2V8h4a3 3 0 0 1 0 6h-2zm0-4v2h2a1 1 0 0 0 0-2h-2zM2 3h20v2H2V3z"/></svg> </span> <span class="ic dn"> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" stroke="currentColor" fill="currentColor"><path d="M4.873 3h14.254a1 1 0 0 1 .809.412l3.823 5.256a.5.5 0 0 1-.037.633L12.367 21.602a.5.5 0 0 1-.706.028c-.007-.006-3.8-4.115-11.383-12.329a.5.5 0 0 1-.037-.633l3.823-5.256A1 1 0 0 1 4.873 3zm.51 2l-2.8 3.85L12 19.05 21.417 8.85 18.617 5H5.383z"/></svg> </span> </div> </div> --> </div> </a> <div class="pdopt"> <button class="byart btn btn-primary mx-auto mb-3"> Acheter </button> </div> </div> </div> <?php } ?> </div> </div> <div class="row"> <div class="col-12"> <nav aria-label="navigation"> <ul id="pagination" class="pagination justify-content-end mt-50"> <?=$pagination?> </ul> </nav> </div> </div> </div> </div> </div> </div> <section class="footer-section"> <div class="container vw"> <div class="row"> <div class="col-12"> <div id="copyright"> <div class="container clearfix"> <div class="col_half nobottommargin"> <span class="font-primary"> Copyright © 2021 | Tous droits réservés à <a class="footer-copyright-link" href="../acceuil/index.php"> Yumeres Shop.</a></span> </div> <div class="col_half col_last nobottommargin"> <div class="copyrights-menu copyright-links fright clearfix"> <a href="../acceuil/index.php">Accueil</a>/<a href="../acceuil/index.php/about">A propos</a>/<a href="mailto:support@yumeres.com">Support</a>/<a href="mailto:contact@yumeres.com">Contact</a> </div> </div> </div> </div> </div> </div> </div> </section> <script src="<?=$js?>jquery.js"></script> <script src="<?=$js?>bootstrap.js"></script> <script src="<?=$js?>plugins.js"></script> <script src="<?=$js?>ns.js"></script> <script src="<?=$js?>function.js"></script> <script type="text/javascript"> function onlyOne(checkbox) { var checkboxes = document.getElementsByName('marque') checkboxes.forEach((item) => { if (item !== checkbox) item.checked = false }); var values = (function() { var a = []; $(".checkbox:checked").each(function() { a.push(this.value); }); return a[0]; })() var url = 'articles_marque.php' if (values != '') { $.ajax({ type : 'POST', url : url, data : { marque : values }, success: function(data){ $('#articles').empty(); $('#articles').html(" "+data).show(); } }); }else{ } } </script> </body> </html>
true
39ee67c7bfbf39103d24650977a9d41c5fae2217
PHP
menthol/laravel-relationships-examples
/app/Report.php
UTF-8
705
2.53125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; /** * App\Report * * @property integer $id * @property integer $user_id * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at * @property-read \App\User $user */ class Report extends Model { public function articles() { return $this->morphedByMany(Article::class, 'reportable'); } public function authors() { return $this->morphedByMany(Author::class, 'reportable'); } public function comments() { return $this->morphedByMany(Comment::class, 'reportable'); } public function user() { return $this->belongsTo(User::class); } }
true
1bca2635669954d87eaa357314421b90ba3ebd2d
PHP
sergio-toro/algorithmic-pleasure
/src/Storo/Math/SumNaturals.php
UTF-8
2,299
3.734375
4
[ "Apache-2.0" ]
permissive
<?php namespace Storo\Math; class SumNaturals { /** * Returns the sum of all natural numbers below $limit that are * multiples of $a or $b, not in a efficient way. * @param integer $a * @param integer $b * @param integer $limit * @return integer */ public function sumIfMultipleBelow($a, $b, $limit = 1000) { $total = 0; $start = $a<$b ? $a : $b; for ($i = $start; $i < $limit; $i++) { if ( ($i % $a===0) || ($i % $b===0) ) { $total += $i; } } return (integer) $total; } /** * Returns the sum of all natural numbers below $limit that are * multiples of $a or $b in a efficient way. * @param integer $a * @param integer $b * @param integer $limit * @return integer */ public function getSumOfMultiplesOfAOrB($a, $b, $limit = 1000) { if ($a%$b==0 || $b%$a==0) { return $this->sumMul($limit, ($a<$b ? $a : $b)); } else { return (integer) $this->sumMul($limit, $a) + $this->sumMul($limit, $b) - $this->sumMul($limit, $this->mcm($a,$b)) ; } } /** * Returns the sum of all natural numbers below $limit that are * multiples of $number * @param integer $limit * @param integer $number * @return integer */ private function sumMul($limit, $number) { $greatestMultiple = $limit-1; while ($greatestMultiple%$number != 0) { $greatestMultiple--; } $last = $greatestMultiple / $number; return (integer) $number * $last * ($last + 1) / 2; } /** * Returns the minimum common divisor of two numbers * @param integer $a * @param integer $b * @return integer */ private function mcd($a, $b) { while (($a % $b) != 0) { $c = $b; $b = $a % $b; $a = $c; } return (integer) $b; } /** * Returns the minimum common multiple of two numbers * @param integer $a * @param integer $b * @return integer */ private function mcm($a, $b) { return (integer) ($a * $b) / $this->mcd($a,$b); } }
true
9779b4ff4fb47dd1eac1e28f3bfd33ecbb56a8b3
PHP
jyan0080/its-pawsibal
/database/migrations/2020_05_17_072756_create_suburbareaaffected_table.php
UTF-8
801
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateSuburbareaaffectedTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('suburbareaaffected', function (Blueprint $table) { $table->id(); $table->string('suburb'); $table->string('neighbouringsuburbs'); $table->string('totalarea'); $table->string('areaaffected'); $table->string('bushfireaffected'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('suburbareaaffected'); } }
true
36cd4c8ff5ba5e5ea974f9e643e1f0414f5d5db5
PHP
ThemeHow/julemagne
/contact.php
UTF-8
1,724
2.734375
3
[]
no_license
<?php $SUBMIT_FROM = 'Julemagne.com <noreply@julemagne.com>'; $SUBMIT_TO = 'iamthetimekiller@gmail.com'; if( !isset($_POST) ) die( 'Quit hacking!' ); $valid = true; $errors = array(); // // Submission data // $ipaddress = $_SERVER['REMOTE_ADDR']; $date = date('m/d/Y'); $time = date('H:i:s'); $useragent = $_SERVER['HTTP_USER_AGENT']; // // Form data // $name = $_POST['name']; $email = $_POST['email']; $enquiry = $_POST['enquiry']; $message = $_POST['message']; // // Validation // if( empty($name) ) { $valid = false; $errors[] = 'You have not entered a name'; } if( empty($email) ) { $valid = false; $errors[] = 'You have not entered an email address'; } elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) ) { $valid = false; $errors[] = 'You have not entered a valid email address'; } if( empty($message) ){ $valid = false; $errors[] = 'You have not entered a message'; } if( $valid ) { $headers = 'From: ' . $SUBMIT_FROM . "\r\n"; $headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n"; $emailbody = <<<EOM <p>You have recieved a new message from the enquiries form on your website.</p> <p><strong>Name: </strong>{$name}</p> <p><strong>Email Address: </strong>{$email}</p> <p><strong>Enquiry: </strong>{$enquiry}</p> <p><strong>Message: </strong>{$message}</p> <div style='border: 1px solid black'> This message was sent from the IP Address: {$ipaddress} on {$date} at {$time}<br> User agent: {$useragent} </div> EOM; mail( $SUBMIT_TO, 'Web enquiry', $emailbody, $headers ); } // // If not requested via AJAX, redirect back // if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest') { header('location: ' . $_SERVER['HTTP_REFERER']); } ?>
true
8f6aa9ce2379177d73d99eba9b8f677d68efed30
PHP
eversudip/officelife
/app/Services/QueuableService.php
UTF-8
381
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace App\Services; use Throwable; /** * Makes a BaseService queuable using the generic ServiceQueue job. */ interface QueuableService { /** * Execute the service. */ public function handle(): void; /** * Handle a job failure. * * @param \Throwable $exception */ public function failed(Throwable $exception): void; }
true
a1f4b4331eb76bf042a15d5eab25d4cbfb4be290
PHP
a6software/symfony2-and-codeception
/tests/unit/A6/CodeceptIsAwesomeBundle/Service/ReverseServiceTest.php
UTF-8
820
2.5625
3
[ "MIT" ]
permissive
<?php class ReverseServiceTest extends \Codeception\TestCase\Test { /** * @var \UnitTester */ protected $tester; private $service; protected function _before() { $this->service = new \A6\CodeceptIsAwesomeBundle\Service\ReverseStringService(); } protected function _after() { } // /** // * @dataProvider ourProvider // */ // public function testStringIsReversedAsExpected($originalString, $expectedString) // { // $this->assertEquals( // $expectedString, // $this->service->reverse($originalString) // ); // } // // public function ourProvider() // { // return array( // array('abc', 'cba'), // array('qaz', 'zaq'), // array('123', '321'), // ); // } }
true
f309a1cc93f85f00fbcf06dc7b5cf6c8f4fc9933
PHP
ritwikabanerjee123/GreenLine-BusProject
/insert.php
UTF-8
1,616
2.546875
3
[]
no_license
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "project"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); if(isset($_POST['insert'])) { echo "fsdf"; //$bus_no = mysqli_real_escape_string($conn,$_POST['inp']); // $sql= "SELECT distance_covered FROM main_input WHERE bus_no='$bus_no' ORDER BY id DESC LIMIT 1"; //$result = mysqli_query($conn,$sql); // $print_data = mysqli_fetch_row($result); $dates = mysqli_real_escape_string($conn,$_POST['dates']); $bus_route = mysqli_real_escape_string($conn,$_POST['bus_route']); $bus_no = mysqli_real_escape_string($conn,$_POST['bus_no']); $driver_name = mysqli_real_escape_string($conn,$_POST['driver_name']); $pump_name = mysqli_real_escape_string($conn,$_POST['pump_name']); $fuel_taken = mysqli_real_escape_string($conn,$_POST['fuel_taken']); $rate_on_date = mysqli_real_escape_string($conn,$_POST['rate_on_date']); $distance_covered = mysqli_real_escape_string($conn,$_POST['distance_covered']); $chalan_no = mysqli_real_escape_string($conn,$_POST['chalan_no']); $amount_paid = mysqli_real_escape_string($conn,$_POST['amount_paid']); $query = "INSERT INTO main_input (dates, bus_route, bus_no, driver_name,pump_name,fuel_taken, rate_on_date , distance_covered, chalan_no , amount_paid) VALUES ('$dates', '$bus_route', '$bus_no', '$driver_name' , '$pump_name' , '$fuel_taken' ,'$rate_on_date', '$distance_covered' ,'$chalan_no' ,'$amount_paid') "; if(mysqli_query($conn, $query)){ echo "inserted"; } } ?>
true
03b4826adbe3994ed413ebe232ab007482f3826c
PHP
poarfrippe/LoginPro
/backend/symetricLogin.php
UTF-8
613
2.859375
3
[]
no_license
<?php session_start(); $request = 2; if(isset($_GET['request'])){ $request = $_GET['request']; //1 = GET, 2 = POST } //POST if($request == 2){ $data = json_decode(file_get_contents("php://input")); $username = $data->username; $passwordArray = $data->passwordArray; $plainArray = array(); for ($i = 0; $i < count($passwordArray); ++$i) { $plainArray[$i] = chr($passwordArray[$i] ^ $_SESSION['diffieKey']); } $plainpasswd = implode("", $plainArray); echo $plainpasswd; exit; }
true
530b45640706d1df6869ec8fd2ceb6a471e28bdd
PHP
puncoz/rat_the_logger_ci
/application/config/rat.php
UTF-8
1,551
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /* * "store_in" allows you to set your preference regarding the storage of your logs. * You can store the logs inside a database by passing "database" as value, * or inside a directory by passing the directory location as value (relative to APPPATH). * If nothing is set, it will save the logs inside the "application/logs" directory. * * If you decide to store the logs inside a database this is the sql for the "rat" table * * SET NAMES utf8; DROP TABLE IF EXISTS `rat`; CREATE TABLE `rat` ( `id` int(11) NOT NULL AUTO_INCREMENT, `user_id` int(11) DEFAULT NULL, `date_time` datetime DEFAULT NULL, `code` int(11) DEFAULT NULL, `message` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; * * * If you decide to store the logs inside a directory make sure the directory and its files are writable (755). */ //$config['store_in'] = ''; $config['store_in'] = ''; //You can choose to keep the logs inside the database or in a specific directory (relative to the APPPath). If you leave blank (''), it will assume the 'application/logs' directory will be used $config['session_user_id'] = ''; // f you want to pass the user's ID automatically to the library when creating the log, you can setup a session value and pass it to this config item. If not, leave blank. $config['table_name'] = ''; // If you wanted to be original and prefered another table name, you must change it here. Leave blank if the table name is 'rat'
true
23a776f5b729d97af5c3c599f5e32f10cb255066
PHP
MacroMan/nitropack-api
/src/NitroPack/Filesystem.php
UTF-8
4,667
2.765625
3
[]
no_license
<?php namespace NitroPack; class Filesystem { public static $storageDriver = NULL; public static function setStorageDriver($driver) { Filesystem::$storageDriver = $driver; } public static function getStorageDriver() { if (Filesystem::$storageDriver === NULL) { Filesystem::$storageDriver = new StorageDriver\Disk(); } return Filesystem::$storageDriver; } public static function getOsPath($parts) { return Filesystem::getStorageDriver()->getOsPath($parts); } public static function deleteFile($path) { if (self::fileExists($path)) { return Filesystem::getStorageDriver()->deleteFile($path); } return true; } public static function createDir($dir) { return Filesystem::getStorageDriver()->createDir($dir); } public static function deleteDir($dir) { return Filesystem::getStorageDriver()->deleteDir($dir); } public static function trunkDir($dir) { return Filesystem::getStorageDriver()->trunkDir($dir); } public static function isDirEmpty($dir) { return Filesystem::getStorageDriver()->isDirEmpty($dir); } public static function createCacheDir($dir) { if (!self::createDir($dir . "/mobile") || !self::createDir($dir . "/tablet") || !self::createDir($dir . "/desktop") ) { return false; } return true; } public static function dirForeach($dir, $callback) { return Filesystem::getStorageDriver()->dirForeach($dir, $callback); } public static function fileMTime($filePath) { return self::fileExists($filePath) ? Filesystem::getStorageDriver()->mtime($filePath) : 0; } public static function touch($filePath) { return Filesystem::getStorageDriver()->touch($filePath); } public static function fileGetHeaders($filePath) { return self::fileGetAll($filePath)->headers; } public static function fileGetContents($filePath) { return self::fileGetAll($filePath)->content; } public static function fileSize($filePath) { return self::fileGetAll($filePath)->size; } public static function fileExists($filePath) { return Filesystem::getStorageDriver()->exists($filePath); } public static function fileGetAll($filePath) { if (!self::fileExists($filePath)) throw new \Exception("File not found: $filePath"); $res = new \stdClass(); $res->headers = []; $res->content = ""; $res->size = 0; list($res->headers, $res->content) = self::explodeByHeaders(Filesystem::getStorageDriver()->getContent($filePath)); $res->size = strlen($res->content); return $res; } public static function filePutContents($file, $content, $headers = NULL) { if ($headers === NULL) { return Filesystem::getStorageDriver()->setContent($file, $content); } else if (is_array($headers)) { $headerStr = implode("\r\n", $headers) . "\r\n\r\n"; return Filesystem::getStorageDriver()->setContent($file, $headerStr . $content); } else if (is_string($headers)) { return Filesystem::getStorageDriver()->setContent($file, $headers . $content); } else { return Filesystem::getStorageDriver()->setContent($file, $content); } } public static function rename($oldName, $newName) { if (self::fileExists($oldName)) { return Filesystem::getStorageDriver()->rename($oldName, $newName); } return false; } private static function explodeByHeaders($content) { $headers = []; $pos = strpos($content, "\r\n\r\n"); if ($pos !== false) { $headerStr = substr($content, 0, $pos); $content = substr($content, $pos+4); if ($headerStr) { $lines = explode("\r\n", $headerStr); foreach ($lines as $line) { $parts = explode(":", $line); $name = strtolower(array_shift($parts)); $value = trim(implode(":", $parts)); if (!empty($headers[$name])) { if (!is_array($headers[$name])) { $headers[$name] = array($headers[$name]); } $headers[$name][] = $value; } else { $headers[$name] = $value; } } } } return array($headers, $content); } }
true
79fe11719911ef3ddc46d3213805a03fd83f3765
PHP
bellows-io/Cli
/src/Gui/Dialog/Alert.php
UTF-8
2,321
2.78125
3
[]
no_license
<?php namespace Cli\Gui\Dialog; use \Cli\Gui\Traits\RowMemoryTrait; use \Cli\Gui\Borderset\Borderset; class Alert extends Dialog { protected $options; protected $highlightFormat = []; public function __construct($terminal, $title, $contents, array $options, Borderset $borderset) { parent::__construct($terminal, $borderset); $this->title = $title; $this->contents = $contents; $o = []; foreach ($options as $i => $option) { $o[] = [$i, $option]; } $this->options = $o; $this->textAlign = self::TEXT_ALIGN_CENTER; } protected function updateLayout() { parent::updateLayout(); $this->calculated[5] -= 2; } public function setHighlightFormat($formats) { $this->highlightFormat = $formats; } public function show() { parent::show(); $option = 0; $this->drawButtons($option); $this->terminal->readInput(function($char, $isControl) use (&$option) { if ($char == '[C') { $option = min($option + 1, count($this->options) - 1); $this->drawButtons($option); } else if ($char == '[D') { $option = max(0, $option - 1); $this->drawButtons($option); } else if ($char == "\n") { return true; } }); $this->terminal->resetFormatting(); return $this->options[$option][0]; } public function drawButtons($selected) { list($startX, $startY, $width, $height, $innerWidth, $innerHeight) = $this->calculated; $top = $this->makeLine( $this->borderSet->getLeftIntersect(), $this->borderSet->getInnerHorizontalEdge(), $this->borderSet->getRightIntersect(), $width); $this->terminal ->setPosition($startX, $startY + $height - 3) ->format($this->borderFormats) ->printf($top); $options = array_map('end', $this->options); $length = strlen(join(' | ', $options)) + 2; $x = $startX + $width - $length - 1; $this->terminal->setPosition($x, $startY + $height - 2); foreach ($options as $i => $option) { if ($i > 0) { $this->terminal->printf('|'); } $string = ' ' . $option . ' '; if ($i == $selected) { $this->terminal ->resetFormatting() ->format($this->highlightFormat) ->printf($string) ->format($this->borderFormats); } else { $this->terminal->printf($string); } $x += strlen($string) + 1; } $this->terminal->setPosition(0, $startY + $height + 1); } }
true
60a19685136b11626ded88448164088be055775a
PHP
chadananda/blink
/blink-wp/bLink-wp.php
UTF-8
19,900
2.734375
3
[]
no_license
<?php /** Plugin Name: bLinks Plugin URI: http://labs.uswebdev.net Description: Automatically links your blog posts other web sites. Author: Daniel Jones Version: 1.1 Author URI: http://labs.uswebdev.net */ include 'blink.class.php'; include_once(ABSPATH . WPINC . '/class-IXR.php'); /** * BLink plugin class implimentation */ class BLinkCollaborationPlugin { function BLinkCollaborationPlugin() { //BL constructor $this->db_check(); } /** * Adds links to content */ function createLinks($content = '') { // get the post ID global $post; $postID = $post->ID; // create the blink class instance $blinkClass = new blink(); // get the maximum number of links per page //$options = $this->getAdminOptions(); $admin_options = get_option('BlinkPluginAdminOptions'); $maxLinks = $admin_options['maxLinks']; $cssClass = get_option('css_class'); // get an array of current links $current_links = $this->getCurrentLinks($postID); $current_links_gids = array(); foreach($current_links as $link) { $current_links_gids[] = $link['gid']; } $existing_link_count = count($current_links); // no pre-existing links if ($existing_link_count == 0) { // get goal links $goal_links = $this->getLinkGoals(); // add them to content if (count($goal_links)) {$currentLinks = $blinkClass->markup_text(&$content, $goal_links, $maxLinks, $cssClass);} // if any were added update database if (count($currentLinks)>0) { $this->insertBlinks($currentLinks, $postID); } } else { // if links allready exist // add existing links $stillCurrentLinks = $blinkClass->markup_text(&$content, $current_links, $existing_link_count, $cssClass); $stillCurrentLinks_gids = array(); foreach ($stillCurrentLinks as $link) { $stillCurrentLinks_gids[] = $link['gid']; } $existing_link_count = count($stillCurrentLinks); // delete removed links $deleted_links = array(); foreach ($current_links as $key => $link) { if (!in_array($link['gid'], $stillCurrentLinks_gids)) { $deleted_links[] = $link; } } if (count($deleted_links)) $this->removeBlinks($deleted_links, $postID); // check if there is room for more links if ($existing_link_count < $maxLinks) { // get an array of all goal links $linkGoals = $this->getLinkGoals(); //remove current links from link goals // build lookup hash $cur_gids = array(); foreach ($stillCurrentLinks as $link) {$cur_gids[] = $link['gid']; } // strip out the exising links foreach ($linkGoals as $key=>$link) {if (in_array($link['gid'], $cur_gids)) {unset($linkGoals[$key]);}} //new link amounts $links_available = $maxLinks - $existing_link_count; // add new links $new_links = $blinkClass->markup_text(&$content, $linkGoals, $links_available, $cssClass); // update the existing links in the table // combine the old links with the newly added links $this->insertBlinks($new_links,$postID); } } return $content; } /** * adds links to the blink_links table * BLINK_LINKS * liid : auto-increment field/key * link_uid : uniqid generated locally * gid : fk to BLINK_GOALS * pid : Blog Post ID * url_override : not currently in use * li_updated : date this link was created (unix time stamp) */ function insertBlinks($links, $postID) { // update Existing Links table if (is_array($links) && count($links) > 0) { global $wpdb; $table_name = $wpdb->prefix . "blink_links"; foreach ($links as $link) { $sql = "INSERT INTO $table_name (link_uid, gid, pid, li_updated) VALUES ('" . uniqid('l', true) . "', " . $link['gid'] . ", $postID, UNIX_TIMESTAMP(now()) )"; $wpdb->query($sql); } } } /** * removes dead links from the blink_links table */ function removeBlinks($links, $postID) { // setup database access if (is_array($links) && count($links) > 0) { global $wpdb; $table_name = $wpdb->prefix . "blink_links"; // remove links foreach ($links as $link) { $sql = "DELETE FROM $table_name WHERE gid = '" . $link['gid'] . "' AND pid = '" . $postID . "'"; $wpdb->query($sql); } } } /** * retrieves previously used links for a blog post * * $results : array( array( * kw => 'human rights', * weight => 35, * url => 'http://www.myblog.com/', * gid => 15 * ),); */ function getCurrentLinks($postID) { global $wpdb; $table_name = $wpdb->prefix . "blink_goals g"; $table2_name = $wpdb->prefix . "blink_links e"; $sql = "SELECT g.kw, g.weight_local weight, g.page url, g.gid FROM $table_name , $table2_name WHERE g.gid = e.gid AND e.pid = $postID"; $results = $wpdb->get_results($sql,ARRAY_A); return $results; } function getLinkGoals() { global $wpdb; // add prefix to table name $table_name = $wpdb->prefix . "blink_goals"; // setup select statement $sql = "SELECT kw, weight_local weight, page url, gid FROM $table_name WHERE weight > 0 AND weight_local > 0"; $results = $wpdb->get_results( $sql, ARRAY_A); return $results; } /* * Initialize Admin Settings */ function init() { $this.getAdminOptions(); } /** * Verify if DB tables have been created */ function db_check() { global $wpdb; $table_name = $wpdb->prefix . "bl_maintainers"; // if tables aren't installed then install them if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { $this->db_install(); } } /** * Create Database Tables * * BLINK_SERVERS * blsid : auto-increment field/key * server : URL to maintainer server * server_key : key pass to allow access to updates * server_weight : priority given to a maintainer server * last_update : last time update was run on this server (unix time stamp) * * BLINK_GOALS * gid : auto-increment field/key * goal_uid : uniqid provided by maintainer * blsid : fk to BLINK_SERVER table * kw : target word or phrase * page : target URL * weight : maintainer provided link priority * weight_local : combination of link and server weights * goal_source : not currently in use * * BLINK_LINKS * liid : auto-increment field/key * link_uid : uniqid generated locally * gid : fk to BLINK_GOALS * pid : Blog Post ID * url_override : not currently in use * li_updated : date this link was created (unix time stamp) * */ function db_install () { global $wpdb; // BLINK_SERVERS $table_name = $wpdb->prefix . "blink_servers"; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( blsid INTEGER AUTO_INCREMENT, server VARCHAR(255) NOT NULL, server_weight VARCHAR(255), last_successful_update INTEGER, last_update INTEGER, UNIQUE KEY blsid (blsid) );"; $wpdb->query($sql); // Hack to get the default server in $sql = "INSERT INTO " . $table_name . " (`blsid`, `server`, `server_weight`, `last_successful_update`, `last_update`) VALUES (1, 'labs.uswebdev.net', '1', NULL, NULL); "; $wpdb->query($sql); // BLINK_GOALS $table_name = $wpdb->prefix . "blink_goals"; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( gid INTEGER NOT NULL AUTO_INCREMENT, goal_uid VARCHAR(255), blsid INTEGER, kw VARCHAR(255), page VARCHAR(500), weight INTEGER, weight_local INTEGER, goal_source VARCHAR(255), UNIQUE KEY gid (gid) );"; $wpdb->query($sql); // BLINK_LINKS $table_name = $wpdb->prefix . "blink_links"; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( liid INTEGER NOT NULL AUTO_INCREMENT, link_uid VARCHAR(255), gid INTEGER, pid INTEGER, url_override VARCHAR(255), li_updated INTEGER, UNIQUE KEY liid (liid));"; $wpdb->query($sql); // create a blink_key to register the server if (!get_option('blink_key')) { $blink_key = uniqid('b', true); update_option('blink_key', $blink_key); } } /** * Retrieve configuration options and maintianers */ function getAdminOptions() { $adminOptionsName = "BlinkPluginAdminOptions"; global $wpdb; $servers_table = $wpdb->prefix . "blink_servers"; $sql = "SELECT * FROM $servers_table ORDER BY server_weight"; $results = $wpdb->get_results( $sql,ARRAY_A); // set array of settings to default values $blNewSettings = array( 'maxLinks' => 5, 'exclude_blinks' => '', 'css_class' => '', 'blink_servers' => $results ); // check if admin options have been set if (get_option($adminOptionsName)) { $currentSettings = get_option($adminOptionsName); $blNewSettings['maxLinks'] = $currentSettings['maxLinks']; $blNewSettings['css_class'] = $currentSettings['css_class']; $blNewSettings['exclude_blinks'] = $currentSettings['exclude_blinks']; } // update options with current or default settings update_option($adminOptionsName,$blNewSettings); return $blNewSettings; } /** * generates the admin page */ function printAdminPage() { require ('adminPage.php'); adminPage($this); } function update_maintainers($server) { // this will need to be reworked to support multiple servers global $wpdb; $servers_table = $wpdb->prefix . "blink_servers"; $currentServers = $wpdb->get_results("SELECT * FROM $servers_table",ARRAY_A); if (count($server)>0 && count($currentServers)>0 ) { if ($server['server'] != $currentServers['server']) { $sql = "UPDATE $servers_table SET server= " . $currentServers['server'] . " SET last_update = null, SET last_successful_update = null WHERE server = '" . $server['server'] . "' "; $wpdb->query($sql); } } elseif (count($currentServers) == 0 && $server['server']) { $sql = "INSERT INTO $servers_table (server, server_weight) VALUES ('" . $server['server'] . "', 1)"; $wpdb->query($sql); } update_option('maxLinks',$server['maxLinks']); $this->checkServers(); } /** * unregistered (update now) * failed_update (check every 1 hr) * pending_approval (check every 4 hrs) * successful_update (check every 7days) */ function checkServers() { global $wpdb; $table_name = $wpdb->prefix . "blink_servers"; $sql = "SELECT *, UNIX_TIMESTAMP(now()) now FROM $table_name"; $servers = $wpdb->get_results($sql,ARRAY_A); // delete orphaned links from trashed posts $blink_links = $wpdb->prefix . "blink_links"; $delete_sql = "DELETE bl FROM $blink_links bl, $wpdb->posts p WHERE bl.pid = p.id AND p.post_status != 'publish' AND p.post_parent = 0"; $wpdb->query($delete_sql); // check server's status if (count($servers)>0) { foreach ($servers as $server) { // if(!$server['last_update']){ // // unregistered // $this->regServer($server); // } elseif (!$server['last_successful_update']) { // // pending approval (14400 == 4hr) // $time_diff = (int)$server['now'] - (int)$server['last_update']; //if($time_diff > 0 ){ $this->updateServer($server);} // } elseif ($server['last_update'] > $server['last_successful_update']){ //echo 'failed'; // // failed_update (3600 == 1hr) // $time_diff = (int)$server['now'] - (int)$server['last_update']; //if($time_diff > 0 ){ //echo 'check 3'; // $this->updateServer($server); // } // } elseif ($server['last_update'] == $server['last_successful_update']){ // // successful update (601200 == 1wk) // $time_diff = (int)$server['now'] - (int)$server['last_update']; //if($time_diff > 0 ){ //echo 'check 4'; $this->updateServer($server); // } // } } } } function updateServer($server) { global $wpdb; $servers_table = $wpdb->prefix . "blink_servers"; $goals_table = $wpdb->prefix . "blink_goals"; // call RPC and get the new goals $blsid = $server['blsid']; $links = $this->getBlinks($blsid); $updateLinks = $this->callRPC($blsid); $newGoals = $updateLinks['linklist']; if (count($newGoals) > 0) { // update server as successfull upgrade $sql = "UPDATE $servers_table SET last_successful_update = UNIX_TIMESTAMP(now()) WHERE blsid = " . $server['blsid']; $wpdb->query($sql); // get existing goal records $sql = "SELECT * FROM $goals_table WHERE blsid = $blsid"; $oldGoals = $wpdb->get_results( $sql,ARRAY_A); if (count($oldGoals) > 0) { // convert existing goals to array with goal_uid as key foreach ($oldGoals as $goal) {$currentGoals[$goal['goal_uid']] = $goal;} // update existing goals foreach ($newGoals as $newGoal) { if ($currentGoal[$newGoal['goal_uid']]) { if ( ($newGoal['weight'] != $currentGoal['weight']) || ($newGoal['url'] != $currentGoal['page']) || ($newGoal['kw'] != $currentGoal['kw']) ) { $sql = "UPDATE $goals_table SET weight = " . $newGoal['weight'] . ", SET page = '" . $newGoal['url'] . ", SET kw = '" . $newGoal['kw'] . "' WHERE goal_uid = " . $newGoal['goal_uid'] ; $wpdb->query($sql); } } } //downgrade removed goals foreach ($currentGoals as $currentGoal) { if (!$newGoals[$currentGoal['goal_uid']]) { $wpdb->query("UPDATE $goals_table SET weight=0, weight_local=0 WHERE goal_uid=" . $currentGoal['goal_uid']); } } } //add new goals $this->addNewGoals($blsid, $newGoals); //update weight_local $sql ="UPDATE $goals_table g, ( SELECT g1.blsid, g1.server_weight / g2.sum_weight sv_weight FROM $servers_table g1, (SELECT blsid, sum(server_weight) sum_weight FROM $servers_table GROUP BY blsid) g2 WHERE g1.blsid = g2.blsid ) svr, ( SELECT g1.gid, g1.blsid, g1.weight/g2.sum_weight goal_weight FROM $goals_table g1, (SELECT blsid, sum(weight) sum_weight FROM $goals_table GROUP BY blsid) g2 WHERE g1.blsid = g2.blsid ) gl SET weight_local = svr.sv_weight * gl.goal_weight *1000 WHERE g.blsid = gl.blsid AND g.gid = gl.gid AND g.blsid = svr.blsid"; $wpdb->query($sql); } } function addNewGoals($blsid, $newGoals) { global $wpdb; $goals_table = $wpdb->prefix . "blink_goals"; $sql = "SELECT * FROM $goals_table WHERE blsid = $blsid"; $oldGoals = $wpdb->get_results( $sql,ARRAY_A); if (count($oldGoals)>0) { foreach ($oldGoals as $goal) {$currentGoals[$goal['goal_uid']] = $goal;} } foreach ($newGoals as $newGoal) { if (!$currentGoals[$newGoal['goal_uid']]) { //insert goal record $sql = "INSERT INTO $goals_table (goal_uid, blsid, kw, page, weight) VALUES ('" . $newGoal['goal_uid'] . "', $blsid, '" . $newGoal['kw'] . "', '" . $newGoal['url'] . "', " .$newGoal['weight'] . ")"; $wpdb->query($sql); } } } /** * * Retrieves an array of exsiting links * sutible for RPC updates */ function getBlinks($blsid) { global $wpdb; $links_table = $wpdb->prefix . "blink_links l "; $post_table = $wpdb->prefix . "posts p "; $goal_table = $wpdb->prefix . "blink_goals g "; $sql = "SELECT l.link_uid, g.goal_uid, l.li_updated, p.guid FROM $links_table, $post_table, $goal_table WHERE g.gid = l.gid AND p.id = l.pid AND g.blsid = $blsid "; $blinks = $wpdb->get_results($sql, ARRAY_A); $results = array(); if (count($blinks) > 0) { foreach ($blinks as $blink) { $results[$blink['link_uid']] = array( 'link_uid'=>$blink['link_uid'], 'goal_uid'=>$blink['goal_uid'], 'page'=>$blink['guid'], 'li_updated'=>$blink['li_updated'] ); } } return $results; } /** * register new server */ function regServer($server) { $key = get_option('blink_key'); $blsid = $server['blsid']; $this->callRPC($blsid); global $wpdb; $table_name = $wpdb->prefix . "blink_servers"; // update the last update field $sql = "UPDATE " . $table_name . " SET last_update = UNIX_TIMESTAMP(now()) " . " WHERE blsid = " . $blsid ; $wpdb->query($sql); } /** * * Comunicate with maintianer module * * @global <type> $wpdb * @param <type> $blsid * @return <type> */ function callRPC($blsid) { $links = $this->getBlinks($blsid); // todo: change how we handle version tracking $version = '1.1wp'; global $wpdb; $table_name = $wpdb->prefix . "blink_servers"; $sql = "SELECT * FROM " . $table_name . " where blsid = " . $blsid ; $blinks = $wpdb->get_results( $sql,ARRAY_A); // get the RPC server's URL $server = $blinks[0]['server']; $server = $this->getURL($server); // get the blog's URL $blog = get_option('siteurl'); //'http://' . $this->getURL(); $key = get_option('blink_key'); $mail = get_option('admin_email'); $result = array(); // create the RPC client object $client = new IXR_Client($server, '/xmlrpc.php'); // either update or register if (count($links) > 0) { //update if (! $client->query('linklistMaintainer.getLinklist', $blog, $mail, $key, $version, $links)) { die($message = 'Something went wrong - ' . $client->getErrorCode() . ' : ' . $client->getErrorMessage()); $result['success'] = false; $result['message'] = $message; } else { $result = $client->getResponse(); } } else { //register if (! $client->query('linklistMaintainer.getLinklist', $blog, $mail, $key)) { die($message = 'Something went wrong - ' . $client->getErrorCode() . ' : ' . $client->getErrorMessage()); } else { $result = $client->getResponse(); } } return $result; } function getURL($url = '') { if (!$url) $url = get_option('siteurl'); return preg_replace('|^[^:]+://([^:/]+).*|', '$1', $url, 1); } } // end class /** * create an instance of our bl class */ if (class_exists("BLinkCollaborationPlugin")) { $bl_collaboration = new BLinkCollaborationPlugin(); } /** * create actions and filters */ if (isset($bl_collaboration)) { //Actions //add_action('wp_head',array(&$bl_collaboration,'db_check'),1); // creates the database add_action('activate_blink-wp/blink-wp.php',array(&$bl_collaboration,'db_check'),1); // sets default options so the admin page can load add_action('activate_blink-wp/blink-wp.php', array(&$bl_collaboration,'init')); add_action('admin_menu','bLinkCollaboration_ap'); add_action('admin_menu', array(&$bl_collaboration,'checkServers'),12); //Filters add_filter('the_content',array(&$bl_collaboration,'createLinks')); } /** * Initialize the admin panel */ function bLinkCollaboration_ap() { global $bl_collaboration; if (!isset($bl_collaboration)) { return; } add_options_page("Blink Settings", "BLink Settings", 9, __FILE__, array(&$bl_collaboration,'printAdminPage')); }
true
3b86ba4f9f870d56bbce932ea0f2922639f884de
PHP
mduk/gowi
/src/Http/Application/Stage/Config/File.php
UTF-8
2,462
2.59375
3
[ "MIT" ]
permissive
<?php namespace Mduk\Gowi\Http\Application\Stage\Config; use Mduk\Gowi\Http\Application; use Mduk\Gowi\Http\Request; use Mduk\Gowi\Http\Response; use Mduk\Gowi\Http\Application\Stage; use Zend\Config\Config as ZendConfig; use Zend\Config\Reader\Ini as IniReader; use Zend\Config\Reader\Xml as XmlReader; use Zend\Config\Reader\Json as JsonReader; use Symfony\Component\Yaml\Yaml as YamlParser; class File implements Stage { protected $path; protected $namespace; protected $required; public function __construct( $path, array $options=[] ) { $this->path = $path; $this->namespace = isset( $options['namespace'] ) ? $options['namespace'] : null; $this->required = isset( $options['required'] ) ? $options['required'] : true; } public function execute( Application $app, Request $req, Response $res ) { if ( !$this->required && !is_readable( $this->path ) ) { return null; } if ( $this->required && !is_readable( $this->path ) ) { throw new File\Exception( "The config file {$this->path} is unreadable", File\Exception::FILE_UNREADABLE ); } $extension = strtolower( pathinfo( $this->path, PATHINFO_EXTENSION ) ); switch ( $extension ) { case 'php': $reader = new ZendConfig( require $this->path ); $config = $reader->toArray(); break; case 'ini': $reader = new IniReader; $config = $reader->fromFile( $this->path ); break; case 'xml': $reader = new XmlReader; $config = $reader->fromFile( $this->path ); break; case 'json': $reader = new JsonReader; $config = $reader->fromFile( $this->path ); break; case 'yaml': case 'yml': $config = YamlParser::parse( file_get_contents( $this->path ) ); break; default: throw new File\Exception( "Unknown file type: {$this->path}", File\Exception::UNKNOWN_TYPE ); } if ( $this->namespace ) { $app->setConfigArray( [ $this->namespace => $config ] ); } else { $app->setConfigArray( $config ); } } }
true
6ed58960eed771b471e9cc0a092a6ba484e58dc3
PHP
MotionlessPotato/Portfolio-Complete
/PHP Files/Animals.PHP
UTF-8
941
4.0625
4
[]
no_license
<html> <title> PHP Arrays </title> <body> <?php //PHP ARRAYS $animals = array("cats","dogs","rabbits"); // in PHP, there are three types of arrays: //indexed array - array with a numeric inded(list in python) //associated array - array with named keys(dicctionary in python) //$Class = array("Marcus" => "D1", //"Joseph => "d2", "Chris B" => "C2",); //$Class ['Joel'] = "D5"; //Search our array (By key or value) //echo "Marcus is in seat ".$Class['Marcus']. ". <br>" //Loop through array //foreach ($class as $x => x_value){ //echo $x." is in seat ".$x_value."<br>"; //} //MultiDimensional arrays- arrays containing arrays //php indexed arrays //Note: can also assign elements of an array manually $animals[3] = "badgers"; echo "I like ".$animals[0]."<br>"; for ($x=0; $x<count($animals);$x++) { echo $animals[$x]."<br>"; } ?>
true
276a70d0cca3099da3d3ef02df56bf2e002576e4
PHP
albetnov/vuetik-laravel
/src/Commands/PurgeUnusedImages.php
UTF-8
1,709
2.859375
3
[ "MIT" ]
permissive
<?php namespace Vuetik\VuetikLaravel\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; use Vuetik\VuetikLaravel\Models\VuetikImages; use Vuetik\VuetikLaravel\Utils; class PurgeUnusedImages extends Command { public $signature = 'purge:unused-images {--after} {--disk} {--path} {--show-log}'; public $description = 'Purge all unused images'; public function handle(): int { $dateTime = $this->option('after'); if (! $dateTime) { $dateTime = config('vuetik-laravel.purge_after'); } $disk = $this->option('disk'); if (! $disk) { $disk = config('vuetik-laravel.storage.disk'); } $storagePath = $this->option('path'); if (! $storagePath) { $storagePath = config('vuetik-laravel.storage.path'); } $images = VuetikImages::where('status', VuetikImages::PENDING) ->where( 'created_at', '<=', now()->min($dateTime) ); foreach ($images->lazy() as $image) { $filePath = Utils::parseStoragePath($storagePath).$image->file_name; $checkExisting = Storage::disk($disk)->exists($filePath); if (! $checkExisting) { $this->error('Failed deleting file (not exist) id: '.$image->id); continue; } Storage::disk($disk)->delete($filePath); if ($this->option('show-log')) { $this->info('Purged: '.$image->id); } $image->delete(); } $this->info('Unused ImageFactory Purged!'); return self::SUCCESS; } }
true
0888194c8e32ddcc08f1a988d26ba0a589f84253
PHP
obynonwane/publisher-pangaea-assessment
/tests/Feature/PublisherTest.php
UTF-8
2,696
2.5625
3
[]
no_license
<?php namespace Tests\Feature; use App\Models\Message; use App\Models\Subscriber; use Tests\TestCase; use App\Models\Topic; use GuzzleHttp\Client; use App\Services\Publisher; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class PublisherTest extends TestCase { use RefreshDatabase; /** Test */ public function test_create_message_return_false_for_non_existing_topic() { //make request to non existing topic $response = $this->postJson('/api/publish/2', ['body' => 'message body']); //check if response status is false and status code is 422 $response->assertStatus(422)->assertJson([ 'status' => false, ]); } /** Test */ public function test_create_message_successful() { //create topic $topic = Topic::create([ 'title' => 'Test Title' ]); //add message to created topic $response = $this->postJson('/api/publish/' . $topic->id, ['body' => 'message body']); //assert that the creation was successful and response contains topic title $response->assertStatus(200)->assertJson([ 'status' => true, ]); } /** Test */ public function test_publish_to_subscriber_works() { //create topic $topic = Topic::create(['title' => 'Test Title']); //create subscriber Subscriber::create(['url' => 'http://127.0.0.1:9000/api/test1', 'topic_id' => $topic->id,]); //create message $message = Message::create(['body' => 'Test Title', 'topic_id' => $topic->id,]); //form data to be sent to subscribers $data = [ "topic" => $topic->title, "data" => ["message" => $message->body, "published_date" => $message->created_at] ]; //get topic subscriber $subscribers = $topic->subscribers; //guzzle client $client = new Client(); if ($subscribers) { //loop and forward message to subscribers urls foreach ($subscribers as $subscriber) { //Http post request to subscribers url $response = $client->post($subscriber->url, [ 'form_params' => $data, 'headers' => [ 'Accept' => 'application/json' ] ]); //response from subscribers $response = json_decode($response->getBody()->getContents(), TRUE); //assert that the response contains true $this->assertContains(true, $response); } } } }
true
528423eac5154332d559c851c6d320e2e114238e
PHP
Folley-05/test
/soutenance_L2/offres2.php
UTF-8
1,495
2.640625
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <?php $connexion=new PDO('mysql:host=localhost;dbname=tourisme', 'root', ''); function isimage($a=array()) { $img=$_FILES['image']; $ext=strtolower(substr($img['name'], -3)); $ext_allow=array("jpg", "png", "gif"); if(in_array($ext, $ext_allow)) { return true; } else { return false; } } function nomimage($a=array()) { move_uploaded_file($a['image']['tmp_name'], "image/".$a['image']['name']); return "image/".$a['image']['name']; } ?> <body> <?php if(isset($_FILES['image'])) { if(isimage($_FILES)) { $requete1='insert into offres_hotels values("", "'.$_POST['titre'].'", "'.$_POST['prix'].'", "'.nomimage($_FILES).'", "'.$_GET['nom'].'", "'.$_POST['qualite'].'", "'.$_POST['supplements'].'", "'.$_POST['commentaire1'].'", "'.$_POST['commentaire2'].'", "'.$_POST['commentaire3'].'", "'.$_POST['condition'].'", "'.$date=date('yy-m-d').'");'; echo $requete1; $connexion->exec($requete1); header('location:promoteurs.php?service=hotels&nom=yaaHot hotel'); } else{echo "votre fichier n'a pas une extension autorisé";} } else echo "error 404 <br> SERVER NOT FOUND"; ?> </body> </html>
true
f2fd96025d99911b26134568552f32db0bd5e9f5
PHP
centreon/centreon
/centreon/src/Centreon/Domain/Repository/CfgResourceInstanceRelationsRepository.php
UTF-8
839
2.65625
3
[ "Apache-2.0" ]
permissive
<?php namespace Centreon\Domain\Repository; use Centreon\Infrastructure\CentreonLegacyDB\ServiceEntityRepository; use PDO; class CfgResourceInstanceRelationsRepository extends ServiceEntityRepository { /** * Export * * @param int[] $pollerIds * @return array */ public function export(array $pollerIds): array { // prevent SQL exception if (!$pollerIds) { return []; } $ids = implode(',', $pollerIds); $sql = "SELECT t.* " . "FROM cfg_resource_instance_relations AS t " . "WHERE t.instance_id IN ({$ids})" ; $stmt = $this->db->prepare($sql); $stmt->execute(); $result = []; while ($row = $stmt->fetch()) { $result[] = $row; } return $result; } }
true
0805e8d41d41c778ddaa8526cde2a493150afd4f
PHP
dpetrenko1991/vk-loc
/index.php
UTF-8
1,654
2.8125
3
[]
no_license
<?php require_once 'classes/db.php'; $errors = array(); if (isset($_POST['data']) && !empty($_POST['data'])) { $data = $_POST['data']; //check email if (!isset($data['mail']) || empty($data['mail'])) { $errors[] = "Введите корректный E-mail"; } //check login if (!isset($data['login']) || empty($data['login'])) { $errors[] = "Введите корректный login"; } //check password if (!isset($data['password']) || empty($data['password'])) { $errors[] = "Введите корректный password"; } //check date if(!isset($data['day'], $data['month'], $data['year'])) { $errors[] = "Введите корректную дату рождения"; } else { $lastDayOfMonth = date('t', strtotime($data['year'] . '-' . $data['month'] . '-1')); if ($data['day'] > $lastDayOfMonth) { $errors[] = "Введите корректную дату рождения"; } } //if all data correct - insert new record if (empty($errors)) { $user = array( ':email' => $data['mail'], ':login' => $data['login'], ':password' => md5($data['password']), ':date_birth' => $data['year'] . "-" . $data['month']. "-" . $data['day'] ); $db = new Db(); $db->_db; if (!$db->query("INSERT INTO users (email, login, password, date_birth) VALUES (:email, :login, :password, :date_birth)", $user)) { $errors[] = 'Ошибка при регистрации.'; } } } include 'block/header.php'; include 'block/sidebar.php'; ?> <div class="content"> <div class="border"> </div> </div> <?php include 'block/footer.php'; ?>
true
57161d8bfababb80d084756b3aa0aec562d5fee2
PHP
uuk020/php-design-patterns
/Structural/Bridge/Abstraction.php
UTF-8
564
3.03125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: WytheHuang * Date: 2019/4/15 * Time: 23:48 */ declare(strict_types = 1); namespace Patterns\Structural\Bridge; abstract class Abstraction { /** * @var \Patterns\Structural\Bridge\Color */ protected $color; /** * 设置颜色 * * @param \Patterns\Structural\Bridge\Color $color */ public function setColor(Color $color) { $this->color = $color; } /** * 绘画 * * @return string */ abstract public function draw(): string; }
true
64e567c266d599d0e8c5358054fb98e99f33ec48
PHP
lolacld/todolist
/helper/DatabaseHelper.php
UTF-8
585
2.984375
3
[]
no_license
<?php // connexion and security file class DatabaseHelper { private static $db_host = 'localhost'; private static $db_name = 'mytotool'; private static $db_user = 'root'; private static $db_password = ''; private static $DB; public static function getDB() { if (is_null(self::$DB)) { self::$DB = self::DBConnect(); } return self::$DB; } private static function DBConnect() { return new PDO('mysql:host=' . self::$db_host . ';dbname=' . self::$db_name, self::$db_user, self::$db_password); } }
true
3705ec8677ecd23cae1874a4ca373e2519a676c9
PHP
slicesofcake/file
/src/View/Helper/FileHelper.php
UTF-8
923
2.78125
3
[ "MIT" ]
permissive
<?php namespace SlicesCake\File\View\Helper; use Cake\View\Helper; class FileHelper extends Helper { /** * {@inheritDoc} */ public $helpers = [ 'Html', ]; /** * Thumb image. * * @param string|array $path Path to the image file, relative to the app/webroot/img/ direct. * @param array $options Array of HTML attributes. See above for special options. * @param string $thumb Name of thumb. * @return string completed img tag. * @see https://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images */ public function thumb($path, array $options = [], string $thumb = 'default'): string { if ($thumb !== 'default') { $path = preg_replace('/default/', $thumb, $path); } if (!is_array($options)) { $options = []; } return $this->Html->image($path, $options); } }
true
3cefda9c72ece768707ab088ddb281af1ae99f61
PHP
ducquyen/Imagick_PHP
/Imagick::Draw/setviewbox2.php
UTF-8
765
2.921875
3
[ "Apache-2.0" ]
permissive
<?php $draw = new \ImagickDraw(); $draw->setStrokeColor('black'); $draw->setFillColor('red'); $points = [['x' => 40 * 5, 'y' => 10 * 5], ['x' => 70 * 5, 'y' => 50 * 5], ['x' => 60 * 5, 'y' => 15 * 5],]; $draw->polygon($points); $draw->setviewbox(0, 0, 200, 200); $draw->setFillColor('green'); $points = [['x' => 40 * 7, 'y' => 10 * 4], ['x' => 70 * 2, 'y' => 50 * 3], ['x' => 60 * 3, 'y' => 15 * 3],]; $draw->polygon($points); $draw->setFillColor('yellow'); $draw->circle(100, 100, 125, 0); $imagick = new \Imagick(); $imagick->newImage(400, 300, 'white'); $imagick->setImageFormat("png"); $imagick->drawImage($draw); header("Content-Type: image/png"); echo $imagick->getImageBlob(); ?>
true
e9bad68e3212cac5f35cdd5eaaec8a144fe67117
PHP
rcdelfin/laravel-mjml
/src/LaravelMJML.php
UTF-8
2,694
3.0625
3
[ "MIT" ]
permissive
<?php namespace Rennokki\LaravelMJML; use GuzzleHttp\Client as GuzzleClient; class LaravelMJML { private $secretKey; protected $appId; public $publicKey; protected $client; protected $mustache; public static $apiEndpoint = 'https://api.mjml.io/v1'; public function __construct() { $this->client = new GuzzleClient(); $this->mustache = new \Mustache_Engine; } /** * Set the public key. * * @param string $publicKey * @return void */ public function setPublicKey(string $publicKey) { $this->publicKey = $publicKey; return $this; } /** * Set the secret key. * * @param string $secretKey * @return void */ public function setSecretKey(string $secretKey) { $this->secretKey = $secretKey; return $this; } /** * Set the App ID. * * @param string $appId * @return void */ public function setAppId(string $appId) { $this->appId = $appId; return $this; } /** * Getting the request response (in JSON) for rendering MJML. * * @param string $mjml * @return string */ public function renderRequest(string $mjml) { try { $request = $this->client->request('POST', Self::$apiEndpoint.'/render', [ 'auth' => [$this->appId, $this->secretKey], 'headers' => [ 'Content-Type' => 'application/x-www-form-urlencoded', 'Accepts' => 'application/json', ], \GuzzleHttp\RequestOptions::JSON => [ 'mjml' => $mjml, ], ]); } catch (\GuzzleHttp\Exception\ClientException $e) { return json_decode($e->getResponse()->getBody()->getContents()); } return json_decode($request->getBody()); } /** * Getting the rendered HTML for a specified MJML. * * @param string $mjml * @return string|null */ public function render(string $mjml) { $request = $this->renderRequest($mjml); if (property_exists($request, 'status_code') && $request->status_code != 200) { return; } return $request->html; } /** * Rendering the MJML given and apllying mustache render on it. * * @param string $mjml * @param array $parameters * @return string|null */ public function renderWithMustache(string $mjml, array $parameters = []) { $html = $this->render($mjml); return $this->mustache->render($html, $parameters); } }
true
1d4196bf38fa57999d1f0b21bc547aa475c2b214
PHP
softwareofsweden/adventofcode
/day_06_part_2.php
UTF-8
884
3.296875
3
[]
no_license
<?php include_once "ProblemInterface.php"; class Day6Part2 implements ProblemInterface { public function expected() { return 3430; } public function solve() { $rows = include 'day_06_input.php'; $totalCount = 0; $questions = "abcdefghijklmnopqrstuvwxyz"; for ($i = 0; $i < count($rows); $i++) { if ($rows[$i] == '') { $rows[$i] = ' '; } else { $rows[$i] .= ','; } } $rows = explode(' ', implode('', $rows)); foreach ($rows as $row) { $nbrPersons = substr_count($row, ','); for ($i = 0; $i < strlen($questions); $i++) { if (substr_count($row, $questions[$i]) == $nbrPersons) { $totalCount++; } } } return $totalCount; } }
true
a5a6654e9be3f26872906ddfdb6004f53b4e4fb1
PHP
itmaster921/FBChatBot-Laravel
/common/Jobs/SendBroadcastToSubscriber.php
UTF-8
1,098
2.796875
3
[]
no_license
<?php namespace Common\Jobs; use Common\Models\Broadcast; use Common\Models\Subscriber; use Common\Services\FacebookMessageSender; use Common\Exceptions\DisallowedBotOperation; class SendBroadcastToSubscriber extends BaseJob { /** * @type Broadcast */ private $broadcast; /** * @type Subscriber */ private $subscriber; /** * SendBroadcast constructor. * @param Broadcast $broadcast * @param Subscriber $subscriber */ public function __construct(Broadcast $broadcast, Subscriber $subscriber) { $this->broadcast = $broadcast; $this->subscriber = $subscriber; } /** * Execute the job. * * @param FacebookMessageSender $FacebookMessageSender * @throws \Exception */ public function handle(FacebookMessageSender $FacebookMessageSender) { $this->setSentryContext($this->broadcast->bot_id); try { $FacebookMessageSender->sendBroadcastMessages($this->broadcast, $this->subscriber); } catch (DisallowedBotOperation $e) { } } }
true
dfe0a9d58eeae506221771ecb84c830b7602a39c
PHP
caiminfang/Learning
/test/349. 两个数组的交集/index.php
UTF-8
1,759
3.984375
4
[]
no_license
<?php /** 给定两个数组,编写一个函数来计算它们的交集。 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [9,4] 说明: 输出结果中的每个元素一定是唯一的。 我们可以不考虑输出结果的顺序。 */ class Solution { /** 暴力法,判断一个数值在另一个数组是否存在 */ function intersection1($nums1, $nums2) { if(count($nums1) <count($nums2)){ $arr = $nums1; $arr1 = $nums2; }else{ $arr = $nums2; $arr1 = $nums1; } $new_arr = []; for ($i = 0;$i <count($arr) ;$i++){ if (in_array($arr[$i],$arr1)){ $new_arr[$arr[$i]]=$arr[$i]; } } return array_values($new_arr); } /** 内置函数 */ function intersection2($nums1, $nums2) { return array_unique(array_intersect($nums1,$nums2)); } /** 先把2个数组排序,通过双指针往前推来进行查找 */ function intersection3($nums1, $nums2) { sort($nums1); sort($nums2); $i = $j = 0; $res=[]; while($i <count($nums1) && $j <count($nums2)){ if ($nums1[$i] == $nums2[$j]){ $res[] = $nums1[$i]; $i++; $j++; }elseif ($nums1[$i] > $nums2[$j]){ $j++; }elseif ($nums1[$i] < $nums2[$j]){ $i++; } } return array_unique($res); } } $solution = new Solution(); //$nums1 = [1,2,2,1]; //$nums2 = [2,2]; $nums1 = [4,9,5]; $nums2 = [9,4,9,8,4]; var_dump($solution->intersection($nums1, $nums2));
true
20ecb91f7691a8a1d4fbc8b9c4eee091d464519d
PHP
GraceWang17/xwang230-comp3512-assign3
/includes/book-content.php
UTF-8
5,813
3.046875
3
[]
no_license
<?php /* Displays the list of books which are sorted by Subcategory or Imprint from books table. */ function outputBooks() { $db = connectDB(); $books = new BooksGateway($db); $sql = $books->getSelectStatement(); // Subcategory filter if (!empty($_GET['subcategory']) && empty($_GET['imprint'])) { $sql .= 'where SubcategoryName = "'. $_GET['subcategory'] .'"'; } // Imprint filter elseif(empty($_GET['subcategory']) && !empty($_GET['imprint'])) { $sql .= 'where Imprint ="' . $_GET['imprint']. '"'; } // Both filter elseif(!empty($_GET['subcategory']) && !empty($_GET['imprint'])) { $sql .= 'where SubcategoryName = "'. $_GET['subcategory'] .'"' . 'AND'.'Imprint ="' . $_GET['imprint']. '"'; } // No filter else { // Print all books. } $sql .= ' group by Title order by Title ASC limit 0,20'; $result = $books->getStatement($sql); //var_dump($result); foreach($result as $key => $value) { $img= '<img src="book-images/thumb/'.$result[$key]['ISBN10']. '.jpg" alt="book">'; echo constructBookLink($result[$key]['ISBN10'], $img) .'<br/>'; echo '<a href="single-book.php?ISBN10=' . $result[$key]['ISBN10'] . '" class="'; if (isset($_GET['ISBN10']) && $_GET['ISBN10'] == $result[$key]['ISBN10']) echo 'active'; echo 'item">'; echo $result[$key]['Title'] . '</a><br/>'; echo '<p>'; echo "<span>Year: </span>". $result[$key]['CopyrightYear'] . "<br/>"; echo "<span>Subcategory Name: </span>". $result[$key]['SubcategoryName'] . "<br/>"; echo "<span>Imprint Name: </span>". $result[$key]['Imprint']. "<br/>"; echo '</P><br/>'; } } /* Constructs a link given the ISBN10 id */ function constructBookLink($id, $label) { $link = '<a href="single-book.php?ISBN10=' . $id . '">'; $link .=$label; $link .='</a>'; return $link; } // Display all Imprints of books in the books table. function generatedImprint() { $db = connectDB(); $imprint = new BooksGateway($db); echo '<a href="../browse-books.php" class="'. 'item">'."All Imprints".'</a><br/>'; $sql = $imprint->getImprint(); $result = $imprint->getStatement($sql); //var_dump($result); foreach ($result as $key =>$value) { echo '<a href="' . $SERVER["SCRIPT_NAME"] . '?imprint=' . $result[$key]['Imprint'] . '" class="'; if (isset($_GET['imprint']) && $_GET['imprint'] == $result[$key]['Imprint']) echo 'active'; echo 'item">'; echo $result[$key]['Imprint'] . '</a><br/>'; } } //<!--Display all Subcategories of all books in the books table.--> function generatedSub() { $db = connectDB(); $subcategory = new BooksGateway($db); echo '<a href="../browse-books.php" class="'. 'item">'."All Subcategories".'</a><br/>'; $sql = $subcategory->getSubcategories(); $result = $subcategory->getStatement($sql); //var_dump($result); foreach ($result as $key => $value) { echo '<a href="' . $SERVER["SCRIPT_NAME"] . '?subcategory=' . $result[$key]['SubcategoryName']. '" class="'; if (isset($_GET['subcategory']) && $_GET['subcategory'] == $result[$key]['SubcategoryName']) echo 'active'; echo 'item">'; echo $result[$key]['SubcategoryName'] . '</a><br/>'; } } ?> <main class="mdl-layout__content mdl-color--grey-50"> <section class="page-content"> <div class="mdl-grid"> <!--mdl-cell + mdl-card --> <div class="mdl-cell mdl-cell--6-col card-lesson mdl-card" id="book"> <div class="mdl-card__title mdl-color--pink"> <h2 class="mdl-card__title-text">Books</h2> </div> <div class="mdl-card__supporting-text"> <ul class="demo-list-item mdl-list"> <?php /* Display books which are based on filter. */ echo outputBooks(); ?> </ul> </div> </div> <!--mdl-cell + mdl-card --> <div class="mdl-cell mdl-cell--6-col card-lesson mdl-card" id="imandsub"> <div class="mdl-cell mdl-cell--6-col card-lesson mdl-card" id="imprint"> <div class="mdl-card__title mdl-color--orange"> <h2 class="mdl-card__title-text">Imprint</h2> </div> <div class="mdl-card__supporting-text"> <ul class="demo-list-item mdl-list"> <?php generatedImprint(); ?> </ul> </div> </div> <!--mdl-cell + mdl-card --> <div class="mdl-cell mdl-cell--6-col card-lesson mdl-card" id="subcategory"> <div class="mdl-card__title mdl-color--orange"> <h2 class="mdl-card__title-text">Subcategory</h2> </div> <div class="mdl-card__supporting-text"> <ul class="demo-list-item mdl-list"> <?php generatedSub(); ?> </ul> </div> </div> </div> </div> </section> </main>
true
952b926658c535b55db843e0c3954bda1e78c2e4
PHP
skullred9x/db_anhtuan
/public/images/mabaomat/mabaomat.php
UTF-8
1,402
2.65625
3
[ "MIT" ]
permissive
<?php session_start();//Khoi dong sesssion //md5: hàm mã hóa ko dịch ngược luôn trả về 32 ký tự //$_SERVER['REMOTE_ADDR']: Địa chỉ IP của người dùng //rand(): Hàm random ra 1 con số từ 0- 32k (đơn vị) //time(): THời gian hiện tại tính bằng giây từ năm 1970 $str=md5(time().$_SERVER['REMOTE_ADDR'].rand()); //substr: Sử dụng hàm cắt chuỗi để lấy 6 ký tự trong 32 ký tự bị mã hóa $code=substr($str,rand(0,25),6); //Lưu mã 6 ký tự trên vào biến SESSION $_SESSION['sercode']=$code; //Sử dụng các hàm PHP làm việc với ảnh //imagecreatefromgif: Lệnh tạo 1 tài nguyên ảnh từ 1 hình ảnh đã có: đối số là đường dẫn ảnh $img=imagecreatefromgif('cross.gif'); //ĐỊnh nghĩa 1 mã màu để sử dụng làm màu sắc cho mã bảo mật khi vẽ lên ảnh $color=imagecolorallocate($img,255,110,0);//Màu RGB $font='arial.ttf';//Đường dẫn đến file FOnt (font chữ cho mã bảo mật: chú ý: nên chọn font nào uốn éo tí) //Lệnh vẽ 1 đoạn văn bản lên 1 đối tượng ảnh imagefttext($img,15,5,7,25,$color,$font,$code); //Chạy lệnh thay đổi kiểu FIle này (file code.php thành file ảnh PNG) header('Content-type: image/png'); //Chạy lệnh tạo ra nội dung của file ảnh imagepng($img); //Hủy biển $img: imagedestroy($img); ?>
true
4fbc86b92967a492e1ee1e31fc32ceddb926db82
PHP
kkosnull/helpdesk
/library/index.php
UTF-8
3,801
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php error_reporting(0); include 'classes/users.php'; include 'connection/credentials.php'; $login_user = new users(); $login_user->setdb($db); $login_user->setUser($user); $login_user->setPassword($password); $login_user->set_username("null"); $user_name="null"; if ($_POST["enterlibrary"]){ $username=$_POST["username"]; $password=$_POST["password"]; $password=md5($password); $login_user->set_username($username); $login_user->set_password($password); $login_user->login(); $user_name=$login_user->getUsername(); $level=$login_user->getLevel(); //echo $login_user->getUsername(); } else if ($_POST["logoff_button"]){ $username="null"; $login_user->set_username($username); $user_name=$login_user->getUsername(); $level=$login_user->getLevel(); //echo $login_user->getUsername(); } ?> <html lang="en"> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8"> <title>ANIP Techical Library</title> <link rel="stylesheet" type="text/css" href="login_style.css" media="screen" /> <script src="scripts.js"></script> <meta name="description" content=""> <meta name="author" content=""> <!-- Mobile Specific Metas ================================================== --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- CSS ================================================== --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body style="background-color:#000"> <?php if ($user_name=="null") { ?> <div class="container" style="max-width:1280px; width:1280px; height:905px; background-image:url('images/back.jpg'); margin-left:auto; margin-right:auto;"> <div class="flat-form"> <ul class="tabs"> <li> <a href="#login" class="active">Φόρμα εισόδου</a> </li> </ul> <div id="login" class="form-action show"> <h1>Τεχνική βιβλιοθήκη </h1> <p> Είσοδος στην τεχνική βιβλιοθήκη της ANIP. </p> <form method="post" action="#"> <ul> <li> <input type="text" placeholder="Username" name="username"/> </li> <li> <input type="password" placeholder="Password" name="password"/> </li> <li> <input type="submit" value="Login" class="button" name="enterlibrary" /> </li> </ul> </form> </div> <!--/#login.form-action--> </div> </div> <?php } else { echo $login_user->getUsername(); echo " level :"; echo $login_user->getLevel(); echo "<form method='post' action='#'> <input type='submit' value='Logoff' name='logoff_button' style='background-color:red; border:0px;color:#fff; position:fixed; top:0px; right:2px; cursor:pointer;'/> </form>";?> <?php if ($level==1){ ?> <iframe src="elfinder.html" width="100%" height="100%" frameborder="0"> </iframe> <?php } else if ($level==2){ ?> <iframe src="elfinder2.html" width="100%" height="100%" frameborder="0"> </iframe> <?php } ?> <?php } ?> <script class="cssdeck" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> </body> </html>
true
1f0294dadbf90d8c88f7d3af05ce82462499075b
PHP
howlee/winzhibo
/app/Console/commands/VideoIndexHtmlCommands.php
UTF-8
1,789
2.59375
3
[]
no_license
<?php /** * Created by PhpStorm. * User: 11247 * Date: 2018/7/5 * Time: 13:07 */ namespace App\Console\commands; use App\Http\Controllers\PC\Live\LiveController; use Illuminate\Console\Command; use Illuminate\Http\Request; use Illuminate\Support\Facades\Storage; class VideoIndexHtmlCommands extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'video_index_html:run'; /** * The console command description. * * @var string */ protected $description = '录像列表html静态化'; /** * Create a new command instance. * HotMatchCommand constructor. */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $cache = Storage::get('/public/static/json/subject/videos/all/1.json'); $json = json_decode($cache, true); if (!isset($json)) { dump('数据不存在'); return; } $page = $json['page'];//获取分页信息 if (!isset($page)) { dump('分页数据不存在'); return; } $lastPage = $page['lastPage']; $liveController = new LiveController(); for ($pageIndex = 1; $pageIndex <= $lastPage; $pageIndex++) { $videoHtml = $liveController->videos(new Request(), $pageIndex); usleep(100); if ($pageIndex == 1) { Storage::disk("public")->put("/static/live/videos/index.html", $videoHtml); } Storage::disk("public")->put("/static/live/videos/index" . $pageIndex . ".html", $videoHtml); } } }
true
b5b5be9aee5dfd81d4573fe707d76d18bb19e02d
PHP
wj008/beacon-standard
/sdopx/plugin/DbvalModifier.php
UTF-8
1,009
2.609375
3
[]
no_license
<?php namespace sdopx\plugin; use beacon\Console; use beacon\DB; class DbvalModifier { private static $cache = []; public static function execute($string, string $tbname, string $field = '', string $where = '') { if (empty($field)) { $field = 'name'; } if (empty($string)) { return ''; } $sql = 'select `' . $field . '` from `' . $tbname . '`'; if (!empty($where)) { $sql .= ' where ' . $where; } else { $sql .= ' where id=?'; } $key = md5($tbname . '|' . $field . '|' . $where . '|' . $string); if (isset(self::$cache[$key])) { return self::$cache[$key]; } $row = DB::getRow($sql, $string); if (!$row) { self::$cache[$key] = ''; return self::$cache[$key]; } else { self::$cache[$key] = isset($row[$field]) ? $row[$field] : ''; return self::$cache[$key]; } } }
true
4c7f02f8c0227e244cf4f47c168c4457b03a4a25
PHP
fpoirotte/DotGraph
/src/Attributes.php
UTF-8
2,016
2.96875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace fpoirotte\DotGraph; class Attributes implements \ArrayAccess, \IteratorAggregate, \Countable { protected $attributes; public function __construct(array $attributes = []) { $this->attributes = []; $this->merge($attributes); } public function merge($attributes): void { $cls = __CLASS__; if (is_object($attributes) && $attributes instanceof $cls) { $attributes = $attributes->asArray(); } if (!is_array($attributes)) { throw new \InvalidArgumentException("\$attributes must be an array or instance of $cls"); } foreach ($attributes as $key => $value) { $this[$key] = $value; } } public function asArray(): array { return $this->attributes; } public function count(): int { return count($this->attributes); } public function offsetGet($offset) { return $this->attributes[$offset] ?? null; } public function offsetSet($offset, $value) { if (!is_string($offset) || !strlen($offset)) { $offset = var_export($offset, true); throw new \InvalidArgumentException("Invalid attribute name $offset: should be a non-empty string"); } if (!is_object($value) || !($value instanceof Attribute)) { $value = new Attribute($offset, $value); } $this->attributes[$offset] = $value; } public function offsetExists($offset) { return isset($this->attributes[$offset]); } public function offsetUnset($offset) { unset($this->attributes[$offset]); } public function getIterator(): \Traversable { yield from $this->attributes; } public function asDot(int $depth = 0): string { $res = []; foreach ($this->attributes as $attr) { $res[] = $attr->asDot($depth); } return implode('', $res); } }
true
22c3b73ef01a1846296e7a5137c2577d97129251
PHP
tesstil/blog-approche_MVC
/app/controller/article/view.php
UTF-8
689
2.765625
3
[]
no_license
<?php // Test du paramètre if(isset($_GET['id'])){ // Récupération des paramètres de l'URL et test éventuel $id = $_GET['id']; // Appel du modèle pour obtenir le détail d'un article include_once("app/model/article/lire_article.php"); $articles = lire_article($id); $article = $articles[0]; // Appel du modèle pour obtenir les commentaires d'un article include_once("app/model/commentaire/lire_commentaires.php"); $commentaires = lire_commentaires($id); // Appel de la vue correspondante define("PAGE_TITLE", "Détail d'un article"); include_once('app/view/article/view.php'); } else { include_once("app/view/404.php"); }
true
9c682fa88b0a992dff60ec5d6899cdea24655bc1
PHP
mishanon/parser-vmstat
/vmstat.php
UTF-8
667
2.734375
3
[]
no_license
<?php function parserVmstat($lines = '') { function isEmpty($value) { return (strlen($value)) != 0; } if (strlen($lines) == 0) { exec('vmstat', $res); } else { $res = $lines; } $keys = explode(' ', $res[1]); $values = explode(' ', $res[2]); $keys = array_values(array_filter( $keys, 'isEmpty')); $values = array_values(array_filter( $values, 'isEmpty')); $parameters = array(); foreach($keys as $key => $value) { $parameters[$value] = $values[$key]; } return $parameters; } $data = parserVmstat(); print_r($data);
true
ee7866cfb16e80802484fc250595651dadd590fc
PHP
brentschuddinck/imdstagram
/explore/profile.php
UTF-8
12,974
2.546875
3
[]
no_license
<?php include_once('../inc/sessiecontrole.inc.php'); include_once('../classes/Post.class.php'); include_once('../classes/User.class.php'); include_once('../classes/Comment.class.php'); include_once('../inc/feedbackbox.inc.php'); include_once('../classes/Search.class.php'); include_once('../classes/Validation.class.php'); if (isset($_GET['user']) && !empty($_GET['user'])) { $username = htmlspecialchars($_GET['user']); $amountOfSearchResults = 0; //controleer geldige locatie $search = new Search(); $user = new User(); $validation = new Validation(); $post = new Post(); if ($validation->isValidSearchTerm($username)) { $username = str_replace('#', '', $username); $username = str_replace('%23', '', $username); //kijk of deze gebruiker bestaat $user->setMSUsername($username); if($user->UsernameAvailable()){ //hergebruik functie. rows = 0 keert true terug. In deze situatie moet dit 1 zijn. header('Location: /imdstagram/error/error404.php'); } } else { header('Location: /imdstagram/error/404.php'); } $post->setMSUsernamePosts($username); $userPosts = $post->getPostsForEachUser(); $user = new User(); $user->setMSUsername($username); //print_r($user->isAccepted()); if(!empty($_GET['id'])){ $user->setMIUserId($_GET['id']); $user->followUser(); header('location: profile.php?user=' . $_GET['user']); } $requests = $user->getFriendRequests(); //accepteer friend requests if(isset($_GET['acceptId']) && !empty($_GET['acceptId'])){ $user->setMIAcceptId($_GET['acceptId']); $user->acceptFriendRequest(); header('location: profile.php?user=' . $_GET['user']); } $followers = $user->getFollowers(); $followings = $user->getFollowing(); // feedback voor als een profiel nog geen foto's, volgers of nog niemand volgt if(empty($userPosts) && $post->countPostsForEachuser() > 0){ $feedback = 'Dit account is privé, stuur een volg verzoek om de foto\'s van deze gebruiker te zien.'; }elseif(empty($userPosts) && $post->countPostsForEachuser() == 0 && $_GET['user'] == $_SESSION['login']['username']){ $feedback = 'Je hebt nog geen foto\'s geplaatst.'; }elseif(empty($userPosts) && $post->countPostsForEachuser() == 0 ){ $feedback = 'Deze gebruiker heeft nog geen foto\'s geplaatst.'; } if(empty($followers) && $user->countFollowers() == 0 && $_GET['user'] != $_SESSION['login']['username']){ $followerfb = 'Deze gebruiker heeft nog geen volgers.'; }elseif( empty($followers) && $user->countFollowers() == 0){ $followerfb = 'Je hebt nog geen volgers.'; } if(empty($followings) && $user->countFollowing() == 0 && $_GET['user'] != $_SESSION['login']['username']){ $followingfb = 'Deze gebruiker volgt nog niemand.'; }elseif( empty($followings) && $user->countFollowing() == 0){ $followingfb = 'Je volgt nog niemand.'; } //welk profiel opvragen? //als querystring user bestaat en de waarde hiervan verschillende is van de gebruikersnaam van de ingelogde gebruiker (sessie), dan wordt een ander profiel bekeken if(isset($_GET['user']) && $_GET['user'] != $_SESSION['login']['username']){ $pageTitle = "Profiel " . htmlspecialchars($_GET['user']);} //in het andere geval wanneer profile.php bezocht wordt zonder user in de querystring, stuur bezoeker door (link zo deelbaar voor anderen) else if(!isset($_GET['user'])){ $_GET['user'] = $_SESSION['login']['username']; header('location: profile.php?user=' . $_GET['user']); //in het andere geval wil de ingelogde gebruiker zijn eigen profiel bekijken. Toon gepaste titel. }else{ $pageTitle = "Mijn profiel"; } if (isset($_POST['btnLikePicture'])) { $post->likePost(); } if (isset($_GET['click']) && !empty($_GET['click'])) { $getclick = $_GET['click']; $post->setMSPostId($getclick); $post->likePost(); } if (isset($_GET['delete']) && !empty($_GET['delete'])) { try { $deletePostId = $_GET['delete']; $post->setMSPostId($deletePostId); $postToDelete = $post->getSinglePost(); if($postToDelete[0]['user_id'] == $_SESSION['login']['userid']){ if($post->deletePost()){ $post->deletePostImage($postToDelete[0]['post_photo']); $feedback = buildFeedbackBox("success", "De post is verwijderd."); header("Location: profile.php?user=". $username); } }else{ $feedback = buildFeedbackBox("danger", "je kan enkel posts wissen die je zelf geplaatst hebt."); } } catch (Exception $e) { $feedback = buildFeedbackBox("danger", $e->getMessage()); } } if (isset($_GET['flag']) && !empty($_GET['flag'])) { try { $flagPostId = $_GET['flag']; $post->setMSPostId($flagPostId); $postToFlag = $post->getSinglePost(); if($post->checkIfUserAlreadyFlagged()){ if($post->flagPost()){ $post->addUsersWhoFlagged(); $feedback = buildFeedbackBox("success", "Bedankt! De post is gerapporteerd."); //header('Location: index.php'); } } } catch (Exception $e) { $feedback = buildFeedbackBox("danger", $e->getMessage()); } } if(!empty($_POST['commentPostId']) && !empty($_POST['commentDescription'])) { $comment = new Comment(); $comment->setMSComment($_POST['commentDescription']); $comment->setMIUserId($_SESSION['login']['userid']); $comment->setMIPostId($_POST['commentPostId']); $comment->postComment(); } } else{ header('Location: /imdstagram/error/404.php'); } ?><!doctype html> <html lang="nl"> <head> <meta charset="UTF-8"> <title>IMDstagram tijdlijn</title> <meta name="description" class="tijdlijn"> <?php include_once('../inc/style.inc.php'); ?> </head> <body class="template"> <?php include_once('../inc/header.inc.php'); ?> <div class="container"> <div class="col-md-10 col-md-offset-1"> <div class="card hovercard"> <div class="card-background"> </div> <div class="useravatar"> <img alt="" src="../img/uploads/profile-pictures/<?php echo htmlspecialchars($user->profilePictureOnProfile()); ?>"> </div> <div class="card-info"> <span class="card-title"><?php echo htmlspecialchars($pageTitle); ?></span> </div> <?php if(isset($_GET['user']) && $_GET['user'] != $_SESSION['login']['username']): ?> <div> <form action="" method="post"> <a style="margin-top: 20px" href="?user=<?php echo $_GET['user'];?>&id=<?php echo $user->getIdFromProfile() ?>" class="likeBtn btn btn-primary"><i class="<?php if($user->isFollowing() == 0){echo 'fa fa-user-plus';}elseif($user->isFollowing() == 1 && $user->isAccepted() == true){echo 'fa fa-user-times';}elseif($user->isFollowing() == 1 && $user->isAccepted() == false){echo 'fa fa-envelope-o';} ?> fa-lg"></i><?php if($user->isFollowing() == 0){echo ' volg deze gebruiker';}elseif($user->isFollowing() == 1 && $user->isAccepted() == true){echo ' niet meer volgen';}elseif($user->isFollowing() == 1 && $user->isAccepted() == false){echo ' verzoek verstuurd';} ?></a> </form> </div> <?php endif ?> </div> <div class="btn-pref btn-group btn-group-justified btn-group-lg" role="group" aria-label="..."> <div class="btn-group" role="group"> <button type="button" id="stars" class="btn btn-primary" href="#tab1" data-toggle="tab"><span class="fa fa-camera" aria-hidden="true"></span> <div class="hidden-xs"><strong><?php echo $post->countPostsForEachuser(); ?></strong> <?php echo $post->countPostsForEachuser() == 1 ? 'foto' : 'foto\'s' ?></div> </button> </div> <div class="btn-group" role="group"> <button type="button" id="favorites" class="btn btn-default" href="#tab2" data-toggle="tab"><span class="fa fa-users" aria-hidden="true"></span> <div class="hidden-xs"><strong><?php echo $user->countFollowers(); ?></strong><?php echo $user->countFollowers() == 1 ? ' volger' : ' volgers' ?></div> </button> </div> <div class="btn-group" role="group"> <button type="button" id="following" class="btn btn-default" href="#tab3" data-toggle="tab"><span class="fa fa-smile-o fa-lg" aria-hidden="true"></span> <div class="hidden-xs"><strong><?php echo $user->countFollowing(); ?></strong> volgend</div> </button> </div> </div> <div class="well"> <div class="tab-content"> <div class="tab-pane fade in active" id="tab1"> <p class="fb"><?php echo !empty($feedback) ? $feedback : ''?></p> <div class="row img-list"> <?php foreach($userPosts as $userPost): ?> <?php $userPost['post_description'] = htmlspecialchars($userPost['post_description']); ?> <div class="col-xs-12 col-sm-4 col-md-4"> <a href="/imdstagram/detail.php?profile=<?php echo htmlspecialchars($username) ?>&postid=<?php echo $userPost['post_id'] ?>" data-toggle="lightbox" data-gallery="multiimages" class="thumbnail picturelist"> <img src="/imdstagram/img/uploads/post-pictures/<?php echo $userPost['post_photo']; ?>" class="img-responsive <?php echo $userPost['photo_effect']; ?>"> </a> </div> <?php endforeach ?> </div> </div> <div class="tab-pane fade in" id="tab2"> <?php if(isset($_GET['user']) && $_GET['user'] == $_SESSION['login']['username']): ?> <h2>Verzoeken</h2> <p><?php echo empty($requests) ? 'Je hebt geen vriendschapsverzoeken':'' ?></p> <?php foreach($requests as $request): ?> <div class="friendRequests"> <div class="user-block""> <a href="/imdstagram/explore/profile.php?user=<?php echo $request['username'];?>"><img class="img-circle" src="../img/uploads/profile-pictures/<?php echo $request['profile_picture'] ?>" alt="<"> <span class="username"><?php echo $request['username']; ?></span></a> <span class="description acceptBtn"><a href="?user=<?php echo $_SESSION['login']['username'];?>&acceptId=<?php echo $request['user_id']; ?>"><li class="fa fa-user-plus"></li> Accepteer</a></span> </div> </div> <?php endforeach ?> <h2>Volgers</h2> <?php endif ?> <?php foreach($followers as $follower): ?> <div class="user-block""> <a href="/imdstagram/explore/profile.php?user=<?php echo $follower['username'];?>"><img class="img-circle" src="../img/uploads/profile-pictures/<?php echo $follower['profile_picture'] ?>" alt="<"> <span class="username"><?php echo $follower['username']; ?></span></a> </div> <?php endforeach ?> <p class="fb"><?php echo !empty($followerfb) ? $followerfb : ''?></p> </div> <div class="tab-pane fade in" id="tab3"> <?php foreach($followings as $following): ?> <div class="user-block profile-block""> <a href="/imdstagram/explore/profile.php?user=<?php echo $following['username'];?>"><img class="img-circle" src="../img/uploads/profile-pictures/<?php echo $following['profile_picture'] ?>" alt="<"> <span class="username"><?php echo $following['username']; ?></span></a> </div> <?php endforeach ?> <p class="fb"><?php echo !empty($followingfb) ? $followingfb : ''?></p> </div> </div> </div> <?php include_once('../inc/footer.inc.php'); ?> <script> $(document).ready(function() { $(".btn-pref .btn").click(function () { $(".btn-pref .btn").removeClass("btn-primary").addClass("btn-default"); $(this).removeClass("btn-default").addClass("btn-primary"); }); }); </script> <!-- lightbox required components --> <script src="/imdstagram/js/lightbox-style.js"></script> <script src="/imdstagram/js/lightbox-call.js"></script> </body> </html>
true
9fae1cf56d91342299fc6e6622b6c3a9e66c2412
PHP
MilitaryShipment/account_service_php
/record.php
UTF-8
5,496
2.734375
3
[]
no_license
<?php require_once __DIR__ . '/db7.php'; if(!isset($GLOBALS['db'])){ $db = new DB(); } interface RecordBehavior{ public function create(); public function update(); public function setFields($updateObj); } interface ContactBehavior{ // public function getNotifications(); // public function getResponses(); // public function call(); // public function fax(); // public function email(); // public function verify(); } abstract class Record implements RecordBehavior{ const MSSQL = 'mssql'; const MYSQL = 'mysql'; public $id; protected $suite; protected $driver; protected $database; protected $table; protected $primaryKey; public function __construct($suite,$driver,$database,$table,$primaryKey,$id) { $this->suite = $suite; $this->driver = $driver; $this->database = $database; $this->table = $table; $this->primaryKey = $primaryKey; if(!is_null($id)){ $this->id = $id; $this->_build(); } } protected function _mssqlGuidStr($binGuid){ $unpacked = unpack('Va/v2b/n2c/Nd', $binGuid); return sprintf('%08X-%04X-%04X-%04X-%04X%08X', $unpacked['a'], $unpacked['b1'], $unpacked['b2'], $unpacked['c1'], $unpacked['c2'], $unpacked['d']); } protected function _build(){ $results = $GLOBALS['db'] ->suite($this->suite) ->driver($this->driver) ->database($this->database) ->table($this->table) ->select("*") ->where($this->primaryKey,"=",$this->id) ->get(); if($this->driver == self::MSSQL){ if(!sqlsrv_num_rows($results)){ throw new Exception('Invalid Record ID'); } while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)){ foreach($row as $key=>$value){ if($key == 'guid' && !is_null($value)){ $this->$key = $this->_mssqlGuidStr($value); }else{ $this->$key = $value; } } } }elseif($this->driver == self::MYSQL){ if(!mysqli_num_rows($results)){ throw new Exception('Invalid Record ID'); } while($row = mysqli_fetch_assoc($results)){ foreach($row as $key=>$value){ $this->$key = $value; } } } return $this; } protected function _buildId(){ $results = $GLOBALS['db'] ->suite($this->suite) ->database($this->database) ->table($this->table) ->select("$this->primaryKey") ->orderBy("$this->primaryKey desc") ->take(1) ->get(); if(strtolower($this->driver) == self::MSSQL){ while($row = sqlsrv_fetch_array($results,SQLSRV_FETCH_ASSOC)){ $this->id = $row[$this->primaryKey]; } }else{ while($row = mysqli_fetch_assoc($results)){ $this->id = $row[$this->primaryKey]; } } return $this; } public function create(){ $reflection = new \ReflectionObject($this); $data = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC); $upData = array(); foreach($data as $obj){ $key = $obj->name; if($key == 'created_date' || $key == 'updated_date'){ $upData[$key] = date("m/d/Y H:i:s"); }elseif(!is_null($this->$key) && !empty($this->$key)){ $upData[$key] = $this->$key; } } unset($upData['id']); $results = $GLOBALS['db'] ->suite($this->suite) ->driver($this->driver) ->database($this->database) ->table($this->table) ->insert($upData) ->put(); $this->_buildId()->_build(); return $this; } public function update(){ $reflection = new \ReflectionObject($this); $data = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC); $upData = array(); foreach($data as $obj){ $key = $obj->name; if($key == 'updated_date'){ $upData[$key] = date("m/d/Y H:i:s"); }elseif(!is_null($this->$key) && !empty($this->$key)){ $upData[$key] = $this->$key; } } if(isset($upData['created_date'])){ unset($upData['created_date']); } unset($upData['id']); unset($upData['guid']); $key = $this->primaryKey; $results = $GLOBALS['db'] ->suite($this->suite) ->driver($this->driver) ->database($this->database) ->table($this->table) ->update($upData) ->where($this->primaryKey,"=",$this->$key) ->put(); return $this; } public function setFields($updateObj){ if(!is_object($updateObj)){ throw new Exception('Trying to perform object method on non object.'); } foreach($updateObj as $key=>$value){ $this->$key = $value; } return $this; } }
true
fe75076e999f27d7c2c136eea763179dd52dfe87
PHP
pptech-ds/Simplon-Project3-FORM
/tests/test_checkString.php
UTF-8
601
3.03125
3
[]
no_license
<?php require '../service/checkPhoneNumberPattern.php'; ?> <?php require '../service/checkString.php'; ?> <?php require '../service/getScore.php'; ?> <?php require '../service/printScore.php'; ?> <h2>TEST function checkString</h2> <?php echo '<br>TEST function checkString "this is a string": ' . checkString('this is a string') . '<br><br>'; echo '<br>TEST function checkString "25": ' . checkString('25') . '<br><br>'; echo '<br>TEST function checkString 25: ' . checkString(25) . '<br><br>'; echo '<br>TEST function checkString true: ' . checkString(true) . '<br><br>';
true
bf8565a189b91220dcf65f8a601dc3ad29eecc24
PHP
mga-py/droid_shop
/app/src/remoto/webservice/dao/pedidos/get_pedido_by_id.php
UTF-8
754
2.734375
3
[]
no_license
<?php require 'PedidoDAO.php'; if ($_SERVER['REQUEST_METHOD'] == 'GET') { if (isset($_GET['id'])) { $parametro = $_GET['id']; $resultado = PedidoDAO::getById($parametro); if ($resultado) { $dato["estado"] = "1"; $dato["mensaje"] = $resultado; print json_encode($dato); } else { //error print json_encode( array( 'estado' => '2', 'mensaje' => 'No se obtuvo el registro' ) ); } } else { print json_encode( //Otro error array( 'estado' => '3', 'mensaje' => 'Se necesita un identificador' ) ); } }
true
12fd7180742c8ee67497cb69b42322502ee9472f
PHP
lucashv/allcrm-apigility
/module/crm/src/crm/V1/Rest/PermissoesAcesso/PermissoesAcessoService.php
UTF-8
798
2.515625
3
[]
no_license
<?php namespace crm\V1\Rest\PermissoesAcesso; use crm\V1\Rest\AbstractService\AbstractService; /** * Classe responsavel pela validacao de acesso atraves do perfil do usuario. * Class PermissoesAcessoService * @package crm\V1\Rest\PermissoesAcesso */ class PermissoesAcessoService extends AbstractService { public function __construct($em,$hydrator, $modolusPermissoesAcesso) { $this->em = $em; $this->hydrator = $hydrator; $this->entity = $modolusPermissoesAcesso; $this->repository = 'crm\Entity\ModulosPermissoes'; } public function getPermissoesPerfil($idPerfil) { $perfil = $this->em->getRepository($this->repository)->findBy( array('perfil' =>$idPerfil ) ); return $this->extractAll($perfil); } }
true
e3a06f311a040e0df71bca94d057f90dd3f1a8fd
PHP
bleen/ps267
/web/modules/contrib/crop/src/CropStorageInterface.php
UTF-8
768
2.609375
3
[ "MIT", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace Drupal\crop; use Drupal\Core\Entity\EntityBundleListenerInterface; use Drupal\Core\Entity\Schema\DynamicallyFieldableEntityStorageSchemaInterface; use Drupal\Core\Entity\Sql\SqlEntityStorageInterface; /** * Provides an interface defining an crop storage controller. */ interface CropStorageInterface extends SqlEntityStorageInterface, DynamicallyFieldableEntityStorageSchemaInterface, EntityBundleListenerInterface { /** * Retrieve crop ID based on image URI and crop type. * * @param string $uri * URI of the image. * @param string $type * Crop type. * * @return \Drupal\crop\CropInterface|null * A Crop object or NULL if nothing matches the search parameters. */ public function getCrop($uri, $type); }
true
edadc64f044e5a1b2a94c9163cf5d7e7ffa69cb4
PHP
daxingyou/developtest
/cgc_jinhua_server/class/vo/vo_JinHuaGame.php
UTF-8
1,169
2.59375
3
[]
no_license
<?php /** * * 金花牌局的数据 * * User: zmliu1 * Date: 17/1/10 * Time: 16:24 */ class vo_JinHuaGame extends BaseVO{ /** 游戏id */ public $id; /** 游戏是否开始 */ public $isStart = false; /** 当前操作者 */ public $currentUid; /* 记录是否有人没有看过牌 */ public $lastSee; /* 最后一次下注的类型 */ public $lastMoneyType = 1; /* 最后一次下注钱 */ public $lastMoney = 1; /** 这一盘所有的钱 */ public $allMoney = 0; /** 每个人的卡牌信息 */ public $cards; /** 当前的看牌信息 */ public $see; /** 放弃信息 */ public $giveup; /** 当前玩家的赌资信息 */ public $money; /** 当前局玩家的赌资信息 */ public $currentMoney; /** 当前的准备信息 */ public $ready; /** 最后一把是谁赢了 */ public $lastWin; /** 最大局数 */ public $maxCount; /** 当前局数 */ public $currentCount; /** 需要的房卡数量 */ public $needRoomCard; /** 操作次数 需要每个人至少操作一次 才能开牌 */ public $operateCount = 0; }
true