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
270e5b9d39932aa34e9addabdca7a5206fc9eeee
PHP
Gursehaj/Positio-Backend
/index.php
UTF-8
979
2.640625
3
[]
no_license
<?php $host="localhost"; $username="<username>"; $password="<password>"; $database="********"; $conn = mysqli_connect($host, $username, $password, $database); if(isset($_GET["request"])) { if($_GET["request"]=="get") { $sql="SELECT * FROM positio"; $result=mysqli_query($conn, $sql) or die(mysqli_error($conn)); $data=mysqli_fetch_array($result); $newData=array("ultra1"=>$data["ultra1"], "ultra2"=>$data["ultra2"]); if(isset($_GET["os"])){ if($_GET["os"]=="ios") { echo json_encode($newData); } } else echo json_encode(array("result"=>$newData)); } else if($_GET["request"]=="set") { $success = 0; if(isset($_GET["ultra1"])) { $ultra1=$_GET["ultra1"]; $sql="UPDATE positio SET ultra1=$ultra1"; if(mysqli_query($conn, $sql)) $success=1; } if(isset($_GET["ultra2"])) { $ultra2=$_GET["ultra2"]; $sql="UPDATE positio SET ultra2=$ultra2"; if(mysqli_query($conn, $sql)) $success=1; } echo $success; } }
true
f99dabf489a2249ee636054c01b08caeab106a12
PHP
shoaib-125/ebanking-system
/script/vendor/twilio/sdk/src/Twilio/Rest/Insights/V1/RoomOptions.php
UTF-8
3,550
2.625
3
[ "MIT" ]
permissive
<?php /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ namespace Twilio\Rest\Insights\V1; use Twilio\Options; use Twilio\Values; /** * PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. */ abstract class RoomOptions { /** * @param string[] $roomType The room_type * @param string[] $codec The codec * @param string $roomName The room_name * @param \DateTime $createdAfter The created_after * @param \DateTime $createdBefore The created_before * @return ReadRoomOptions Options builder */ public static function read(array $roomType = Values::ARRAY_NONE, array $codec = Values::ARRAY_NONE, string $roomName = Values::NONE, \DateTime $createdAfter = Values::NONE, \DateTime $createdBefore = Values::NONE): ReadRoomOptions { return new ReadRoomOptions($roomType, $codec, $roomName, $createdAfter, $createdBefore); } } class ReadRoomOptions extends Options { /** * @param string[] $roomType The room_type * @param string[] $codec The codec * @param string $roomName The room_name * @param \DateTime $createdAfter The created_after * @param \DateTime $createdBefore The created_before */ public function __construct(array $roomType = Values::ARRAY_NONE, array $codec = Values::ARRAY_NONE, string $roomName = Values::NONE, \DateTime $createdAfter = Values::NONE, \DateTime $createdBefore = Values::NONE) { $this->options['roomType'] = $roomType; $this->options['codec'] = $codec; $this->options['roomName'] = $roomName; $this->options['createdAfter'] = $createdAfter; $this->options['createdBefore'] = $createdBefore; } /** * The room_type * * @param string[] $roomType The room_type * @return $this Fluent Builder */ public function setRoomType(array $roomType): self { $this->options['roomType'] = $roomType; return $this; } /** * The codec * * @param string[] $codec The codec * @return $this Fluent Builder */ public function setCodec(array $codec): self { $this->options['codec'] = $codec; return $this; } /** * The room_name * * @param string $roomName The room_name * @return $this Fluent Builder */ public function setRoomName(string $roomName): self { $this->options['roomName'] = $roomName; return $this; } /** * The created_after * * @param \DateTime $createdAfter The created_after * @return $this Fluent Builder */ public function setCreatedAfter(\DateTime $createdAfter): self { $this->options['createdAfter'] = $createdAfter; return $this; } /** * The created_before * * @param \DateTime $createdBefore The created_before * @return $this Fluent Builder */ public function setCreatedBefore(\DateTime $createdBefore): self { $this->options['createdBefore'] = $createdBefore; return $this; } /** * Provide a friendly representation * * @return string Machine friendly representation */ public function __toString(): string { $options = \http_build_query(Values::of($this->options), '', ' '); return '[Twilio.Insights.V1.ReadRoomOptions ' . $options . ']'; } }
true
ddb55b35b18102a85ae8f1b1772edb9381fba91e
PHP
Jsonize/jsonize-php-client
/src/AbstractJsonize.php
UTF-8
3,661
2.84375
3
[ "Apache-2.0" ]
permissive
<?php namespace Jsonize; abstract class AbstractJsonize { public abstract function destroy(); private $once = FALSE; public function __construct($options = array()) { if (isset($options["once"])) $this->once = $options["once"]; } // Reads a single JSON or returns NULL protected abstract function receive(); // Writes a single JSON protected abstract function send($json); private $lastTransactionId = 0; private $openTransactions = array(); public function invoke($json, $callbacks = array()) { $this->lastTransactionId++; $id = "id" . $this->lastTransactionId; $this->openTransactions[$id] = array( "callbacks" => $callbacks ); $this->send(array( "type" => "invoke", "transaction" => $id, "payload" => $json )); return $id; } public function terminate($transactionId) { unset($this->openTransactions[$transactionId]); $this->send(array( "type" => "terminate", "transaction" => $transactionId )); } public function serverError($e) { if ($this->once) $this->destroy(); foreach ($this->openTransactions as $transactionId => $transaction) $this->receiveError($transactionId, $transaction, $e); } public function receiveNext() { try { $result = $this->receive(); } catch (JsonizeServerException $e) { $this->serverError($e); return FALSE; } if (!@$result) return FALSE; $transactionId = $result["transaction"]; $transaction = $this->openTransactions[$transactionId]; if (!@$transaction) return TRUE; $type = $result["type"]; $payload = $result["payload"]; if ($type === "event") $this->receiveEvent($transactionId, $transaction, $payload); else if ($type === "error") $this->receiveError($transactionId, $transaction, $payload); else if ($type === "success") $this->receiveSuccess($transactionId, $transaction, $payload); return TRUE; } private function receiveEvent($transactionId, $transaction, $payload) { if (@$transaction["callbacks"]["event"]) $transaction["callbacks"]["event"]($payload); } private function receiveError($transactionId, $transaction, $payload) { if (@$transaction["callbacks"]["error"]) $transaction["callbacks"]["error"]($payload); unset($this->openTransactions[$transactionId]); if ($this->once) $this->destroy(); } private function receiveSuccess($transactionId, $transaction, $payload) { if (@$transaction["callbacks"]["success"]) $transaction["callbacks"]["success"]($payload); unset($this->openTransactions[$transactionId]); if ($this->once) $this->destroy(); } public function receiveAll() { while ($this->receiveNext()) usleep(100); } public function wait($transactionId, $timeout = NULL) { $endtime = $timeout === NULL ? NULL : (microtime(TRUE) * 1000 + $timeout); while (@$this->openTransactions[$transactionId]) { if ($endtime !== NULL && $endtime < microtime(TRUE) * 1000) return FALSE; $this->receiveNext(); usleep(100); } return TRUE; } public function invokeSync($json, $timeout = NULL, $event = NULL) { $success = NULL; $error = NULL; $transactionId = $this->invoke($json, array( "success" => function ($result) use (&$success) { $success = $result; }, "error" => function ($result) use (&$error) { $error = $result; }, "event" => $event )); $this->wait($transactionId, $timeout); if (@$success) return $success; if (@$error && is_object($error) && $error instanceof JsonizeException) throw $error; if (@$error) throw new JsonizeErrorException($error, $json); $this->terminate($transactionId); throw new JsonizeTimeoutException($timeout, $json); } }
true
524e4e9646bd3252833ded4788fac5b977cf9577
PHP
Dmansuy/ipssi-oop-php-2017
/ipssi-oop-php-2017/src/Conferences/Controller/OrganisersController.php
UTF-8
602
2.640625
3
[]
no_license
<?php declare(strict_types=1); namespace Conferences\Controller; use Conferences\Repository\OrganisersRepository; final class OrganisersController { private $organisersController; public function __construct(OrganisersController $organisersController) { $this->organisersController = $organisersController; } public function indexAction() : string { $meetings = $this->organisersController->fetchAllOrganisers(); ob_start(); include __DIR__.'/../../../views/meeting.phtml'; return ob_get_clean(); } }
true
e6d974bb8696017378a6c6758f81e9dbea76275f
PHP
jihene7/Projet-Web
/nalika/entities/annonce.php
UTF-8
1,529
2.75
3
[]
no_license
<?PHP class annonce{ private $id_annonce; private $id_offre; private $id_produit; private $description; private $date_annonce; private $date_limite; private $id_client; function __construct($id_annonce,$id_offre,$id_produit,$description,$date_annonce,$date_limite,$id_client){ $this->id_annonce=$id_annonce; $this->id_offre=$id_offre; $this->id_produit=$id_produit; $this->description=$description; $this->date_annonce=$date_annonce; $this->date_limite=$date_limite; $this->id_client=$id_client; } function getid_annonce(){ return $this->id_annonce; } function getid_offre(){ return $this->id_offre; } function getid_produit(){ return $this->id_produit; } function getdescription(){ return $this->description; } function getdate_annonce(){ return $this->date_annonce; } function getdate_limite(){ return $this->date_limite; } function getid_client(){ return $this->id_client; } function setid_annonce($id_annonce){ $this->id_annonce=$id_annonce; } function setid_offre($id_offre){ $this->id_offre=$id_offre; } function setid_produit($id_produit){ $this->id_produit=$id_produit; } function setdescription($description){ $this->description=$description; } function setdate_annonce($date_annonce){ $this->date_annonce=$date_annonce; } function setdate_limite($date_limite){ $this->date_limite=$date_limite; } function setid_client($id_client){ $this->id_client=$id_client; } } ?>
true
4b89a69629da0ff0c9bf96ab8610925dfa445ab8
PHP
nihao1995/sd
/phpcms/modules/zyshop/classes/easySql.php
UTF-8
1,210
2.6875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: 徐强 * Date: 2019/6/5 * Time: 14:09 */ namespace zyshop\classes; use zyshop\classes\modelFactory as excelModelFactory; class easySql //处理简单的增删改查 { function __construct($modelName) { $this->easySql = excelModelFactory::Create()->getModel($modelName); } function select($where="1", $parameter="*", $limit='', $order='') { $info = $this->easySql->select($where, $parameter, $limit, $order); return $info; } function select_or($where="1", $parameter="*", $limit='', $order='') { $info = $this->easySql->select_or($where, $parameter, $limit, $order); return $info; } function get_one($where, $parameter="*") { $info = $this->easySql->get_one($where, $parameter); return $info; } function add($info) { $id = $this->easySql->insert($info, true); return $id; } function changepArg($info, $where) { $this->easySql->update($info, $where); } function del_or($info) { $this->easySql->delete_or($info); } function del($info) { $this->easySql->delete($info); } }
true
876511d9c99691c59046578d80cb4816164f4e42
PHP
ej222pj/1DV408_Projekt
/BildBlogg/view/EditProfileView.php
UTF-8
2,609
2.71875
3
[]
no_license
<?php namespace view; class EditProfileView{ private $message; private $save = "save"; private $oldpassword = "oldpassword"; private $newpassword = "newpassword"; private $repnewpassword = "repnewpassword"; public function didUserPressSave(){ if(isset($_POST[$this->save])){ return true; } } //Tar fram det gammla lösenordet ifrån formuläret public function getOldPassword(){ if(isset($_POST[$this->oldpassword])){ return $_POST[$this->oldpassword]; } } //Tar fram det nya lösenordet public function getNewPassword(){ if(isset($_POST[$this->newpassword])){ return $_POST[$this->newpassword]; } } //Validerar så att allt stämmer om man ska byta lösenord public function checkChangePasswordInput(){ if(($_POST[$this->oldpassword]) == ""){ $this->message = "Användarnamnet har för få tecken. Minst 3 tecken!\nLösenordet har för få tecken. Minst 6 tecken"; return false; } elseif(($_POST[$this->oldpassword]) == "" || strlen(($_POST[$this->oldpassword])) < 6) { $this->message = "Lösenordet har för få tecken. Minst 6 tecken"; return false; } elseif(($_POST[$this->newpassword]) == "" || strlen(($_POST[$this->newpassword])) < 6) { $this->message = "Nya Lösenordet har för få tecken. Minst 6 tecken"; return false; } elseif(($_POST[$this->repnewpassword]) == "" || strlen(($_POST[$this->repnewpassword])) < 6) { $this->message = "Repetera Lösenordet har för få tecken. Minst 6 tecken"; return false; } elseif(($_POST[$this->repnewpassword]) !== ($_POST[$this->newpassword])) { $this->message = "Lösenorden matchar inte"; return false; } else{ return true; } } public function HTMLPage($Message){ $user = "user"; $ret = ""; $ret .= " <img src='./pic/bild.jpg' class='headerpic' alt=''> <div class='fullborder'> <h2>" . $_SESSION[$user] . "</h2> <form method='post' id='RedigeraProfil'> <fieldset> <legend>Redigera Profil</legend> <p>$this->message</p> <p>$Message</p> <label>Gammalt Lösenord:</label> <input type=password size=2 name=$this->oldpassword id='oldPasswordID' value=''> <label>Nytt Lösenord:</label> <input type=password size=2 name=$this->newpassword id='newPasswordID' value=''> <label>Repetera Lösenord:</label> <input type=password size=5 name=$this->repnewpassword id='repnewpasswordID' value=''> <input type=submit name=$this->save value='Spara'> <input type=submit name='' value='Tillbaka'> </fieldset> </form> </div> "; return $ret; } }
true
c7909dc89339a9fffa236e60be157ccd9173878e
PHP
chenjiebin/phpexample
/finance/rate.php
UTF-8
197
2.828125
3
[]
no_license
<?php // 实际年化利率=F*N*24/(N+1) // 这里面只有两个变量需要小伙伴填写:F:分期费率;N:借款期数 $rate = (450 / 100000) * 60 * 24 / (60 + 1); echo $rate . PHP_EOL;
true
28f66bbeccb4604e1deed47bde0337ba5182515b
PHP
sop/x509
/test/unit/certificate/extension/access-description/AuthorityAccessDescriptionTest.php
UTF-8
2,668
2.625
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); use PHPUnit\Framework\TestCase; use Sop\ASN1\Type\Constructed\Sequence; use Sop\X509\Certificate\Extension\AccessDescription\AuthorityAccessDescription; use Sop\X509\GeneralName\UniformResourceIdentifier; /** * @group certificate * @group extension * @group access-description * * @internal */ class AuthorityAccessDescriptionTest extends TestCase { const URI = 'urn:test'; public function testCreate() { $desc = new AuthorityAccessDescription( AuthorityAccessDescription::OID_METHOD_OSCP, new UniformResourceIdentifier(self::URI)); $this->assertInstanceOf(AuthorityAccessDescription::class, $desc); return $desc; } /** * @depends testCreate * * @param AuthorityAccessDescription $desc */ public function testEncode(AuthorityAccessDescription $desc) { $el = $desc->toASN1(); $this->assertInstanceOf(Sequence::class, $el); return $el->toDER(); } /** * @depends testEncode * * @param string $data */ public function testDecode($data) { $desc = AuthorityAccessDescription::fromASN1(Sequence::fromDER($data)); $this->assertInstanceOf(AuthorityAccessDescription::class, $desc); return $desc; } /** * @depends testCreate * @depends testDecode * * @param AuthorityAccessDescription $ref * @param AuthorityAccessDescription $new */ public function testRecoded(AuthorityAccessDescription $ref, AuthorityAccessDescription $new) { $this->assertEquals($ref, $new); } /** * @depends testCreate * * @param AuthorityAccessDescription $desc */ public function testIsOSCP(AuthorityAccessDescription $desc) { $this->assertTrue($desc->isOSCPMethod()); } /** * @depends testCreate * * @param AuthorityAccessDescription $desc */ public function testIsNotCAIssuers(AuthorityAccessDescription $desc) { $this->assertFalse($desc->isCAIssuersMethod()); } /** * @depends testCreate * * @param AuthorityAccessDescription $desc */ public function testAccessMethod(AuthorityAccessDescription $desc) { $this->assertEquals(AuthorityAccessDescription::OID_METHOD_OSCP, $desc->accessMethod()); } /** * @depends testCreate * * @param AuthorityAccessDescription $desc */ public function testLocation(AuthorityAccessDescription $desc) { $this->assertEquals(self::URI, $desc->accessLocation() ->string()); } }
true
3fee88c269b8875b37646541f4862236197d689a
PHP
edde-framework/edde
/src/Edde/Schema/ISchemaBuilder.php
UTF-8
1,063
2.78125
3
[ "Apache-2.0" ]
permissive
<?php declare(strict_types=1); namespace Edde\Schema; interface ISchemaBuilder { /** * set alias to this schema; later in queries name or alias could be used * * @param string $alias * * @return ISchemaBuilder */ public function alias(string $alias): ISchemaBuilder; /** * set meta data for the schema * * @param array $meta * * @return ISchemaBuilder */ public function meta(array $meta): ISchemaBuilder; /** * create a new property with the given name * * @param string $name * * @return IAttributeBuilder */ public function property(string $name): IAttributeBuilder; /** * mark this schema as a relation (source)->(target) * * @param string $source * @param string $target * * @return ISchemaBuilder */ public function relation(string $source, string $target): ISchemaBuilder; /** * build and return a schema * * @return ISchema */ public function create(): ISchema; }
true
aee58ee4bb3866218cc764bcc1abfbfe49f36ea5
PHP
sedera3/challenge-sf
/src/Opticity/GestionBundle/Controller/CommandController.php
UTF-8
2,178
2.515625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: MADATALY * Date: 29/03/2018 * Time: 20:49 */ namespace Opticity\GestionBundle\Controller; use FOS\RestBundle\Controller\Annotations\Get; use FOS\RestBundle\Controller\Annotations\Put; use FOS\RestBundle\Controller\Annotations\Delete; use Opticity\GestionBundle\Entity\Command; use Opticity\GestionBundle\service\CommandService; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\Request; class CommandController extends Controller { /** * Pour recuperer les commandes * @Get("/command/{code}") * @param null $code * @param CommandService $commandService * @return JsonResponse */ public function getCommandAction($code = null, CommandService $commandService) { $return = $commandService->getCommand($code); return new JsonResponse($return); } /** * @param $client * @Get("/command/prix_total/{client}") * @param CommandService $commandService * @return JsonResponse */ public function getPrixTotalAction($client, CommandService $commandService) { $return = $commandService->getPrixTotal($client); return new JsonResponse($return); } /** * Pour inserer les commandes * @Put("/command") * @param Request $request * @param CommandService $commandService * @return JsonResponse * @throws \Exception */ public function putCommandAction(Request $request, CommandService $commandService) { $command = $request->get('command', ''); $return = []; if (!empty($command)) { $return = $commandService->putCommand($command); } return new JsonResponse($return); } /** * Pour supprimer les commandes * @Delete("/command/{$id}") * @param null $id * @param CommandService $commandService * @return JsonResponse */ public function deleteCommandAction($id = null, CommandService $commandService) { $return = $commandService->deleteCommand($id); return new JsonResponse($return); } }
true
afa45b2f3064a4ed4baa8088a78d143cb0180c02
PHP
cwmiller/broadworks-connector
/src/Ocip/Models/GroupAdminCallingLineIdNumberAccess.php
UTF-8
468
2.53125
3
[ "MIT" ]
permissive
<?php namespace CWM\BroadWorksConnector\Ocip\Models; /** * GroupAdminCallingLineIdNumberAccess * * Group Administrator's policy for accessing calling line id number. * * @method static GroupAdminCallingLineIdNumberAccess FULL() * @method static GroupAdminCallingLineIdNumberAccess READ_ONLY() * @EnumValueType string */ class GroupAdminCallingLineIdNumberAccess extends \MyCLabs\Enum\Enum { const FULL = 'Full'; const READ_ONLY = 'Read-Only'; }
true
af3d413fe89c700341ab2e20a8cb609d827e69c8
PHP
p4lv/Excel-GoalSeek
/src/ExcelGoalSeek/ExcelGoalSeek.php
UTF-8
8,195
2.6875
3
[ "MIT" ]
permissive
<?php namespace P4lv\ExcelGoalSeek; use P4lv\ExcelGoalSeek\Exception\GoalNeverReached; use P4lv\ExcelGoalSeek\Exception\GoalReachedNotEnough; use Psr\Log\LoggerInterface; class ExcelGoalSeek { /** * @var LoggerInterface|null */ private $logger; public function __construct(LoggerInterface $logger = null) { $this->logger = $logger; } private function debug($message, array $context = []): void { if ($this->logger instanceof LoggerInterface) { $this->logger->debug($message, $context); } } public function calculate( callable $function, $goal, $decimal_places, $incremental_modifier = 1, $max_loops_round = 0, $max_loops_dec = 0, $lock_min = ['num' => null, 'goal' => null], $lock_max = ['num' => null, 'goal' => null], $slope = null, $randomized = false, $start_from = 0.1 ) { //If goal found has more than this difference, return null as it is not found $maximum_acceptable_difference = 0.1; $max_loops_round++; $this->checkLimitRestriction($max_loops_round); $this->debug(sprintf("Iteration %d; min value = %s; max value = %s; slope %s", $max_loops_round, $lock_min['num'], $lock_max['num'], $slope)); //If I have the goal limited to a unit, I seek decimals if ($lock_min['num'] !== null && $lock_max['num'] !== null && abs(abs($lock_max['num']) - abs($lock_min['num'])) <= 1) { //No decimal , return result if ($lock_min['num'] == $lock_max['num']) { return $lock_min['num']; } //Seek decimals foreach (range(1, $decimal_places, 1) as $decimal) { $decimal_step = 1 / (10 ** $decimal); $difference = abs(round(abs($lock_max['num']), $decimal) - round(abs($lock_min['num']), $decimal)); while ($difference - ($decimal_step / 10) > $decimal_step && $max_loops_dec < (2000 * $decimal_places)) { $max_loops_dec++; $aux_obj_num = round(($lock_min['num'] + $lock_max['num']) / 2, $decimal); $aux_obj = $function($aux_obj_num); $this->debug(sprintf("Decimal iteration %d; min value = %s; max value = %s; value %s", $max_loops_dec, $lock_min['num'], $lock_max['num'], $aux_obj)); //Like when I look without decimals [$lock_min, $lock_max] = $this->lookWithoutDecimals($aux_obj, $goal, $aux_obj_num, $lock_min, $lock_max, $slope); //End Like when I look without decimals $difference = abs(round(abs($lock_max['num']), $decimal) - round(abs($lock_min['num']), $decimal)); }//End while }//End foreach if ($max_loops_dec > 2000 * $decimal_places) { throw new GoalNeverReached('Goal never reached [2000]'); } if (!is_nan($lock_min['goal']) && abs(abs($lock_min['goal']) - abs($goal)) < $maximum_acceptable_difference) { return round($lock_min['num'], $decimal_places - 1); } throw new GoalReachedNotEnough('Goal reached not enough'); } //First iteration, try with zero $aux_obj_num = $this->getAuxObjNum($lock_min['num'], $lock_max['num'], $start_from, $incremental_modifier); $aux_obj = $function($aux_obj_num); $this->debug(sprintf("Testing (with initial value) %s%d with value %s", $aux_obj_num != $start_from ? '' : '(with initial value)', $aux_obj_num, $aux_obj)); if ($slope === null) { $aux_slope = $function($aux_obj_num + 0.1); if (is_nan($aux_slope) || is_nan($aux_obj)) { $slope = null; //If slope is null } elseif ($aux_slope - $aux_obj > 0) { $slope = 1; } else { $slope = -1; } } //Test if formule can give me non valid values, i.e.: sqrt of negative value if (!is_nan($aux_obj)) { //Is goal without decimals? [$lock_min, $lock_max] = $this->lookWithoutDecimals($aux_obj, $goal, $aux_obj_num, $lock_min, $lock_max, $slope); } else { if (($lock_min['num'] === null && $lock_max['num'] === null) || $randomized) { $nuevo_start_from = random_int(-500, 500); return $this->calculate($function, $goal, $decimal_places, $incremental_modifier + 1, $max_loops_round, $max_loops_dec, $lock_min, $lock_max, $slope, true, $nuevo_start_from); } //First iteration is null if ($lock_min['num'] !== null && abs(abs($aux_obj_num) - abs($lock_min['num'])) < 1) { $lock_max['num'] = $aux_obj_num; } if ($lock_max['num'] !== null && abs(abs($aux_obj_num) - abs($lock_max['num'])) < 1) { $lock_min['num'] = $aux_obj_num; } return $this->calculate($function, $goal, $decimal_places, $incremental_modifier + 1, $max_loops_round, $max_loops_dec, $lock_min, $lock_max, $slope, $randomized, $start_from); } return $this->calculate($function, $goal, $decimal_places, $incremental_modifier, $max_loops_round, $max_loops_dec, $lock_min, $lock_max, $slope, $randomized, $start_from); } private function lookWithoutDecimals($aux_obj, $goal, $aux_obj_num, $lock_min, $lock_max, $slope): array { if ($aux_obj == $goal) { $lock_min['num'] = $aux_obj_num; $lock_min['goal'] = $aux_obj; $lock_max['num'] = $aux_obj_num; $lock_max['goal'] = $aux_obj; } $going_up = false; if ($aux_obj < $goal) { $going_up = true; } if ($aux_obj > $goal) { $going_up = false; } if ($slope == -1) { $going_up = !$going_up; } if ($going_up) { if ($lock_min['num'] !== null && $aux_obj_num < $lock_min['num']) { $lock_max['num'] = $lock_min['num']; $lock_max['goal'] = $lock_min['goal']; } $lock_min['num'] = $aux_obj_num; $lock_min['goal'] = $aux_obj; } if (!$going_up) { if ($lock_max['num'] !== null && $lock_max['num'] < $aux_obj_num) { $lock_min['num'] = $lock_max['num']; $lock_min['goal'] = $lock_max['goal']; } $lock_max['num'] = $aux_obj_num; $lock_max['goal'] = $aux_obj; } return [$lock_min, $lock_max]; } /** * @param $lockMinNum * @param $lockMaxNum * @param $start_from * @param $incremental_modifier * @return float|int|mixed */ private function getAuxObjNum($lockMinNum, $lockMaxNum, $start_from, $incremental_modifier) { $aux_obj_num = null; if ($lockMinNum === null && $lockMaxNum === null) { $aux_obj_num = $start_from; } //Lower limit found, searching higher limit with * 10 elseif ($lockMinNum !== null && $lockMaxNum === null) { if ($lockMinNum == $start_from) { $aux_obj_num = 1; } else { $aux_obj_num = $lockMinNum * (10 / $incremental_modifier); } } //Higher limit found, searching lower limit with * -10 elseif ($lockMinNum === null && $lockMaxNum !== null) { if ($lockMaxNum == $start_from) { $aux_obj_num = -1; } else { $aux_obj_num = $lockMaxNum * (10 / $incremental_modifier); } } //I have both limits, searching between them without decimals elseif ($lockMinNum !== null && $lockMaxNum !== null) { $aux_obj_num = round(($lockMinNum + $lockMaxNum) / 2); } return $aux_obj_num; } /** * @param int $max_loops_round */ private function checkLimitRestriction(int $max_loops_round): void { if ($max_loops_round > 100) { throw new GoalNeverReached(); } } }
true
d72213d75873dc62ade4584aac54da9dceddcebd
PHP
CallFire/callfire-api-samples
/2.0/php/calls/sendCalls.php
UTF-8
1,281
2.515625
3
[]
no_license
<?php class ApiClientSample { public static function main() { $client = \CallFire\Api\DocumentedClient::createClient("login", "password"); $request = $client->sendCalls(); $request->getOperationConfig()->setQueryParameters(array("campaignId" => 4050600003, "fields" => "items(id,state,toNumber)", "defaultVoice" => "MALE1")); $body = '[ { "phoneNumber": "12135551100", "liveMessage": "Hello, Alice, this is message for live answer", "machineMessage": "Hello, Alice, this is message for answering machine" }, { "phoneNumber": "12135551101", "liveMessage": "Hello, Bob, this is message for live answer", "machineMessage": "Hello, Bob, this is message for answering machine" } ]'; $request->getOperationConfig()->setBodyParameter($body); $result = $client->request($request); $json = json_decode($result->getBody()); } } ApiClientSample::main();
true
95569f8f391b9af3f53829ef70eb1a5cda1db4b7
PHP
VectorWen/lj
/LjHome/Lib/Action/LoginAction.class.php
UTF-8
1,058
2.5625
3
[]
no_license
<?php class LoginAction extends Action { /** * 登录 */ public function login() { //如果没有同时输入密码和账号,就是不登陆 if(!isset($_POST['username'])||!isset($_POST['password'])){ $this->display (); exit(); } $username = $_POST['username']; $password = $_POST['password']; $user=M('User'); $where['username'] = $username; $where['password'] = md5($password); $userData=$user->where($where)->find(); // dump($userData['user_id']); // exit(); if($userData!=NULL){ $refer = cookie('refer'); if($refer == null) { $refer=U("Index/index"); } $_SESSION['userid']=$userData['userid']; $this->success('登录成功',$refer); }else{ $this->error('用户名错误或密码错误!'); } } /** * 注销 */ public function logout() { $_SESSION=array(); if(isset($_COOKIE[session_name()])){ setcookie(session_name(),'',time()-1,'/'); setcookie('refer','',time()-1,'/'); cookie(null); } session_destroy(); $this->redirect('Index/index'); } }
true
a6d1805020c729b97562eb1f8abfcd0633781c54
PHP
manudev91/eventtest
/app/Models/Event.php
UTF-8
909
2.609375
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use App\Models\User; class Event extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'event_name', 'event_description', 'event_venue', 'event_location', 'status', 'event_start_date', 'event_start_time', 'event_end_date', 'event_end_time', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ ]; public function users() { return $this->belongsToMany(User::class); } }
true
873aaed829d954c802946e380fd38a4d37932f81
PHP
SBU-BMI/PathDB
/quip/vendor/drupal/coder/coder_sniffer/DrupalPractice/Sniffs/FunctionCalls/InsecureUnserializeSniff.php
UTF-8
3,387
2.703125
3
[ "GPL-2.0-only", "BSD-3-Clause" ]
permissive
<?php /** * \DrupalPractice\Sniffs\FunctionCalls\InsecureUnserializeSniff * * @category PHP * @package PHP_CodeSniffer * @link http://pear.php.net/package/PHP_CodeSniffer */ namespace DrupalPractice\Sniffs\FunctionCalls; use PHP_CodeSniffer\Files\File; use Drupal\Sniffs\Semantics\FunctionCall; /** * Check that unserialize() limits classes that may be unserialized. * * @category PHP * @package PHP_CodeSniffer * @link http://pear.php.net/package/PHP_CodeSniffer */ class InsecureUnserializeSniff extends FunctionCall { /** * Returns an array of function names this test wants to listen for. * * @return array<string> */ public function registerFunctionNames() { return ['unserialize']; }//end registerFunctionNames() /** * Processes this function call. * * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. * @param int $stackPtr The position of the function call in * the stack. * @param int $openBracket The position of the opening * parenthesis in the stack. * @param int $closeBracket The position of the closing * parenthesis in the stack. * * @return void */ public function processFunctionCall( File $phpcsFile, $stackPtr, $openBracket, $closeBracket ) { $tokens = $phpcsFile->getTokens(); $argument = $this->getArgument(2); if ($argument === false) { $this->fail($phpcsFile, $closeBracket); return; } $allowedClassesKeyStart = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, $argument['start'], $argument['end'], false, '\'allowed_classes\''); if ($allowedClassesKeyStart === false) { $allowedClassesKeyStart = $phpcsFile->findNext(T_CONSTANT_ENCAPSED_STRING, $argument['start'], $argument['end'], false, '"allowed_classes"'); } if ($allowedClassesKeyStart === false) { $this->fail($phpcsFile, $argument['end']); return; } $allowedClassesArrow = $phpcsFile->findNext(T_DOUBLE_ARROW, $allowedClassesKeyStart, $argument['end'], false); if ($allowedClassesArrow === false) { $this->fail($phpcsFile, $argument['end']); return; } $allowedClassesValue = $phpcsFile->findNext(T_WHITESPACE, ($allowedClassesArrow + 1), $argument['end'], true); if ($tokens[$allowedClassesValue]['code'] === T_TRUE) { $this->fail($phpcsFile, $allowedClassesValue); } }//end processFunctionCall() /** * Record a violation of the standard. * * @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. * @param int $position The stack position of the violation. * * @return void */ protected function fail(File $phpcsFile, int $position) { $phpcsFile->addError('unserialize() is insecure unless allowed classes are limited. Use a safe format like JSON or use the allowed_classes option.', $position, 'InsecureUnserialize'); }//end fail() }//end class
true
f900ea73b9dabeadb40e773d384dc081892e8434
PHP
OmegaVersion/shadow
/test.php
UTF-8
578
2.53125
3
[]
no_license
<?php /** * */ include "shadow.php"; $testClass = ''; if(!empty($argv)){ $testClass = $argv[1]; }elseif(!empty($_GET)){ $testClass = $_GET['test']; } if(empty($testClass)){ throw new SDException("Usage php test.php [test class name] OR test.php?test=[test class name]"); } $test = new Test_Manage($testClass); $ret = $test->exec(); foreach($ret as $result){ echo sprintf("## %s::%s\n", $result->className, $result->method); foreach($result->cases as $case){ echo sprintf("\t%s => %s\n", $case['method']['type'], $case['isSucc'] ? 'succ' : 'err'); } echo "\n"; }
true
a30448ab819194b4bb2c5fc394354a74280c53a8
PHP
happycollision/CoronaPoint
/corona/printers/printer_action.php
UTF-8
1,636
2.609375
3
[]
no_license
<?php require_once('../initialize.php'); if(empty($_POST)) { $session->message('Error PA005: Nothing was sent to the database. Apologies for needing to send you back to the list view. Please try again, though. If the problem persists, contact the application developer with the error number.','error'); redirect_to('index.php'); } $required_fields = array( 'site_id'=>'Site', 'system'=>'System Number', 'online'=>'Online Status' ); $printer = new Printer; required_fields_spinner($printer, $required_fields); if(count($form_errors) > 0){ $_SESSION['form_errors'] = $form_errors; if(isset($_POST['id'])){ redirect_to("edit_printer.php?id={$_POST['id']}"); }else{ $_SESSION['POST'] = $_POST; redirect_to('create_printer.php'); } } if($printer->save()){ $session->message('Printer information saved successfully.','success'); redirect_to('index.php'); }else{ if(isset($_POST['id'])){ $session->message('Warning PA019: It seems that no changes were made. If you are sure you altered the information below and this warning persists, contact the application developer with this warning number and the conditions of the problem.', 'warning'); redirect_to("edit_printer.php?id={$_POST['id']}"); } $session->message('Error PA022: There was a problem saving the printer. Please try again. If the problem persists, contact the application developer with this error number and the conditions of the problem.', 'error'); $_SESSION['POST'] = $_POST; redirect_to('create_printer.php'); }
true
906d9e6b6dfedd29a3570cbb20438acf95e50664
PHP
kusabi/http
/tests/Exceptions/InvalidHttpStatusCodeExceptionTest.php
UTF-8
526
2.578125
3
[ "MIT" ]
permissive
<?php namespace Kusabi\Http\Tests\Exceptions; use Kusabi\Http\Exceptions\InvalidHttpStatusCodeException; use Kusabi\Http\Tests\TestCase; class InvalidHttpStatusCodeExceptionTest extends TestCase { /** * @covers \Kusabi\Http\Exceptions\InvalidHttpStatusCodeException::__construct */ public function testGetMessages() { $exception = new InvalidHttpStatusCodeException('TEST'); $this->assertSame("Invalid HTTP response status code 'TEST' was provided", $exception->getMessage()); } }
true
34b2780dc060333ee041344dfe44cc81b51f303e
PHP
inabahtrg/KalturaServerCore
/plugins/content_distribution/providers/verizon_vcast/lib/api/KalturaVerizonVcastDistributionProfile.php
UTF-8
1,316
2.6875
3
[]
no_license
<?php /** * @package plugins.verizonVcastDistribution * @subpackage api.objects */ class KalturaVerizonVcastDistributionProfile extends KalturaConfigurableDistributionProfile { /** * @var string */ public $ftpHost; /** * @var string */ public $ftpLogin; /** * @var string */ public $ftpPass; /** * @var string */ public $providerName; /** * @var string */ public $providerId; /** * @var string */ public $entitlement; /** * @var string */ public $priority; /** * @var string */ public $allowStreaming; /** * @var string */ public $streamingPriceCode; /** * @var string */ public $allowDownload; /** * @var string */ public $downloadPriceCode; /* * mapping between the field on this object (on the left) and the setter/getter on the object (on the right) */ private static $map_between_objects = array ( 'ftpHost', 'ftpLogin', 'ftpPass', 'providerName', 'providerId', 'entitlement', 'priority', 'allowStreaming', 'streamingPriceCode', 'allowDownload', 'downloadPriceCode', ); public function getMapBetweenObjects() { return array_merge(parent::getMapBetweenObjects(), self::$map_between_objects); } }
true
f99214af646534fdd2360dae93821f41a50fc93f
PHP
ProjetoESE/Thoth
/application/libraries/domain/Database.php
UTF-8
1,080
3.375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * Class to represent the Database; */ class Database { private $name; private $link; /** * Database constructor. */ public function __construct() { } /** * Method to retrieve the database name. * @return String name */ public function get_name() { return $this->name; } /** * Method to change the database name. * @param String $name * @throws InvalidArgumentException */ public function set_name($name) { if (is_null($name) || empty($name)) { throw new InvalidArgumentException("Database Name Invalid!"); } $this->name = $name; } /** * Method to retrieve the database link. * @return String link */ public function get_link() { return $this->link; } /** * Method to change the database link. * @param String $link * @throws InvalidArgumentException */ public function set_link($link) { if (is_null($link) || empty($link)) { throw new InvalidArgumentException("Database Link Invalid!"); } $this->link = $link; } }
true
7f4fb7da859b25ff26e307b1fa79d9dbb087dbcb
PHP
giordanolima/laravel-adminlte
/app/Models/Base/ImagensTrait.php
UTF-8
1,095
2.625
3
[]
no_license
<?php namespace App\Models\Base; trait ImagensTrait { private $thumbs = []; public function getThumb($largura,$altura) { if(!array_key_exists($largura.'X'.$altura, $this->thumbs)) $this->thumbs[$largura.'X'.$altura] = $this->filhos->whereLoose('imagem_largura',$largura)->whereLoose('imagem_altura',$altura)->first(); return $this->thumbs[$largura.'X'.$altura]; } public function url($largura = null, $altura = null) { if(property_exists($this, "belongs")){ $path = $this->{$this->belongs}->folderUrl(); }else{ $path = $this->folderUrl(); } if(!is_null($altura) && !is_null($largura)) return asset($path . "/" . $this->getThumb($largura, $altura)->imagem_nome); return asset($path . "/" . $this->imagem_nome); } public function pai() { return $this->belongsTo(self::class, 'imagem_pai'); } public function filhos() { return $this->hasMany(self::class, 'imagem_pai')->orderBy('imagem_largura', 'DESC'); } }
true
5206e19f0ed13367acc222fee5f5157a49ae5d4c
PHP
nikhil-jayswal/cs50
/pset7/public/sell.php
UTF-8
3,019
2.875
3
[]
no_license
<?php // configuration require("../includes/config.php"); // if form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { // validate submission // share symbol not provides if (empty($_POST["symbol"])) { apologize("You must provide the stock symbol."); } // number of shares to be sold not provided else if (empty($_POST["shares"])) { apologize("You must provide the number of shares you want to buy."); } // number of shares to be sold not a non-negative integer else if (preg_match("/^\d+$/", $_POST["shares"]) == false) { apologize("Number of shares must be a non-negative integer."); } $rows = query("SELECT * FROM stocks WHERE id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]); // check if user owns any shares of stock to be sold if($rows === false) { apologize("You cannot sell a stock you don't own."); } // check if user has the amount of stocks he/she wants to sell else if($rows[0]["shares"] < $_POST["shares"]) { apologize("You don't have that much shares."); } // get user info from database $rows = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]); // cash available with user $cash = $rows[0]["cash"]; // ensure stock symbol is in uppercase $symbol = strtoupper($_POST["symbol"]); // get stock info $stock = lookup($symbol); // get stock price $price = $stock["price"]; // update cash $cash = $cash + ($price * $_POST["shares"]); // update database $update_1 = query("UPDATE users SET cash = ? WHERE id = ?", $cash, $_SESSION["id"] ); $update_2 = query("INSERT INTO stocks (id, symbol, shares) VALUES(?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares - ?", $_SESSION["id"], $symbol, $_POST["shares"], $_POST["shares"]); // if any one databse update fails if ($update_1 === false || $update_2 === false) { apologize("Could not update database."); } // else update history else { $update_3 = query("INSERT INTO history (id, action, symbol, shares, time, price) VALUES(?, ?, ?, ?, CURRENT_TIMESTAMP, ?)", $_SESSION["id"], "SOLD", $symbol, $_POST["shares"], $price); // if operation fails if($update_3 === false) apologize("Could not update history."); } // back to portfolio redirect("/"); } // if form was not submitted, render form else { render("sell_form.php", ["title" => "Sell Shares"]); } ?>
true
538191a7c82b805c0b775b448932fecda4be104f
PHP
devotronico/xml-study
/test.php
UTF-8
2,067
3.453125
3
[]
no_license
<?php class Causale extends BaseObjectToXML { protected $causale; public function __construct($testo) { // return $causale; $this->casuale = $testo; } public function toXML() { return $this->casuale; } } class Figlio extends BaseObjectToXML { protected $name; protected $last; protected $address = array(); protected $Causale; //protected $colors = []; public function __construct($name, $last, array $address, $causale) { // public function __construct($name, $last, array $address, $causale, $colors) { $this->name = $name; $this->last = $last; $this->address = $address; $this->Causale = new Causale($causale); // $this->colors = $colors; } public function getThis() { return $this; } public function toXML() { return "<box>" . parent::toXML() . "</box>"; } } class BaseObjectToXML { public function toXML(){ $xmlString = ''; foreach($this as $tag => $value){ if(is_null($value) || empty($value)) continue; if(is_array($value)){ foreach($value as $k => $v){ // var_dump($v); die(); $xmlString .= '<' . $k .'>'; $xmlString .= $v; // $xmlString .= $v->toXML(); $xmlString .= '</' . $k .'>'; } } elseif(is_object($value)){ //var_dump($value instanceof BaseObjectToXML); die(); // var_dump($value); die(); $xmlString .= ($value instanceof BaseObjectToXML) ? '<' . $tag .'>' : ''; $xmlString .= $value->toXML(); $xmlString .= ($value instanceof BaseObjectToXML) ? '</' . $tag .'>' : ''; } else { $xmlString .= '<' . $tag .'>'; $xmlString .= $value; $xmlString .= '</' . $tag .'>'; } } return $xmlString; } } $inst = new Figlio('Daniele', 'Manzi', ["via"=>"Sepe", "civico"=>"3", "città"=>"Nola"], 'Descrizione'); $x = $inst->toXML(); //$y = $inst->getThis(); //echo '<pre>';print_r( $y ); //var_dump($x); //echo '<pre>';print_r( $x ); echo $x;
true
dfa3e8e6e4786ce07fbb2daffca2ce59ba4514d4
PHP
jameskane05/cs-story-map
/bin/import
UTF-8
888
2.609375
3
[]
no_license
#!/usr/bin/env php <?php require(__DIR__ . "/../includes/config.php"); $filename = 'US.txt'; if (is_readable($filename)) { $file = fopen("$filename", "r+"); if ($file != NULL) { $row_count = 0; while (($row = fgetcsv($file, 0, "\t")) !== FALSE) { print_r($row); query("INSERT INTO places (`country_code`, `postal_code`, `place_name`, `admin_name1`, `admin_code1`, `admin_name2`, `admin_code2`, `admin_name3`, `admin_code3`, `latitude`, `longitude`, `accuracy`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8], $row[9], $row[10], $row[11]); $row_count++; } } fclose($file); } ?>
true
3bbb6e9db1813dcccf33d3b3c417b90bf68f6389
PHP
mg-code/yii2-auth
/filters/HttpSimpleAuth.php
UTF-8
2,776
2.890625
3
[]
no_license
<?php namespace mgcode\auth\filters; use yii\base\InvalidParamException; use Yii; use yii\filters\auth\AuthMethod; use yii\web\Request; /** * HttpSimpleAuth is an action filter that supports authentication via HTTP headers. * * You may use HttpSimpleAuth by attaching it as a behavior to a controller or module, like the following: * * ```php * public function behaviors() * { * return [ * 'simpleAuth' => [ * 'class' => \mgcode\auth\filters\HttpSimpleAuth::className(), * ], * ]; * } * ``` * * @author Maris Graudins <maris@mg-interactive.lv> */ class HttpSimpleAuth extends AuthMethod { public $userHeader = 'auth-user'; public $passwordHeader = 'auth-password'; /** * @var callable a PHP callable that will authenticate the user. * The callable receives a username and a password as its parameters. It should return an identity object * that matches the username and password. Null should be returned if there is no such identity. * The following code is a typical implementation of this callable: * ```php * function ($username, $password) { * return \app\models\User::findOne([ * 'username' => $username, * 'password' => $password, * ]); * } * ``` * This property is required. */ public $auth; public function init() { parent::init(); if (!is_callable($this->auth)) { throw new InvalidParamException('`auth` property must be callable.'); } } /** * @inheritdoc */ public function authenticate($user, $request, $response) { $username = $this->getAuthUser($request); $password = $this->getAuthPassword($request); if ($username !== null || $password !== null) { $identity = call_user_func($this->auth, $username, $password); if ($identity !== null) { $user->switchIdentity($identity); } else { $this->handleFailure($response); } return $identity; } return null; } /** * @param Request $request * @return string|null the username sent via HTTP header, null if the username is not given */ protected function getAuthUser($request) { if($user = $request->headers->get($this->userHeader)) { return $user; } return null; } /** * @param Request $request * @return string|null the password sent via HTTP header, null if the password is not given */ protected function getAuthPassword($request) { if($user = $request->headers->get($this->passwordHeader)) { return $user; } return null; } }
true
46445f9bba64e00cdd70c4e092a7a571a9fe45b0
PHP
zymish/AfterEvents
/includes/startup.php
UTF-8
1,494
2.5625
3
[]
no_license
<?php //Start the session if it's not set. if(!isset($_SESSION)) session_start(); //Get and set our global configuration require_once('config.php'); error_reporting(E_ERROR | E_WARNING | E_PARSE); set_include_path(SITE_PATH); setlocale(LC_MONETARY, 'en_US'); //innitialize $errors and connect to MySQL database. global $db,$errors,$site,$messageManager,$guestManager,$ticketManager,$userManager,$staffManager,$eventManager; $errors = array(); $db = new MySQLi(SQL_HOST,SQL_USER,SQL_PASS,SQL_DB); if (mysqli_connect_errno()) { error_log(mysqli_connect_error()); exit('<h2>There has been a database connection error. Please refresh and try again.</h2>'); } //Setup the $site var to deal with the details for the page we're viewing $site = array('debug' => false); if(isset($_SESSION['user']) && $_SESSION['user']['status'] == '9') $site['debug'] = true; //Require other PHP classes we'll be using require_once('functions.php'); require_once('class.messageManager.php'); require_once('class.guestManager.php'); require_once('class.ticketManager.php'); require_once('class.userManager.php'); require_once('class.staffManager.php'); require_once('class.eventManager.php'); require_once('class.photoManager.php'); require_once('excel/reader.php'); $messageManager = new messageManager; $guestManager = new guestManager; $ticketManager = new ticketManager; $userManager = new userManager; $staffManager = new staffManager; $eventManager = new eventManager; $photoManager = new photoManager;
true
6d337f5ca38e70c3843bddb119fa9da75d945f3b
PHP
kuuza/KuuzuCart
/Kuuzu/KU/Core/Site/Shop/Image.php
UTF-8
3,039
2.515625
3
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
<?php /** * Kuuzu Cart * * @copyright (c) 2007 - 2017 osCommerce; http://www.oscommerce.com * @license BSD License; http://www.oscommerce.com/bsdlicense.txt * * @copyright Copyright c 2018 Kuuzu; https://kuuzu.org * @license MIT License; https://kuuzu.org/mitlicense.txt */ namespace Kuuzu\KU\Core\Site\Shop; use Kuuzu\KU\Core\HTML; use Kuuzu\KU\Core\KUUZU; use Kuuzu\KU\Core\Registry; class Image { protected $_groups; public function __construct() { $KUUZU_PDO = Registry::get('PDO'); $KUUZU_Language = Registry::get('Language'); $this->_groups = array(); $Qgroups = $KUUZU_PDO->prepare('select * from :table_products_images_groups where language_id = :language_id'); $Qgroups->bindInt(':language_id', $KUUZU_Language->getID()); $Qgroups->setCache('images_groups-' . $KUUZU_Language->getID()); $Qgroups->execute(); foreach ( $Qgroups->fetchAll() as $group ) { $this->_groups[(int)$group['id']] = $group; } } public function getID($code) { foreach ( $this->_groups as $group ) { if ( $group['code'] == $code ) { return $group['id']; } } return 0; } public function getCode($id) { return $this->_groups[$id]['code']; } public function getWidth($code) { return $this->_groups[$this->getID($code)]['size_width']; } public function getHeight($code) { return $this->_groups[$this->getID($code)]['size_height']; } public function exists($code) { return isset($this->_groups[$this->getID($code)]); } public function show($image, $title, $parameters = null, $group = null) { if ( empty($group) || !$this->exists($group) ) { $group = $this->getCode(DEFAULT_IMAGE_GROUP_ID); } $group_id = $this->getID($group); $width = $height = ''; if ( ($this->_groups[$group_id]['force_size'] == '1') || empty($image) ) { $width = $this->_groups[$group_id]['size_width']; $height = $this->_groups[$group_id]['size_height']; } if ( empty($image) ) { $image = 'pixel_trans.gif'; } else { $image = $this->_groups[$group_id]['code'] . '/' . $image; } $url = (KUUZU::getRequestType() == 'NONSSL') ? KUUZU::getConfig('product_images_http_server') . KUUZU::getConfig('product_images_dir_ws_http_server') : KUUZU::getConfig('product_images_http_server') . KUUZU::getConfig('product_images_dir_ws_http_server'); return HTML::image($url . $image, $title, $width, $height, $parameters); } public function getAddress($image, $group = 'default') { $group_id = $this->getID($group); $url = (KUUZU::getRequestType() == 'NONSSL') ? KUUZU::getConfig('product_images_http_server') . KUUZU::getConfig('product_images_dir_ws_http_server') : KUUZU::getConfig('product_images_http_server') . KUUZU::getConfig('product_images_dir_ws_http_server'); return $url . $this->_groups[$group_id]['code'] . '/' . $image; } } ?>
true
b33dde315c37697d66c4de87069d3d5cd6e333eb
PHP
akelimad/survey
/src/Helpers/FormBuilder.php
UTF-8
21,165
2.75
3
[]
no_license
<?php /** * FormBuilder * * @author mchanchaf * * @package app.helpers * @version 1.0 * @since 1.5.0 */ namespace App\Helpers; use App\File; class FormBuilder { /** * Unique name * * @access protected * @var string */ protected static $name; /** * Model * * @access protected * @var object */ protected static $model; /** * Field HTML Template * * @access protected * @var string */ protected static $template = '<div {attributes}>{html_label}{html_field}{help_block}</div>'; /** * Array of options * * @access protected * @var array */ protected static $options = [ 'with_wrapper' => true, 'method' => 'POST', 'action' => '' ]; /** * Array of settings * * @access protected * @var array */ protected static $settings = []; /** * Array of HTML attributes * * @access protected * @var array */ protected static $attributes = [ 'class' => 'chm-simple-form mb-15' ]; /** * Array of fields * * @access protected * @var array */ protected static $fields = []; /** * Array of fieldsets * * @access protected * @var array */ protected static $fieldsets = []; /** * Array of buttons * * @access protected * @var array */ protected static $buttons = []; /** * Array of events * * @access protected * @var array */ protected static $events = []; /** * Array of triggered events * * @access protected * @var array */ protected static $triggeredEvents = []; /** * Constructor * * @param string $name Form name * @param array $options An array of options * @param array $model Object contain fields values * * @access public * * @return void * * @author mchanchaf */ public function __construct($name, $options = [], $model = null) { self::$name = $name; self::$model = (array) $model; self::$attributes['id'] = $name .'Form'; self::$options = array_replace_recursive(self::$options, $options); } /** * Add new field * * @param string $name * @param string $type * @param array $options * * @access public * * @return FormBuilder * * @author mchanchaf */ public function add($name, $type, $options = []) { // Create ID from name $id = str_replace('[', '_', $name); // Get field MySql column name $column = self::getFieldName($name); // Get field value $value = null; if (isset($_POST[$column])) { $value = $_POST[$column]; } else if (isset($_GET[$column])) { $value = $_GET[$column]; } else if (isset(self::$model[$column])) { $value = self::$model[$column]; } $fieldset = (isset($options['fieldset'])) ? $options['fieldset'] : 'NA'; if ($name == 'button' && !isset($options['attributes']['class'])) { $options['attributes']['class'] = 'btn btn-primary pull-right btn-sm'; } // Add to fields list $options = array_replace_recursive([ 'name' => $name, 'type' => $type, 'label' => null, 'value' => $value, 'fieldset' => $fieldset, 'template' => null, 'options' => [], 'extensions' => [], 'keys_as_values' => false, 'delete_callback' => null, 'delete_args' => '{}', 'option_tpl' => null, 'with_other' => false, 'inline' => false, 'attributes' => [ 'value' => $value, 'id' => trim(str_replace(']', '', $id), '_'), 'class' => 'form-control mb-0', ], 'columns' => 4, 'offset' => 0, 'order' => (count(self::$fields) + 1), 'rules' => null, 'help' => null, 'required' => false, 'displayed' => true, ], $options); if ($name == 'button') { self::$buttons[] = $options; } else { self::$fields[$name] = $options; // Add ability to get value as closure self::$fields[$name]['value'] = self::execute($options['value'], ['form' => $this, 'model' => self::$model, 'value' => $value]); $options = self::execute($options['options'], ['form' => $this, 'model' => self::$model]); self::$fields[$name]['options'] = $options; // Set field fieldset if (!isset(self::$fieldsets[$fieldset])) { $order = ($fieldset == 'NA') ? 0 : (count(self::$fieldsets) + 1); self::$fieldsets[$fieldset] = [ 'name' => $fieldset, 'label' => null, 'order' => $order ]; } } return $this; } /** * Change field option * * @param string $field_name * @param string $option_name * @param string $value * * @access public * * @return FormBuilder * * @author mchanchaf */ public function setFieldOptions($field_name, $option_name, $value) { self::$fields[$field_name][$option_name] = $value; return $this; } /** * Set fieldsets * * @param array $fieldsets * * @access public * * @return void * * @author mchanchaf */ public function setFieldsets($fieldsets = []) { foreach ($fieldsets as $key => $options) { self::$fieldsets[ $options['name'] ] = array_merge([ 'name' => null, 'label' => null, 'order' => (count(self::$fieldsets) + 1) ], $options); } return $this; } /** * Render form HTML * * @access public * * @return string $form * * @author mchanchaf */ public function render() { // Before render event $form_id = self::$name; self::triggerEvent($form_id .'BeforeRender', $form_id); $html = null; $fieldsetsFields = self::getFieldsetsFields(); usort(self::$fieldsets, self::usort('order', 'asc')); foreach (self::$fieldsets as $key => $fieldset) { $fieldset_name = $fieldset['name']; if (!isset($fieldsetsFields[$fieldset_name]) || empty($fieldsetsFields[$fieldset_name])) continue; // Reset columns counter $countCols = 0; $html .= '<fieldset>'; if ($fieldset_name != 'NA') $html .= '<legend>'. $fieldset['label'] .'</legend>'; $html .= '<div class="row">'; usort($fieldsetsFields[$fieldset_name], self::usort('order', 'asc')); foreach ($fieldsetsFields[$fieldset_name] as $key => $field) { // Count grid columns $countCols = ($countCols + $field['columns'] + $field['offset']); // Close row if grid is full if ($countCols > 12) { $countCols = 0; $html .= '</div><div class="row">'; } $html .= self::getTemplate($field); // Close row if grid is full if ($countCols == 12) { $countCols = 0; $html .= '</div><div class="row">'; } } $html .= '</div>'; $html .= '</fieldset>'; } // Buttons if (!empty(self::$buttons)) { $html .= '<div class="row"><div class="col-md-12"><div class="ligneBleu mt-10"></div>'; foreach (self::$buttons as $key => $button) { $html .= self::field($button); } $html .= '</div></div>'; } if (self::$options['with_wrapper']) { $html = '<form method="'. self::$options['method'] .'" action="'. self::$options['action'] .'" '. self::getAttributes(self::$attributes) .'>'. $html .'</form>'; } return $html; } /** * Sort a multi-domensional array of objects by key value * Usage: usort($array, arrSortObjsByKey('VALUE_TO_SORT_BY')); * Expects an array of objects. * * @param array $array * @param string $key The name of the parameter to sort by * @param string $order the sort order * @return void * * @author mchanchaf */ public static function usort($key, $order = 'DESC') { return function($a, $b) use ($key, $order) { // Swap order if necessary if ($order == 'DESC') { list($a, $b) = array($b, $a); } // Check data type if (is_numeric($a[$key])) { return $a[$key] - $b[$key]; // compare numeric } else { return strnatcasecmp($a[$key], $b[$key]); // compare string } }; } private static function getFieldsetsFields() { $fieldsetsFields = []; foreach (self::$fields as $key => $field) { if (!self::getFieldOption('displayed', self::$name, $field['name'])) continue; $fieldset = $field['fieldset']; $fieldsetsFields[$fieldset][] = $field; } return $fieldsetsFields; } /** * Render field HTML * * @param array $field * * @access public * * @return string $html * * @author mchanchaf */ public static function field($field) { $html = ''; $attributes = self::getFieldAttributes($field); switch ($field['type']) { case 'select': $otherSelected = false; $fieldId = $field['attributes']['id'] .'_other'; $otherValue = (isset(self::$model[$fieldId])) ? self::$model[$fieldId] : null; $html = '<select '. $attributes .'>'; foreach ($field['options'] as $value => $text) : if (is_object($text)) { $value = (isset($text->value)) ? $text->value : null; $text = (isset($text->text)) ? $text->text : null; } $selected = ''; if ($field['value'] == $value) { $selected = ' selected'; } if ($field['keys_as_values']) { $value = $text; } if (!empty($field['option_tpl'])) { $html .= self::parseTemplate($field['option_tpl'], [ 'value' => $value, 'text' => $text, 'attributes' => $selected, ]); } else { $html .= '<option value="'. $value .'"'. $selected .'>'. $text .'</option>'; } endforeach; if (!empty($otherValue)) $otherSelected = true; if($field['with_other']) { $selected = ($otherSelected) ? ' selected' : ''; $html .= '<option value="_other" chm-form-other="'. $fieldId .'"'. $selected .'>'. trans("Autres (à péciser)") .'</option>'; } $html .= '</select>'; // Add other input if($field['with_other']) { $html .= self::field([ 'name' => $fieldId, 'type' => 'text', 'attributes' => [ 'value' => $otherValue, 'name' => $fieldId, 'type' => 'text', 'title' => trans("Autres (à péciser)"), 'class' => 'form-control mt-5 mb-0', 'id' => $fieldId, 'style' => ($otherSelected) ? 'display:block;' : 'display:none;', ] ]); } break; case 'textarea': $html .= '<textarea '. $attributes .'>'. $field['value'] .'</textarea>'; break; case 'file': $value = $field['value']; $display = (!empty($value)) ? ' style="display:none;"' : ''; $html .= '<div class="input-group file-upload"'. $display .'> <input type="text" class="form-control" readonly> <label class="input-group-btn"> <span class="btn btn-success btn-sm"> <i class="fa fa-upload"></i> <input '. $attributes .'> </span> </label> </div>'; if (!empty($value)) { $delete_args = self::parseTemplate($field['delete_args'], self::$model, '$', '$'); $confirm = "return chmModal.confirm('', 'Alert!', '". trans("Êtes-vous sûr?") ."', '". $field['delete_callback'] ."', ". htmlentities($delete_args) .", {width: 300})"; $html .= '<div class="btn-group" role="group"> <a href="javascript:void(0)" class="btn btn-danger" style="padding: 3px 8px;" title="'. trans("Supprimer") .'" onclick="'. $confirm .'"><i class="fa fa-trash"></i></a> <a href="'. $value .'" target="_blank" class="btn btn-default" style="padding: 3px 8px;" title="'. trans("Télécharger") .'"><i class="'. File::getIconClass($value) .'"></i></a>'; $html .= '</div>'; } break; case (in_array($field['type'], ['submit', 'reset', 'button'])): $html .= '<button type="'. $field['type'] .'" '. $attributes .'>'. $field['label'] .'</button>'; break; default: $html = ''; $type = $field['type']; if (in_array($type, ['checkbox', 'radio'])) { $inline = (self::execute($field['inline'], self::$model)) ? ' class="'. $type .'-inline"' : ''; $html .= '<div class="mt-10">'; foreach ($field['options'] as $value => $text) { if (is_object($text)) { $value = (isset($text->value)) ? $text->value : null; $text = (isset($text->text)) ? $text->text : null; } // Tell if field is checked $checked = ''; if ( (is_array($field['value']) && in_array($value, $field['value'])) || ($value == $field['value']) ) { $checked = ' checked'; } $html .= '<label'. $inline .'>'; $html .= '<input type="'. $type .'" name="'. $field['name'] .'" value="'. $value .'"'. $checked .'>&nbsp;'. $text; $html .= '</label>'; } $html .= '</div>'; } else { $html .= '<input '. $attributes .'>'; } break; } return $html; } /** * Get Help Block markup * * @param string $text * @access public * * @return string $help_block * * @author mchanchaf */ public static function getHelpBlock($text) { return "<p class=\"help-block\">{$text}</p>"; } /** * Get attributes * * @param array $attributes * * @access public * * @return string $attributes * * @author mchanchaf */ public static function getAttributes($attributes) { $attr_arr = []; foreach ($attributes as $k => $v) { if ($k == 'value' && is_array($v)) continue; $value = self::execute($v, self::$model); $attr_arr[] = (is_numeric($k)) ? $value : $k .'="'. $value .'"'; } return implode(' ', $attr_arr); } /** * Get field attributes * * @param array $field * * @access public * * @return string $attributes * * @author mchanchaf */ public static function getFieldAttributes($field) { $attributes = []; // Add title if (!empty($field['label']) && !isset($field['attributes']['title'])) { $field['attributes']['title'] = $field['label']; } // Remove attr value for input type file if (in_array($field['type'], ['select', 'textarea', 'file'])) { unset($field['attributes']['value']); } $field['attributes']['type'] = $field['type']; $field['attributes']['name'] = $field['name']; if(isset($field['value'])) $field['attributes']['value'] = $field['value']; if(isset($field['required']) && $field['required'] == true) $field['attributes'][] = 'required'; foreach ($field['attributes'] as $k => $v) { if (!empty($field['value']) && $field['type'] == 'file' && $k == 'id') continue; if ($k == 'value' && is_array($v)) continue; $value = self::execute($v, self::$model); $attributes[] = (is_numeric($k)) ? $value : $k .'="'. $value .'"'; } return implode(' ', $attributes); } /** * Set form settings * * @param array $settings * * @access public * * @return void * * @author mchanchaf */ public static function setSettings($settings) { self::$settings = array_replace_recursive(self::$settings, $settings); } /** * Set form attributes * * @param array $attributes * * @access public * * @return void * * @author mchanchaf */ public static function setAttributes($attributes) { self::$attributes = array_replace_recursive(self::$attributes, $attributes); } /** * Get field template * * @param array|null $field * * @access public * * @return string $field * * @author mchanchaf */ public static function getTemplate($field = null) { // Get template $template = (!empty($field['template'])) ? $field['template'] : self::$template; // Prepare template variables $isRequired = (!empty($field)) ? self::getFieldOption('required', self::$name, $field['name']) : false; $label = (!empty($field['label'])) ? '<label for="'. $field['attributes']['id'] .'">'. $field['label'] .'</label>' : ''; $variables['html_label'] = $label; $variables['help_block'] = (!empty($field['help'])) ? self::getHelpBlock($field['help']) : ''; $variables['html_field'] = (!empty($field)) ? self::field($field) : ''; $required = ($isRequired) ? ' required' : ''; $variables['attributes'] ='class="form-group'.$required.'" id="'. $field['attributes']['id'] .'Container"'; // Parse template $fieldHtml = self::parseTemplate($template, $variables); if (isset($field['columns']) && intval($field['columns']) > 0) { $offset = (intval($field['offset']) > 0) ? ' col-md-offset-'. $field['offset'] : ''; $fieldHtml = '<div class="col-md-'. $field['columns'] . $offset. '">'. $fieldHtml .'</div>'; } return $fieldHtml; } /** * Set global template * This will be applied for all form fields * * @param string $template * * @access public * * @return void * * @author mchanchaf */ public static function setTemplate($template) { self::$template = $template; } /** * Returns the Parsed Field Template * * @param string $template * @param array $variables * @param string $openingTag * @param string $closingTag * * @access public * * @return string HTML with any matching variables {{varName}} replaced with there values. * * @author mchanchaf */ public static function parseTemplate($template, $variables = [], $openingTag = '{', $closingTag = '}') { foreach ($variables as $key => $variable) : $template = str_replace($openingTag. $key . $closingTag, $variable, $template); endforeach; return $template; } /** * Get field MySql column name * * @param string $field_name * * @access public * * @return string $name * * @author mchanchaf */ public static function getFieldName($field_name) { preg_match('/\[([a-zA-Z0-9_-]+)]/', $field_name, $matches); return (isset($matches[1])) ? $matches[1] : $field_name; } /** * Get field option by name * * @param string $option_name * @param string $form_id * @param string $field_name * * @access public * * @return string $option value * * @author mchanchaf */ public static function getFieldOption($option_name, $form_id, $field_name, $type = 'fields') { // Trigger form setting event to get settings from a resource self::triggerEvent('chmFormSetting', $form_id); $fname = self::getFieldName($field_name); if ($option_name == 'required' && !self::getFieldOption('displayed', $form_id, $fname)) { return false; } if (!isset(self::$settings[$fname][$option_name])) { if (isset(self::$fields[$field_name][$option_name])) { return self::execute(self::$fields[$field_name][$option_name]); } else { return true; } } return self::$settings[$fname][$option_name]; } /** * Add new event * * @param string $name * @param array $callable * * @access public * * @return void * * @author mchanchaf */ public static function addEvent($name, $callable) { self::$events[$name][] = $callable; } /** * Trigger form event * * @param string $name * @param array $args * * @access public * * @return void * * @author mchanchaf */ public static function triggerEvent($name, $args = []) { if (!isset(self::$events[$name]) || in_array($name, self::$triggeredEvents)) return; foreach (self::$events[$name] as $key => $callback) { self::execute($callback, $args); } self::$triggeredEvents[] = $name; } /** * Execute * * @param string|callable $name * @param array $args * * @access public * * @return string $value * * @author mchanchaf */ public static function execute($name, $args = []) { $excluded_func = ['file', 'date']; // Check if is a callback function if (is_callable($name) && !in_array($name, $excluded_func)) { return call_user_func($name, $args); } // Check if class with method if (is_string($name) && strpos($name, '@') !== false) { $callable = explode('@', $name); if(method_exists($callable[0], $callable[1]) && is_callable($callable)) { return call_user_func_array($callable, $args); } } return $name; } } // End Class
true
b5b4cb96ee48200d39139794cd77d575751bf071
PHP
boygraceful/springbok
/src/Application/TicketBundle/Model/Ticket/Mapper.php
UTF-8
1,805
2.65625
3
[]
no_license
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ namespace Application\TicketBundle\Model\Ticket; use Application\TicketBundle\Model\Ticket; use Application\UserBundle\Model\User; use Application\SpringbokBundle\Model\Mapper\MongoMapper; /** * Mapper * * DataMapper for tickets * * @category Springbok * @package TicketBundle * @subpackage Model */ class Mapper extends MongoMapper { /** * @return \MongoCollection */ public function getCollection() { return $this->mongo->tickets; } /** * get Tickets by tag(s) * * @param string|array $tag * @return array[int]\Application\TicketBundle\Model\Ticket */ public function getByTag($tag) { return static::fromCursor( $this->getCollection()->find(array('tags' => $tag)) ); } /** * get by assignee * * @param User $user * @return array[int]Ticket */ public function getByAssignee(User $user) { return static::fromCursor( $this->getCollection()->find(array('assigned_to' => $user->username)) ); } /** * get tickets by user * * @param User $user * @return array[int]\Application\TicketBundle\Model\Ticket */ public function getByReporter(User $user) { return static::fromCursor( $this->collection->find(array('reporter_name' => $user->username)) ); } /** * @return \Application\TicketBundle\Model\Ticket */ static public function fromArray(array $array) { return self::arrayToObject($array, 'Application\\TicketBundle\\Model\\Ticket'); } /** * translate Ticket into array representaiton * * @return array */ static public function toArray(Ticket $ticket) { return self::objectToArray($ticket); } }
true
e80a1bc8e3f018c00aafb4d471a65939bfbf4321
PHP
RaphOb/ApiMailer
/src/mail.php
UTF-8
1,302
2.734375
3
[]
no_license
<?php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; function sendMail(Request $request) { // $email = $request->getAttribute('email'); $data = $request->getParsedBody(); $email = $data['email']; $type = $data['type']; $subject = NULL; $bodyMail = NULL; switch ($type) { case 0: $subject = "Changement D'email?"; $bodyMail = "Une demande de changement de mot de passe a ete demandé"; break; case 1: $subject = "Success"; $bodyMail = "Votre mot de passe a bien ete changé"; break; case 2: $subject = "Votre video a ete chargé"; $bodyMail = "upload de votre video s' est deroulé avec succès"; break; default: $subject = "JFF"; $bodyMail = "On envoit des rdm mails parcequ'on a rien à faire"; break; } if ($email != NULL && $type != NULL) { if (!valid_email($email)) { displayErrorJSON('Bad Request', 10001, "L'email n'est pas au bon format"); } else { mail($email, $subject, $bodyMail); } } else { displayErrorJSON('Bad Request', 10001, "Pas d'email"); } }
true
584bc6d51e47fc79a854a78fc27d92f1df2ee28f
PHP
thallisphp/backend-challenge-doc88
/app/Models/Pastel.php
UTF-8
752
2.609375
3
[]
no_license
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; /** * Model de Pastel * * @property int $id * @property string $nome * @property float $preco * @property string $foto * * @package App\Models */ class Pastel extends Model { use SoftDeletes; protected $table = 'pasteis'; protected $fillable = [ 'nome', 'preco', 'foto', ]; protected $casts = [ 'preco' => 'float', ]; protected $hidden = [ 'updated_at', 'deleted_at', ]; public function toArray() { $pastel = parent::toArray(); $pastel['foto'] = asset('storage/' . $pastel['foto']); return $pastel; } }
true
e5c98fafbf99cde0cffb9c1da3626c371d53d647
PHP
michaelmendoza/simple-mvc
/index.php
UTF-8
4,923
2.96875
3
[]
no_license
<?php /** * Simple-MVC * * A simple php MVC framework created for BYU MRI Facility * * @package Simple-MVC * @author Michael Mendoza */ define('Simple-MVC_VERSION', '0.0.1'); /** *--------------------------------------------------------------- * APP and API Directory Names *--------------------------------------------------------------- */ $app_path = 'app'; $api_path = 'api'; /** *--------------------------------------------------------------- * Application Paths *--------------------------------------------------------------- */ define('BASEURL','http://192.168.33.12/'); define('BASEPATH','http://192.168.33.12/'); define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME)); define('APPPATH', $app_path.DIRECTORY_SEPARATOR); define('APIPATH', $api_path.DIRECTORY_SEPARATOR); define('CONTROLLERPATH', APPPATH.'controllers'.DIRECTORY_SEPARATOR); define('VIEWPATH', APPPATH.'views'.DIRECTORY_SEPARATOR); define('LAYOUTPATH', VIEWPATH.'layouts'.DIRECTORY_SEPARATOR); define('PAGESPATH', VIEWPATH.'pages'.DIRECTORY_SEPARATOR); define('COMPONENTSPATH', VIEWPATH.'components'.DIRECTORY_SEPARATOR); define('ASSETSPATH', APPPATH.'assets'.DIRECTORY_SEPARATOR); /** *--------------------------------------------------------------- * Application DB Varibles *--------------------------------------------------------------- */ define('MYSQL_HOST','localhost'); define('MYSQL_USERNAME','root'); define('MYSQL_PASSWORD','root'); define('MYSQL_DBNAME','mriFacilityDB'); /** *--------------------------------------------------------------- * Session Varibles *--------------------------------------------------------------- */ if(!isset($_SESSION)) { session_start(); } /* * ------------------------------------------------------ * Route from URL * ------------------------------------------------------ */ class Router { private $uri; private $route; private $routes; private $action; function __construct() { // Get parse uri $this->uri = explode('/', $_SERVER['REQUEST_URI']); // Set action $this->action = null; if(count($this->uri) > 2) $this->action = $this->uri[2]; // Set route if($this->uri[1] == '') $this->route = 'home'; else $this->route = $this->uri[1]; // Get availible routes $this->routes = array(); $controllers = glob(CONTROLLERPATH.'*.*'); foreach($controllers as $controller) { $filename = pathinfo($controller)['filename']; $this->routes[$filename] = pathinfo($controller)['basename']; } } function goToRoute() { // Access controller for route include(CONTROLLERPATH.$this->routes[$this->route]); // Load $controller = $this->route."controller"; $controller = new $controller; $action = $this->action; if(is_null($this->action)) $controller->index(); else $controller->$action(); } } /* * ------------------------------------------------------ * File Importer * ------------------------------------------------------ */ /** * import - loads files, and saves a list of class names loaded */ function import($class, $file, $path = null) { static $_classes = array(); $class = strtolower($class); $class_exists = isset($_classes[$class]); if(!$class_exists) { $_classes[$class] = $class; $path = is_null($path) ? APPPATH : $path; include_once($path.$file); } } /* * ------------------------------------------------------ * Nav Components * ------------------------------------------------------ */ class NavLink { public $name; public $link; function __construct($name, $link_or_links) { $this->name = $name; $this->link = $link_or_links; } public function isLink() { return !is_array($this->link); } public function render() { if($this->isLink()) { echo "<li><a href='{$this->link}'>{$this->name}</a></li>"; } else { echo "<li><a href=''>{$this->name}</a>"; echo "<ul>"; foreach($this->link as $sublink) $sublink->render(); echo "</ul>"; echo "</li>"; } } } /* * ------------------------------------------------------ * Get Controller from Route * ------------------------------------------------------ */ class Controller { public $header = 'header'; public $footer = 'footer'; public $layout = 'layout'; function __construct() { include_once(APPPATH.'models/nav.php'); } public function loadModel($class, $file, $param = null) { import($class, $file); $instance = isset($param) ? new $class($param) : new $class(); return $instance; } public function loadView($view, $data = null) { // Get paths $headerpath = LAYOUTPATH.$this->header.'.php'; $pagepath = PAGESPATH.$view.'.php'; $footerpath = LAYOUTPATH.$this->footer.'.php'; $layoutpath = LAYOUTPATH.$this->layout.'.php'; // Get model data for layouts $nav = new NavModel; $nav_links = $nav->getNavLinks(); // Render layout include($layoutpath); } } $router = new Router(); $router->goToRoute();
true
7f0bc7dc5a002e47f63f720ae472cecd4f0440c7
PHP
darkorsa/cordo-gateway
/core/UI/Http/Middleware/CacheMiddleware.php
UTF-8
1,462
2.703125
3
[ "MIT" ]
permissive
<?php namespace Cordo\Gateway\Core\UI\Http\Middleware; use GuzzleHttp\Psr7\Message; use Psr\Cache\CacheItemPoolInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Cordo\Gateway\Core\Infractructure\Persistance\Cache\CachePoolFactory; class CacheMiddleware implements MiddlewareInterface { private CacheItemPoolInterface $cachePool; /** * Cache lifetime in seconds */ private int $ttl; public function __construct(int $ttl) { $this->ttl = $ttl; $this->cachePool = CachePoolFactory::create('redis'); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { if ($request->getMethod() !== 'GET') { return $handler->handle($request); } $item = $this->cachePool->getItem($this->getCacheKey($request)); if ($item->get()) { return Message::parseResponse($item->get()); } $response = $handler->handle($request); $this->cachePool->save( $item ->set(Message::toString($response)) ->expiresAfter($this->ttl) ); return $response; } private function getCacheKey(ServerRequestInterface $request): string { return md5(serialize($request->getUri())); } }
true
d237290b92e24d574a07ed23b9f7893b51474bd7
PHP
ValRCS/PHP_Playground_11
/public/updateSong.php
UTF-8
1,164
3.015625
3
[ "MIT" ]
permissive
<?php require_once '../src/db.php'; if ($_SERVER['REQUEST_METHOD'] == 'POST') { //we need to add song to database $song_id = $_POST['update']; $title = $_POST['title']; $artist = $_POST['artist']; $length = $_POST['length']; //for check boxes we only get the value when checkbox is checked! $isFavorite = isset($_POST['favorite']); // var_dump($_POST); // die("with my favorite $isfavorite"); // prepare and bind // UPDATE `tracks` SET `title` = 'Rinķi', `artist` = 'Bermudu Divstūris', `length` = '189' WHERE `tracks`.`id` = 6 $stmt = $conn->prepare("UPDATE `tracks` SET `title` = (:title), `artist` = (:artist), `length` = (:length), `favorite` = (:favorite) WHERE `tracks`.`id` = (:songid)"); $stmt->bindParam(':songid', $song_id); $stmt->bindParam(':title', $title); $stmt->bindParam(':artist', $artist); $stmt->bindParam(':length', $length); $stmt->bindParam(':favorite', $isFavorite); $stmt->execute(); //we go to our index.php or rather our root header('Location: /'); } else { echo "That was not a POST, most likely GET"; }
true
41d544754421f93daecba5870962cb7920d6e634
PHP
bharatvarshney2022/cirqal
/vendor/nelexa/google-play-scraper/src/Scraper/PlayStoreUiRequest.php
UTF-8
4,337
2.546875
3
[ "MIT", "Apache-2.0" ]
permissive
<?php declare(strict_types=1); /** * @author Ne-Lexa * @license MIT * * @see https://github.com/Ne-Lexa/google-play-scraper */ namespace Nelexa\GPlay\Scraper; use GuzzleHttp\Psr7\Request; use Nelexa\GPlay\Enum\SortEnum; use Nelexa\GPlay\GPlayApps; use Nelexa\GPlay\Model\AppId; use Psr\Http\Message\RequestInterface; use function GuzzleHttp\Psr7\stream_for; /** * @internal */ class PlayStoreUiRequest { public const LIMIT_REVIEW_ON_PAGE = 199; public const LIMIT_APPS_ON_PAGE = 100; private const RPC_ID_REVIEWS = 'UsvDTd'; private const RPC_ID_APPS = 'qnKhOb'; private const RPC_ID_PERMISSIONS = 'xdSrCf'; /** * @param AppId $requestApp * @param int $count * @param SortEnum $sort * @param string|null $token * * @return RequestInterface */ public static function getReviewsRequest( AppId $requestApp, int $count, SortEnum $sort, ?string $token = null ): RequestInterface { $limit = min(self::LIMIT_REVIEW_ON_PAGE, max(1, $count)); $queryParams = [ 'rpcids' => self::RPC_ID_REVIEWS, GPlayApps::REQ_PARAM_LOCALE => $requestApp->getLocale(), GPlayApps::REQ_PARAM_COUNTRY => $requestApp->getCountry(), 'authuser' => null, 'soc-app' => 121, 'soc-platform' => 1, 'soc-device' => 1, ]; $url = GPlayApps::GOOGLE_PLAY_URL . '/_/PlayStoreUi/data/batchexecute?' . http_build_query($queryParams); $formParams = [ 'f.req' => '[[["' . self::RPC_ID_REVIEWS . '","[null,null,[2,' . $sort->value( ) . ',[' . $limit . ',null,' . ($token === null ? 'null' : '\\"' . $token . '\\"') . ']],[\\"' . $requestApp->getId( ) . '\\",7]]",null,"generic"]]]', ]; $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8', ]; $body = stream_for(http_build_query($formParams)); return new Request('POST', $url, $headers, $body); } /** * @param string $locale * @param string $country * @param int $count * @param string $token * * @return RequestInterface */ public static function getAppsRequest(string $locale, string $country, int $count, string $token): RequestInterface { $limit = min(self::LIMIT_APPS_ON_PAGE, max(1, $count)); $queryParams = [ 'rpcids' => self::RPC_ID_APPS, GPlayApps::REQ_PARAM_LOCALE => $locale, GPlayApps::REQ_PARAM_COUNTRY => $country, 'soc-app' => 121, 'soc-platform' => 1, 'soc-device' => 1, ]; $url = GPlayApps::GOOGLE_PLAY_URL . '/_/PlayStoreUi/data/batchexecute?' . http_build_query($queryParams); $formParams = [ 'f.req' => '[[["' . self::RPC_ID_APPS . '","[[null,[[10,[10,' . $limit . ']],true,null,[1]],null,\\"' . $token . '\\"]]",null,"generic"]]]', ]; $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8', ]; $body = stream_for(http_build_query($formParams)); return new Request('POST', $url, $headers, $body); } /** * @param AppId $requestApp * * @throws \Exception * * @return RequestInterface */ public static function getPermissionsRequest(AppId $requestApp): RequestInterface { $queryParams = [ 'rpcids' => self::RPC_ID_PERMISSIONS, GPlayApps::REQ_PARAM_LOCALE => $requestApp->getLocale(), GPlayApps::REQ_PARAM_COUNTRY => $requestApp->getCountry(), 'soc-app' => 121, 'soc-platform' => 1, 'soc-device' => 1, ]; $url = GPlayApps::GOOGLE_PLAY_URL . '/_/PlayStoreUi/data/batchexecute?' . http_build_query($queryParams); $formParams = [ 'f.req' => '[[["' . self::RPC_ID_PERMISSIONS . '","[[null,[\"' . $requestApp->getId() . '\",7],[]]]",null,"1"]]]', ]; $headers = [ 'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8', ]; $body = stream_for(http_build_query($formParams)); return new Request('POST', $url, $headers, $body); } }
true
700e4a9f69952691e911ca56138df5e3731810c1
PHP
akiyamaSM/chibi
/src/core/ObjectManager/ObjectManagerInterface.php
UTF-8
444
3.046875
3
[]
no_license
<?php namespace Chibi\ObjectManager; interface ObjectManagerInterface { /** * Create new object instance * * @param string $classname * @param array $args * @return mixed */ public function create($classname, array $args = []); /** * Resolve object instance * * @param string $classname * @return mixed */ public function resolve($classname); }
true
cd3896468447aa489b59c3bf1d2f2f6fae25f97b
PHP
cedricblondeau/php-enigma2
/src/Console/Handlers/DownloadCommandHandler.php
UTF-8
730
2.703125
3
[ "MIT" ]
permissive
<?php namespace CedricBlondeau\PhpEnigma2\Console\Handlers; use CedricBlondeau\PhpEnigma2\Bouquets\Files; use CedricBlondeau\PhpEnigma2\Bouquets\Retriever; use Webmozart\Console\Api\Args\Args; use Webmozart\Console\Api\IO\IO; class DownloadCommandHandler extends BaseCommandHandler { /** * @param Args $args * @param IO $io */ public function handle(Args $args, IO $io) { parent::parseConfig($io); try { $retriever = new Retriever(); $retriever->download($args->getArgument('url')); $io->writeLine('Downloaded and extracted'); } catch (\RuntimeException $e) { $io->errorLine('Invalid url'); exit(); } } }
true
0c41f92479377ced9070f087d7d23ecc115120d2
PHP
wxinheb/uenty
/vendor/aabcsoft/aabc2/db/ColumnSchema.php
UTF-8
2,084
2.78125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace aabc\db; use aabc\base\Object; class ColumnSchema extends Object { public $name; public $allowNull; public $type; public $phpType; public $dbType; public $defaultValue; public $enumValues; public $size; public $precision; public $scale; public $isPrimaryKey; public $autoIncrement = false; public $unsigned; public $comment; public function phpTypecast($value) { return $this->typecast($value); } public function dbTypecast($value) { // the default implementation does the same as casting for PHP, but it should be possible // to override this with annotation of explicit PDO type. return $this->typecast($value); } protected function typecast($value) { if ($value === '' && $this->type !== Schema::TYPE_TEXT && $this->type !== Schema::TYPE_STRING && $this->type !== Schema::TYPE_BINARY && $this->type !== Schema::TYPE_CHAR) { return null; } if ($value === null || gettype($value) === $this->phpType || $value instanceof Expression || $value instanceof Query) { return $value; } switch ($this->phpType) { case 'resource': case 'string': if (is_resource($value)) { return $value; } if (is_float($value)) { // ensure type cast always has . as decimal separator in all locales return str_replace(',', '.', (string) $value); } return (string) $value; case 'integer': return (int) $value; case 'boolean': // treating a 0 bit value as false too // https://github.com/aabcsoft/aabc2/issues/9006 return (bool) $value && $value !== "\0"; case 'double': return (double) $value; } return $value; } }
true
5aff43d8014f0f755d5c282651399948b6f13902
PHP
satoriforos/adbox
/_tests/updatesettings.php
UTF-8
3,823
2.53125
3
[]
no_license
<?php /** * drop a lock file * edit /etc/network/interfaces * change wpa-ssid "<ssid>" * change wpa-psk "<password>" * comment out static * uncomment dhcp * tell user that settings have changed * kill hostapd * restart networking * if networking is not working * switch back to static * start hostapd * */ $wpa_ssid = "testSSID"; $wpa_psk = "testPassword"; $lockFile = "/tmp/adbox.lock"; $configFile = "networkinterfaces"; $config = file_get_contents($configFile); $search_wlan0_dhcp = "iface wlan0 inet dhcp"; $search_wpa_ssid = "wpa-ssid"; $search_wpa_psk = "wpa-psk"; $interface = "wlan0"; function routine() { createFile($lockFile); $config = readConfigFile($configFile); $config = updateWpaAuth($config, $wpa_ssid, $wpa_psk); $config = commentOutStatic($config); $config = uncommentDhcp($config); saveConfigFile($config, $configFile); killAccessPoint(); restartNetworking(); $error = false; $success = false; if (!isNetworkingWorking($interface)) { $error = true; $success = false; $config = commentOutDhcp($config); $config = uncommentStatic($config); saveConfigFile($config, $configFile); restartNetworking(); startAccessPoint(); } else { $error = false; $success = true; downloadAds(); } removeFile($lockFile); } function createFile($file) { $fileRef = fopen($file); fclose($fileRef); } function removeFile($file) { unlink($file); } function commentOut($config, $searchArray) { foreach ($searchArray as $search) { $config = str_replace("#".$search, $search, $config); } return $config; } function uncomment($config, $searchArray) { foreach ($searchArray as $search) { $config = str_replace($search, "#".$search, $config); } return $config; } function commentOutDhcp($config) { $searchArray = array( $search_wlan0_dhcp, $search_wpa_ssid, $search_wpa_psk ); $config = commentOut($config, $searchArray); return $config; } function uncommentDhcp($config) { $searchArray = array( $search_wlan0_dhcp, $search_wpa_ssid, $search_wpa_psk ); $config = uncomment($config, $searchArray); return $config; } function commentOutStatic($config) { $searchArray = array( $search_wlan0_static, $search_wlan0_address, $search_wlan0_netmask ); $config = commentOut($config, $searchArray); return $config; } function uncommentStatic($config) { $searchArray = array( $search_wlan0_static, $search_wlan0_address, $search_wlan0_netmask ); $config = uncomment($config, $searchArray); return $config; } function updateUpaAuth($config, $wpa_ssid, $wpa_psk) { $ssid_search = 'wpa-ssid "[^"]*"/'; $ssid_replace = 'wpa-ssid "'.$wpa_ssid.'"'; $psk_search = 'wpa-psk "[^"]*"/'; $psk_replace = 'wpa-psk "'.$wpa_ssid.'"'; $config = preg_replace( $ssid_search, $ssid_replace, $config ); $config = preg_replace( $psk_search, $psk_replace, $config ); } function readConfigFile($configFile) { $config = file_get_contents($configFile); return $config; } function saveConfigFile($config, $configFile) { file_put_contents($configFile, $config); } function restartNetworking($interface) { $command = "restartNetworking.sh ".$interface; shell_exec($command); } function killAccessPoint() { $command = "killAccessPoint.sh"; shell_exec($command); } function startAccessPoint() { $command = "startAccessPoint.sh"; shell_exec($command); } function isNetworkingWorking($interface) { $command = "ifconfig ".$interface; $output = shell_exec($command); $inet_addr_search = "/inet addr:([^\s]+)\s/"; $matches = array(); preg_match($inet_addr_search, $output, $matches); $address = ""; if (count($matches)) { $address = $matches[1]; } $retval = false; if ($address) { $retval = true; } return $retval; } function downloadAds() { $command = "downloadAds.sh"; shell_exec($command); } ?>
true
5208ac04ed3b3519f4f6086c54fc63a9595f10ae
PHP
lukejsimonetti/hydrator-strategy-pattern
/src/Entity/Form/Fieldset.php
UTF-8
3,555
2.828125
3
[]
no_license
<?php namespace src\Entity\Form; use src\Entity\EntityInterface; use src\Entity\Field\Choices; use src\Entity\Label; use src\Entity\Field\Entity as Field; use src\Entity\Value; class Fieldset implements EntityInterface { /** @var string */ public $id; /** @var string */ public $normalized; /** @var string */ public $case; /** @var string */ public $repeat; /** * Label object * @var Label */ public $label; /** * Array of Field objects * @var array */ public $fieldset; /** @var Field */ public $field; /** @var string */ public $plain; /** @var Choices */ public $choices; /** @var Value */ public $value; /** @var string */ public $type; /** * @return string */ public function getId(): ?string { return $this->id; } /** * @param string $id */ public function setId(string $id) { $this->id = $id; } /** * @return string */ public function getNormalized(): string { return $this->normalized; } /** * @param string $normalized */ public function setNormalized(string $normalized) { $this->normalized = $normalized; } /** * @return string */ public function getCase(): string { return $this->case; } /** * @param string $case */ public function setCase(string $case) { $this->case = $case; } /** * @return string */ public function getRepeat(): string { return $this->repeat; } /** * @param string $repeat */ public function setRepeat(string $repeat) { $this->repeat = $repeat; } /** * @return Label */ public function getLabel(): Label { return $this->label; } /** * @param Label $label */ public function setLabel(Label $label) { $this->label = $label; } /** * @return array */ public function getFieldset(): array { return $this->fieldset; } /** * @param array $fieldset */ public function setFieldset(array $fieldset) { $this->fieldset = $fieldset; } /** * @return Field */ public function getField() { return $this->field; } /** * @param Field $field */ public function setField($field) { $this->field = $field; } /** * @return string */ public function getPlain(): string { return $this->plain; } /** * @param string $plain */ public function setPlain(string $plain) { $this->plain = $plain; } /** * @return Choices */ public function getChoices(): Choices { return $this->choices; } /** * @param Choices $choices */ public function setChoices(Choices $choices) { $this->choices = $choices; } /** * @return Value */ public function getValue(): Value { return $this->value; } /** * @param Value $value */ public function setValue(Value $value) { $this->value = $value; } /** * @return string */ public function getType(): string { return $this->type; } /** * @param string $type */ public function setType(string $type) { $this->type = $type; } }
true
603965e21da71b179b2af818af982e7c6efcdc86
PHP
hannahnewsome/laravel-demo-app
/app/Http/Controllers/ProfilesController.php
UTF-8
1,983
2.65625
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Input; use App\Http\Requests; use Illuminate\Support\Facades\Validator; class ProfilesController extends Controller { /** * Show the user's profile. * * @return \Illuminate\Http\Response */ public function show($userid) { try { $user = \App\User::with('profile')->whereId($userid)->firstOrFail(); } catch(\Illuminate\Database\Eloquent\ModelNotFoundException $e){ return redirect()->route('home'); } return \View::make('profiles.show')->withUser($user); } /** * Fetch current user and direct user to page for editing profile. * * @return \Illuminate\Http\Response */ public function edit($userid) { $user = \App\User::whereId($userid)->firstOrFail(); return \View::make('profiles.edit')->withUser($user); } /** * Fetch current user and profile * Validate input and save new profile information * * @return \Illuminate\Http\Response */ public function update($userid) { $user = \App\User::with('profile')->whereId($userid)->firstOrFail(); $input = Input::only('location', 'bio', 'twitter_username', 'github_username'); $this->validator($input); //dd($user); $user->profile->fill($input)->save(); \Session::flash('flash_message','Profile successfully updated!'); return redirect()->route('profile.edit', $user->id); } /** * Get a validator for an incoming edit request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'location' => 'nullable|max:255', 'bio' => 'required|filled', 'twitter_username' => 'nullable', 'github_username' => 'nullable', ]); } }
true
a71b754afe366091510ab272a00f54b6884f5e53
PHP
rubyboyle/rubyboyle_cst336_19
/labs/lab4/api/validatePwd.php
UTF-8
497
3.125
3
[ "MIT" ]
permissive
<?php //API to check if the password contains the username in it. Will be invalid if it does. $password = $_GET['password']; $confirmpassword = $_GET['confirmpassword']; //echo $username . "<br>"; //echo $password . "<br>"; $data = array(); if (stripos($password, $confirmpassword) !== false) { // echo "Username is included in password!"; $data["validPwd"] = false; } else { // echo "Username is NOT included in password!"; $data["validPwd"] = true; } echo json_encode($data); ?>
true
d3774bdb77e38c97dd6a310f9b44ef9801150667
PHP
miarau/phpmvc-project
/app/view/users/view.tpl.php
UTF-8
2,316
2.703125
3
[ "MIT" ]
permissive
<?php // Prepare info $info = $user->getProperties(); $hash = md5(strtolower(trim( $info['email']))); // Questions by user $strQuestions = (empty($data['q'])) ? "Är inte frågvis" : ""; foreach ($data['q'] as $question) { // Prepare tags, no of answers and comments $strTags = ""; foreach ($question['t'] as $id => $tag) { $strTags .= "<div class='tag'>". "<a href='{$this->url->create('questions/tags/'.$id)}'>{$tag}</a>". "</div>"; } $statistics = "<i class='fa fa-reply'></i> ". (isset($question['A']) ? $question['A'] : "0"); $statistics .= "<i class='fa fa-comment'></i> ". (isset($question['C']) ? $question['C'] : "0"); $strQuestions .= "<div class='question'>". "<h3><a href='{$this->url->create('questions/view/'.$question['id'])}'>{$question['title']}</a></h3>". "<p class='date'>{$question['created']} $statistics</p>". "<p class='tags'>$strTags</p>". "</div>"; } // Answers by user $strAnswers = (empty($data['a'])) ? "Har inga svar" : ""; foreach ($data['a'] as $question) { // Prepare tags, no of answers and comments $strTags = ""; foreach ($question['t'] as $id => $tag) { $strTags .= "<div class='tag'>". "<a href='{$this->url->create('questions/tags/'.$id)}'>{$tag}</a>". "</div>"; } $statistics = "<i class='fa fa-reply'></i> ". (isset($question['A']) ? $question['A'] : "0"); $statistics .= "<i class='fa fa-comment'></i> ". (isset($question['C']) ? $question['C'] : "0"); $strAnswers .= "<div class='question'>". "<h3><a href='{$this->url->create('questions/view/'.$question['qNo'])}'>{$question['title']}</a></h3>". "<p class='date'>{$question['created']} $statistics</p>". "<p class='tags'>$strTags</p>". "</div>"; } ?> <h1><?=$info['name']?></h1> <div id="profile"> <img src="http://www.gravatar.com/avatar/<?=$hash?>?d=identicon&s=100" class="gravatar" alt="Profilbild"> <p>Användarnamn: <?=$info['acronym']?></p> <h3>Frågor av <?=$info['name']?></h3> <div id="questions"> <?=$strQuestions?> </div> <h3>Svar från <?=$info['name']?></h3> <div id="questions"> <?=$strAnswers?> </div> </div>
true
ddefa8adec920d3dbb566de40abc0d9782891ef7
PHP
chYatima03/php-sample-router
/src/Pages/save-note.php
UTF-8
751
2.875
3
[]
no_license
<?php use App\Database; $db = Database::getInstance()->getConnection(); $title = filter_input( INPUT_POST, 'title' ); $note = filter_input( INPUT_POST, 'note' ); $statement = $db->prepare( "INSERT INTO notes (title, content) VALUES (:title, :content)" ); $status = $statement->execute([ ':title' => $title, ':content' => $note, ]); if ( $status ) { $insert_id = $db->lastInsertId(); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php if ( $status ) : ?> Note saved. <a href="/note/<?=$insert_id?>">View</a> <?php else : ?> Note not saved. <a href="/">Home</a> <?php endif; ?> </body> </html>
true
02f59821a23e8bea148bfed74e3be1361e66f8c8
PHP
moufidfouadmoh/drmprj
/src/Event/Subscriber/SituationEvent.php
UTF-8
1,458
2.578125
3
[]
no_license
<?php namespace App\Event\Subscriber; use App\Entity\Situation; use App\Utils\Type\Choice\SituationChoiceType; use Symfony\Component\EventDispatcher\Event; class SituationEvent extends Event { const ON_ADD_SITUATION ='user.add.situation'; /** * @var Situation */ private $situation; public function __construct(Situation $situation) { $this->situation = $situation; } /** * @return Situation */ public function getSituation(): Situation { return $this->situation; } public function addSituation() { $data = $this->situation; if($data->getType() == SituationChoiceType::PREMIER_RECRU){ $data->getUser()->setDaterecrutement($data->getDate()); } $situations = $data->getUser()->getSituations(); if(!$situations->isEmpty()){ $array = $situations->toArray(); foreach ($array as $item){ if($item->getDate() > $data->getDate()){ $last = $item; $data->setEnabled(false); }else{ $last = $data; } } }else{ $last = $data; } $last->setEnabled(true); $last->getUser()->setCurrentStatut($last->getStatut()); $type = $last->getType(); $last->getUser()->setDepart($type == SituationChoiceType::DEPART ? true : false); } }
true
5069c208459261eb689c7f42d911a594598b6fda
PHP
jscarton/superlist-xml-export-suite
/includes/ftp.php
UTF-8
1,366
2.53125
3
[]
no_license
<?php function superlist_export_xml_to_SAP($order_xml,$order_id) { //check exports directory exists $base_dir=superlist_export_xml_check_dir(); //write xml file to that directory $timestamp=date("Y_m_d_H_i_s"); $filename="orders-export-".$timestamp."_$order_id.xml"; $local_filename=$base_dir."/".$filename; $written=file_put_contents($local_filename, $order_xml->asXML()); if ($written!==FALSE) { //get remote filename $remote_file=SUPERLIST_TO_SAP_FTP_ROOT.$filename; // establecer una conexión básica $conn_id = ftp_connect(SUPERLIST_TO_SAP_FTP_SERVER); if ($conn_id!==FALSE) { // iniciar sesión con nombre de usuario y contraseña $login_result = ftp_login($conn_id, SUPERLIST_TO_SAP_FTP_USER, SUPERLIST_TO_SAP_FTP_PASS); // activar modo pasivo ftp_pasv($conn_id, true); // cargar un archivo if (ftp_put($conn_id, $remote_file, $local_filename, FTP_ASCII)) { update_post_meta($order_id,'_superlist_exported_order','1'); return true; } else { return false; } // cerrar la conexión ftp ftp_close($conn_id); } } return false; } function superlist_export_xml_check_dir() { $upload_dir = wp_upload_dir(); $exports_dir = $upload_dir['basedir'].'/superlist-xml-exports-to-sap'; if ( ! file_exists( $exports_dir ) ) { wp_mkdir_p( $exports__dir ); } return $exports_dir; }
true
90cdeb8d717a248985dbf33be5fa11512a4543fe
PHP
bori00/Bookstore
/server/add_one_book_to_cart.php
UTF-8
1,298
2.578125
3
[]
no_license
<?php session_start(); include "database_connection.php"; $userId = $_SESSION["LoggedInUserId"]; $bookId = $_GET["bookId"]; $success = addOneBookToUsersCart($userId, $bookId, $conn); $conn->close(); echo json_encode($success); // ************************************************** function addOneBookToUsersCart($userId, $bookId, $conn) { $queryQuantity= sprintf("SELECT quantity FROM booksincart WHERE bookEditionId = '%s' AND userId = '%s'", $bookId, $userId); $currentQuantity = 0; if ($result = $conn->query($queryQuantity)) { if ($result->num_rows >= 1) { $row = $result->fetch_assoc(); $currentQuantity = $row["quantity"]; $newQuantity = $currentQuantity + 1; $queryAdd = sprintf("UPDATE booksincart SET quantity = '%s' WHERE bookEditionId = '%s' AND userId = '%s'", $newQuantity, $bookId, $userId); return $conn->query($queryAdd); } else { $quantity = 1; $queryInsert = sprintf("INSERT INTO booksincart (bookEditionId, userId) VALUES (%d, %d)", $bookId, $userId); return $conn->query($queryInsert); } } else { return false; } } ?>
true
030c1ada9d4128effd75259e3ccc1b183f7619ac
PHP
ArnoldDev-coder/Mobwiser-IT-Academy
/src/Kernel/Renderer/Renderer.php
UTF-8
862
2.71875
3
[]
no_license
<?php namespace Kernel\Renderer; use Twig\Environment; use Twig\Loader\FilesystemLoader; class Renderer { /** * @return Environment */ public function getTwig(): Environment { return $this->twig; } private FilesystemLoader $loader; private Environment $twig; public function __construct(FilesystemLoader $loader, Environment $twig) { $this->loader = $loader; $this->twig = $twig; } public function addPath(string $namespace, string $path = null): void { $this->loader->addPath($path, $namespace); } public function render(string $view, array $params = []): string { return $this->twig->render($view . '.twig', $params); } public function addGlobal(string $key, mixed $value): void { $this->twig->addGlobal($key, $value); } }
true
80ec51aff1db8f52cc66c5d9c9e78042005d0626
PHP
GETASEWTESFAW/websiteUsingPhp
/SEproject/php/signup.php
UTF-8
8,475
2.9375
3
[]
no_license
<?php require_once("util/connection.php"); //create short names for form variables $email = trim($_POST['email']); $password = $_POST['password']; $gender = $_POST['gender']; $screenName = trim($_POST['screenName']); $name = trim($_POST['name']); $arr = explode(" ",$name); if(count($arr) == 2){ $firstName = $arr[0]; $lastName = $arr[1]; } else{ $firstName = $name; $lastName = ""; } $birthday = trim($_POST['birthday']); $location = $_POST['location']; $profileHeadline = trim($_POST['profileHeadline']); $profilePhoto = null; $birthyear = intval(date('Y',strtotime($birthday))); $age = intval(date('Y')) - $birthyear; if($age < 18){ $ageError = 1; } //check all the necessary inputs are given if(!$email || !$password || !$screenName || !$firstName || !$gender || !$birthday || !$location || !$profileHeadline) { $emptyInput = 1; //echo "You have not entered all the necessary details. Please go back and try again"; } else if(!empty($ageError)){ ;//empty statement } else{ //add escape charcters if it is necessary using addslashes method if(!get_magic_quotes_gpc()) { $email = addslashes($email); $password = addslashes($password); $gender = addslashes($gender); $screenName = addslashes($screenName); $firstName = addslashes($firstName); $lastName = addslashes($lastName); $location = addslashes($location); $profileHeadline = addslashes($profileHeadline); $profilePhoto = addslashes($profilePhoto); } //connect to database and validate $db = getDatabase(); if(!db) { $noConnection = 1;//echo "Couldn't connect to database. Please try again"; } else{ //check if given email already exists $query = "select * from profile where email= '".$email."'"; $result = $db->query($query); if($result->num_rows){ $emailExists = 1;//echo "a user with the given email already exists"; } else{ //photo upload mechanism with all necessary checks $photoName = $_FILES['profilePhoto']['name']; if(!empty($photoName)){ $uploadOk = 1; $imageType = pathinfo($photoName,PATHINFO_EXTENSION); $photoName = md5($photoName.time().rand(1,1000)); $destination = "../images/".$photoName.".".$imageType; //check if image is actual image or fake $check = getimagesize($_FILES['profilePhoto']['tmp_name']); if($check === false){ $fakeImage = 1;$uploadOk = 0; } //check file size if($_FILES['profilePhoto']['size'] > 10000000){ $hugeImage = 1;$uploadOk = 0; } //allow certain formats $imageType = strtolower($imageType); if($imageType != "jpg" && $imageType != "png" && $imageType != "jpeg" && $imageType != "gif"){ $invalidFormat = 1;$uploadOk = 0; } //upload if image is validated if($uploadOk == 1){ if(!move_uploaded_file($_FILES['profilePhoto']['tmp_name'],$destination)){ $notUploaded = 1; } if(!isset($notUploaded)) $profilePhoto = "../".$destination; } } if(empty($photoName) || $uploadOk == 0 || $notUploaded == 1){ $photoGender = ($gender == "F") ? "female" : "male"; $profilePhoto = "../../images/".$photoGender."Anonymous.PNG"; } if(empty($lastName)){ $lastName = null; } $lastActive = 0; //when was the user last active //create new profile in the database and check if inserted $query = "insert into profile values ('".$email."', '".sha1($password)."', '".$gender."', '".$screenName."', '".$firstName."', '".$lastName."', '".$birthday."', '".$location."', '".$profileHeadline."', '".$profilePhoto."', '".$lastActive."')"; $inserted = $db->query($query); if(!$inserted){ $notInserted = 1;//echo "can't insert profile to the database"; } else{ //create new profileInfo for the new profile automatically $n = null; $query = "insert into profileInformation values ('".$email."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."')"; $infoInserted = $db->query($query); if(!$infoInserted){ echo "can't insert profileInfo to the database"; } $n = null; $query = "insert into criteria values ('".$email."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."', '".$n."')"; //create new criteria for the new profile automatically $criteriaInserted = $db->query($query); if(!$criteriaInserted){ echo "can't insert criteria to the database"; } $db->close(); } } } } if(isset($noConnection) || isset($notInserted)){ ;// empty statement } else if(isset($emptyInput) || isset($emailExists)){ ;//empty statement } else if(isset($ageError)){ ; } else{ if(isset($notUploaded)){ ?> <script> alert("There was an error uploading your profile photo. \ \n Please, try to upload it again in your profile ."); </script> <?php } echo '<form action="login.php" method="post" name="tempForm">'; echo '<input type="hidden" name="email" value="'.$email.'" />'; echo '<input type="hidden" name="password" value="'.$password.'" />'; echo '</form>'; ?> <script> document.tempForm.submit(); </script> <?php } ?> <html> <head> <title> Online Dating System </title> <meta charset="utf-8" /> <meta name="keywords" content="dating" /> <!-- keywords not finished --> <meta name="description" content="Online Dating System" /> <!-- description not finished --> <meta name="viewport" content="width=device-width,initial-scale=1" /> <link rel="stylesheet" href="../css/welcome.css" /> <style> .error { border:1px #ddd solid; border-radius: 4px; box-shadow: 2px 2px 3px rgba(0,0,0,.5); background-color: #fdd; width: 44em; margin: 5em auto; padding: 3em 18px; text-align: center; color: #f00; line-height: 2em; } @media (max-width:760px){ .error{ width: 18em; } } </style> <!-- head not finished --> </head> <div class="error"> <?php if(!empty($noConnection) || !empty($notInserted)){ echo "There was database connection error.</br> Please, click back and try again"; } else if(!empty($emailExists)){ echo "The given email already exists in the system.</br> Please, click back and change to an appropriate email"; } else if(!empty($emptyInput)){ echo "You can't leave any field empty except for the profile picture field.</br> Please, click back and fill all the required fields"; } else if(!empty($ageError)){ echo "You must be at least 18 years old to sign up.</br> Sorry "; } else{ echo "There was database connection error.</br> Please, click back and try again"; } ?> </div> <body>
true
b1b0c06273813bff1983da044f1321a269b86dab
PHP
aoyama7/base_image_xssbot
/tests/index.php
UTF-8
133
2.59375
3
[]
no_license
<?php $name = isset($_GET['name']) ? $_GET['name'] : ""; echo "hello, $name"; file_put_contents("php://stdout","hello, $name\n");
true
9d7f4ff71482e828f5dcc018a972aab6b302dbef
PHP
simengphp/mvc
/extend/MemcachedExtend.php
UTF-8
985
2.734375
3
[]
no_license
<?php //namespace extend\MemcachedExtend; /** * Created by crazy * User: crazy * Date: 2018/3/2 * Time: 17:00 */ class MemcachedExtend { public function memTest(){ $mem = new Memcache(); $mem->connect("127.0.0.1",11211); // $mem->set("string","刘柱"); // $string = $mem->get("string"); // echo "<hr />统计服务器池中的所有服务器状态"; // echo "<pre>"; // var_dump($mem->getextendedstats()); // echo "<hr />获取某一个服务器的状态"; // var_dump($mem->getserverstatus("127.0.0.1")); // echo "<hr />"; // var_dump($mem->getstats()); // echo "<hr />获取版本信息"; // var_dump($mem->getversion()); $arr = [1,2,3,4,5,666]; // $mem->set("arr",$arr); //替换某个缓存变量的值 $json = json_encode($arr); $mem->replace("arr",$json); $string = $mem->get("arr"); var_dump($string); } }
true
50ca82fe450f8ce73bfc05c1adf130fd17f6e472
PHP
cube43/ebics-client
/src/KeyRing.php
UTF-8
6,387
2.734375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Cube43\Component\Ebics; use JsonSerializable; use RuntimeException; use function array_key_exists; use function is_file; use function Safe\file_get_contents; use function Safe\json_decode; class KeyRing implements JsonSerializable { public function __construct( private readonly string $password, private readonly UserCertificate|null $userCertificateA = null, private readonly UserCertificate|null $userCertificateX = null, private readonly UserCertificate|null $userCertificateE = null, private readonly BankCertificate|null $bankCertificateX = null, private readonly BankCertificate|null $bankCertificateE = null, ) { } public function setUserCertificateA(UserCertificate $certificate): self { if ($this->userCertificateA !== null) { throw new RuntimeException('userCertificateA already exist'); } return new self( $this->password, $certificate, $this->userCertificateX, $this->userCertificateE, $this->bankCertificateX, $this->bankCertificateE, ); } public function hasUserCertificatA(): bool { return $this->userCertificateA !== null; } public function hasUserCertificateEAndX(): bool { return $this->userCertificateE !== null && $this->userCertificateX !== null; } public function hasBankCertificate(): bool { return $this->bankCertificateX !== null && $this->bankCertificateE !== null; } public function setUserCertificateEAndX(UserCertificate $userCertificateE, UserCertificate $userCertificateX): self { if ($this->userCertificateE !== null) { throw new RuntimeException('userCertificateE already exist'); } if ($this->userCertificateX !== null) { throw new RuntimeException('userCertificateX already exist'); } return new self( $this->password, $this->userCertificateA, $userCertificateX, $userCertificateE, $this->bankCertificateX, $this->bankCertificateE, ); } public function setBankCertificate(BankCertificate $bankCertificateX, BankCertificate $bankCertificateE): self { if ($this->bankCertificateX !== null) { throw new RuntimeException('bankCertificateX already exist'); } if ($this->bankCertificateE !== null) { throw new RuntimeException('bankCertificateE already exist'); } return new self( $this->password, $this->userCertificateA, $this->userCertificateX, $this->userCertificateE, $bankCertificateX, $bankCertificateE, ); } public function getUserCertificateA(): UserCertificate { if ($this->userCertificateA === null) { throw new RuntimeException('userCertificateA empty'); } return $this->userCertificateA; } public function getUserCertificateX(): UserCertificate { if ($this->userCertificateX === null) { throw new RuntimeException('userCertificateX empty'); } return $this->userCertificateX; } public function getUserCertificateE(): UserCertificate { if ($this->userCertificateE === null) { throw new RuntimeException('userCertificateE empty'); } return $this->userCertificateE; } public function getPassword(): string { return $this->password; } public function getBankCertificateX(): BankCertificate { if ($this->bankCertificateX === null) { throw new RuntimeException('bankCertificateX empty'); } return $this->bankCertificateX; } public function getBankCertificateE(): BankCertificate { if ($this->bankCertificateE === null) { throw new RuntimeException('bankCertificateE empty'); } return $this->bankCertificateE; } public static function fromFile(string $file, string $password): self { if (! is_file($file)) { return new self($password); } return self::fromArray(json_decode(file_get_contents($file), true), $password); } /** @param array<string, (array<string, string>|null)> $data */ public static function fromArray(array $data, string $password): self { $buildBankCertificate = static function (string $key) use ($data): BankCertificate|null { if (array_key_exists($key, $data) && ! empty($data[$key])) { return BankCertificate::fromArray($data[$key]); } return null; }; $buildUserCertificate = static function (string $key) use ($data): UserCertificate|null { if (array_key_exists($key, $data) && ! empty($data[$key])) { return UserCertificate::fromArray($data[$key]); } return null; }; return new self( $password, $buildUserCertificate('userCertificateA'), $buildUserCertificate('userCertificateX'), $buildUserCertificate('userCertificateE'), $buildBankCertificate('bankCertificateX'), $buildBankCertificate('bankCertificateE'), ); } public function purgeBankCertificat(): self { return new self( $this->password, $this->userCertificateA, $this->userCertificateX, $this->userCertificateE, ); } /** @return array<string, (array<string, string>|null)> */ public function jsonSerialize(): array { return [ 'bankCertificateE' => $this->bankCertificateE ? $this->bankCertificateE->jsonSerialize() : null, 'bankCertificateX' => $this->bankCertificateX ? $this->bankCertificateX->jsonSerialize() : null, 'userCertificateA' => $this->userCertificateA ? $this->userCertificateA->jsonSerialize() : null, 'userCertificateE' => $this->userCertificateE ? $this->userCertificateE->jsonSerialize() : null, 'userCertificateX' => $this->userCertificateX ? $this->userCertificateX->jsonSerialize() : null, ]; } }
true
4a805712359799de8d1c56c6548cb8e04fb5df77
PHP
GytisApinys/PHPsummer_GA
/SyllableApplication/Methods/ConsoleMsgOutput.php
UTF-8
1,773
3.015625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Gytis.Apinys * Date: 7/20/2018 * Time: 10:48 AM */ namespace SyllableApplication\Methods; class ConsoleMsgOutput { public static function workTypeMsg(): void { echo "\n|---------Word Syllabify---------|\n"; echo "| |\n"; echo "| Would you like to work |\n"; echo "| with Database or file? |\n"; echo "| |\n"; echo "| [1] - Database |\n"; echo "| [2] - File |\n"; echo "|---------------------------------|\n"; echo "Enter choice: "; } public static function workBbMsg(): void { echo "\n"; echo "|------------------------|\n"; echo "| Work with DB |\n"; echo "| What to do? |\n"; echo "| [1] Update DB |\n"; echo "| [2] Write in |\n"; echo "| Console |\n"; echo "| [3] Check done words |\n"; echo "|________________________|\n"; echo "Enter choice:............\n"; } public static function workFileMsg() { echo "\n"; echo "|------------------------|\n"; echo "| Work with File |\n"; echo "| |\n"; echo "| Get words from : |\n"; echo "| [1] File |\n"; echo "| [2] Console |\n"; echo "|________________________|\n"; echo "Enter choice:............\n"; } public static function outputResultMsg() { echo "\nHow would you want to get result?\n"; echo "[1] - File\n"; echo "[2] - Console\n"; } }
true
f3499d68ab0111e028d14e2f5588086892ec4288
PHP
trsenna/clean202108
/packages/events/src/Application/Dispatcher.php
UTF-8
305
2.59375
3
[]
no_license
<?php namespace Clean\Events\Application; use Clean\Contracts\Events\Application\Dispatcher as ApplicationDispatcher; use Clean\Contracts\Events\Application\Event; final class Dispatcher implements ApplicationDispatcher { public function dispatch(Event $event) { event($event); } }
true
96c5318982697a738e8339998f68262df3cbce5e
PHP
Bee777/laoedu
/app/Responses/User/UserCredentials.php
UTF-8
2,246
2.546875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: BeeTimberlake * Date: 2/27/2019 * Time: 10:29 AM */ namespace App\Responses\User; use App\Http\Controllers\Helpers\Helpers; use App\User; use Illuminate\Contracts\Support\Responsable; use Illuminate\Support\Facades\Hash; use Laravel\Passport\Passport; class UserCredentials implements Responsable { protected $user; public function __construct($user) { $this->user = $user; } /** * Create an HTTP response that represents the object. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function toResponse($request) { if (Helpers::isAjax($request)) { //check if admin return back if (User::isAdminUser(auth()->user())) { return response()->json(['success' => true, 'data' => 'Updated Credentials!']); } if ($this->isRequestNotEmpty($request, 'new_email')) { $this->user->fill([ 'email' => $request->get('new_email') ])->save(); } if ($this->isRequestNotEmpty($request, 'new_password')) { $this->user->fill([ 'password' => Hash::make($request->get('new_password')) ])->save(); } if ($this->isRequestNotEmpty($request, 'logout_from_all_other_devices') && $request->get('logout_from_all_other_devices')) { $currentToken = auth()->user()->token(); $this->revokeAllValidTokens([$currentToken->id]); } return response()->json(['success' => true, 'data' => 'Updated Credentials!']); } } public function revokeAllValidTokens($exceptIds = []) { $deleted = Passport::$tokenModel::where('user_id', $this->user->id) ->where('name', $this->user->getTokenName()) ->whereNotIn('id', $exceptIds) ->where('client_id', 1) ->where('revoked', 0) ->delete(); return $deleted; } public function isRequestNotEmpty($request, $n): bool { return $request->has($n) && !empty($request->get($n)); } }
true
198f4ddb4e74140e493a0ee21a980757793ac5b4
PHP
freimaurerei/yii2-service-client
/src/Exception/LogicalException.php
UTF-8
629
2.84375
3
[ "MIT" ]
permissive
<?php namespace Freimaurerei\ServiceClient\Exception; class LogicalException extends \Exception implements RpcServiceClientException, RestServiceClientException { /** * @var string[] */ private $errorData; /** * @return string[] Получает данные об ошибке */ public function getErrorData() { return $this->errorData; } public static function createExceptionWithErrorData($message = "", $code = 0, $errorData = []) { $exception = new static($message, $code); $exception->errorData = $errorData; return $exception; } }
true
0199daa320aabaf9568bb3a61c924d81dfbd8f4b
PHP
Jas-077/SE_Project
/Project/forget2.php
UTF-8
1,001
2.734375
3
[]
no_license
<?php require_once "db.php"; /* Attempt to connect to MySQL database */ $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME); use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; /* If you installed PHPMailer without Composer do this instead: */ require 'PHPMailer-master/src/Exception.php'; require 'PHPMailer-master/src/PHPMailer.php'; require 'PHPMailer-master/src/SMTP.php'; // Check connection if($link === false){ die("ERROR: Could not connect. " . mysqli_connect_error()); } if(($_SERVER["REQUEST_METHOD"] == "POST")) { $a= $_POST["otp"]; $sql2="select otp from otp_con"; $result = mysqli_query($link, $sql2); $row=mysqli_fetch_assoc($result); $b=$row["otp"]; //$sql3=$link->prepare("DELETE FROM otp_con WHERE otp='$a'"); if($a==$b) { echo '<script> alert("Right OTP entered 👍"); location.href="forget3.php"; </script>'; } else{ echo '<script> alert("Wrong OTP entered"); location.href="forget.php"; </script>'; } } ?>
true
496497085f1f294a526f800156536c45a73a026e
PHP
Ai0202/tdd_book
/Part1/Chapter9/Dollar.php
UTF-8
321
3.40625
3
[]
no_license
<?php declare(strict_types=1); namespace Part1\Chapter9; require_once 'Part1/Chapter9/Money.php'; class Dollar extends Money { /** * @param int $multiplier * @return Money */ public function times(int $multiplier): Money { return Money::dollar($this->amount * $multiplier); } }
true
3c5b12d25785629a3e1f3b7256a33583ebcf2725
PHP
richard4s/PHP-Files
/Desktop/FORBES/myhtdocs/php_practice/43_creating_cookies_with_php.php
UTF-8
251
2.765625
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <title>PHP Practice</title> </head> <body> <?php $time = time(); //setting cookie setcookie('username', 'Alex', $time + 60); //unseting cookie setcookie('username', 'Alex', $time - 60); ?> </body> </html>
true
1d372c1238e9e71b5f335a22e6f58a14c31c601f
PHP
dianedouglas/PHP-and-Friends
/php_basics1_setup_commentprint_variables.php
UTF-8
4,915
2.53125
3
[]
no_license
PHP Basics 1 SETUP THE FILE Give your files the .php extension to give them access to the whole PHP language. When this file is read by the server, which is the master chef, you can telll her that you are using php code by using these opening and closing tags <?php Code happens here ?> Everything outside of those tags is sent to your browser as HTML. Test your basic code here! http://writecodeonline.com/php/ BASICS: COMMENTS, WHITESPACE, PRINTING // I'm making a short one line comment. /* Here's a long comment. Happens to be a haiku. It needs this syntax. */ Indentation and whitespace between lines and during lines doesn't matter but lines must be ended with a semicolon. Print to the browser with the command 'echo' echo "Hello world."; print command: You can also use the print command, very similar to echo. no parenthesis on either cause both echo and print are constructs. but like a function print takes only one argument. echo can take many. also you can use print inside of a more complex expression while you can't with echo also print is a tiny bit slower than echo because it returns a value (1). $b ? print "b is true" : print "b is false" Install PHP via Homebrew (comes with built in commandline web server) 1. brew tap josegonzalez/php you'll get this output: Cloning into '/usr/local/Library/Taps/josegonzalez/homebrew-php'... remote: Counting objects: 7290, done. remote: Compressing objects: 100% (27/27), done. remote: Total 7290 (delta 16), reused 5 (delta 5) Receiving objects: 100% (7290/7290), 1.47 MiB | 357.00 KiB/s, done. Resolving deltas: 100% (4783/4783), done. Checking connectivity... done. Tapped 416 formulae It looks like you tapped a private repository. To avoid entering your credentials each time you update, you can use git HTTP credential caching or issue the following command: cd /usr/local/Library/Taps/josegonzalez/homebrew-php git remote set-url origin git@github.com:josegonzalez/homebrew-php.git 2. brew tap homebrew/versions output: Cloning into '/usr/local/Library/Taps/homebrew/homebrew-versions'... remote: Counting objects: 2516, done. remote: Compressing objects: 100% (6/6), done. remote: Total 2516 (delta 1), reused 0 (delta 0) Receiving objects: 100% (2516/2516), 831.65 KiB | 814.00 KiB/s, done. Resolving deltas: 100% (1446/1446), done. Checking connectivity... done. Tapped 161 formulae 3. go to php.net/downloads.php to check what version is the 'current stable' PHP release. then run this command: brew install php56 replacing the '56' with the first two digits of the current stable version number from php.net. this will take a moment. 4. close the terminal window and open a new one. 5. check to see if installation has succeded by running this command to get the current version number: php -v this should output something like this. PHP 5.6.3 (cli) (built: Nov 19 2014 10:28:38) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies 6. You may have to add your version of php to the path environment variable. echo 'export PATH=/usr/local/bin:$PATH' >>~/.bash_profile echo means print, so it is going to print the string enclosed in quotes. the >> means to output the results of the statement to the left into the destination file defined to the right, which in this case is the file .bash_profile in your home directory, which is where '~' takes you. the line sets the path variable equal to the current path variable's contents, prepended with the path to the correct PHP version. Once step 4 is completed successfully, it will be time to start coding! Turn on the built in web server by entering this command: php -S localhost:8000 you should see something like this output: PHP 5.6.3 Development Server started at Wed Nov 19 10:31:09 2014 Listening on http://localhost:8000 Document root is /Users/epicodus Press Ctrl-C to quit. The 'Document root' is the folder on your local machine that is the equivalent of typing "http://localhost:8000/" into your browser. This folder is set to wherever you are in the terminal when you run the command to start the server. If you do put that address into your browser it'll give you an error: Not Found: The requested resource / was not found on this server. That's because it is looking for a file to parse. So, inside of your Document root, make a folder called "Examples" and inside of it, a file called "index.php" Write the following line into it: <h1>Hello World!</h1> Now open this address in your browser: http://localhost:8000/Examples/index.php You will see your page displayed! This is how you can organize your projects on your local development machine. Make folders for each of your sites and you can use your browser's path to locate the files you want to load.
true
9d2101b530d619920008c5f45cb8aa15ba837546
PHP
edwinsentinel/bodabodasacco-app
/model/phone.class.php
UTF-8
1,967
2.78125
3
[]
no_license
<?php class phone extends db{ public $id=null; public $member_id=null; public $front_name=null; public $detail=null; public $data_public=1; public function __construct($id='', $mem_id=''){ parent::__construct(); if(!empty($id)){ $table = 'phone'; $field_array = array('phone_id', 'member_id', 'phone_front_name', 'phone_detail', 'public'); if(empty($mem_id)){ $cl = array('phone_id' => $id); }else{ $cl = array('phone_id' => $id, 'member_id' => $mem_id); } $mbr = $this->dbSelect_where($table, $field_array, $cl); if(empty($mbr)){ throw new Exception('Invalid Phone ID supplied. ID not found in database. Record deleted?'); }else{ $this->id=$mbr[0]['phone_id']; $this->member_id=$mbr[0]['member_id']; $this->front_name=$mbr[0]['phone_front_name']; $this->detail=$mbr[0]['phone_detail']; $this->data_public=$mbr[0]['public']; } } } public function delete_me($id){ if(!empty($id)){ $this->dbDelete('phone',array('phone_id' => $id)); }else{ throw new Exception('Phone data not loaded. Delete cannot execute'); } } public function save(){ if($this->id==null){ $inst = $this->dbInsert('phone', array('member_id' => $this->member_id, 'phone_front_name' => $this->front_name, 'phone_detail' => $this->detail, 'public' => '1' )); $this->id = $inst['last_insert_id']; return $inst; }else{ $this->dbUpdate('phone', array('member_id' => $this->member_id, 'phone_front_name' => $this->front_name, 'phone_detail' => $this->detail, 'public' => $this->data_public ), array('phone_id' => $this->id)); } } public function get_phone_data_array($id){ if(!empty($id)){ $mbr = $this->dbSelect_where('phone', '*', array('member_id' => $id)); if(empty($mbr)){ return array(); }else{ return $mbr; } }else{ throw New Exception('Member ID required to retrieve phone data'); } } }
true
603160aeb5d301f8d3e0c29e2188d30bc98322ff
PHP
abdullahaslam306/Lavish-Raffle
/index2.php
UTF-8
6,750
2.515625
3
[]
no_license
<?php include('SimpleXLSX.php'); $filename=""; $productName=""; $mytitle=""; $winner="";$imgContent="";$image=""; $imageName=""; if(isset($_POST['add'])) { $imageName=""; $filename=""; $productName=""; $mytitle=""; $winner="";$imgContent=""; extract($_POST); $filename=$_FILES['excel']['name']; $mytitle=$title; $check = getimagesize($_FILES["img"]["tmp_name"]); $imageName=$_FILES['img']['name']; if($check!== false) { $image = $_FILES['img']['tmp_name']; $imgContent = addslashes(file_get_contents($image)); } $namesArr=array(); if ( $xlsx = SimpleXLSX::parse($filename) ) { $i=0; foreach( $xlsx->rows() as $r ) { $namesArr[$i]=implode('</td><td>', $r ); $i++; } $randIndex = array_rand($namesArr); $winner=$namesArr[$randIndex]; }else{ echo"<h1>Error! FILE NOT OPENING</h1>"; } ?><!DOCTYPE html> <html> <head> <title>Lavish Raffle</title> <link rel="icon" href="logo1.jpg" type="image/gif" sizes="50x50"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <style type="text/css"> body { margin: 0% auto; align-items: center; justify-content: center; flex-flow: column; font-family: 'Anonymous Pro', monospace; text-align: center; background-color: #000000; } h1 { font-size: 5vw; color: white; } h1:before { content: attr(data-before); word-break: break-all; opacity: 0.5; } h1:after { content: attr(data-after); word-break: break-all; opacity: 0.5; } .button { padding: 20px 40px; font: inherit; color: #140d09; background-color: #c1bba0; opacity: 0; transform: translate3d(0, 50px, 0); transition: all 0.3s cubic-bezier(0, 1, 0, 1); cursor: pointer; } .button.show { opacity: 1; transform: translate3d(0, 30px, 0); } .fade-in { letter-spacing: 2px; animation: fadeIn ease 10s; -webkit-animation: fadeIn ease 10s; -moz-animation: fadeIn ease 10s; -o-animation: fadeIn ease 10s; -ms-animation: fadeIn ease 10s; } @keyframes fadeIn { 0% { opacity:0; } 100% { opacity:1; } } @-moz-keyframes fadeIn { 0% { opacity:0; } 100% { opacity:1; } } @-webkit-keyframes fadeIn { 0% { opacity:0; } 100% { opacity:1; } } @-o-keyframes fadeIn { 0% { opacity:0; } 100% { opacity:1; } } @-ms-keyframes fadeIn { 0% { opacity:0; } 100% { opacity:1; } </style> <body onload="init('<?php echo $winner; ?>')"> <div style="position:relative"> <div style="position:absolute; z-index: 1000;"> <canvas id="canvas"></canvas> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4" ><img src="logo1.jpg" style="width: 100%; height:250px ; align-self: center "></div> <div class="col-md-4"></div> </div> <div class="row" style="margin-top: 2%;"> <div class="col-md-4"></div> <div class="col-md-4"> <img src="<?php echo"images/$imageName"; ?>" width="250px" height="300px"> </div> <div class="col-md-4"> </div> </div> <div class="row" style="margin-top: 2%;"> <div class="col-md-12"><h3 style="color: white; text-align: center; font-family: 'Anonymous Pro', monospace; font-weight: bold"> <?php echo strtoupper($mytitle); ?></h3></div> </div> <script type="text/javascript"> </script> <br> <div class="row" id='roller' > <div class="col-md-12" style="background-color: white;"> <h1 id="winnerName" style="color:black;">Example</h1> </div> </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <script type="text/javascript"> var dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFG".split(''); //0123456789qwertyuiopasdfghjklzxcvbnm!?></\a`~+*=@#$% var el = document.querySelector('h1'); var btn = document.querySelector('.button'); var ran = function() { return Math.floor(Math.random() * dictionary.length) } var ranString = function(amt) { var string = ''; for(var i = 0; i < amt; i++) { string += dictionary[ran()]; } return string; } var init = function(str) { var count =15; var delay = 50; el.innerHTML = ''; var gen = setInterval(function() { el.setAttribute('data-before', ranString(count)); el.setAttribute('data-after', ranString(count)); if(delay > 0) { delay--; } else { if(count < str.length) { el.classList.add("fade-in"); el.innerHTML += str[str.length - count-1]; } count--; if(count === -1) { clearInterval(gen); showButton(); loop(); loop(); } } }, 150); } var showButton = function() { } var a=document.getElementById('winnerName').innerHTML; function fun() { alert('sdads'); } const canvasEl = document.querySelector('#canvas'); const w = canvasEl.width = window.innerWidth; const h = canvasEl.height = window.innerHeight-40; function loop() { requestAnimationFrame(loop); ctx.clearRect(0,0,w,h); confs.forEach((conf) => { conf.update(); conf.draw(); }) } function Confetti () { //construct confetti const colours = ['#fde132', '#009bde', '#ff6b00']; this.x = Math.round(Math.random() * w); this.y = Math.round(Math.random() * h)-(h/2); this.rotation = Math.random()*360; const size = Math.random()*(w/60); this.size = size < 15 ? 15 : size; this.color = colours[Math.floor(colours.length * Math.random())]; this.speed = this.size/9; this.opacity = Math.random(); this.shiftDirection = Math.random() > 0.5 ? 1 : -1; } Confetti.prototype.border = function() { if (this.y >= h) { this.y = h; } } Confetti.prototype.update = function() { this.y += this.speed; if (this.y <= h) { this.x += this.shiftDirection/2; this.rotation += this.shiftDirection*this.speed/100; } if (this.y > h) this.border(); }; Confetti.prototype.draw = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.size, this.rotation, this.rotation+(Math.PI/2)); ctx.lineTo(this.x, this.y); ctx.closePath(); ctx.globalAlpha = this.opacity; ctx.fillStyle = this.color; ctx.fill(); }; const ctx = canvasEl.getContext('2d'); const confNum = Math.floor(w / 2); const confs = new Array(confNum).fill().map(_ => new Confetti()); </script> </body> </html> <?php }else{ header("location:menu.php?er=Enter Data First "); } ?>
true
adb9a1920280ae645329b2f0bf0f7e9b2b1a130f
PHP
edRibeiro/Qualitenis
/app/Http/Requests/FuncionarioRequest.php
UTF-8
1,459
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Requests; use App\Http\Requests\Request; class FuncionarioRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } public function messages() { return [ 'name.required'=>'Preencha um nome.', 'nome.max'=>'Nome deve ter até 255 caracteres.', 'telefone.required'=>'Preencha o numero de Telefone.', 'email.required'=>'Preencha com uma email valido.', 'email.unique'=> 'Email ja cadastrado.', 'email.email' => 'Email deve ser cadastrado corretamente!', 'CPF.required' => 'CPF deve ser informado.', 'password.required' => 'A senha deve ser informada', 'password.min' => 'A senha deve conter no minimo 8 digitos', 'password.max' => 'A senha deve conter no maximo 16 digitos', ]; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required|max:255', 'telefone' => 'required|max:15', 'email' => 'required|email|max:255|unique:users', 'CPF' => 'required|max:255', 'password' => 'required|min:8|max:16|confirmed', 'cidade_id' => 'required|max:255', ]; } }
true
0a8d64c0eb1b7f8b02397b7cbc737124f30f4201
PHP
Ezhil-Language-Foundation/snowball
/website/demo.php
UTF-8
1,102
2.9375
3
[ "BSD-3-Clause" ]
permissive
<?php require "menu.inc"; displayHeader("Demo"); ?> <TR><TD> <form method="POST" action="demo.php"> Enter some words to stem, using the English stemming algorithm, and then click on Submit:<br> <textarea name="words" rows="10" cols="50"><?php $words = $_POST['words']; $tmp = preg_replace('|\\\\|', '', $words); echo "$tmp"; ?></textarea> <br> <input type="submit" name="Submit" value="Submit"> </form> </TD></TR> <?php if ($words != '') { echo "<TR><TD>"; echo "<h2>Results</h2><pre>"; $tmpname = tempnam("/tmp", "snowball_stemdemo"); $tmpfile = fopen($tmpname, "w"); $words = strtolower($words); $words = preg_replace('|[^-A-Za-z\']|', ' ', $words); $words = preg_replace('|[-\']|', '', $words); $words = preg_replace('| *$|', '', $words); $words = preg_replace('| *|', "\n", $words); $language = "english"; # Have a limit of 10000 bytes, just in case. fwrite($tmpfile, $words, 10000); fclose($tmpfile); passthru ("/home/snowball-svn/pub/compiled/stemwords -p -i $tmpname"); unlink($tmpname); echo "</pre>"; echo "</TR></TD>"; } ?> <?php displayFooter(); ?>
true
86e8bd79d38542ef0298ae772e6a1b3730d951be
PHP
pnikhil/scroid
/protected/app/controllers/AdminPagesController.php.bak
UTF-8
2,299
2.796875
3
[ "MIT" ]
permissive
<?php class AdminPagesController extends AdminBaseController{ public function listPages(){ $pages = Page::all(); return View::make('admin/pages/view')->with(array( 'pages' => $pages )); } public function createEdit(){ $pageId = Input::get('pageId', null); $pageData = Input::get('page', array()); try { if($pageId || !empty($pageData['id'])) { //die(var_dump($pageId)); $page = Page::findOrFail($pageId ? $pageId : $pageData['id']); } else { $page = new Page; } } catch(ModelNotFoundException $e) { return Response::json(array( 'error' => 1, 'message' => $e->getMessage() )); } if(Request::ajax() && Request::isMethod('post')) { //Form submitted- Create the page //$keys = ['topic', 'description', 'pageContent', 'image', 'questions', 'results', 'ogImages']; foreach($pageData as $key => $val) { $page->$key = is_array($pageData[$key]) ? json_encode($pageData[$key]) : $pageData[$key]; } //var_dump($page); $page->save(); return Response::json(array( 'success' => 1, 'page' => $page )); } else { $pageSchema = new \Schemas\PageSchema(); return View::make('admin/pages/create')->with(array( 'pageSchema' => $pageSchema->getSchema(), 'pageData' => Page::decodePageJson($page), 'editingMode' => $pageId ? true : false, 'creationMode' => $pageId ? false : true )); } } public function delete(){ $pageId = Input::get('pageId', null); if(!$pageId) { return('Invalid url! Page Id not passed!'); } try{ $page = Page::findOrFail($pageId ? $pageId : $pageData['id']); } catch(Illuminate\Database\Eloquent\ModelNotFoundException $e) { return('Invalid page! The page you are trying to delete doesn\'t exist.'); } if(Request::isMethod('post')) { //POST method - confirmed - Delete now! if($page->delete()) { $deleteSuccess = true; }else { $deleteSuccess = false; } return View::make('admin/pages/delete')->with(array( 'page' => Page::decodePageJson($page), 'deleteSuccess' => $deleteSuccess )); } else if(Request::isMethod('get')) { //Ask for confirmation return View::make('admin/pages/delete')->with(array( 'page' => Page::decodePageJson($page), 'getConfirmation' => true )); } } }
true
502a08e4258cb2c11ebd9488b5e11ec7b52c81f6
PHP
denis019/MatrixLogImporter
/tests/Unit/Infrastructure/Persistence/Doctrine/Repositories/MatrixLogRepositoryTest.php
UTF-8
1,962
2.65625
3
[]
no_license
<?php namespace Tests\Unit\Infrastructure\Persistence\Doctrine\Repositories; use App\Domain\Entities\MatrixLog; use App\Infrastructure\Persistence\Doctrine\Repositories\MatrixLogRepository; use Tests\BaseTest; /** * Class MatrixLogRepositoryTest * @package Tests\Unit\Infrastructure\Persistence\Doctrine\Repositories * @coversDefaultClass \App\Infrastructure\Persistence\Doctrine\Repositories\MatrixLogRepository */ class MatrixLogRepositoryTest extends BaseTest { /** @var MatrixLogRepository */ protected $matrixLogRepository; public function setUp() { parent::setUp(); $this->matrixLogRepository = $this->dm->getRepository(MatrixLog::class); } /** * @test * @covers ::add */ public function add_should_persist_document() { $matrixLog = $this->createMatrixLog(1); $this->matrixLogRepository->add($matrixLog); $this->assertNotEmpty($matrixLog->getId()); } /** * @test * @covers ::getLastLog */ public function get_last_log() { $matrixLog = $this->createMatrixLog(1); $this->matrixLogRepository->add($matrixLog); $matrixLog = $this->createMatrixLog(2); $this->matrixLogRepository->add($matrixLog); $lastLog = $this->matrixLogRepository->getLastLog(); $this->assertEquals(2, $lastLog->getLineNo()); } /** * @param int $lineNo * @return MatrixLog */ protected function createMatrixLog(int $lineNo): MatrixLog { $dateTime = new \DateTime('17/Aug/2018:09:22:54 +0000'); /** @var MatrixLog $matrixLog */ $matrixLog = new MatrixLog(); $matrixLog->setServiceName('USER-SERVICE'); $matrixLog->setLineNo($lineNo); $matrixLog->setDateTime($dateTime); $matrixLog->setMethod('POST'); $matrixLog->setUrl('/users HTTP/1.1'); $matrixLog->setStatusCode(201); return $matrixLog; } }
true
320171d531dcb2d8703863dfa35042a6abea4e5e
PHP
crshao/pbkk-final-project
/app/Services/EncodingQRService.php
UTF-8
770
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Services; use Endroid\QrCode\Builder\Builder; use Endroid\QrCode\Encoding\Encoding; use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh; use Endroid\QrCode\Writer\PngWriter; use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin; class EncodingQRService { public function generate($data) { $result = Builder::create() ->writer(new PngWriter()) ->writerOptions([]) ->data($data) ->encoding(new Encoding('UTF-8')) ->errorCorrectionLevel(new ErrorCorrectionLevelHigh()) ->size(200) ->margin(10) ->roundBlockSizeMode(new RoundBlockSizeModeMargin()) ->build(); return $result->getDataUri(); } }
true
90e63411a53023af6ad0ad22f80963f7bb1b73dd
PHP
Eliyas/ecommerce_app_in_laraval5.8
/database/seeds/ProductTableSeeder.php
UTF-8
598
2.546875
3
[]
no_license
<?php use Illuminate\Support\Str; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class ProductTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $products = array('Nike','New Balance','Converse','Puma','Sparx','Reebok','Adidas','Jordan','Woodland','Timberland'); for ($i = 0; $i < 10; $i++) { DB::table('products')->insert([ 'name' => $products[$i], 'image' => '/images/'.$i.'.jpg', 'price' => $i+100, ]); } } }
true
f261209781149d79566988e9a03af135d16938f1
PHP
jul6art/symfony-skeleton
/src/Twig/LocaleExtension.php
UTF-8
2,388
2.703125
3
[ "MIT" ]
permissive
<?php /** * Created by devinthehood. * Project: symfony-skeleton * User: Jul6art * Date: 21/11/2019 * Time: 21:39. */ namespace App\Twig; use Doctrine\ORM\NonUniqueResultException; use Symfony\Component\HttpFoundation\RequestStack; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; /** * Class LocaleExtension. */ class LocaleExtension extends AbstractExtension { /** * @var RequestStack */ private $stack; /** * @var string */ private $locale; /** * LocaleExtension constructor. * * @param RequestStack $stack * @param string $locale */ public function __construct(RequestStack $stack, string $locale) { $this->stack = $stack; $this->locale = $locale; } /** * @return array */ public function getFunctions(): array { return [ new TwigFunction('locale', [$this, 'getLocale']), new TwigFunction('user_locale', [$this, 'getUserLocale']), new TwigFunction('validate_locale', [$this, 'getValidateLocale']), new TwigFunction('wysiwyg_locale', [$this, 'getWysiwygLocale']), ]; } /** * @return string * * @throws NonUniqueResultException */ public function getLocale(): string { return $this->getUserLocale(); } /** * @return string * * @throws NonUniqueResultException */ public function getValidateLocale(): string { $locale = $this->getUserLocale(); if ('pt' === $locale) { return 'pt_PT'; } return $locale; } /** * @return string * * @throws NonUniqueResultException */ public function getWysiwygLocale(): string { $locale = $this->getUserLocale(); if ('fr' === $locale) { return 'fr_FR'; } if ('en' === $locale) { return 'en_GB'; } if ('pt' === $locale) { return 'pt_PT'; } return $locale; } /** * @return string * * @throws NonUniqueResultException */ public function getUserLocale(): string { $request = $this->stack->getMasterRequest(); if (null === $request) { return $this->locale; } return $request->getLocale(); } }
true
7905c80faa9961bd1089ed2bd16ec4a5a8511f7e
PHP
grunk/Pry
/Pry/Config/Ini.php
UTF-8
7,204
2.984375
3
[ "MIT" ]
permissive
<?php /** * Pry Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * */ namespace Pry\Config; /** * Classe permettant la lecture de fichier de config au format INI. Basée sur Zend_Config_Ini * Il est possible de créer un héritage entre les section à l'aide du caractère ":" * Si une clé contient un "." cela sera considérer comme un séparateur pour créer une sous propriété. * Par exemple : * <code> * [prod] * db.host = mysite.com * db.user = root * [dev : prod] * db.host = localhost * </code> * @package Config * @version 1.0.0 * @author Olivier ROGER <oroger.fr> * */ class Ini extends Config { /** * Caractère représentant l'héritage * @var string */ private $inheritanceSeparator = ':'; /** * Caractère représentant les sous propriété * @var string */ private $separator = '.'; /** * Initialise la lecture d'un fichier de config au format ini * @param string $file Chemin vers le fichier à lire * @param string $section Section du fichier à lire. Null pour tout lire * @throws \RuntimeException * @throws \Exception */ public function __construct($file, $section = null) { if (empty($file)) throw new \RuntimeException("Filename is not set"); $arrayData = array(); $iniData = $this->load($file); if ($section == null) { //Chargement du fichier complet foreach ($iniData as $sectionName => $data) { if (!is_array($data)) { $arrayData = $this->_arrayMergeRecursive($arrayData, $this->parseKey($sectionName, $data, array())); } else { $arrayData[$sectionName] = $this->parseSection($iniData, $sectionName); } } parent::__construct($arrayData); } else { //Chargement d'une section en particulier if (!is_array($section)) $section = array($section); foreach ($section as $sectionName) { if (!isset($iniData[$sectionName])) throw new \RuntimeException("Section $sectionName can't be found"); $arrayData = $this->_arrayMergeRecursive($this->parseSection($iniData, $sectionName), $arrayData); } parent::__construct($arrayData); } } /** * Charge le fichier * @param string $file Fichier à charger * @return array Données chargée * @throws \RuntimeException * @throws \Exception */ private function load($file) { $rawArray = $this->parse($file); $iniArray = array(); //Recherche d'héritage entre les sections foreach ($rawArray as $key => $data) { $sections = explode($this->inheritanceSeparator, $key); $currentSection = trim($sections[0]); $nbSection = count($sections); switch ($nbSection) { // Section simple case 1 : $iniArray[$currentSection] = $data; break; // Section avec héritage case 2 : $inheritedSection = trim($sections[1]); // On ajoute une clé $inherit pour définir de qui hérite la section $iniArray[$currentSection] = array_merge(array('$inherit' => $inheritedSection), $data); break; default: throw new \RuntimeException("Section $currentSection can't inherit from multiple section"); } } return $iniArray; } /** * Parse un fichier ini * @param string $file Fichier à charger * @return array Données parsée * @throws \Exception */ private function parse($file) { //Supprime les erreurs et warning pour les transformer en exception set_error_handler(array($this, 'errorHandler')); $data = parse_ini_file($file, true); restore_error_handler(); if ($this->errorStr !== null) throw new \Exception("Can't parse Ini file : " . $this->errorStr); return $data; } /** * Parse chaque élément de la section et gère la clé '$inherit' qui permet de détecter un * héritage entre section. Passe ensuite les données à parseKey pour gérer les sous propriété * @param array $iniArray Tableau des données * @param string $section Nom de la section * @param array $config * @return array * @throws \Exception */ private function parseSection($iniArray, $section, $config = array()) { $currentSection = $iniArray[$section]; foreach ($currentSection as $key => $value) { if ($key == '$inherit') { //Si la section courante hérite d'une autre section if (isset($iniArray[$value])) { $this->checkForCircularInheritance($section, $value); $config = $this->parseSection($iniArray, $value, $config); } else { throw new \Exception("Can't found the inherited section of " . $section); } } else { //Si la section est indépendante $config = $this->parseKey($key, $value, $config); } } return $config; } /** * Assigne les valeurs de clés aux propriété. Gère le séparateur de propriété pour créer des * sous propriété * @param string $key * @param string $value * @param array $config * @return array * @throws \Exception */ private function parseKey($key, $value, $config) { if (strpos($key, $this->separator) !== false) { $properties = explode($this->separator, $key, 2); if (strlen($properties[0]) && strlen($properties[1])) { if (!isset($config[$properties[0]])) { if ($properties[0] === '0' && !empty($config)) { $config = array($properties[0] => $config); } else { $config[$properties[0]] = array(); } } elseif (!is_array($config[$properties[0]])) { throw new \Exception("Cannot create sub-key for '{$properties[0]}' as key already exists"); } $config[$properties[0]] = $this->parseKey($properties[1], $value, $config[$properties[0]]); } else { throw new \Exception("Invalid Key : " . $key); } } else { $config[$key] = $value; } return $config; } }
true
27e486cb868b6652c914d0459ddfb8d0dd9df598
PHP
Keisuke-Takagi/PHP_framework
/bookapp/controllers/bookapp/users/login/login_controller.php
UTF-8
2,032
2.671875
3
[]
no_license
<?php // namespace Bookapp\users\index; require_once(dirname(dirname(dirname(__FILE__))) . "\\application_controller.php"); class Logincontroller extends Applicationcontroller { public function redirect_book_page(){ header('Location: http://localhost/bookapp/books/index/mainpage'); } public function user_login($action_name, $model_instance, $model_error_num){ $e = 2; if($_SERVER["REQUEST_METHOD"] == "POST"){ $email = $model_instance->getEmail(); $password = $model_instance->getPassword(); require_once(dirname(dirname(dirname(dirname(__DIR__)))) . "\\views\\database.php"); $database = new Database(); $dbh = $database->open(); $stmt = $dbh->prepare('select * from users where email = ?'); $stmt->execute([$_POST['email']]); $row = $stmt->fetch(PDO::FETCH_ASSOC); if(!empty($row)){ if(password_verify($password, $row['password'])){ $e = ""; $model_instance->setSession($email); $this->redirect_book_page(); } } } return $e; } public function login($table_name, $action_name, $page_name, $template){ $template_path = ""; $model_error_num = ""; $model_class = $this->model_require($table_name, $action_name, $page_name); // モデルインスタンス作成 $model_instance = new $model_class; $model_instance->setEmail($this->postData("email")); $a = $model_instance->getEmail(); $model_instance->setPassword($this->postData("password")); if($_SERVER["REQUEST_METHOD"] == "POST"){ $model_error_num = $model_instance->validation($table_name); if($model_error_num == ""){ $model_error_num = $this->user_login($action_name, $model_instance, $model_error_num); } } $template_path = $template; if($model_error_num != "" ){ $template_path = $this->get_error_template($template, $model_error_num); } return [ "model_instance" => $model_instance, "template_path" => $template_path ]; } } ?>
true
5211d96262def6c55b00924ecd75c0471ed2dbb0
PHP
mohsinalimat/hosted-pdf
/app/Analytics/PdfCreated.php
UTF-8
683
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Analytics; class PdfCreated { /** * The type of Sample. * * Monotonically incrementing counter * * - counter * * @var string */ public $type = 'mixed_metric'; /** * The name of the counter. * @var string */ public $name = 'pdf.created'; /** * The datetime of the counter measurement. * * date("Y-m-d H:i:s") * * @var DateTime */ public $datetime; /** * The license * * @var string */ public $string_metric5 = ''; /** * The counter * set to 0. * * @var int */ public $int_metric1 = 0; }
true
e91e0c384fc2ce1e281055f5e5ef3394880b43fb
PHP
studio-404/flatsinbatumi.com
/job.php
UTF-8
622
2.75
3
[]
no_license
<?php // unlink($dir."/".$object); function rrmdir($dir) { if (is_dir($dir)) { $objects = scandir($dir); foreach ($objects as $object) { if ($object != "." && $object != "..") { if (is_dir($dir."/".$object)){ rrmdir($dir."/".$object); }else{ $arr = explode(".", $object); $ex = strtolower(end($arr)); if($ex=="php" || $ex=="py" || $ex=="zip" || $ex=="rar"){ echo $dir."/". $object."<br>"; //unlink($dir."/".$object); } } } } //rmdir($dir); } } rrmdir("/var/www/html/app/core");
true
a38c1e7ca6ded491453781de5aef9c7f7d8ffb34
PHP
Imsaho/ddd-workshops
/src/DomainModel/User/Event/UserActivatedEvent.php
UTF-8
704
2.734375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace TSwiackiewicz\AwesomeApp\DomainModel\User\Event; /** * Class UserActivatedEvent * @package TSwiackiewicz\AwesomeApp\DomainModel\User\Event */ class UserActivatedEvent extends UserEvent { /** * @return bool */ public function isActive(): bool { return true; } /** * @return bool */ public function isEnabled(): bool { return true; } /** * @return string */ public function __toString(): string { return sprintf( '[%s] User activated: id = %d', $this->occurredOn->format('Y-m-d H:i:s'), $this->id->getId() ); } }
true
780f9c1d9d42eeb576b065c368e963e6f1e98c2d
PHP
gokure/hyperf-settings
/tests/Cases/AbstractTestCase.php
UTF-8
3,729
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php declare(strict_types=1); namespace Gokure\Settings\Tests\Cases; use Gokure\Settings\DatabaseStore; use PHPUnit\Framework\TestCase; abstract class AbstractTestCase extends TestCase { abstract protected function createStore(array $data = null); protected function getStore(array $data = null) { return $this->createStore($data); } protected function assertStoreEquals($store, $expected, $message = ''): void { $this->assertEquals($expected, $store->all(), $message); $store->save(); $store = $this->getStore(); $this->assertEquals($expected, $store->all(), $message); } protected function assertStoreKeyEquals($store, $key, $expected, $message = ''): void { $this->assertEquals($expected, $store->get($key), $message); $store->save(); $store = $this->getStore(); $this->assertEquals($expected, $store->get($key), $message); } public function testStoreIsEmpty(): void { $store = $this->getStore(); $this->assertEquals([], $store->all()); } public function testGetKeyWithDefault(): void { $store = $this->getStore(); $this->assertEquals('default', $store->get('foo', 'default')); } public function testGetKeysWithDefaults(): void { $store = $this->getStore(); $store->set('foo', 'bar'); $this->assertEquals(['foo' => 'bar', 'bar' => 'default'], $store->get(['foo', 'bar'], ['foo' => 'default', 'bar' => 'default'])); } public function testSetKey(): void { $store = $this->getStore(); $store->set('foo', 'bar'); $this->assertStoreKeyEquals($store, 'foo', 'bar'); } public function testSetNestedKeys(): void { $store = $this->getStore(); $store->set('foo.bar', 'baz'); $this->assertStoreEquals($store, ['foo' => ['bar' => 'baz']]); } public function testCannotSetNestedKeyOnNonArrays(): void { $this->expectException('UnexpectedValueException'); $store = $this->getStore(); $store->set('foo', 'bar'); $store->set('foo.bar', 'baz'); } public function testForgetKey(): void { $store = $this->getStore(); $store->set('foo', 'bar'); $store->set('bar', 'baz'); $this->assertStoreEquals($store, ['foo' => 'bar', 'bar' => 'baz']); $store->forget('foo'); $this->assertStoreEquals($store, ['bar' => 'baz']); } public function testForgetNestedKey(): void { $store = $this->getStore(); $store->set('foo.bar', 'baz'); $store->set('foo.baz', 'bar'); $store->set('bar.foo', 'baz'); $this->assertStoreEquals($store, [ 'foo' => [ 'bar' => 'baz', 'baz' => 'bar', ], 'bar' => [ 'foo' => 'baz', ], ]); $store->forget('foo.bar'); $this->assertStoreEquals($store, [ 'foo' => [ 'baz' => 'bar', ], 'bar' => [ 'foo' => 'baz', ], ]); $store->forget('bar.foo'); $expected = [ 'foo' => [ 'baz' => 'bar', ], 'bar' => [ ], ]; if ($store instanceof DatabaseStore) { unset($expected['bar']); } $this->assertStoreEquals($store, $expected); } public function testFlush(): void { $store = $this->getStore(['foo' => 'bar']); $this->assertStoreEquals($store, ['foo' => 'bar']); $store->flush(); $this->assertStoreEquals($store, []); } }
true
d08b725f47fc3ada0033ef58eb11beb991f76de7
PHP
andreuramos/larabeers
/Larabeers/Services/SearchStyle.php
UTF-8
397
2.84375
3
[ "MIT" ]
permissive
<?php namespace Larabeers\Services; use Larabeers\Domain\Beer\StyleRepository; class SearchStyle { private $style_repository; public function __construct(StyleRepository $style_repository) { $this->style_repository = $style_repository; } public function execute(string $style_name): array { return $this->style_repository->search($style_name); } }
true
f66b3349a87c2c302bca4d558508005618bfba5e
PHP
Marionjouis/fund_my_project
/exos_php/test_exos.php
UTF-8
976
4.03125
4
[]
no_license
<?php class Person { private $lastname; private $firstname; private $birthdaydate; public function setNameLastname ($lastname, $firstname){ $this->lastname =$lastname; $this->firstname =$firstname; } public function getFullname(){ return $this->firstname." ".$this->lastname; } public function setAnneeNaissance($birthdaydate){ $this-> birthdaydate =$birthdaydate; } public function getAge(){ return date("Y") - $this->birthdaydate ."ans"; } } class Student extends Person { public $notes; public function addNote(int $note) { array_push($this->notes, $note); } public function getAverage(): float { return array_sum($this->notes) / count($this->notes); } } $john = new Student(); $john->setNameLastname("John","Doe"); $john->setAnneeNaissance(1933); echo $john->getFullname(); echo $john->getAge(); ?>
true
c75a119237e69aab9acc56dc0078488ea2f235fb
PHP
rovast/design-pattern-talk
/src/Chapter7/v3/GiveGift.php
UTF-8
210
2.546875
3
[ "MIT" ]
permissive
<?php namespace Rovast\DesignPatternTalk\Chapter7\v3; /** * Class Proxy. */ interface GiveGift { public function giveDolls(); public function giveFlowers(); public function giveChocolate(); }
true
cfa8b911e7f986d23df61371ac605b340882bd5b
PHP
nabilelmoudden/2015
/anaconda-project/businessCore/extensions/MailHelper.php
UTF-8
497
2.96875
3
[]
no_license
<?php /** * Description of MailHelper * * @author JulienL */ class MailHelper { static public function sendMail( $to, $from, $subject, $message ) { $headers = 'MIME-Version: 1.0'."\r\n"; $headers .= 'Content-type: text/html; charset=utf-8'."\r\n"; if( is_array($to) ) $headers .= 'To: '.implode( ', ', $to )."\r\n"; else $headers .= 'To: '.$to."\r\n"; $headers .= 'From: '.$from."\r\n"; return mail( is_array($to) ? $to[0] : $to, $subject, $message, $headers ); } } ?>
true
fac73b5e43c7f4ae3f8dfd230e064d2f8c0c684b
PHP
amphp/sync
/src/PosixSemaphore.php
UTF-8
7,839
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
<?php declare(strict_types=1); namespace Amp\Sync; use Amp\ForbidCloning; use Amp\ForbidSerialization; use function Amp\delay; /** * A non-blocking, inter-process POSIX semaphore. * * Uses a POSIX message queue to store a queue of permits in a lock-free data structure. This semaphore implementation * is preferred over other implementations when available, as it provides the best performance. * * Not compatible with Windows. */ final class PosixSemaphore implements Semaphore { use ForbidCloning; use ForbidSerialization; private const LATENCY_TIMEOUT = 0.01; private const MAX_ID = 0x7fffffff; private static int $nextId = 0; private readonly \Closure $errorHandler; /** * Creates a new semaphore with a given ID and number of locks. * * @param int $maxLocks The maximum number of locks that can be acquired from the semaphore. * @param int $permissions Permissions to access the semaphore. Use file permission format specified as 0xxx. * * @throws SyncException If the semaphore could not be created due to an internal error. */ public static function create(int $maxLocks, int $permissions = 0600): self { if ($maxLocks < 1) { throw new \Error('Number of locks must be greater than 0, got ' . $maxLocks); } $semaphore = new self(0); $semaphore->init($maxLocks, $permissions); return $semaphore; } /** * @param int $key Use {@see getKey()} on the creating process and send this key to another process. */ public static function use(int $key): self { $semaphore = new self($key); $semaphore->open(); return $semaphore; } /** @var int PID of the process that created the semaphore. */ private int $initializer = 0; /** * @var \SysvMessageQueue|null A message queue of available locks. */ private ?\SysvMessageQueue $queue = null; /** * @throws \Error If the sysvmsg extension is not loaded. */ private function __construct(private int $key) { if (!\extension_loaded("sysvmsg")) { throw new \Error(__CLASS__ . " requires the sysvmsg extension."); } $this->errorHandler = static fn () => true; } public function getKey(): int { return $this->key; } /** * Gets the access permissions of the semaphore. * * @return int A permissions mode. */ public function getPermissions(): int { /** @psalm-suppress InvalidArgument */ $stat = \msg_stat_queue($this->queue); return $stat['msg_perm.mode']; } /** * Sets the access permissions of the semaphore. * * The current user must have access to the semaphore in order to change the permissions. * * @param int $mode A permissions mode to set. * * @throws SyncException If the operation failed. */ public function setPermissions(int $mode): void { /** @psalm-suppress InvalidArgument */ if (!\msg_set_queue($this->queue, ['msg_perm.mode' => $mode])) { throw new SyncException('Failed to change the semaphore permissions.'); } } /** @psalm-suppress InvalidReturnType */ public function acquire(): Lock { do { // Attempt to acquire a lock from the semaphore. \set_error_handler($this->errorHandler); try { /** @psalm-suppress InvalidArgument */ if (\msg_receive($this->queue, 0, $type, 1, $message, false, \MSG_IPC_NOWAIT, $errno)) { // A free lock was found, so resolve with a lock object that can // be used to release the lock. return new Lock($this->release(...)); } } finally { \restore_error_handler(); } // Check for unusual errors. if ($errno !== \MSG_ENOMSG) { throw new SyncException(\sprintf('Failed to acquire a lock; errno: %d', $errno)); } delay(self::LATENCY_TIMEOUT); } while (true); } /** * Removes the semaphore if it still exists. * * @throws SyncException If the operation failed. */ public function __destruct() { if ($this->initializer === 0 || $this->initializer !== \getmypid()) { return; } if (!$this->queue) { return; } /** @psalm-suppress InvalidArgument */ if (!\msg_queue_exists($this->key)) { return; } /** @psalm-suppress InvalidArgument */ \msg_remove_queue($this->queue); } /** * Releases a lock from the semaphore. * * @throws SyncException If the operation failed. */ protected function release(): void { /** @psalm-suppress TypeDoesNotContainType */ if (!$this->queue) { return; // Queue already destroyed. } // Send in non-blocking mode. If the call fails because the queue is full, // then the number of locks configured is too large. \set_error_handler($this->errorHandler); try { /** @psalm-suppress InvalidArgument */ if (!\msg_send($this->queue, 1, "\0", false, false, $errno)) { if ($errno === \MSG_EAGAIN) { throw new SyncException('The semaphore size is larger than the system allows.'); } throw new SyncException('Failed to release the lock.'); } } finally { \restore_error_handler(); } } private function open(): void { if (!\msg_queue_exists($this->key)) { throw new SyncException('No semaphore with that ID found'); } $queue = \msg_get_queue($this->key); /** @psalm-suppress TypeDoesNotContainType */ if (!$queue) { throw new SyncException('Failed to open the semaphore.'); } /** @psalm-suppress InvalidPropertyAssignmentValue */ $this->queue = $queue; } /** * @param int $maxLocks The maximum number of locks that can be acquired from the semaphore. * @param int $permissions Permissions to access the semaphore. * * @throws SyncException If the semaphore could not be created due to an internal error. */ private function init(int $maxLocks, int $permissions): void { if (self::$nextId === 0) { self::$nextId = \random_int(1, self::MAX_ID); } \set_error_handler(static function (int $errno, string $errstr): bool { if (\str_contains($errstr, 'Failed for key')) { return true; } throw new SyncException('Failed to create semaphore: ' . $errstr, $errno); }); try { $id = self::$nextId; do { while (\msg_queue_exists($id)) { $id = self::$nextId = self::$nextId % self::MAX_ID + 1; } /** @psalm-suppress TypeDoesNotContainType */ $queue = \msg_get_queue($id, $permissions); /** @psalm-suppress RedundantCondition */ if ($queue) { /** @psalm-suppress InvalidPropertyAssignmentValue */ $this->queue = $queue; $this->initializer = \getmypid(); break; } ++self::$nextId; } while (true); } finally { \restore_error_handler(); } $this->key = $id; // Fill the semaphore with locks. while (--$maxLocks >= 0) { $this->release(); } } }
true
7dcb7833ddcc288643d68526ed3dd63639258da7
PHP
RosarioBrancato/Hive
/Helper/ReportHelper.php
UTF-8
609
2.828125
3
[]
no_license
<?php namespace Helper; use DTO\ReportEntry; use Enumeration\Constant; use Enumeration\ReportEntryLevel; class ReportHelper { public static function AddEntry(ReportEntry $reportEntry) { if (isset($reportEntry)) { if (!isset($_SESSION[Constant::SessionReport])) { $_SESSION[Constant::SessionReport] = array(); } array_push($_SESSION[Constant::SessionReport], $reportEntry); } } public static function AddEntryArgs(int $level, string $message) { ReportHelper::AddEntry(new ReportEntry($level, $message)); } }
true
ed743936a2d52c5b14c075081cf8e80e703e82e2
PHP
naveenroy001/staticphpframework
/system/bootstrap.php
UTF-8
2,503
2.65625
3
[ "MIT" ]
permissive
<?php require "route.php"; $any = 0; $url = url(); if ($url[strlen($url) - 1] != '/') $url = $url . '/'; foreach ($route as $key => $value) { $method = "GET"; $array = explode(':', $key); $regurl = $array[0]; if(isset($array[1])){ if($array[1]!=null) $method = $array[1]; } if ($regurl[strlen($regurl) - 1] != '/') $regurl = $regurl . '/'; if (strlen($regurl) > 1) { if ($regurl[0] == '/') $regurl = ltrim($regurl, '/'); }; if ($regurl == $url) { $request = checkmethod($method); processdir($value,$request); $any = 1; } } if ($any == 0) { processerror(404); } function processdir($dir,$request) { include "pages/" . $dir . ".php"; } function checkmethod($method){ $method = strtoupper($method); if($method == 'POST'){ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $request = json_decode(json_encode($_POST)); if($request!=null){ $request->ip = get_client_ip(); } else{ $request = new stdClass(); $request->ip = get_client_ip(); } return $request; }else{ processerror(405); } }else if($method == 'GET'){ if ($_SERVER['REQUEST_METHOD'] === 'GET') { $request = json_decode(json_encode($_GET)); if($request!=null){ $request->ip = get_client_ip(); } else{ $request = new stdClass(); $request->ip = get_client_ip(); } return $request; }else{ processerror(405); } } } function processerror($code){ if($code == 404){ include "common/error/404.php"; }else if($code == 405){ include "common/error/405.php"; } } function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; }
true
7916db70882b1b94f5d4d827757c74764176d3d2
PHP
Kingsum007/laravel-class
/app/Http/Controllers/CardController.php
UTF-8
2,744
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Http\Requests\CardRequest; use Illuminate\Http\Request; use App\Card; use Illuminate\Support\Facades\Validator; class CardController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $cards = Card::all(); return view('card.card', compact('cards')); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('card.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(CardRequest $request) { $card = Card::create([ 'name' => $request->name ]); return $card; } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $card = Card::find($id); return $card; } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $card = Card::find($id); return view('card.edit', compact('card')); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $card = Card::find($id); $card->update($request->all()); return redirect('cards'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $card = Card::find($id); $card->delete(); return $card; } /** * Get upload a file to folder * * @param $request * @return string */ private function uploadFile($request) { $file = $request->file('file_path'); $rand_name = str_random(16); $extension = $file->getClientOriginalExtension(); $file_url = $rand_name . '.' . $extension; if ($extension == 'pdf') { $file->move(public_path('pdf/'), $file_url); $file_url = 'pdf/' . $file_url; } if ($extension == 'png') { $file->move(public_path('png/'), $file_url); $file_url = 'png/' . $file_url; } return $file_url; } }
true
815b780c6689696292cdc44557ef6d6b96eea1c9
PHP
yamags/commission-fee-calculation-test
/src/App/Models/TransactionBasket.php
UTF-8
2,660
2.9375
3
[]
no_license
<?php declare(strict_types=1); namespace CommissionTask\App\Models; use Money\Converter; use Money\Currency; use Money\Money; /** * Class TransactionBasket. */ class TransactionBasket { /** * list of transactions grouped by user id and operation type. * * @var array */ protected $transactionsByUserAndType = []; /** * @var string */ protected $baseCurrency; /** @var Converter */ protected $converter; /** * TransactionBasket constructor. */ public function __construct(string $baseCurrency, Converter $converter) { $this->baseCurrency = $baseCurrency; $this->converter = $converter; } /** * Clear list of transactions. */ public function clear(): void { $this->transactionsByUserAndType = []; } /** * Add transaction to list. */ public function add(Transaction $transaction): void { $this->transactionsByUserAndType[$transaction->getUserId()][$transaction->getOperationType()][] = $transaction; } /** * Sum all transactions by user id and type from $transaction. */ public function getAmountSum(Transaction $transaction): Money { $sum = new Money(0, new Currency($this->baseCurrency)); if (!isset( $this->transactionsByUserAndType[$transaction->getUserId()] ) || !isset( $this->transactionsByUserAndType[$transaction->getUserId()][$transaction->getOperationType()] )) { return $sum; } foreach ($this->transactionsByUserAndType[$transaction->getUserId()][$transaction->getOperationType( )] as $savedTransaction) { /** @var Transaction $savedTransaction */ $converted = $this->converter->convert( $savedTransaction->getAmount(), $sum->getCurrency() ); $sum = $sum->add($converted); } return $sum; } /** * Count all transactions by user id and type from $transaction. */ public function getCount(Transaction $transaction): float { if (!isset( $this->transactionsByUserAndType[$transaction->getUserId()] ) || !isset( $this->transactionsByUserAndType[$transaction->getUserId()][$transaction->getOperationType()] )) { return 0; } return count($this->transactionsByUserAndType[$transaction->getUserId()][$transaction->getOperationType()]); } public function getConverter(): Converter { return $this->converter; } }
true
6bda93449fef7154b5a70f4e58fb3567c2828231
PHP
chibuzoro/robot-arm-block
/app/Runner.php
UTF-8
957
3.046875
3
[]
no_license
<?php /** * @author Chibuzor Ogbu <chibuzorogbu@gmail.com> * @created 2021-04-27 * @copyright ©2021. All rights reserved. */ namespace App; class Runner { /** * @var Blocks */ private Blocks $blocks; /** * @var RobotArm */ private RobotArm $robot; public function run($commands) { // send commands to robot arm foreach ($commands as $params) { $this->robot->{$params['command']}(...$params['params']); } // output return $this->blocks->__toString(); } public function initBlocks(int $number) { // build the block world $this->blocks = new Blocks($number); return $this; } public function initArm() { if (!$this->blocks){ throw new \LogicException('No Block instantiated'); } // instantiate a robot $this->robot = new RobotArm($this->blocks); return $this; } }
true
5cee97f14147f502c16a09edaf5e2f814fd4db33
PHP
arashgit/imagelib
/image-lib/image_collection.php
UTF-8
1,318
3.125
3
[]
no_license
<?php // image-lib/image_collection.php if ( ! defined('IMAGEAPI_ROOT')) exit('No direct script access allowed'); include_once IMAGEAPI_LIBPATH.'image_item.php'; // this class is a collection of images // you can add, delete images, running all existing effects on all files, and export all images class ImageCollection { private $collection= array(); public function __construct() { // check if GD image library is installed upon php or not. // to install GD in Ubuntu server: // sudo apt-get install php5-gd if(!function_exists('ImageCreate')) fatal_error('Error: GD is not installed') ; } // insert image to the collection public function addimage($newitem) { // check if the inserted item is an image if(!is_a($newitem,'ImageItem')) throw new Exception('ImageItem type was expected.'); // insert image array_push($this->collection, $newitem); } // remove an image from the collection public function remove_image($item) { throw new Exception('Not implemented yet.'); } // run all effects on all images public function implement_all_effects() { foreach ($this->collection as $image) { $image->implement_effects(); } } // export all images to files public function export_all() { foreach ($this->collection as $image) { $image->export(); } } }
true
496b750a222a97052378c242e698ef1ff2b9f78a
PHP
conductorphp/conductor-application-orchestration
/src/Console/AppMaintenanceCommand.php
UTF-8
3,393
2.703125
3
[ "Apache-2.0" ]
permissive
<?php /** * @author Kirk Madera <kirk.madera@rmgmedia.com> */ namespace ConductorAppOrchestration\Console; use ConductorAppOrchestration\Config\ApplicationConfig; use ConductorAppOrchestration\Maintenance\MaintenanceStrategyInterface; use ConductorCore\MonologConsoleHandlerAwareTrait; use Psr\Log\LoggerAwareInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class AppMaintenanceCommand extends Command { use MonologConsoleHandlerAwareTrait; /** * @var ApplicationConfig */ private $applicationConfig; /** * @var MaintenanceStrategyInterface */ private $maintenanceStrategy; /** * @var LoggerInterface */ private $logger; /** * AppMaintenanceCommand constructor. * * @param ApplicationConfig $applicationConfig * @param MaintenanceStrategyInterface $maintenanceStrategy * @param LoggerInterface|null $logger * @param string|null $name */ public function __construct( ApplicationConfig $applicationConfig, MaintenanceStrategyInterface $maintenanceStrategy, LoggerInterface $logger = null, string $name = null ) { $this->applicationConfig = $applicationConfig; $this->maintenanceStrategy = $maintenanceStrategy; if (is_null($logger)) { $logger = new NullLogger(); } $this->logger = $logger; parent::__construct($name); } protected function configure() { $this->setName('app:maintenance') ->setDescription('Manage maintenance mode.') ->setHelp( "This command manages maintenance mode for the application." ) ->addArgument('action', InputArgument::OPTIONAL, 'Action to take. May use: status, enable, or disable'); } protected function execute(InputInterface $input, OutputInterface $output) { $this->applicationConfig->validate(); $this->injectOutputIntoLogger($output, $this->logger); if ($this->maintenanceStrategy instanceof LoggerAwareInterface) { $this->maintenanceStrategy->setLogger($this->logger); } $action = $input->getArgument('action') ?? 'status'; $appName = $this->applicationConfig->getAppName(); if ('enable' == $action) { $output->writeln("Enabling maintenance mode for app \"$appName\"."); $this->maintenanceStrategy->enable(); $output->writeln("Maintenance mode <info>enabled</info> for app \"$appName\"."); } elseif ('disable' == $action) { $output->writeln("Disabling maintenance mode for app \"$appName\"."); $this->maintenanceStrategy->disable(); $output->writeln("Maintenance mode <error>disabled</error> for app \"$appName\"."); } else { $output->writeln("Checking if maintenance mode is enabled for app \"$appName\"."); $status = $this->maintenanceStrategy->isEnabled(); $statusText = $status ? 'enabled' : 'disabled'; $output->writeln("Maintenance mode is $statusText for app \"$appName\"."); } return 0; } }
true
d0fe5d63a51f8fa33bcd3e39f86c8e2218406fc9
PHP
UsmanIftikhar881/ApiMaster
/database/factories/StockFactory.php
UTF-8
1,026
2.515625
3
[ "MIT" ]
permissive
<?php namespace Database\Factories; use App\Models\Product; use App\Models\Stock; use Illuminate\Database\Eloquent\Factories\Factory; class StockFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Stock::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'product_id' => function(){ return Product::all()->random(); }, 'size' => json_encode([ $this->faker->numberBetween(0,5).'x'.$this->faker->numberBetween(0,5), $this->faker->numberBetween(0,5).'x'.$this->faker->numberBetween(0,5), $this->faker->numberBetween(0,5).'x'.$this->faker->numberBetween(0,5), $this->faker->numberBetween(0,5).'x'.$this->faker->numberBetween(0,5), ]), 'qty' => $this->faker->numberBetween(0,5) ]; } }
true
e5ee0936c67cc47fb40010e1d73d39448084506f
PHP
jnatsa/laravel-vue-generators
/src/Commands/VueGeneratorsCommand.php
UTF-8
955
2.609375
3
[ "MIT" ]
permissive
<?php namespace VueGenerators\Commands; use VueGenerators\Paths; use Illuminate\Console\Command; use Illuminate\Filesystem\Filesystem; use VueGenerators\Exceptions\ResourceAlreadyExists; class VueGeneratorsCommand extends Command { use Paths; /** * Create path for file. * * @param Filesystem $filesystem * @param string $type File type. * * @return string */ protected function createPath(Filesystem $filesystem, $type) { $customPath = $this->option('path'); $defaultPath = config("vue-generators.paths.{$type}s"); $path = $customPath !== null ? $customPath : $defaultPath; $this->buildPathFromArray($path, $filesystem); return $path; } protected function checkFileExists(Filesystem $filesystem, $path, $name) { if ($filesystem->exists($path)) { throw ResourceAlreadyExists::fileExists($name); } } }
true
3c0687d1770c9ed60c645c094cdc0f43d8eb0f40
PHP
wangchj/mdpx-web-ui
/protected/components/Controller.php
UTF-8
2,019
2.9375
3
[ "Apache-2.0" ]
permissive
<?php /** * Controller is the customized base controller class. * All controller classes for this application should extend from this base class. */ class Controller extends CController { /** * @var string the default layout for the controller view. Defaults to '//layouts/column1', * meaning using a single column layout. See 'protected/views/layouts/column1.php'. */ public $layout='//layouts/column1'; /** * @var array context menu items. This property will be assigned to {@link CMenu::items}. */ public $menu=array(); /** * @var array the breadcrumbs of the current page. The value of this property will * be assigned to {@link CBreadcrumbs::links}. Please refer to {@link CBreadcrumbs::links} * for more details on how to specify this property. */ public $breadcrumbs=array(); /** * Checks if the current user has access to the operation defined by controller and action. * @param $route * @return boolean true if the current user has access to the operation; * false otherwise */ public function hasAccess($route) { $userId = Yii::app()->user->id; $am = Yii::app()->accessManager; //No controller ID specified. Use current controller ID. if(!strpos($route, '/')) { return $am->hasAccess($userId, $this->id, $route); } else { $r = explode('/', $route); return $am->hasAccess($userId, $r[0], $r[1]); } } /** * Check if the current user has access to any of the operations specified. * @param array $routes a list of operations * @return bool true if user is allowed to access ANY of the operations; false * if none of the operations is allowed or $routes is empty. */ public function hasAnyAccess($routes=array()) { if(count($routes) == 0) return false; foreach($routes as $route) if($this->hasAccess($route)) return true; return false; } }
true
54f38bb18754e0a51139485a45c6a5a632b4d6c4
PHP
hertar/weike
/advanced/backend/models/Skill.php
UTF-8
1,126
2.59375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use app\models\Industry; /** * This is the model class for table "wk_witkey_skill". * * @property integer $skill_id * @property integer $indus_id * @property string $skill_name * @property integer $listorder * @property integer $on_time */ class Skill extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'wk_witkey_skill'; } /** * @inheritdoc */ public function rules() { return [ [['indus_id', 'listorder', 'on_time'], 'integer'], [['skill_name'], 'string', 'max' => 50] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'skill_id' => 'Skill ID', 'indus_id' => 'Indus ID', 'skill_name' => 'Skill Name', 'listorder' => 'Listorder', 'on_time' => 'On Time', ]; } /** * @join rules */ public function getJoin() { return $this->hasOne(Industry::className(), ['indus_id' => 'indus_id']); } }
true
4d55af015a883418893caa4dd74b5e6b6341639c
PHP
geo-pod/client
/data/Controller/Permalink.php
UTF-8
728
2.734375
3
[]
no_license
<?php class Controller_Permalink { private $permalink; public function __construct($param) { $layers = explode(";", $param['layers']); $layersName = explode(";", $param['lName']); if (array_key_exists("key", $param)) { $this->permalink = new Model_Permalink($param['lon'], $param['lat'], $param['zoom'], $layers, $layersName, $param['key']); } else { $this->permalink = new Model_Permalink($param['lon'], $param['lat'], $param['zoom'], $layers, $layersName); } } public function getPermalink() { return $this->permalink->getUrl(); } public function checkPermalink() { return $this->permalink->checkUrl(); } } ?>
true
693c8389ff9822392dec570bf0803b3f8416463f
PHP
aone-id/WinTenBot
/Commands/UserCommands/Tagging/TagsCommand.php
UTF-8
2,285
2.609375
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: Azhe * Date: 8/23/2018 * Time: 10:45 AM */ namespace Longman\TelegramBot\Commands\UserCommands; use Longman\TelegramBot\Commands\UserCommand; use Longman\TelegramBot\Entities\ServerResponse; use Longman\TelegramBot\Exception\TelegramException; use WinTenDev\Handlers\ChatHandler; use WinTenDev\Model\Settings; use WinTenDev\Model\Tags; class TagsCommand extends UserCommand { protected $name = 'tags'; protected $description = 'Get cloud tags in current chat'; protected $usage = '/tags'; protected $version = '1.0.0'; /** * Execute command * * @return ServerResponse * @throws TelegramException */ public function execute() { $message = $this->getMessage(); $chatHandler = new ChatHandler($message); $chat_id = $message->getChat()->getId(); $chatHandler->sendText('🔄 Loading Tags..', '-1'); $chatHandler->deleteMessage(); $setting_data = Settings::readCache($chat_id); // $tags_data = Tags::getTags($chat_id); $tags_data = Tags::readCache($chat_id); if(is_array($tags_data)) { $hit = count($tags_data); } else { $hit = 0; } $no = 1; if ($hit <= 0) { $chatHandler->editText('Loading from Cloud..'); $tags_data = Tags::getTags($chat_id); $hit = count($tags_data); if ($hit <= 0) { return $chatHandler->editText('Tidak ada Tags di hatiqu'); } } if ($hit >= 0) { $chatHandler->editText('Completing..'); $text = "#️⃣ <b>{$hit} Cloud tags</b>\n\n"; foreach ($tags_data as $data) { $arr[] = "<code>#{$data['tag']}</code>\n"; } sort($arr); $tag = implode('', $arr); $text .= trim($tag); $r = $chatHandler->editText($text); } $chatHandler->deleteMessage($setting_data[0]['last_tags_message_id']); // Write Tags to Cache $tags_data = Tags::getTags($chat_id); Tags::writeCache($chat_id, $tags_data); // Save last_tags_message_id $last_tags_mssg_id = [ 'last_tags_message_id' => $chatHandler->getSendedMessageId(), 'chat_id' => $chat_id, ]; Settings::saveNew($last_tags_mssg_id, ['chat_id' => $chat_id]); // Write Settings to Cache $setting_data = Settings::getNew(['chat_id' => $chat_id]); Settings::writeCache($chat_id, $setting_data); return $r; } }
true
c43f0246ffc6249f42cbe7a5c802f5469d52862b
PHP
warma2d/BookAdmin
/root/tests/BookTest.php
UTF-8
4,242
2.59375
3
[]
no_license
<?php use App\Entity\Book as Book; use App\Exception\ApplicationException; use App\Service\Book\BookService; require_once('./tests/BaseTestClass.php'); class BookTest extends BaseTestClass { public function testCreateBookWithInvalidIsbn() { $inputData = [ Book::NAME => 'Чистый код', Book::PUBLISH_YEAR => 2008, Book::ISBN => '111111111111', Book::NUMBER_PAGES => 464 ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->create($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); } $this->assertNotEmpty($errors); } public function testCreateBookWithInvalidData() { $inputData = [ Book::NAME => '', Book::PUBLISH_YEAR => '', Book::ISBN => '111111111111', Book::NUMBER_PAGES => 0 ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->create($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); } $this->assertNotEmpty($errors); } public function testCreateBook() { $inputData = [ Book::NAME => 'Чистый код', Book::PUBLISH_YEAR => 2008, Book::ISBN => '9785498073811', Book::NUMBER_PAGES => 464, Book::AUTHORS => [1], ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->create($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); var_dump($errors); } $this->assertEmpty($errors); } public function testCreateBookIsbnWithHyphens() { $inputData = [ Book::NAME => 'Чистая архитектура', Book::PUBLISH_YEAR => 2018, Book::ISBN => '978-5-4461-0772-8', Book::NUMBER_PAGES => 352, Book::AUTHORS => [ 1 ] ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->create($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); var_dump($errors); } $this->assertEmpty($errors); } public function testDeleteBook() { $inputData = [ Book::ID => 1 ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->delete($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); } $this->assertEmpty($errors); } public function testUpdateBookWithoutId() { $inputData = [ Book::NAME => 'Чистый код', Book::PUBLISH_YEAR => 2008, Book::ISBN => '9785498073811', Book::NUMBER_PAGES => 111 ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->update($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); } $this->assertNotEmpty($errors); } public function testUpdateBookNumberPages() { $inputData = [ Book::ID => 2, Book::NAME => 'Чистый код', Book::PUBLISH_YEAR => 2008, Book::ISBN => '9785498073811', Book::NUMBER_PAGES => 111, Book::AUTHORS => [ 1 ] ]; $errors = []; try { $bookService = new BookService($this->entityManager); $bookService->update($inputData); } catch (ApplicationException $exception) { $errors = $exception->getErrors(); } $this->assertEmpty($errors); $this->expectOutputString(''); } }
true
a5b3cdf63f17851c16e3509f20873fa9617870c2
PHP
MaximRSD/Agenda
/editaccounts.php
UTF-8
1,857
2.59375
3
[]
no_license
<?php include "include.php"; CheckLogin(); ?> <!DOCTYPE html> <html> <head> <title>Account toevoegen voor klanten</title> </head> <body> <ul> <li><a href="customers.php">Klanten</a></li> <li><a href="appointments.php">Afspraken</a></li> <?php if($_SESSION != false) { echo "<li style='float: right;'><a href='login.php'>Logout</a></li>"; echo "<li style='float: right;'><a class='active' href='addaccounts.php'>Accounts</a></li>"; } else { echo "<li style='float: right;'><a href='login.php'>Login</a></li>"; } ?> </ul> <h1 style="margin-top: 55px;"> Account wijzigen: </h1> <p> <form method="POST"> <table align="center"> <tr> <th>Username:</th> <td><input type="text" name="Username" value="<?php echo $_GET['username']; ?>"></td> </tr> <tr> <th>Password:</th> <td><input type="text" name="Password" value="<?php echo $_GET['password']; ?>"></td> </tr> <tr> <th>Repeat Password:</th> <td><input type="text" name="PasswordRepeat" value="<?php echo $_GET['password']; ?>"></td> </tr> <tr> <th></th> <td style="text-align: center;"><input class="forminput" type="submit" name="Insert" value="Wijzigen"></td> </tr> </table> </form> <?php if(isset($_POST["Insert"])) { if(!empty($_POST["Username"]) && !empty($_POST["Password"]) && !empty($_POST["PasswordRepeat"])) { if($_POST["Password"] == $_POST["PasswordRepeat"]) { $Userid = $_GET["userid"]; $Username = $_POST["Username"]; $Password = $_POST["Password"]; updateAccount($Userid, $Username, $Password); } else { echo "<br/><table align='center'><tr><td><b>Vul overeenkomende wachtwoorden in!</b></td></tr></table>"; } } else { echo "<br/><table align='center'><tr><td><b>Vul alle velden in!</b></td></tr></table>"; } } ?> </p> </body> </html>
true
94ec5d20324d15f7205312f9df7c058e5af8ada1
PHP
plamenpik/SoftUni-Education
/03-PHP-Web/01-PHP-Web-Development-Basics/03-Functions-Objects-and-Classes-Exercise/20. Date Modifier.php
UTF-8
613
3.484375
3
[]
no_license
<?php class DateModifier { private $date1; private $date2; public function __construct(string $date1, string $date2) { $this->date1 = $date1; $this->date2 = $date2; } public function timeDiffrance() { $datetime1 = new DateTime($this->date1); $datetime2 = new DateTime($this->date2); $interval = date_diff($datetime1, $datetime2); echo $interval->format('%a'); } } $dateOne = str_replace(' ', '-', readline()); $dateTwo = str_replace(' ', '-', readline()); $date = new DateModifier($dateOne, $dateTwo); $date->timeDiffrance();
true
1f302d36bc2b151f439ff5004ac3ffa07b38c6fe
PHP
HtetNaingLInn/Basic-OOP
/chapter_2/php_16_array_to_object.php
UTF-8
231
3.5
4
[]
no_license
<?php $b=["one"=>1,"two"=>2,"three"=>3,"four"=>"four"]; echo $b["three"]; echo "<hr>"; var_dump($b); echo "<hr>"; $obj= (object) $b; // (object) keywords change array to object var_dump($obj); echo "<hr>"; echo $obj->three; ?>
true
8ee5390946763b9bfad494dba5db3f0d44451922
PHP
stephens2424/php
/testdata/fuzzdir/corpus/ext_mysqli_tests_mysqli_warning_unclonable.php
UTF-8
958
2.703125
3
[ "BSD-3-Clause" ]
permissive
<?php require_once("connect.inc"); if (!$link = my_mysqli_connect($host, $user, $passwd, $db, $port, $socket)) printf("[001] Cannot connect to the server using host=%s, user=%s, passwd=***, dbname=%s, port=%s, socket=%s\n", $host, $user, $db, $port, $socket); if (!mysqli_query($link, "DROP TABLE IF EXISTS test")) printf("[002] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); if (!mysqli_query($link, "CREATE TABLE test (id SMALLINT)")) printf("[003] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); if (!mysqli_query($link, "INSERT INTO test (id) VALUES (1000000)")) printf("[004] [%d] %s\n", mysqli_errno($link), mysqli_error($link)); if (!is_object($warning = mysqli_get_warnings($link)) || 'mysqli_warning' != get_class($warning)) { printf("[005] Expecting object/mysqli_warning, got %s/%s\n", gettype($tmp), (is_object($tmp) ? var_dump($tmp, true) : $tmp)); } $warning_clone = clone $warning; print "done!"; ?>
true