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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d19594ed6c63c450113972668a6eaaf7112ac7c4 | PHP | victorfdt/theliteracycenter | /app/Http/Middleware/VerifyUserAsAdmin.php | UTF-8 | 538 | 2.71875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Middleware;
use Closure;
class VerifyUserAsAdmin
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
# $userId = $request->user()->id;
#$user = App\User::find($userId);
if($request->user() == null || !$request->user()->isAdmin()){
return redirect('/');
}
return $next($request);
}
}
| true |
d974afaa61131389c5e4315585c8d08fabcb29ae | PHP | davidgonsaga/rateable | /src/Repositories/RateRepository.php | UTF-8 | 1,575 | 2.53125 | 3 | [] | no_license | <?php
namespace Webeleven\Rateable\Repositories;
use Illuminate\Support\Facades\DB;
use Webeleven\Rateable\Models\Rate;
use Webeleven\Rateable\Interfaces\RateRepositoryInterface;
class RateRepository extends BaseRepository implements RateRepositoryInterface
{
public function save($data)
{
return Rate::create($data);
}
public function update($rate_id, array $data = [])
{
return !! Rate::where('id', '=', $rate_id)->update($data);
}
public function delete($rate_id)
{
return !! Rate::where('id', '=', $rate_id)->delete();
}
public function find($rate_id)
{
return Rate::find($rate_id);
}
public function getAll($limit = null, $skip = 0)
{
$query = Rate::query();
$query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip);
return $query->get();
}
public function getAllByResourceIdAndType($resource_id, $resource_type, $limit = null, $skip = 0)
{
$query = Rate::where('resource_id', '=', $resource_id)
->where('resource_type', '=', $resource_type);
$query = $this->applyLimitAndOffsetIfNecessary($query, $limit, $skip);
return $query->get();
}
public function getRatePointsDiscriminated($resource_id, $resource_type)
{
return Rate::select(DB::raw('rating, COUNT(id) AS quantity'))
->where('resource_id', '=', $resource_id)
->where('resource_type', '=', $resource_type)
->groupBy('rating')->get();
}
} | true |
b28a43185f4bc7e121cb96e3649686b7276ecace | PHP | adeng322/airlines-webapp | /app/database/migrations/2019_03_10_190733_create_statistics_table.php | UTF-8 | 1,452 | 2.640625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStatisticsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('statistics', function (Blueprint $table) {
$table->increments('id');
$table->string('airport_code');
$table->string('carrier_code');
$table->integer('month');
$table->integer('year');
$table->unique(['airport_code', 'carrier_code', 'month', 'year']);
$table->timestamps();
});
ini_set('memory_limit', '400M');
$file = file_get_contents(__DIR__ . "/../../resources/airlines.json");
$file_rows = json_decode($file, true);
foreach ($file_rows as $file_row) {
DB::table('statistics')->insert(
[
'airport_code' => $file_row['airport']['code'],
'carrier_code' => $file_row['carrier']['code'],
'month' => $file_row['time']['month'],
'year' => $file_row['time']['year'],
]
);
}
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('statistics');
}
}
| true |
9348dd7d19413ebc72b7690cc1fe12aa33b40dde | PHP | kavindumanaram/k_chat | /model/user.php | UTF-8 | 1,861 | 2.515625 | 3 | [] | no_license | <?php
require_once 'connection.php';
class User {
function getuserDetails(){
$conn=new Connection();
$sql="select *from user";
$conn->query($sql);
}
function getUserPassword1($userName){
$conn=new connection();
$sql="SELECT * FROM user where email='$userName'";
echo $sql;
$result=$conn->query($sql);
return $result;
}
function userLogin($userName,$password){
$conn = new connection();
$sql="SELECT * FROM user WHERE email='$userName'
AND password='$password'";
echo $sql;
$result=$conn->query($sql);
return $result;
}
function messageCount(){
$conn = new connection();
$sql="SELECT COUNT( *) AS messageCount
FROM messages";
// echo $sql;
$result=$conn->query($sql);
return $result;
}
function friendCount(){
$conn = new connection();
$sql="SELECT (COUNT( * )-1) AS friendCount
FROM user";
// echo $sql;
$result=$conn->query($sql);
return $result;
}
function onlineCount(){
$conn = new connection();
$sql="SELECT (COUNT( * )) AS friendCount
FROM user where status='2'";
// echo $sql;
$result=$conn->query($sql);
return $result;
}
function getFriends(){
$conn = new connection();
$sql="SELECT * FROM user";
// echo $sql;
$result=$conn->query($sql);
return $result;
}
function logoutInfor($user_id){
$conn=new Connection();
$date=Date('Y-m-d');
$curr_time= date("G:i:s", time()+12600-1740);
$sql="UPDATE user SET logout_date = '$date', logout_time='$curr_time',STATUS = '1' WHERE id = '$user_id'";
echo $sql;
$conn->query($sql);
}
}
?>
| true |
4729ae3acfc2949199c447f96388d3617493e56c | PHP | kingfac/kingfac | /app/Http/Livewire/Admin/Actualites.php | UTF-8 | 2,954 | 2.53125 | 3 | [] | no_license | <?php
namespace App\Http\Livewire\Admin;
use App\Models\actualite;
use Livewire\Component;
use Illiminate\Support\Facades\Storage;
use Livewire\WithFileUploads;
class Actualites extends Component
{
use WithFileUploads;
public $actualites;
public $selectedId;
public $photo;
public $titre="";
public $sous_titre="";
public $descri="";
protected $listeners = ['imgUpdate'=>'$refresh'];
public function render()
{
$this->actualites = actualite::all();
return view('livewire.admin.actualites');
}
public function resetFields(){
$this->selectedId = 0;
$this->photo = '';
$this->titre = '';
$this->sous_titre = '';
$this->descri='';
}
/* Saving record in database and in filesystem */
public function store(){
$validateactualite = $this->validate([
'titre'=>'required',
'sous_titre'=>'required',
'descri'=>'required'
]);
$this->validate([
'photo'=>'required'
]);
$record = actualite::create($validateactualite);
$this->photo->storePubliclyAs('public/actualite/', $record->id.'.png');
//$this->photos[$index]->storePubliclyAs('public/galleries/', $data->id.'.png' );
session()->flash('message', 'actualite enregistré avec succès');
$this->emit('Added');
$this->dispatchBrowserEvent('Added');
$this->resetFields();
}
public function charger($record){
$this->selectedId = $record['id'];
$this->titre = $record['titre'];
$this->sous_titre = $record['sous_titre'];
$this->descri = $record['descri'];
}
public function update(){
$validateactualite = $this->validate([
'titre'=>'required',
'sous_titre'=>'required',
'descri'=>'required'
]);
$record = actualite::find($this->selectedId);
$record->update($validateactualite);
/* update image file */
if(!empty($this->photo)){
$this->photo->storePubliclyAs('public/actualite/', $this->selectedId.'.png');
$this->emitSelf('imgUpdate');
}
session()->flash('message', 'actualite modifié avec succès');
$this->emit('Updated');
$this->dispatchBrowserEvent('Updated');
$this->resetFields();
}
public function delete(){
/* $validateactualite = $this->validate(['']) */
$record = actualite::find($this->selectedId);
$record->delete();
/* update image file */
Storage::delete('public/_actualite/'.$this->selectedId.'.png');
/* $this->photo->storePubliclyAs('public/_actualite/'.$this->selectedId.'.png'); */
session()->flash('message', 'actualite modifié avec succès');
$this->emit('Deleted');
$this->dispatchBrowserEvent('Deleted');
$this->resetFields();
}
}
| true |
7690d2ca767bbb9816c32eb0f23ea0a15b911ad8 | PHP | timber/teak | /lib/Compiler/Method/Method.php | UTF-8 | 2,435 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace Teak\Compiler\Method;
use phpDocumentor\Reflection\Php\Function_;
use Teak\Compiler\ClassList;
use Teak\Compiler\CompilerInterface;
use Teak\Compiler\Tag\Deprecated;
use Teak\Compiler\Tag\Description;
use Teak\Compiler\Tag\Link;
use Teak\Compiler\Tag\Return_;
use Teak\Compiler\Param\Table;
use Teak\Compiler\Tag\Example;
use Teak\Compiler\Tag\See;
use Teak\Compiler\Tag\Since;
use Teak\Compiler\Tag\Summary;
use Teak\Compiler\Heading;
use Teak\Reflection\MethodReflection;
/**
* Class Method
*/
class Method implements CompilerInterface
{
/**
* @var MethodReflection
*/
public $method;
/**
* ClassMethodListCompiler constructor.
*
* @param \phpDocumentor\Reflection\Php\Method|Function_ $method
*/
public function __construct($method)
{
$this->method = new MethodReflection($method);
}
/**
* Compile.
*
* @return string
*/
public function compile()
{
$contents = '';
$name = $this->method->getName();
if ($this->method->isDeprecated()) {
$name = '~~' . $this->method->getName() . '~~';
}
// Add parenthesis to mark it as a function
$name .= '()';
// Heading
$contents .= (new Heading($name, 3))->compile();
// Summary
$contents .= (new Summary($this->method->getDocBlock()))->compile();
// Deprecated tag
$contents .= (new Deprecated($this->method->getDocBlock()))->compile();
// Description
$contents .= (new Description($this->method->getDocBlock()))->compile();
// See tag
$contents .= (new See($this->method->getDocBlock()))->compile();
// Link tag
$contents .= (new Link($this->method->getDocBlock()))->compile();
// Since tag
$contents .= (new Since($this->method->getDocBlock()))->compile();
// Function definition
$contents .= (new Definition($this->method))->compile();
// Return Tag
$contents .= (new Return_($this->method))->compile();
if ($this->method->hasParameters()) {
$paramsTable = new Table($this->method->getParameters());
$contents .= $paramsTable->compile();
}
// Code Example
$contents .= (new Example($this->method->getDocBlock()))->compile();
$contents .= self::DIVIDER;
return $contents;
}
}
| true |
a99bbbddcc1fa8ca420ce42532c8081c28f2c444 | PHP | wpstarter/framework | /src/WpStarter/Wordpress/Admin/Services/ScreenOption.php | UTF-8 | 1,259 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
namespace WpStarter\Wordpress\Admin\Services;
use WpStarter\Support\Arr;
class ScreenOption
{
protected $priority=10;
static protected $booted=false;
protected $options=[];
public function __construct()
{
$this->bootIfNotBooted();
}
protected function bootIfNotBooted(){
if(static::$booted){
return ;
}
$this->boot();
static::$booted=true;
}
protected function boot(){
add_action('check_admin_referer',function($action){
if($action==='screen-options-nonce'){
add_filter('set-screen-option', [$this,'processScreenOption'] , $this->priority, 3);
}
});
}
function processScreenOption($screen_option, $option, $value) {
if (isset($this->options[$option])) {
$optionCallback=$this->options[$option];
if($optionCallback instanceof \Closure){
return $optionCallback($value);
}
return $value;
}
return $screen_option;
}
function add($options,$valueCallback=true){
foreach (Arr::wrap($options) as $option) {
$this->options[$option] = $valueCallback;
}
return $this;
}
}
| true |
3a5107c07017610d1f44e266b609d1c38394ce09 | PHP | dshafik/Squiz-Framework | /DAL/Parsers/DALCaseParser.inc | UTF-8 | 6,334 | 2.515625 | 3 | [] | no_license | <?php
/**
* DALAlterParser.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2, as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program as the file license.txt. If not, see
* <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>
*
* @package Framework
* @subpackage DAL
* @author Squiz Pty Ltd <products@squiz.net>
* @copyright 2010 Squiz Pty Ltd (ACN 084 670 600)
* @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt GPLv2
*/
require_once 'DAL/Parsers/DALQueryParser.inc';
require_once 'DAL/Parsers/DALSelectParser.inc';
require_once 'DAL/Parsers/DALWhereParser.inc';
require_once 'Libs/XML/XML.inc';
/**
* DALCaseParser.
*
* INSERT query parser.
*/
class DALCaseParser extends DALQueryParser
{
/**
* Constructor.
*
* Private to avoid instantiating the object.
* All DALBaker methods should be called statically.
*/
private function __construct()
{
}//end __construct()
/**
* Construct the CASE query from XML element.
*
* @param DomElement $xmlQuery The query element.
* @param boolean $noParent If the query element is the start of the query.
*
* @return array
* @throws Exception When parsing error occurs.
*/
public static function parse(DomElement $xmlQuery, $noParent=FALSE)
{
$query = array();
$caseTag = NULL;
if ($noParent === TRUE) {
$caseTag = $xmlQuery;
} else {
$cases = $xmlQuery->getElementsByTagName('case');
for ($i=0; $i<$cases->length; $i++) {
if ($cases->item($i)->parentNode->isSameNode($xmlQuery) === TRUE) {
// We are looking for the first case directly underneath this query.
$caseTag = $cases->item($i);
break;
}
}
}
if ($caseTag !== NULL) {
$alias = $xmlQuery->getAttribute('alias');
$query['CASE'] = array(
'CONDITIONS' => array(),
'ALIAS' => $xmlQuery->getAttribute('alias'),
);
$index = 0;
$expectWhen = TRUE;
$expectThen = FALSE;
for ($i = 0; $i < $caseTag->childNodes->length; $i++) {
$node = $caseTag->childNodes->item($i);
if ($node !== NULL && $node->nodeType === XML_ELEMENT_NODE) {
if ($expectThen === TRUE && $node->nodeName !== 'then') {
throw new Exception('Expecting then');
}
if ($expectWhen === TRUE
&& ($node->nodeName !== 'when' && $node->nodeName !== 'else')
) {
throw new Exception('Expecting when or else');
}
$innerNode = NULL;
foreach ($node->childNodes as $child) {
if ($child->nodeType !== XML_ELEMENT_NODE) {
continue;
} else {
$innerNode = $child;
break;
}
}
if ($node->nodeName === 'when') {
$expectThen = TRUE;
$expectWhen = FALSE;
$query['CASE']['CONDITIONS'][] = array(
'WHEN' => array(),
'THEN' => array(),
);
if ($innerNode->nodeName === 'select') {
$query['CASE']['CONDITIONS'][$index]['WHEN'] = DALSelectParser::parse($innerNode);
} else if ($innerNode->nodeName === 'condition') {
$query['CASE']['CONDITIONS'][$index]['WHEN'] = DALWhereParser::getWhereConditions($innerNode);
} else {
$query['CASE']['CONDITIONS'][$index]['WHEN'] = DALWhereParser::getWhereConditions($innerNode->parentNode);
}
} else if ($node->nodeName === 'then') {
$expectThen = FALSE;
$expectWhen = TRUE;
$query['CASE']['CONDITIONS'][$index]['THEN'] = array();
if ($innerNode->nodeName === 'select') {
$query['CASE']['CONDITIONS'][$index]['THEN'] = DALSelectParser::parse($innerNode);
} else {
$query['CASE']['CONDITIONS'][$index]['THEN'] = DALQueryParser::parseSingleField($innerNode);
}
$index++;
} else if ($node->nodeName === 'else') {
$query['CASE']['ELSE'] = array();
if ($innerNode->nodeName === 'select') {
$query['CASE']['ELSE'] = DALSelectParser::parse($innerNode);
} else {
$query['CASE']['ELSE'] = DALQueryParser::parseSingleField($innerNode);
}
}//end if
}//end if
}//end for
}//end if
return $query;
}//end parse()
/**
* Validates INSERT query.
*
* Throws DALParserException. Note: This validation checks required XML
* elements and attributes. It does not check if tables, columns etc
* exists in the system.
*
* @param DomElement $query The query element.
*
* @return void
* @throws DALParserException If the INSERT tag is malformed.
*/
public static function validate(DomElement $query)
{
}//end validate()
}//end class
?>
| true |
cf5bd95968944a1ea9296d866500c130f40cb105 | PHP | ASIR-CuraValera/Betanetic | /src/DatabaseBundle/Entity/Detallepedidos.php | UTF-8 | 1,159 | 2.625 | 3 | [
"BSD-3-Clause",
"MIT"
] | permissive | <?php
namespace DatabaseBundle\Entity;
/**
* Detallepedidos
*/
class Detallepedidos
{
/**
* @var string
*/
private $codigoproducto;
/**
* @var \DatabaseBundle\Entity\Pedido
*/
private $codigopedido;
/**
* Set codigoproducto
*
* @param string $codigoproducto
*
* @return Detallepedidos
*/
public function setCodigoproducto($codigoproducto)
{
$this->codigoproducto = $codigoproducto;
return $this;
}
/**
* Get codigoproducto
*
* @return string
*/
public function getCodigoproducto()
{
return $this->codigoproducto;
}
/**
* Set codigopedido
*
* @param \DatabaseBundle\Entity\Pedido $codigopedido
*
* @return Detallepedidos
*/
public function setCodigopedido(\DatabaseBundle\Entity\Pedido $codigopedido = null)
{
$this->codigopedido = $codigopedido;
return $this;
}
/**
* Get codigopedido
*
* @return \DatabaseBundle\Entity\Pedido
*/
public function getCodigopedido()
{
return $this->codigopedido;
}
}
| true |
deb428ff820621eda35af6b796df2752bde118b4 | PHP | saidaltintop/goygoy.edu | /src/GoyGoyEdu/AuthBundle/Entity/Person.php | UTF-8 | 3,886 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace GoyGoyEdu\AuthBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Person
*/
class Person
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $surname;
/**
* @var string
*/
private $mothername;
/**
* @var string
*/
private $fathername;
/**
* @var integer
*/
private $mothersecurityid;
/**
* @var integer
*/
private $fathersecurityid;
/**
* @var \GoyGoyEdu\AuthBundle\Entity\Role
*/
private $role;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Person
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* @param string $surname
* @return Person
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set mothername
*
* @param string $mothername
* @return Person
*/
public function setMothername($mothername)
{
$this->mothername = $mothername;
return $this;
}
/**
* Get mothername
*
* @return string
*/
public function getMothername()
{
return $this->mothername;
}
/**
* Set fathername
*
* @param string $fathername
* @return Person
*/
public function setFathername($fathername)
{
$this->fathername = $fathername;
return $this;
}
/**
* Get fathername
*
* @return string
*/
public function getFathername()
{
return $this->fathername;
}
/**
* Set mothersecurityid
*
* @param integer $mothersecurityid
* @return Person
*/
public function setMothersecurityid($mothersecurityid)
{
$this->mothersecurityid = $mothersecurityid;
return $this;
}
/**
* Get mothersecurityid
*
* @return integer
*/
public function getMothersecurityid()
{
return $this->mothersecurityid;
}
/**
* Set fathersecurityid
*
* @param integer $fathersecurityid
* @return Person
*/
public function setFathersecurityid($fathersecurityid)
{
$this->fathersecurityid = $fathersecurityid;
return $this;
}
/**
* Get fathersecurityid
*
* @return integer
*/
public function getFathersecurityid()
{
return $this->fathersecurityid;
}
/**
* Set role
*
* @param \GoyGoyEdu\AuthBundle\Entity\Role $role
* @return Person
*/
public function setRole(\GoyGoyEdu\AuthBundle\Entity\Role $role = null)
{
$this->role = $role;
return $this;
}
/**
* Get role
*
* @return \GoyGoyEdu\AuthBundle\Entity\Role
*/
public function getRole()
{
return $this->role;
}
/**
* @var integer
*/
private $securityid;
/**
* Set securityid
*
* @param integer $securityid
* @return Person
*/
public function setSecurityid($securityid)
{
$this->securityid = $securityid;
return $this;
}
/**
* Get securityid
*
* @return integer
*/
public function getSecurityid()
{
return $this->securityid;
}
}
| true |
95535a2c123a89eef9a032e43f4d6403b9a23c0a | PHP | quangminhnguyen/LearnPHP | /tut92.php | UTF-8 | 477 | 3.34375 | 3 | [] | no_license | <?php
// Every time the page is refresh ==> call the count function to update the text file with the counting value.
function hit_count() {
$file = fopen('count92.txt', 'r');
// Read current value in the fle count.
$current = fread($file, filesize('count92.txt'));
fclose($file);
// Increment the current value in the file.
echo $current += 1;
// rewrite the value into the file
$file = fopen('count92.txt', 'w');
fwrite($file, $current);
fclose($file);
}
?> | true |
6a97f0d44edd58ba3704cce8b2ae7b5d3191ef8f | PHP | elnva/nanodb | /src/AbstractRepository.php | UTF-8 | 3,888 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | <?php
declare(strict_types=1);
namespace midorikocak\nanodb;
use Exception;
use midorikocak\querymaker\QueryInterface;
use ReflectionException;
use function array_filter;
use function array_key_exists;
use function array_map;
use function is_array;
use function lcfirst;
use function preg_replace;
use function str_replace;
use function strtolower;
use function ucwords;
abstract class AbstractRepository implements RepositoryInterface
{
protected Database $db;
protected string $primaryKey = 'id';
protected array $foreignKeys = [];
protected string $tableName = '';
protected string $className = '';
public function __construct(Database $db)
{
$this->db = $db;
}
/**
* @throws ReflectionException
*/
public function read(string $id): Item
{
if ($id) {
$this->db->select($this->tableName)->where($this->primaryKey, $id)->execute();
} else {
$this->db->select($this->tableName)->execute();
}
return $this->className::fromArray($this->db->fetch());
}
public function readResultSet(QueryInterface $query): array
{
return ResultSet::getResultArray($this->db, $query);
}
/**
* @return Item[]
*/
public function readAll(?QueryInterface $query = null): array
{
if ($query !== null) {
$db = $this->db->query($query);
} else {
$db = $this->db->select($this->tableName);
}
$db->execute();
$items = $db->fetchAll();
return array_map(function ($item) {
$object = $this->className::fromArray($item);
if (array_key_exists($this->primaryKey, $item)) {
$object->{self::getSetter($this->primaryKey)}($item[$this->primaryKey]);
}
foreach ($this->foreignKeys as $key) {
if (array_key_exists($key, $item)) {
$object->{self::getSetter($key)}($item[$key]);
}
}
return $object;
}, $items);
}
/**
* @param Item $item
* @throws ReflectionException
*/
public function save($item): Item
{
$itemData = array_filter($item->toArray(), fn($item) => !is_array($item) && $item);
if ($item->getId() !== null) {
$id = $itemData[$this->primaryKey];
unset($itemData[$this->primaryKey]);
$this->db->update($this->tableName, $itemData)->where($this->primaryKey, $id)->execute();
return $this->read($id);
}
if ($this->db->insert($this->tableName, $itemData)->execute() === false) {
throw new Exception('Not Found.');
}
$lastInsertId = $this->db->lastInsertId();
$updatedItem = $this->db->select($this->tableName)->where($this->primaryKey, $lastInsertId)->fetch();
$item = $this->className::fromArray($updatedItem);
$item->setFromArray($updatedItem);
return $item;
}
public function remove($item): int
{
$id = $item->getId();
if ($id !== null) {
$this->db->delete($this->tableName)->where($this->primaryKey, $id)->execute();
return $this->db->rowCount();
}
return 0;
}
private static function getSetter(string $arrayKey): string
{
return 'set' . lcfirst(self::makeCamel($arrayKey));
}
private static function makeKebab($camel): string
{
return strtolower(preg_replace('%([A-Z])([a-z])%', '_\1\2', $camel));
}
private static function makeCamel($kebab, $capitalizeFirstCharacter = false): string
{
$str = str_replace('-', '', ucwords($kebab, '-'));
$str = str_replace('_', '', ucwords($str, '_'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
}
| true |
492157c21e446043557ab786c712654dbf743bd6 | PHP | MuaathAlhaddad/arabic-learning-platform | /app/Events/MessageSent.php | UTF-8 | 1,195 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Events;
use App\Tutor;
use app\Message;
use app\Student;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
/**
* Create a new event instance.
*
* @return void
*/
public $message;
public $student;
public $tutor;
public function __construct(Tutor $tutor , Student $student, Message $message)
{
$this->tutor = $tutor;
$this->student = $student;
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
$channel = "chat.{$this->tutor->id}.{$this->student->id}";
return new PrivateChannel($channel);
}
}
| true |
3c380608d79a18ca7e59c5093be80bcde5fa1144 | PHP | Seanxuyongfeng/Php | /phoneconnect/lapi/Response.php | UTF-8 | 441 | 2.75 | 3 | [] | no_license | <?php
class Response{
public static $CODE_OK = 0;
public static $CODE_ERRO = 1;
/**
* result 返回的提示码
* desc 返回的提示信息
* $data 返回的信息
*/
public static function json($code, $message='', $data = array()){
if(!is_numeric($code)){
return '';
}
$result = array(
'result'=>$code,
'desc'=>$message,
'data'=>$data
);
echo json_encode($result,JSON_UNESCAPED_UNICODE);
exit;
}
}
?> | true |
e96bf85aed71a976d8f35d0ada20f7af3ccdcd4e | PHP | misdianti/berkuliah | /protected/components/TwitterApi.php | UTF-8 | 989 | 2.84375 | 3 | [
"MIT"
] | permissive | <?php
/**
* A class representing Twitter API.
*
* @author Ashar Fuadi <fushar@gmail.com>
*/
class TwitterApi extends CComponent
{
/**
* The Twitter username of this application.
*/
public $username;
/**
* The initialization method.
*/
public function init()
{
}
/**
* Returns the JavaScript script for Twitter share.
* @param string $buttonId the id of the button of Twitter share
* @param array $message the message to be shared
* @return string the script to be used in HTML pages.
*/
public function getShareScript($buttonId, $message)
{
return
"$('#$buttonId').click(function(){" .
" window.open('https://twitter.com/share?" .
"url=" . urlencode(Yii::app()->request->hostInfo . CHtml::normalizeUrl($message['link'])) . "&" .
"text=" . urlencode($message['default_text']) . "&" .
"via=$this->username" .
" ', '" . $buttonId . "', 'status=0,toolbar=0,menubar=0,scrollbars=1,location=0,resizable=0,width=500,height=300');" .
"});";
}
} | true |
077d5cdeea26f73a3bdd13520770b50f81da331a | PHP | geisagabrielli/HealthApp | /application/app/Entity/Proc.php | UTF-8 | 2,604 | 3.09375 | 3 | [] | no_license | <?php
namespace App\Entity;
use \App\Db\localhost;
use \PDO;
class Proc{
/**
* Identificador único do procedimento
* @var integer
*/
public $id;
/**
* Nome do Procedimento
* @var string
*/
public $name;
/**
* Tipo > Procedimento ou Exame
* @var string
*/
public $typeproc;
/**
* Tipo Procedimental > Laboratorial ou Imagem
* @var string(s/n)
*/
public $typeproc1;
/**
* Método responsável por cadastrar um novo procedimento no banco
* @return boolean
*/
public function cadastrar(){
//DEFINIR A DATA
$this->data = date('Y-m-d H:i:s');
//INSERIR O NOME DO PROCEDIMENTO NO BANCO
$obDatabase = new localhost('proc');
$this->id = $obDatabase->insert([
'id' => $this->id,
'typeproc' => $this->typeproc,
'name' => $this->name,
'typeproc1'=> $this->typeproc1,
]);
//RETORNAR SUCESSO
return true;
}
/**
* Método responsável por atualizar um procedimento no banco
* @return boolean
*/
public function atualizar(){
return (new localhost('proc'))->update('id' => $this->id,[
'typeproc' => $this->typeproc,
'name' => $this->name,
'typeproc1' => $this->typeproc1,
]);
}
/**
* Método responsável por excluir um procedimento no banco
* @return boolean
*/
public function excluir(){
return (new Database('proc'))->delete('id = '.$this->id);
}
/**
* Método responsável por obter o procedimento no banco
* @param string $where
* @param string $order
* @param string $limit
* @return array
*/
public static function getProc($where = null, $order = null, $limit = null){
return (new Database('proc'))->select($where,$order,$limit)
->fetchAll(PDO::FETCH_CLASS,self::class);
}
/**
* Método responsável por buscar um procedimento com base em seu ID
* @param integer $profregister
* @return User
*/
public static function getProc($id){
return (new Database('proc'))->select('id = '.$id)
->fetchObject(self::class);
}
} | true |
153cc8bc9395fc145fa25dddedfa51c1d0e7af17 | PHP | VirgilSecurity/virgil-sdk-php | /sample/index.php | UTF-8 | 2,808 | 2.65625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
/**
* Copyright (C) 2015-2020 Virgil Security Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* (1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* (3) Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Lead Maintainer: Virgil Security Inc. <support@virgilsecurity.com>
*/
require '../vendor/autoload.php';
require 'VirgilCryptoSample.php';
// Load .env:
(new Dotenv\Dotenv('.', '.env'))->load();
// Init:
$idAlice = "alice@email.com";
$idBob = "bob@email.com";
$message = "Hello, Bob!";
try {
$vcs = new VirgilCryptoSample();
// Login as Alice. Store private key and create card
$vcs->setIdentity($idAlice);
$cAlice = $vcs->storePrivateKeyAndCreateCard();
// Login as Bob. Store private key and create card
$vcs->setIdentity($idBob);
$cBob = $vcs->storePrivateKeyAndCreateCard();
// Login as Alice. Sign and encrypt data for Bob
$vcs->setIdentity($idAlice);
$messageEncryptedForBob = $vcs->signThenEncryptData($idBob, $message);
// Login as Bob. Decrypt data and verify signature
$vcs->setIdentity($idBob);
$messageDecryptedForBob = $vcs->decryptDataThenVerifySignature($idAlice, $messageEncryptedForBob);
// Result:
var_dump(
$cAlice, $cBob, $messageEncryptedForBob,
[
$message => $messageDecryptedForBob,
"isEquals" => $message==$messageDecryptedForBob
]
);
} catch (\Exception $e) {
var_dump($e->getMessage(), $e->getCode());
}
| true |
ed188dd8e385761ed366cb6ea2be54b9a6453a01 | PHP | LuizJarduli/Projetos_Web_Tecnico | /projetos_php_mySql/Aulas etc/Upload Aula 12_03/upload.php | UTF-8 | 2,711 | 3.078125 | 3 | [] | no_license | <?php
$_UP["pasta"] = 'upload/';
$_UP["tamanho"] = 1024 * 1024 * 2; // este tamanho tem que ser informado em bytes.O php por padrão aceita até dois megabytes de tamanho de arquivos, para modificar no php.ini é a linha upload_max_filesize =2M
$_UP["extensoes"] = array('jpg','png','gif');
$_UP["renomeia"] = false;// vetor para mudar nome do arquivo(false), caso queira que o servidor mude o nome durante o processo é só definir true
$_UP["erros"][0] = "Não houve erros";
$_UP["erros"][1] = "O arquivo do upload é maior do que o limite do php";
$_UP["erros"][2] = "O arquivo ultrapassa o limite de tamanho especificado";
$_UP["erros"][3] = "O upload do arquivo foi feito parcialmente";
$_UP["erros"][4] = "Não foi feito o upload do arquivo";
if ($_FILES["arquivo"]["error"] !=0) {// super global $_FILES é responsável por recuperar arquivos, é a única super global que é uma matriz
die("não foi possével fazer upload, erro: ".$_UP["erros"][$_FILES["arquivo"]["error"]]);
exit; // para encerrar o código
}
$ext = explode('.', $_FILES["arquivo"]["name"]);// explode é uma função que divide uma string e divide entre várias strings, primeiro coloca- se o caractere delimitador
$exten = end($ext);// função end pega o ultimo valor do vetor, no caso seria a extensão do arquivo
$extensao = strtolower($exten);// strtolower tranforma tudo em minúsculo
if (array_search($extensao, $_UP["extensoes"]) === false) { // array_search, procura o que voce quiser dentro de um vetor, seus parametros são : o vetor qu esta guardando o arquivo e o vetor que quero pesquisar as extensões, tres sinais de igualdade significa que se é igual e do mesmo tipo de dados.
echo "Envie arquivos com as seguintes extensões: jpg, png ou gif";
exit;
}
if ($_UP["tamanho"] < $_FILES["arquivo"]["size"]) {
echo "O arquivo enviado é maior que dois megas(2MB)";
exit;
}
if ($_UP["renomeia"] == true) {
$nome_final =time()."jpg"; // time() = pega a hora, minutos, segundos. Ano, Mês e dia tambem
} else {
$nome_final = $_FILES["arquivo"]["name"];// $_FILES["arquivo"]["name"] ele guarda o nome completo do arquivo no servidor neste caso
}
if (move_uploaded_file($_FILES["arquivo"]["tmp_name"], $_UP["pasta"].$nome_final)) { // detalhe importante é colocar move_upload dentro de um if(se), move_upload precisa de dois parâmetros -> o lugar onde esta(local temporário) e o lugar para onde irá(local de destino)
echo "Upload efetuado com sucesso!<br/>";
echo '<a href="'.$_UP["pasta"].$nome_final.'">Clique aqui para acessar o arquivo<a/><br/><br/>';
echo '<a href="apagar.php?nome='.$_UP["pasta"].$nome_final.'">Apagar<a/>';
} else{
echo "Não foi possível enviar o arquivo, tente novamente";
}
?> | true |
5a1e461ccbf2702c03cd06f8b188b3d0ccf02784 | PHP | kunsang/Klatschmohn | /include/include/metaboxes/ThemeMetabox.php | UTF-8 | 1,005 | 2.59375 | 3 | [
"MIT"
] | permissive | <?php
class ThemeMetabox {
public $name = 'Price Table';
public $title;
public function getId() {
return '';
}
public function __construct() {
$this->title = HONEY_THEME_NAME.' - '.$this->name;
}
function getOptions() {
return array();
}
public function getValue($data, $value) {
if (isset($data[$value]))
{
return $data[$value];
}
return null;
}
public function form() {
global $post;
$data = get_post_meta($post->ID, 'theme_metabox', true);
$options = $this->getOptions();
foreach($options as $key => $option) {
$options[$key]['name'] = 'metabox['.$this->getId().']['.$key.']';
}
echo '<div id="framework-inc">';
$elements = new ThemeElements($options, new ThemeSettings($data[$this->getId()]));
echo $elements->render();
echo '</div>';
}
}
?>
| true |
b12c394a5db6a9852ee43399952b83ee74fa884e | PHP | amin007/v2 | /Aplikasi/Kelas/Kitab/Kawal.php | UTF-8 | 2,401 | 2.734375 | 3 | [] | no_license | <?php
namespace Aplikasi\Kitab; //echo __NAMESPACE__;
class Kawal
{
#==================================================================================================
function __construct()
{
//echo '<br>class Kawal';
$this->papar = new \Aplikasi\Kitab\Papar();
}
#==================================================================================================
#--------------------------------------------------------------------------------------------------
public function jemaahTaskil($nama)
{
//echo '<hr><kbd>Nama class :' . __METHOD__ . '</kbd><hr>';
//$this->semakPembolehubah($nama,'nama');
list($tanya,$tanda,$Nama) = $this->semakPencam($nama);
if (file_exists($tanya))
{
$tanyaNama = '\\Aplikasi\Tanya\\' . $Nama . '_Tanya';
//echo '<hr><kbd>$tanyaNama->' . $tanyaNama . '</kbd><hr>';
if(class_exists($tanyaNama))
$this->tanya = new $tanyaNama();
else
{
$amaran = 'class ' . $tanyaNama . ' tidak wujud tetapi fail '
. $tanya . ' wujud.';
Peta2::classTanyaTidakWujud($amaran);
//trigger_error("Tidak boleh muatkan class: $tanyaNama", E_USER_WARNING);
//exit();
}
}//*/
}
#--------------------------------------------------------------------------------------------------
function semakPencam($nama)
{
$failTanya = GetMatchingFiles(GetContents(TANYA),$nama . '_tanya.php');
$tanya = $failTanya[0];
$Nama = huruf('Besar_Depan', $nama);
$tanda = 'fail ' . $nama . '_tanya tidak wujud';
/*echo '<br> class Kawal :: $nama : ' . $nama . '|';
echo '$Nama->' . $Nama . '|TANYA->' . TANYA . '';
echo '<pre>$failTanya->'; print_r($failTanya); echo '</pre>';
echo '$tanya->' . $tanya . '<br>';
//*/
return array($tanya,$tanda,$Nama);
}
#--------------------------------------------------------------------------------------------------
public function semakPembolehubah($senarai,$jadual,$p='0')
{
echo '<pre style="background:#fff">$' . $jadual . '=><br>';
if($p == '0') print_r($senarai);
if($p == '1') var_export($senarai);
echo '</pre>';//*/
//$this->semakPembolehubah($ujian,'ujian',0);
#http://php.net/manual/en/function.var-export.php
#http://php.net/manual/en/function.print-r.php
}
#--------------------------------------------------------------------------------------------------
#==================================================================================================
} | true |
faf54b98078659994a490060ca3d0b8426ab2237 | PHP | starti-tecnologia/mini-fwk | /src/Console/Command/MakeWorkerCommand.php | UTF-8 | 1,709 | 2.78125 | 3 | [] | no_license | <?php
namespace Mini\Console\Command;
use Commando\Command as Commando;
class MakeWorkerCommand extends AbstractCommand
{
/**
* @return string
*/
public function getName()
{
return 'make:worker';
}
/**
* @return string
*/
public function getDescription()
{
return 'Make a worker class';
}
/**
* @param Commando $commando
*/
public function setUp(Commando $commando)
{
$commando->option('name')
->describedAs('Worker name, example: "SendEmail"')
->required();
$commando->option('sleepTime')
->describedAs('Interval between executions, in seconds')
->defaultsTo(10);
}
/**
* @param Commando $commando
*/
public function run(Commando $commando)
{
$path = app()->get('Mini\Kernel')->getWorkersPath();
$neededPath = $path . '/scanned';
if (! is_dir($neededPath)) {
shell_exec('mkdir -p ' . $neededPath);
}
$className = ucwords($commando['name']) . 'Worker';
$file = $path . DIRECTORY_SEPARATOR . $className . '.php';
$replaces = [
'ClassNamePlaceholder' => $className,
'WorkerNamePlaceholder' => $commando['name'],
'SleepTimePlaceholder' => $commando['sleepTime'] * 1000
];
$template = file_get_contents(__DIR__ . '/Templates/WorkerTemplate.php');
file_put_contents(
$file,
str_replace(array_keys($replaces), array_values($replaces), $template)
);
$this->write('Worker file created at ' . $file, 'green');
(new WorkerCommand)->scanWorkers();
}
}
| true |
78d9dc95d4a04d7f23c2e93acf75549a51e880b8 | PHP | information-machine/information-machine-api-php | /src/Models/Cart.php | UTF-8 | 2,471 | 3.15625 | 3 | [
"MIT"
] | permissive | <?php
/*
* InformationMachineAPILib
*
*
*/
namespace InformationMachineAPILib\Models;
use JsonSerializable;
/**
* @todo Write general description for this model
*/
class Cart implements JsonSerializable {
/**
* @todo Write general description for this property
* @required
* @maps cart_id
* @var uuid|string $cartId public property
*/
public $cartId;
/**
* @todo Write general description for this property
* @required
* @maps cart_name
* @var string $cartName public property
*/
public $cartName;
/**
* @todo Write general description for this property
* @required
* @maps cart_items
* @var CartItem[] $cartItems public property
*/
public $cartItems;
/**
* @todo Write general description for this property
* @required
* @maps created_at
* @var string $createdAt public property
*/
public $createdAt;
/**
* @todo Write general description for this property
* @required
* @maps updated_at
* @var string $updatedAt public property
*/
public $updatedAt;
/**
* Constructor to set initial or default values of member properties
* @param uuid|string $cartId Initialization value for the property $this->cartId
* @param string $cartName Initialization value for the property $this->cartName
* @param array $cartItems Initialization value for the property $this->cartItems
* @param string $createdAt Initialization value for the property $this->createdAt
* @param string $updatedAt Initialization value for the property $this->updatedAt
*/
public function __construct()
{
if(5 == func_num_args())
{
$this->cartId = func_get_arg(0);
$this->cartName = func_get_arg(1);
$this->cartItems = func_get_arg(2);
$this->createdAt = func_get_arg(3);
$this->updatedAt = func_get_arg(4);
}
}
/**
* Encode this object to JSON
*/
public function jsonSerialize()
{
$json = array();
$json['cart_id'] = $this->cartId;
$json['cart_name'] = $this->cartName;
$json['cart_items'] = $this->cartItems;
$json['created_at'] = $this->createdAt;
$json['updated_at'] = $this->updatedAt;
return $json;
}
} | true |
dc4e36b2f82e7fb58c6080d1433105938834455a | PHP | amstrad/backstarter | /database/migrations/2018_09_15_000000_create_users_table.php | UTF-8 | 1,516 | 2.578125 | 3 | [] | no_license | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 40);
$table->string('lastname', 40)->nullable();
$table->string('username', 40);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('mobile', 40)->nullable();
$table->string('description', 200)->nullable();
$table->string('image', 200)->nullable();
$table->boolean('active')->default(1);
$table->integer('idrol')->unsigned();
$table->foreign('idrol')->references('id')->on('roles');
$table->rememberToken();
$table->timestamps();
});
DB::table('users')->insert([
'name' => 'Boss',
'lastname' => 'Master',
'username' => 'Admin',
'email' => 'admin@email.com',
'password' => bcrypt('1234'),
'idrol' => 1
]);
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
| true |
f2ab2e83ac9cabbe6f66c64578d25561e64456e3 | PHP | meiryanne/OrdemServico | /app/Repositories/TelefoneRepository.php | UTF-8 | 311 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Repositories;
use App\Models\Telefone;
class TelefoneRepository extends Repository
{
public function __construct(Telefone $telefone)
{
$this->model = $telefone;
}
public function find($id)
{
return $this->model->where('cod_cl', $id)->first();
}
}
| true |
41ca0fc8e0536e39f11045ebbe0102713210e5e1 | PHP | madayo/serenium-webdriver-template | /tests/Pages/Home.php | UTF-8 | 694 | 2.53125 | 3 | [] | no_license | <?php
namespace Tests\Pages;
use Facebook\WebDriver\WebDriverExpectedCondition;
/**
* PageObjects<br>
* HOME
*/
class Home extends \Tests\Pages\Contracts\Page
{
private const SEARCH_INPUT_ID = 'srchtxt';
private const SEARCH_SUBMIT_ID = 'srchbtn';
/** {@inheritdoc} */
protected $title = 'Yahoo! JAPAN';
/** {@inheritdoc} */
protected $url = 'https://www.yahoo.co.jp/';
/**
* 検索を実行する
* @return \Pages\Services\SeachResult
*/
public function search($search)
{
$this->type(self::SEARCH_INPUT_ID, $search)
->click(self::SEARCH_SUBMIT_ID);
return new SearchResult($this->driver, $search);
}
}
| true |
65ae29a17a64898caa63a1bd68a5691ac6acf547 | PHP | ShaneRich5/levi-backend | /app/Http/Controllers/OrganizationController.php | UTF-8 | 3,457 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\Address;
use App\Models\Church;
use App\Models\DistrictOffice;
use App\Models\NationalOffice;
use App\Models\Organization;
use Illuminate\Http\Request;
use App\Http\Requests\StoreOrganization;
class OrganizationController extends Controller
{
protected $organization;
protected $districtOffice;
protected $nationalOffice;
protected $church;
public function __construct(Organization $organization, NationalOffice $nationalOffice, DistrictOffice $districtOffice, Church $church)
{
$this->organization = $organization;
$this->nationalOffice = $nationalOffice;
$this->districtOffice = $districtOffice;
$this->church = $church;
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$organizations = $this->organization->get();
$nationalOffices = $this->nationalOffice->get();
$districtOffices = $this->districtOffice->get();
$churches = $this->church->get();
return response()->json([
'organizations' => $organizations,
'district_offices' => $districtOffices,
'national_offices' => $nationalOffices,
'churches' => $churches
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreOrganization $request)
{
$address = new Address;
$address->street = $request->street;
$address->parish = $request->parish;
$address->country = $request->country;
$address->save();
$organization = new Organization;
$organization->name = $request->name;
$organization->save();
$organization->addresses()->attach($address);
$types = $request->types;
return $organization;
}
/**
* Display the specified resource.
*
* @param \App\Models\Organization $organization
* @return \Illuminate\Http\Response
*/
public function show(Organization $organization)
{
return response()->json(['organization' => $organization]);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Organization $organization
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Organization $organization)
{
dd($request->all());
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Organization $organization
* @return \Illuminate\Http\Response
*/
public function destroy(Organization $organization)
{
//
}
public function reports($id)
{
$organization = Organization::find($id);
$result = [];
$church = $organization->church()->first();
$districtOffice = $organization->districtOffice()->first();
$nationalOffice = $organization->nationalOffice()->first();
if ($church != null) {
$result['church_reports'] = $church->churchReports()->get();
}
if ($districtOffice != null) {
$result['district_reports'] = $districtOffice->districtReports()->get();
}
return $result;
}
}
| true |
9f469fc657adb0ff446605e4023d55b4cd1c337c | PHP | offbeatwp/framework | /src/Components/ComponentInterfaceTrait.php | UTF-8 | 352 | 2.53125 | 3 | [] | no_license | <?php
namespace OffbeatWP\Components;
trait ComponentInterfaceTrait {
public function render($settings)
{
$component = container()->make($this->componentClass);
if (is_array($settings)) {
$settings = (object)$settings;
}
return container()->call([$component, 'render'], [$settings]);
}
} | true |
ae917be71e796ed1fa3ee346c5affe85079bac26 | PHP | RomainSimplon/Compar_operator | /tp_final_poo/interface_utilisateur/class/TourOperator.php | UTF-8 | 1,528 | 3.171875 | 3 | [] | no_license | <?php
class TourOperator {
private $id;
private $name;
private $grade;
private $link;
private $is_premium;
private $image;
private $imagewb;
public function __construct(array $donnees)
{
$this->hydrate($donnees);
}
public function hydrate(array $donnees)
{
foreach ($donnees as $key => $value)
{
$method = 'set'.ucfirst($key);
if(method_exists($this, $method))
{
$this->$method($value);
}
}
}
public function setId($id){
$this->id = $id;
}
public function getId(){
return $this->id;
}
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
public function setGrade($grade){
$this->grade = $grade;
}
public function getGrade(){
return $this->grade;
}
public function setLink($link){
$this->link = $link;
}
public function getLink(){
return $this->link;
}
public function setIs_premium($is_premium){
$this->is_premium = $is_premium;
}
public function getIsPremium(){
return $this->is_premium;
}
public function setImage($image){
$this->image = $image;
}
public function getImage(){
return $this->image;
}
public function setImageWb($imagewb){
$this->imagewb = $imagewb;
}
public function getImageWb(){
return $this->imagewb;
}
} | true |
d02dea7237a433c9c4fe609731b12ebf2263d493 | PHP | udotb/Niche-Practice | /Modules/User/Database/Migrations/2021_01_19_142212_create_notifications.php | UTF-8 | 1,172 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateNotifications extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
// foreign relationship of users table.
$table->integer('sender'); // admin/system/superadmin
$table->integer('receiver'); // user
$table->text('message')->nullable();
$table->integer('parent')->unsigned()->nullable(); //new
$table->foreign('parent')->references('id')->on('notifications');
$table->string('action')->nullable()->comment('reply_awaiting, set_schedule'); //new
$table->tinyInteger('read')->default(0); //new
$table->integer('business_id')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('');
}
}
| true |
84859847dd0b55e6c43057c1a4a6117efda45f66 | PHP | Xqf5683/YB | /YB_homework/G_sn_work/Work/1.php | UTF-8 | 719 | 4.40625 | 4 | [] | no_license | 作业
1.编写一个带参数函数,函数判断参数大于'a'输出a,大于e输出e,其他情况输出ok
2.编写一个带参数函数,判断参数大于2输出"大于2",否则输出“小于2”,格式要用“ ($a>$b)?"a大于b":"a不大于b"; ”形式
3.写一个例子,利用foreach遍历输出一个数组中的每一个值
<?php
if($a>'a')
echo"a";
else if($a>'e')
echo"e";
else
echo"ok";
?>
<?php
if($a>2)
echo"大于2";
if($a<=2)
echo"小于2";
?>
<?php
$a = array (1, 2, 3, 5);
foreach ($a as $v)
{
print "\$a的数组的当前值为:{$v} <br>";
}
$b = array ('a'=>1, 'b'=> 2, 'c'=> 3, 'd'=>17);
foreach ($b as $i => $v)
{
echo "{$i} => {$v}<br>";
}
?>
| true |
371e05e09ddb9ddd7acedded02a4dc3ceb04f6dd | PHP | bilalyasin1616/laravel-template | /api-template/app/Http/Controllers/UserController.php | UTF-8 | 1,319 | 2.609375 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\ResponseModel;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class UserController extends Controller
{
public function Signup(Request $request){
$user = User::Create($request->input());
return response()->json(new ResponseModel($user,"User inserted successfully",200));
}
public function Signin(Request $request){
$user = User::where('email',$request->email)->where('password',$request->password)->First();
if ($user==null)
return response()->json(new ResponseModel(null,"User not exists",500));
$credentials = $request->only('email', 'password');
dd(JWTAuth::fromUser($user));
return response()->json(new ResponseModel($user,"User signin successfully",200));
}
public function GetAll(){
$users = User::All();
return response()->json(new ResponseModel($users,"Retrieved users successfully",200));
}
public function Get(Request $request){
$user = User::Find($request->id);
if ($user!=null)
return response()->json(new ResponseModel($user,"Retrieve user successfully",200));
return response()->json(new ResponseModel($user,"User not found",500));
}
} | true |
c0bb07c07e3d4cf363c89c6fb1d354b8183b135e | PHP | britneysiwu/Projek-UAS-Pemrograman-Web | /index.php | UTF-8 | 1,412 | 2.640625 | 3 | [] | no_license | <?php
require 'functions.php';
$cards = query("SELECT * FROM cards
ORDER BY RAND()
LIMIT 1;");
session_start();
//menghalangi user pindah ke halaman upload apabila user belum berhasil login
if( !isset($_SESSION["login"]) ) {
header("Location: login2.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width", height=device-height, initial-scale=1>
<title>Projek UAS</title>
<link href="instyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php foreach( $cards as $row ) : ?>
<div class="container">
<h1 class="title">MEMORIZE HELPER</h1>
<div class="term">
<h3><?= $row["istilah"]; ?></h3>
</div>
<div class="definition">
<h3><?= $row["definisi"]; ?></h3>
</div>
<div class="button">
<button class="check">Lihat Jawaban</button>
<button class="hide">Sembunyikan</button>
<!-- <button class="col">Ganti Warna</button> -->
<form actions="" method="post"><button type="submit" name="submit" class="next">Selanjutnya</button></form>
<button class="back"><a href ="home2.php">Kembali</button>
</div>
<?php endforeach; ?>
</div>
<script src="script2.js"></script>
</body>
</html> | true |
316234a8da53ede4b9a57f71fcbf6f54b886b59f | PHP | ziopod/Tanuki-core | /classes/Model/Page.php | UTF-8 | 1,756 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php defined('SYSPATH') OR die ('No direct script access');
/**
* # Page Model
*
* Model for Tanuki page
*
* @package Tanuki
* @category Model
* @author Ziopod <ziopod@gmail.com>
* @copyright (c) 2013-2014 Ziopod
* @license http://opensource.org/licenses/MIT
**/
class Model_Page extends Flatfile {
/**
* Apply filter on data
**/
public function filters()
{
return array(
'excerpt' => array(
array('Flatfile::Markdown'),
),
'content' => array(
array('Flatfile::Markdown'),
),
'credit' => array(
array('json_decode'),
),
'license' => array(
array('json_decode'),
),
'sections' => array(
array(array($this, 'load_parts'), array(':value', 'sections')),
),
);
}
/**
* Return specifics data
**/
public function url()
{
return URL::base(TRUE, TRUE) . $this->slug;
}
/**
* Load adittionnal content part
*
* @param string $parts part name or list of part names
* @param string $sub_directory subdirectory name
*
* @return array
**/
public function load_parts($parts, $subcategory = NULL)
{
$parts = func_get_arg(0);
$sub_directory = func_get_arg(1);
$sub_directory = $sub_directory ? $sub_directory . '/' : NULL;
$result = array();
if ( strpos($parts, ',') === FALSE)
{
// Just one entry
try
{
$result[] = new Model_Page($sub_directory . $parts);
}
catch(Kohana_exception $e)
{
Log::instance()->add(Log::WARNING, $e->getMessage());
}
}
else
{
// Multiples entries
foreach (explode(',', $parts) as $part)
{
try
{
$result[] = new Model_Page($sub_directory . $part);
}
catch(Kohana_exception $e)
{
Log::instance()->add(Log::WARNING, $e->getMessage());
}
}
}
return $result;
}
} | true |
1d2a31037417a344bacb79585024ef332c06df70 | PHP | matkro96/moje-projekty | /JS-przyklady/Untitled Folder/02 Sortable connectWith multiple/classes/classes.php | UTF-8 | 1,134 | 3.03125 | 3 | [] | no_license | <?php
class Display
{
private $db;
function __construct($db) {
$this->db = $db;
}
public function lots() {
$output = '';
$stmt = $this->db->query("SELECT * FROM parts WHERE quantity = 'lots'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output .= '<li id="' . $row['id'] . '">' . $row['name'] . '</li>';
}
return $output;
}
public function enough() {
$output = '';
$stmt = $this->db->query("SELECT * FROM parts WHERE quantity = 'enough'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output .= '<li id="' . $row['id'] . '">' . $row['name'] . '</li>';
}
return $output;
}
public function none() {
$output = '';
$stmt = $this->db->query("SELECT * FROM parts WHERE quantity = 'none'");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output .= '<li id="' . $row['id'] . '">' . $row['name'] . '</li>';
}
return $output;
}
}
?> | true |
76207566a7b2056dd22a9fae93d2614cfa3995d3 | PHP | Akachukwu007/myPorfolio | /selectPage.php | UTF-8 | 2,187 | 3.09375 | 3 | [] | no_license |
<?php
include('conn.php');
if(isset($_GET['id'])){
$id= $_GET['id'];
}
$sql = mysqli_query($conn, "SELECT * FROM portfolioForm order by
id desc") or die ("Could not select portfolioForm" .mysqli_error($conn));
$count = 0; // use $count to identify the first value
//check if something is in the database
if(mysqli_num_rows($sql)>$count){
//fetch each array
while($row= mysqli_fetch_assoc($sql))
{
//select whatever is in the table
$id[] = $row["id"];
$name[]= $row["name"];
$email[]= $row['email'];
$sub[]= $row["subject"];
$message[]=$row['message'];
$date[]= date('j, F, Y', strtotime($row['date']));
$count++;
}
}
$sn=1;
?>
<!doctype html>
<html>
<head>
</head>
<body>
<table width="300px" style="border:solid 1px black">
<tr>
<td width="85" style="border:solid 1px black">SN </td>
<td width="496" style="border:solid 1px black">Name </td>
<td width="114" style="border:solid 1px black">Email </td>
<td width="114" style="border:solid 1px black">Subject </td>
<td width="500" style="border:solid 1px black">Message </td>
<td width="150" style="border:solid 1px black">date </td>
<td width="150" style="border:solid 1px black"> </td>
<td width="150" style="border:solid 1px black"> </td>
<td width="150" style="border:solid 1px black"> </td>
</tr>
<?php for($s=0; $s<$count; $s++){?>
<tr>
<td style="border:solid 1px black" ><?php echo $sn++ ?></td>
<td style="border:solid 1px black" ><?php echo $name[$s]?> </td>
<td style="border:solid 1px black" ><?php echo $email[$s]?> </td>
<td style="border:solid 1px black" ><?php echo $sub[$s]?> </td>
<td style="border:solid 1px black" ><?php echo $message[$s]?> </td>
<td style="border:solid 1px black" ><?php echo $date[$s]?> </td>
<td style="border:solid 1px black" ><a href="editpage.php?id=<?php echo $id[$s]?>">Edit</a> </td>
<td style="border:solid 1px black" id="del" onClick="alert('DELETED')">
<a href="select.php? id=<?php echo $id[$s]?>">Delete</a> </td>
<td style="border:solid 1px black"><a href="viewPage.php?id=<?php echo $id[$s] ?>">View </a></td>
</tr>
<?php }?>
</table>
</body>
</html> | true |
11a3f5a0590ffc0830bdc8915751e0e41be02c9f | PHP | smaloron/citation-test | /test-pdo.php | UTF-8 | 888 | 3.578125 | 4 | [] | no_license | <?php
// Importation de la bibliothèque perso pdo.php
require "lib/pdo.php";
// Test de la connexion
try {
$connexion = getPDO();
echo "ça marche <br>";
// Requête sur la base de données
$sql = "SELECT * FROM citations";
$query = $connexion->query($sql);
// Récupération des données ligne à ligne
$data = $query->fetch();
var_dump($data);
echo "<br>";
$data = $query->fetch();
var_dump($data);
// Récupération de toutes les données
echo "<pre>";
$data = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($data);
echo "</pre>";
// Afficher les données de $data (juste la colonne texte) dans une liste à puce
echo "<ul>";
foreach($data as $citation){
echo "<li>". $citation['texte']. "</li>";
}
echo "</ul>";
} catch(Exception $error){
echo $error->getMessage();
}
| true |
2a7d3f7e42aa0770250eb3aa0377c65ae0dcdf4b | PHP | piraanjung/sirimongkol_new | /migrations/m171225_140146_create_instalmentcostdetails_table.php | UTF-8 | 1,091 | 2.546875 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
use yii\db\Migration;
/**
* Handles the creation of table `instalmentcostdetails`.
*/
class m171225_140146_create_instalmentcostdetails_table extends Migration
{
/**
* @inheritdoc
*/
public function up()
{
$this->createTable('instalmentcostdetails', [
'id' => $this->primaryKey(),
'instalment_id'=> $this->integer()->notNull(),
'contructor_id' => $this->integer()->notNull(),
'house_id' => $this->integer()->notNull(),
'workclassify_id' => $this->integer()->notNull(),
'worktype_id' => $this->integer()->notNull(),
'money_type_id' =>$this->integer()->notNull(),
'amount' => $this->float()->notNull(),
'summoney_id' => $this->integer()->notNull(),
'saver_id' =>$this->integer()->notNull(),
'create_date' => $this->dateTime(),
'update_date' => $this->dateTime()
]);
}
/**
* @inheritdoc
*/
public function down()
{
$this->dropTable('instalmentcostdetails');
}
}
| true |
25b6ea92946545000f88bb424d5ab5e8adb393a7 | PHP | IRramanovich/ubertracker | /app/Cars.php | UTF-8 | 2,423 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cars extends Model
{
protected $table = 'Cars';
public $timestamps = false;
protected $fillable = ['id', 'car_gov_number', 'car_model', 'production_year', 'buy_date', 'car_bloked', 'car_code'];
static public function getAllCars(){
return Cars::All();
}
static public function getAllBlockCars(){
return Cars::where('car_bloked', 1)->get();
}
static public function getAllActiveCars(){
return Cars::where('car_bloked', 0)->get();
}
static public function getCarByNumber($number){
$number = str_replace(' ','',$number);
$number = str_replace('-','',$number);
$number = str_replace('BY','',$number);
$car_code = strtolower($number);
$car = Cars::where('car_code',$car_code)->first();
if (!is_null($car)) {
return $car;
}
$car_code = str_replace('СА','ca',$car_code);
$car_code = str_replace('РН','ph',$car_code);
$car = Cars::where('car_code',$car_code)->first();
return $car;
}
static public function getIdAndNumber(){
$response = [];
$cars = Cars::getAllActiveCars();
foreach ($cars as $car){
$response[$car->id] = $car->car_gov_number;
}
return $response;
}
public function addCar($request){
$this->car_gov_number = $request->gov_number;
$this->car_model = $request->model;
$this->production_year = $request->year_productions;
$this->buy_date = $request->buy_date;
$this->save();
Cars::updateCarCode();
}
static public function blockCar($id){
Cars::where('id',$id)
->update(['car_bloked' => 1]);
}
static public function unblockCar($id){
Cars::where('id',$id)
->update(['car_bloked' => 0]);
}
static public function updateCarCode(){
$cars = Cars::All();
$result = [];
foreach ($cars as $car){
$carCode = $car->car_gov_number;
$first = substr($carCode, 0, 4);
$last = substr($carCode, -1, 1);
$middle = strtolower(substr($carCode, -4, 2));
$carCode = $first.$middle.$last;
$car->car_code = $carCode;
array_push($result, $car->save());
}
return $result;
}
}
| true |
fe60f8315449773afbaadc052b39ca7fa3de433d | PHP | hugdru/LBAW | /ltw/ltw-poll/codeIncludes/https.php | UTF-8 | 747 | 2.609375 | 3 | [] | no_license | <?php
// Set default_charset = "utf-8"; in php.ini if we have access
// Avoid browser automatic charset detection which may interpret
// certain strings as malicious code for XSS attacks, for instance
// if an attacker sends a byte sequence as utf-7, the html-entities
// won't detect it and hence escape them.
header('Content-Type: text/html; charset=utf-8');
ini_set('default_charset', 'utf-8'); // Some functions are aware of this value
$use_sts = true;
if ($use_sts && isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
header('Strict-Transport-Security: max-age=31536000');
} else if ($use_sts) {
header(
'Location: https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'],
true, 301
);
exit();
}
?>
| true |
65be8f31ab03cf20c7e84e4993d490adc87039a7 | PHP | pazzitiv/lesson-5 | /index.php | UTF-8 | 600 | 2.9375 | 3 | [] | no_license | <?php
require __DIR__ . '/vendor/autoload.php';
use Monad\Monad;
use \Monad\Stack;
use Notations\Polish;
use SortStation\Station;
$getString = function (string $item) {
$input = $item . fgets(STDIN);
return $input;
};
$IO = new Monad();
$formula = $IO->apply('')
->map($getString);
$Calc = new Monad();
$result = $Calc->apply((string)$formula)
->map(fn($item) => eval("return {$item};"));
$Polish = (clone $formula)
->map(fn($item) => Station::sort($item))
->map(fn($item) => Polish::notation($item));
echo "Formula: {$formula}";
echo "Polish: {$Polish} = {$result}\n"; | true |
6c5245d7284b00d6991bb315a9a1f3888b3a44ea | PHP | emanuele78/mybnb | /app/ReservedDay.php | UTF-8 | 1,368 | 2.875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use DB;
use Illuminate\Database\Eloquent\Model;
class ReservedDay extends Model {
public $timestamps = false;
protected $casts = [
'day' => 'date',
];
protected $fillable = ['apartment_id', 'day'];
/**
* Eloquent relationship
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function apartment() {
return $this->belongsTo(Apartment::class);
}
/**
* Return the reserved day set by the owner. These days cannot be booked by customers
*
* @param $apartment_id
* @return mixed
*/
public static function forApartment($apartment_id) {
return ReservedDay::where('apartment_id', $apartment_id)->get();
}
/**
* Replace the reserved days for the given apartment
*
* @param $apartment_id
* @param $reserved_days
*/
public static function replaceDays($apartment_id, $reserved_days) {
DB::table('reserved_days')->where('apartment_id', $apartment_id)->delete();
self::addDays($apartment_id, $reserved_days);
}
/**
* Reserve days if any
*
* @param $apartment_id
* @param $reserved_days
*/
public static function addDays($apartment_id, $reserved_days) {
foreach ($reserved_days as $reserved_day) {
self::create(['apartment_id' => $apartment_id, 'day' => $reserved_day]);
}
}
}
| true |
2403fc0baaefa3569d6b497743440b1babeabcf1 | PHP | Lutie/Homeland-Npc | /src/Entity/Character.php | UTF-8 | 2,995 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity()
* @ORM\Table(name="characters")
*/
class Character
{
const SEX_UNDEFINED = 0;
const SEX_MALE = 1;
const SEX_FEMALE = 2;
const SEX_TYPES_BY_STR = [
'male' => self::SEX_MALE,
'female' => self::SEX_FEMALE,
'unknown' => self::SEX_UNDEFINED
];
const SEX_TYPES_BY_INT = [
self::SEX_MALE => 'male',
self::SEX_FEMALE => 'female',
self::SEX_UNDEFINED => 'unknown'
];
use IdTrait;
use DescriptionTrait;
use SummaryTrait;
use ParticularityTrait;
use AttributesTrait;
/**
* @ORM\Column()
* @Assert\NotNull()
* @Assert\Type("string")
* @Assert\Length(min=2, max=50)
*/
private $firstname;
/**
* @ORM\Column()
* @Assert\NotNull()
* @Assert\Type("string")
* @Assert\Length(min=2, max=50)
*/
private $lastname;
/**
* @ORM\Column(type="datetime", nullable=true)
* @Assert\Type("\DateTimeInterface")
*/
private $createAt;
/**
* @ORM\Column()
* @Assert\NotNull()
* @Assert\Type("integer")
*/
private $sex = self::SEX_UNDEFINED;
/**
* @ORM\Column()
* @Assert\NotNull()
* @Assert\Type("integer")
*/
private $age = 18;
/**
* Only for form purpose
*/
public $defaults = [];
public $ethnic;
public $morphologies = [];
public $occupation;
public $job;
public $character;
public $alignement;
public $persona;
public $manias = [];
public $distinctives = [];
public $cultural;
public $liabilities = [];
public $universe;
public $size;
public $stature;
public $qualities = [];
public $ideal;
public function __construct()
{
$this->particularities = new ArrayCollection();
$this->attributes = new ArrayCollection();
$this->createAt = new \DateTime();
}
public function getFirstname()
{
return $this->firstname;
}
public function setFirstname($firstname)
{
$this->firstname = $firstname;
}
public function getLastname()
{
return $this->lastname;
}
public function setLastname($lastname)
{
$this->lastname = $lastname;
}
public function getName()
{
return $this->lastname . ' ' . $this->lastname;
}
public function getCreateAt()
{
return $this->createAt;
}
public function setCreateAt($createAt)
{
$this->createAt = $createAt;
}
public function getSex()
{
return $this->sex;
}
public function setSex($sex)
{
$this->sex = $sex;
}
public function getAge()
{
return $this->age;
}
public function setAge($age)
{
$this->age = $age;
}
}
| true |
49e2c083e32587f87fd329f63b575e314f5384bd | PHP | SoulBringerOnline/ci_project | /www/apiservice/libs/mongo/MongoDB.class.php | UTF-8 | 1,180 | 2.734375 | 3 | [] | no_license | <?php
namespace Libs\Mongo;
class MongoDB {
protected $database; // 数据表
protected static $connections = array();
protected function __construct($database) {
$this->connection_op = new \MongoClient( $this->config->item('mongodb_op') );
$this->mongo_op = new \MongoDB($this->connection_op, 'gsk');
}
public static function getConnection($collection) {
$config = self::getConfig();
$url = $config["servers"][$collection];
if (!isset(self::$connections[$url])) {
self::$connections[$url] = self::connect($url);
}
return self::$connections[$url];
}
public static function getMongoDB($collection, $database) {
$connection = self::getConnection($collection);
$momgodb = new \MongoDB($connection, $database);
return $momgodb;
}
public static function connect($url) {
return new \MongoClient($url);
}
//TODO
protected static function getConfig() {
$config = \Frame\ConfigFilter::instance()->getConfig('mongo');
return $config;
}
public static function releaseConns() {
if(count(self::$connections) > 1) {
foreach(self::$connections as $key => $conn) {
$conn->close();
unset(self::$connections[$key]);
}
}
}
} | true |
b62a5c985186e29d5b6d970b132d0edc78c8843c | PHP | kongpingfan/easy-tips | /algorithm/sort/bubble.php | UTF-8 | 2,216 | 3.59375 | 4 | [
"Apache-2.0"
] | permissive | <?php
/**
* php算法实战
* php algorithm's practice
*
* 排序算法-冒泡排序
* sort algorithm - bubble sort algorithm
*
* @author TIGERB <https://github.com/TIGERB>
*/
/**
* 冒泡排序
* bubble sort algorithm
*
* @param array $value 待排序数组 the array that is waiting for sorting
* @return array
*/
function bubble($value = [])
{
$length = count($value) - 1;
// 外循环
// outside loop
for ($j = 0; $j < $length; ++$j) {
// 内循环
// inside loop
for ($i = 0; $i < $length; ++$i) {
// 如果后一个值小于前一个值,则互换位置
// if the next value is less than the current value, exchange each other.
if ($value[$i + 1] < $value[$i]) {
$tmp = $value[$i + 1];
$value[$i + 1] = $value[$i];
$value[$i] = $tmp;
}
}
}
return $value;
}
/**
* 优化冒泡排序
* optimized bubble sort algorithm
*
* @param array $value 待排序数组 the array that is waiting for sorting
* @return array
*/
function bubble_better($value = [])
{
$flag = true; // 标示 排序未完成 the flag about the sorting is whether or not finished.
$length = count($value)-1; // 数组最后一个元素的索引 the index of the last item about the array.
$index = $length; // 最后一次交换的索引位置 初始值为最后一位 the last exchange of index position, default value is equal to the last index.
while ($flag) {
$flag = false; // 假设排序已完成 let's suppose the sorting is finished.
for ($i=0; $i < $index; $i++) {
if ($value[$i] > $value[$i+1]) {
$flag = true; // 如果还有交换发生,则排序未完成 if the exchange still happen, it show that the sorting is not finished.
$last = $i; // 记录最后一次发生交换的索引位置 taking notes the index position of the last exchange.
$tmp = $value[$i];
$value[$i] = $value[$i+1];
$value[$i+1] = $tmp;
}
}
$index = $last;
}
return $value;
}
| true |
28fcd227ef471f6c8ab37282efe77cd3221b2535 | PHP | lilipbb/webmvc | /app/test/tryTest.php | UTF-8 | 813 | 3.515625 | 4 | [] | no_license | <?php
namespace Test{
class tryTest{
public static function Test(){
self::Try1();
self::Try2();
}
public static function Try1(){
$a="wode";
try{
throw new \Exception("error");
}
catch (\Exception $e){
echo($e->getMessage());
}
echo('<br>');
}
public static function Try2(){
$a="wode";
try{
echo("start ");
throw new \Exception("error");
echo("end ");
}
catch (\Exception $e){
echo($e->getMessage());
}
finally{
echo " finally";
}
echo('<br>');
}
}
} | true |
0ad2260cd73532116a8b55002fc9854ec8b970ff | PHP | AiScreamBamboozler/php_bootcamp | /rush00/add_to_cart.php | UTF-8 | 415 | 2.640625 | 3 | [] | no_license | <?php
session_start();
if (isset($_GET["quantity"]) && isset($_GET["ref"]))
{
if ($_SESSION["cart"][$_GET["ref"]] == NULL)
$_SESSION["cart"][$_GET["ref"]] = $_GET["quantity"];
else
$_SESSION["cart"][$_GET["ref"]] += $_GET["quantity"];
header("Location: index.php");
//echo $_GET["quantity"]." item(s) succesfully added to cart";
}
?>
| true |
a781262e41503712e1865505feb93aca7ab305e0 | PHP | OlgaNesteruk/test | /index.php | UTF-8 | 610 | 2.671875 | 3 | [] | no_license | <?php
$file = fopen('feed.csv', "r");
echo '<table cellspacing = "0" border = "1" width = "500">';
while(!feof($file)) {
$mass = fgetcsv($file, 2000);
echo '<tr aling = "center">';
echo '<td width = "25%">';
echo $mass[1];
echo '</td>';
$pants = 'PANTS';
$find = stripos($mass[1], $pants);
if ($find === false) {
echo '<td width = "25%">';
echo $mass[4];
echo '</td>';
}else {
echo '<td width = "25%">';
$price_more_pants=$mass[4]*40/100+$mass[4];
echo $price_more_pants;
echo '</td>';
}
//var_dump($mass[1]);
}
echo '</table>';
fclose($file);
?>
| true |
97689eba7e52d53083c065a81f223f3457f451f5 | PHP | Kellaritehdas/Karahvi | /karahvi/inc/sana.php | UTF-8 | 2,896 | 2.640625 | 3 | [] | no_license | <?php
// Haetaan tiedot lomakkeelta
$email = $_REQUEST['email'];
$muuttuja = $_REQUEST['muuttuja'];
$merkki = $_REQUEST['merkki'];
$subject = 'Uusi salasana Karahviin';
$url = "http://(web-address)/luouusisalasana.php?muuttuja=".$muuttuja."&valinta=".$merkki;
$message = '<p>Olemme saaneet pyyntösi uusia salasana Karahviin.</p>';
$message .='<p>Jos teit pyynnön, aseta uusi salasana oheisesta linkistä.</p>';
$message .='<p>Jos et tehnyt tätä pyyntöä, poista tämä viesti.</p>';
$message .='<p>Linkki on voimassa 30 minuutin ajan.</p>';
$message .='<p>Linkki salasanan uusimista varten: </p>';
$message .='<a href="'.$url.'">'.$url.'</a></p></br>';
$message .='<p>Terveisin Karahvi!</p>';
// Täytä seuraavat kohdat omilla tiedoilla
$from = 'xx@xx.xx'; // Webhotelliin luodun sähköpostilaatikon osoite
$pass = 'password'; // Sähköpostilaatikon salasana
$to = $email; // Osoite johon viestit lähetetään
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Load composer's autoloader
// Tarkista kansio polut että ne vastaavat sitä miten purit phpMailerin webhotelliisi
require '../PHPMailer-master/src/Exception.php';
require '../PHPMailer-master/src/PHPMailer.php';
require '../PHPMailer-master/src/SMTP.php';
// phpMailer osuus alkaa
$mail = new PHPMailer(true);
try {
//Server settings
$mail->SMTPDebug = 0; // Tähän voi asettaa myös "2", jolloin näkee enemmän tietoja lähetyksestä
$mail->isSMTP();
$mail->Host = 'localhost'; // Määritetään sähköpostipalvelin
$mail->SMTPAuth = true;
$mail->Username = $from; // Haetaan ylempänä annettu sähköpostiosoite
$mail->Password = $pass; // Haetaan salasana
$mail->SMTPSecure = '';
$mail->SMTPAutoTLS = false;
$mail->Port = 587;
//Recipients
$mail->setFrom($from, 'Karahvi'); // "Palaute" näkyy viestissä lähettäjän nimenä, jonka voitte valita vapaasti
$mail->addAddress($to); // Haetaan ylempänä annettu osoite, johon viestit lähetetään
$mail->addReplyTo($email); // Haetaan lomakkeeseen täytetty sähköpostiosoite
//Content
$mail->isHTML(true);
$mail->Subject = $subject; // Vapaavalintainen viestin otsikko
$mail->Body = $message; // Haetaan lomakkeeseen täytetty viesti
$mail->AltBody = $message; // Haetaan lomakkeeseen täytetty viesti
$mail->send();
// echo 'Tilaus lähetetty onnistuneesti!'; // Ilmoitus viestin lähtyksen onnistumisesta
echo "<script>location.href='../uusisalasana.php?reset=onnistui';</script>"; // Esimerkki uudelleen ohjauksesta toiselle sivulle
} catch (Exception $e) {
echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; // Ilmoitus viestin lähetyksen epäonnistumisesta
// echo "<script>location.href='epaonnistui.html';</script>"; // Esimerkki uudelleen ohjauksesta toiselle sivulle
} | true |
ad3d0576ccba89bb84ad7e9d9b5920c36028fac2 | PHP | strapieno/str-utils | /library/Model/Entity/RoleAwareTrait.php | UTF-8 | 447 | 2.734375 | 3 | [] | no_license | <?php
namespace Strapieno\Utils\Model\Entity;
/**
* Class RoleAwareTrait
*/
trait RoleAwareTrait
{
/**
* @var string
*/
protected $roleId;
/**
* @return string
*/
public function getRoleId()
{
return $this->roleId;
}
/**
* @param string $roleId
* @return $this
*/
public function setRoleId($roleId)
{
$this->roleId = $roleId;
return $this;
}
} | true |
778515c70cc173ccaa39301a4e524f8d903be84c | PHP | andrewscaya/basic-maths-compiler | /src/Node/BinaryOp/AbstractBinaryOp.php | UTF-8 | 616 | 3.234375 | 3 | [
"MIT"
] | permissive | <?php
declare(strict_types = 1);
namespace BasicMaths\Node\BinaryOp;
use BasicMaths\Node\NodeInterface;
abstract class AbstractBinaryOp implements NodeInterface
{
/**
* @var NodeInterface
*/
private $left;
/**
* @var NodeInterface
*/
private $right;
public function __construct(NodeInterface $left, NodeInterface $right)
{
$this->left = $left;
$this->right = $right;
}
public function getLeft() : NodeInterface
{
return $this->left;
}
public function getRight() : NodeInterface
{
return $this->right;
}
}
| true |
e3a571fb860bb749a15ad63b87c6ae7282433b6a | PHP | leuchtdiode/laminas-ecommerce | /src/Cart/Item/Provider.php | UTF-8 | 724 | 2.765625 | 3 | [] | no_license | <?php
namespace Ecommerce\Cart\Item;
use Ecommerce\Common\DtoCreatorProvider;
use Ecommerce\Db\Cart\Item\Entity;
use Ecommerce\Db\Cart\Item\Repository;
class Provider
{
private DtoCreatorProvider $dtoCreatorProvider;
private Repository $repository;
public function __construct(DtoCreatorProvider $dtoCreatorProvider, Repository $repository)
{
$this->dtoCreatorProvider = $dtoCreatorProvider;
$this->repository = $repository;
}
public function byId($id): ?Item
{
return ($entity = $this->repository->find($id))
? $this->createDto($entity)
: null;
}
private function createDto(Entity $entity): Item
{
return $this->dtoCreatorProvider
->getCartItemCreator()
->byEntity($entity);
}
} | true |
f0114dbc8f0bc5a5126c0f8cc9f9724ab051c167 | PHP | oleksiv/seo-analyzer | /src/Entity/SearchResult.php | UTF-8 | 1,945 | 2.625 | 3 | [] | no_license | <?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SearchResultRepository")
*/
class SearchResult
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var
* @ORM\ManyToOne(targetEntity="App\Entity\Keyword", inversedBy="keyword")
*/
private $keyword;
/**
* @return mixed
*/
public function getKeyword()
{
return $this->keyword;
}
/**
* @param $keyword
* @return $this
*/
public function setKeyword($keyword)
{
$this->keyword = $keyword;
return $this;
}
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $title;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $description;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $h1_tag;
/**
* @ORM\Column(type="text")
*/
private $url;
public function getId()
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(?string $title): self
{
$this->title = $title;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(?string $description): self
{
$this->description = $description;
return $this;
}
public function getH1Tag(): ?string
{
return $this->h1_tag;
}
public function setH1Tag(?string $h1_tag): self
{
$this->h1_tag = $h1_tag;
return $this;
}
public function getUrl(): ?string
{
return $this->url;
}
public function setUrl(string $url): self
{
$this->url = $url;
return $this;
}
}
| true |
c3574967a7a1623d7bd74d82ccc167dc629e9502 | PHP | veasey/pagination | /src/paginator.php | UTF-8 | 1,720 | 3.421875 | 3 | [] | no_license | <?php
namespace Paginator;
class Paginator implements Pagination
{
private $elements;
private $elementsPerPage;
private $pages;
public $currentPage = 1;
public function elements(): iterable {
return $this->elements;
}
public function currentPage(): int {
return $this->currentPage;
}
public function pages(): array {
return $this->pages;
}
public function totalElements(): int {
return count($this->elements());
}
public function totalElementsOnCurrentPage(): int {
$pages = $this->pages();
$currentPage = $pages[$this->currentPage()-1];
return count($currentPage);
}
public function totalElementsPerPage(): int {
return $this->elementsPerPage;
}
public function setPage(int $pageNumber): bool {
if ($pageNumber < 1) {
$this->currentPage = 1;
return false;
}
$totalPages = count($this->pages);
if ($pageNumber > $totalPages) {
$this->currentPage = $totalPages;
return false;
}
$this->currentPage = $pageNumber;
return true;
}
public function paginateElements(iterable $feed, int $elementsPerPage = 3): array {
// save arguments for later
$this->elements = $feed;
$this->elementsPerPage = $elementsPerPage;
// make iterable an array
$items = [];
foreach ($feed as $item) {
$items[] = $item;
}
$pages = array_chunk($items, $elementsPerPage);
$this->pages = $pages;
return $pages;
}
public function setPageNumber(int $pageNumber): bool {
$this->currentPage = $pageNumber;
return true;
}
}
| true |
feaf9c87e8a6e7481b9e8f607097d60dec8e313f | PHP | aoding9/php2021 | /code/1-php基础语法/7-错误处理/1错误类型.php | UTF-8 | 349 | 3.5 | 4 | [] | no_license | <?php
// 语法错误 变量名开头不能为数字
// echo $1a;
// 运行时错误 虽然语法正确,但是没有定义$a
// echo $a;
// 逻辑错误 代码正常执行,但是由于写代码时逻辑有问题,得不到想要的结果
// 比如把++$a写成$a++导致结果不同
$a = 1;
// $b = ++$a *2;
$b = $a++ *2;
echo $b; | true |
dfb9c783830cb81472355479bd9f7ecb3433a6a1 | PHP | shivakarna2991/kkphpcode_with_old_features | /core/tools/DumpCounts.php | UTF-8 | 6,855 | 2.6875 | 3 | [] | no_license | <?php
require_once '/home/idax/DBParams.php';
$layoutids = array();
// Retrieve command line parameters
$params = getopt("v:l:");
// layoutid or videoid required, if videoid provided layoutid is ignored and all layouts for the specified video are gathered
if (array_key_exists("v", $params)) {
$videoid = $params['v'];
} else if (array_key_exists("l", $params)) {
$layoutids[] = $params['l'];
} else {
echo "DumpCounts.php usage: -v<videoid> | -l<layoutid>\n";
exit;
}
echo "\n\n";
// check connection to database
$con = mysqli_connect(IDAX_DATABASE_HOST, IDAX_DATABASE_USERNAME, IDAX_DATABASE_PASSWORD, IDAX_DATABASE_NAME);
if (!mysqli_connect_errno($con)) {
// if videoid is set, retrieve list of layoutids
if (isset($videoid)) {
$result0 = mysqli_query($con, "SELECT layoutid from idax_video_layouts WHERE videoid=$videoid AND status='COUNT_COMPLETED'");
if ($result0) {
$numRows = mysqli_num_rows($result0);
for ($i=0; $i<$numRows; $i++) {
$row0 = mysqli_fetch_row($result0);
$layoutids[] = $row0[0];
}
}
}
// get video start time
$result0 = mysqli_query($con, "SELECT capturestarttime FROM idax_video_files WHERE videoid=$videoid");
if ($result0) {
$row0 = mysqli_fetch_row($result0);
$startdatetime = strtotime($row0[0]);
}
// for each layoutid, create a formatted dump of the counts
foreach ($layoutids as $layoutid) {
// get countedby_user(s) for this layout
$result1 = mysqli_query($con, "SELECT DISTINCT countedby_user FROM idax_video_counts WHERE layoutid=$layoutid AND rejected=0");
if ($result1) {
$numRows = mysqli_num_rows($result1);
for ($j=0; $j<$numRows; $j++) {
$row1 = mysqli_fetch_row($result1);
$userid = $row1[0];
$result2 = mysqli_query($con, "SELECT email, firstname, lastname FROM accounts WHERE accountid=$userid");
if ($result2) {
$row2 = mysqli_fetch_row($result2);
}
$result3 = mysqli_query($con, "SELECT count(*) FROM idax_video_counts WHERE layoutid=$layoutid AND counttype!='PED' AND rejected=0 AND countedby_user=$userid");
if ($result3) {
$row3 = mysqli_fetch_row($result3);
}
echo "Userid: ".$userid.", ".$row2[0].",,,,,,,, ".$row2[1].",,,, ".$row2[2].",,,,, Total counts:".$row3[0]."\n";
}
// add table header
echo "Interval Start, ";
// get layoutleg directions by legindex for this layout
$result = mysqli_query($con, "SELECT direction FROM idax_video_layoutlegs WHERE layoutid=$layoutid order by legindex");
if ($result) {
$numlegs = mysqli_num_rows($result);
for ($i=0; $i<$numlegs; $i++) {
$row = mysqli_fetch_row($result);
echo $row[0].",,,,";
}
echo "15-min Total, Rolling One Hour\n";
}
echo ", ";
for ($i=0; $i<$numlegs; $i++) {
echo "UT, LT, TH, RT";
if ($i < $numlegs-1) {
echo ", ";
}
}
echo ", ,\n";
$startpos = 0;
$endpos = 0;
$lasttimeslottotal = 0;
$rollinghourtotal = 0;
$totaltotal = 0;
for ($timeslot=0; $timeslot<4; $timeslot++) {
$timeslottotal = 0;
// initialize zeroed-out leg array
$legarray = array();
for ($leg=0; $leg<$numlegs; $leg++) {
$legarray[] = array("UTURN"=> 0, "LTURN"=> 0, "STRAIGHT"=> 0, "RTURN"=> 0);
}
// save first timeslot legarray as the totalarray
if ($timeslot == 0) {
$totalarray = $legarray;
}
$startpos = $endpos;
$endpos = $endpos + 900;
// get split of counts for the timeperiod
$result4 = mysqli_query($con, "SELECT legindex, counttype, COUNT(*) FROM idax_video_counts WHERE layoutid=$layoutid AND rejected=0 AND counttype!='PED' AND videoposition>=$startpos AND videoposition<$endpos GROUP BY legindex, counttype ORDER BY legindex");
if ($result4) {
$numRows = mysqli_num_rows($result4);
for ($k=0; $k<$numRows; $k++) {
$row4 = mysqli_fetch_row($result4);
$legarray[$row4[0]][$row4[1]] = $row4[2];
$timeslottotal += (int)$row4[2];
// add timeslot totals to $totalarray
$totalarray[$row4[0]][$row4[1]] += $row4[2];
}
}
$rollinghourtotal += $timeslottotal;
$totaltotal += $timeslottotal;
$interval = date("g:i", $startdatetime+($timeslot*900));
echo $interval.", ";
for ($leg=0; $leg<$numlegs; $leg++) {
echo $legarray[$leg]["UTURN"].", ".$legarray[$leg]["LTURN"].", ".$legarray[$leg]["STRAIGHT"].", ".$legarray[$leg]["RTURN"].", ";
}
if ($timeslot > 2) {
$rollinghourtotal = $rollinghourtotal - $lasttimeslottotal;
$lasttimeslottotal = $timeslottotal;
echo $timeslottotal.", ".$rollinghourtotal."\n";
} else {
echo $timeslottotal.", 0\n";
}
}
// echo the totals
echo "Count Total, ";
for ($leg=0; $leg<$numlegs; $leg++) {
echo $totalarray[$leg]["UTURN"].", ".$totalarray[$leg]["LTURN"].", ".$totalarray[$leg]["STRAIGHT"].", ".$totalarray[$leg]["RTURN"].", ";
}
echo $totaltotal.", 0";
echo "\n\n";
}
}
mysqli_close($con);
}
else {
echo "Failed to connect to USERs database. Error=".mysqli_connect_errno()."\n";
}
?>
| true |
2ca36f9d10029bfc26447a2c347195033a4056a9 | PHP | AmitXShukla/elish-education-portal-app | /local/app/QuizResult.php | UTF-8 | 4,920 | 2.671875 | 3 | [
"MIT"
] | permissive | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Auth;
use DB;
class QuizResult extends Model
{
protected $table = 'quizresults';
public static function getRecordWithSlug($slug)
{
return QuizResult::where('slug', '=', $slug)->first();
}
/**
* Returns the history of exam attempts based on the current logged in user
* @return [type] [description]
*/
public function getHistory()
{
return QuizResult::where('user_id', '=', Auth::user()->id)->orderBy('id', 'DESC')->limit(5)->get();
}
/**
* Returns the list of toppers based on the highest
* percentage scored and the current quiz
* @param string $quiz_id [description]
* @return [type] [description]
*/
public function getToppersList($quiz_id='')
{
$list = array();
if($quiz_id=='')
return $list;
return QuizResult::
where('quiz_id', '=', $quiz_id)
->where('exam_status', '=', 'pass')
->orderBy('percentage', 'DESC')->limit(5)
->groupBy('user_id')
->get();
}
/**
* Returns the current result quiz record
* @return [type] [description]
*/
public function quizName()
{
return $this->belongsTo('App\Quiz', 'quiz_id');
}
/**
* Returns the current quiz user record
* @return [type] [description]
*/
public function getUser()
{
return $this->belongsTo('App\User', 'user_id');
}
public function getOverallSubjectsReport($user)
{
$overallSubjectAnalysis = [];
$records = Quiz::join('quizresults', 'quizzes.id', '=', 'quizresults.quiz_id')
->select(['subject_analysis','quizresults.user_id'])
->where('quizresults.user_id', '=', $user->id)
->get();
// dd($records);
foreach ($records as $result) {
foreach(json_decode($result->subject_analysis) as $subject)
{
$subject_id = $subject->subject_id;
if(!array_key_exists($subject_id, $overallSubjectAnalysis)){
$overallSubjectAnalysis[$subject_id]['subject_name'] = Subject::where('id','=',$subject_id)->first()->subject_title;
$overallSubjectAnalysis[$subject_id]['correct_answers'] = 0;
$overallSubjectAnalysis[$subject_id]['wrong_answers'] = 0;
$overallSubjectAnalysis[$subject_id]['not_answered'] = 0;
$overallSubjectAnalysis[$subject_id]['time_to_spend'] = 0;
$overallSubjectAnalysis[$subject_id]['time_spent'] = 0;
$overallSubjectAnalysis[$subject_id]['time_spent_on_correct_answers'] = 0;
$overallSubjectAnalysis[$subject_id]['time_spent_on_wrong_answers'] = 0;
$overallSubjectAnalysis[$subject_id]['time_spent_on_wrong_answers'] = 0;
$overallSubjectAnalysis[$subject_id]['time_spent_on_wrong_answers'] = 0;
}
$overallSubjectAnalysis[$subject_id]['correct_answers'] += $subject->correct_answers;
$overallSubjectAnalysis[$subject_id]['wrong_answers'] += $subject->wrong_answers;
$overallSubjectAnalysis[$subject_id]['not_answered'] += $subject->not_answered;
$overallSubjectAnalysis[$subject_id]['time_to_spend'] += $subject->time_to_spend;
$overallSubjectAnalysis[$subject_id]['time_spent'] += $subject->time_spent;
$overallSubjectAnalysis[$subject_id]['time_spent_on_correct_answers'] += $subject->time_spent_correct_answers;
$overallSubjectAnalysis[$subject_id]['time_spent_on_wrong_answers'] += $subject->time_spent_wrong_answers;
}
}
return $overallSubjectAnalysis;
}
/**
* Returns the overall performanance of the user
* @param [type] $user [description]
* @return [type] [description]
*/
public function getOverallQuizPerformance($user)
{
$overallQuizPerformance = [];
$records = Quiz::join('quizresults', 'quizzes.id', '=', 'quizresults.quiz_id')
->select(['quiz_id', 'quizzes.title',DB::raw('Max(percentage) as percentage'), 'quizresults.user_id'])
->where('quizresults.user_id', '=', $user->id)
->groupBy('quizresults.quiz_id')
->get();
return $records;
}
public function getQuizzesUsage($type='', $user_id='', $year='')
{
$query = 'select count(qr.quiz_id) as total, q.title as quiz_title from quizzes q, quizresults qr where qr.quiz_id = q.id group by qr.quiz_id';
if($type=='paid')
{
$query = 'select count(qr.quiz_id) as total, q.title as quiz_title from quizzes q, quizresults qr where qr.quiz_id = q.id and q.is_paid=1 group by qr.quiz_id';
}
$result = DB::select($query);
return $result;
}
}
| true |
fe1cb5e4ddc332622ce600cbbf22cb0b494a02f3 | PHP | sara-ahrari/eCommerce-website | /update_user.php | UTF-8 | 563 | 2.53125 | 3 | [] | no_license | <?php
require_once 'helpers.php';
session_start();
if (detected_csrf($_POST['csrf'])) {
die('CSRF prevented!');
}
$username = get_session_username();
$homeAddress = validated_input($_POST['homeAddress']);
updateUser($username, $homeAddress);
set_session_homeAddress($homeAddress);
redirect('index.php');
function updateUser($username, $home_adress)
{
$db = create_mysqli();
$stmt = $db->prepare('UPDATE users SET home_address = ? WHERE username = ?');
$stmt->bind_param('ss',$home_adress, $username);
$stmt->execute();
$db->close();
} | true |
331e7a3d0fd9a80fb9f87048b87b347f3d6b75de | PHP | Riowaldy/PKL | /app/Http/Controllers/DynamicPDFController.php | UTF-8 | 1,536 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use PDF;
class DynamicPDFController extends Controller
{
function indexProjectPDF()
{
$posts = $this->get_post_data();
return view('dynamic_pdf')->with('posts', $posts);
}
function get_post_data()
{
$posts = DB::table('posts')
->limit(10)
->get();
return $posts;
}
function pdfProjectPDF()
{
$pdf = \App::make('dompdf.wrapper');
$pdf->loadHTML($this->convert_post_data_to_html());
return $pdf->stream();
}
function convert_post_data_to_html()
{
$posts = $this->get_post_data();
$output = '
<h3 align="center">Data Project</h3>
<table width="100%" style="border-collapse: collapse; border: 0px;">
<tr>
<th style="border: 1px solid; padding:12px; text-align:center;" width="10%">Judul Project</th>
<th style="border: 1px solid; padding:12px; text-align:center;" width="20%">Isi Project</th>
<th style="border: 1px solid; padding:12px; text-align:center;" width="10%">Created at</th>
</tr>
';
foreach($posts as $post)
{
$output .= '
<tr>
<td style="border: 1px solid; padding:12px;">'.$post->title.'</td>
<td style="border: 1px solid; padding:12px; text-align:justify;">'.$post->content.'</td>
<td style="border: 1px solid; padding:12px; text-align:center;">'.$post->created_at.'</td>
</tr>
';
}
$output .= '</table>';
return $output;
}
} | true |
f82f7b874b1f9625ea4bcf2d1d1537e47e8a4f3c | PHP | budde377/Part | /lib/util/task/RequireHTTPSPreTaskImpl.php | UTF-8 | 981 | 2.578125 | 3 | [
"MIT"
] | permissive | <?php
namespace ChristianBudde\Part\util\task;
use ChristianBudde\Part\BackendSingletonContainer;
use ChristianBudde\Part\util\helper\HTTPHeaderHelper;
use ChristianBudde\Part\Website;
/**
* Created by PhpStorm.
* User: budde
* Date: 8/13/14
* Time: 5:05 PM
*/
class RequireHTTPSPreTaskImpl implements Task{
private $backendContainer;
public function __construct(BackendSingletonContainer $backendContainer){
$this->backendContainer = $backendContainer;
}
public function execute()
{
if($this->backendContainer->getConfigInstance()->getDomain() !== $_SERVER['HTTP_HOST']){
return;
}
if(!$this->isSecure()){
HTTPHeaderHelper::redirectToLocation("https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}
}
private function isSecure() {
return
(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| $_SERVER['SERVER_PORT'] == 443;
}
} | true |
40cf0dcaac335abc01c33fe56a6cb1213e58696a | PHP | haipham/ddfc | /app/Http/Controllers/WelcomeController.php | UTF-8 | 1,437 | 2.53125 | 3 | [
"MIT"
] | permissive | <?php namespace App\Http\Controllers;
use Gaia\Repositories\PostRepositoryInterface;
use Gaia\Repositories\NewsRepositoryInterface;
use Auth;
class WelcomeController extends Controller {
protected $postRepos, $newsRepos;
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct(PostRepositoryInterface $postRepos, NewsRepositoryInterface $newRepos)
{
$this->postRepos = $postRepos;
$this->newsRepos = $newRepos;
//$this->middleware('auth');
}
/**
* Show the application welcome screen to the user.
*
* @return Response
*/
public function index()
{
$voices = $this->postRepos->getAllByPostTypeSlug('voices', 3, true);
$slides = $this->postRepos->getAllByPostTypeSlug('slides');
$campaigns = $this->postRepos->getAllByPostTypeSlug('campaign',1,true);
if(count($campaigns))
{
$campaign = $campaigns[0];
$youtubeid = "";
if($campaign->youtube_url != "")
{
preg_match('/[\\?\\&]v=([^\\?\\&]+)/', $campaign->youtube_url, $matches);
$youtubeid = $matches[1];
}
}
else
{
$campaign = null;
$youtubeid = null;
}
$news = $this->newsRepos->getOnlyWithContent(2);
//if(Auth::user())
return view('front.index', ['voices' => $voices, 'news' => $news, 'slides' => $slides, 'campaign' => $campaign, 'youtubeid' => $youtubeid]);
//else
// return view('front.comingsoon');
}
}
| true |
2f35432637cbe294234b5c53548640e4f55153a0 | PHP | Childdreams/laravelIoc | /vendor/baofeng/Demo/src/Route/Route.php | UTF-8 | 1,614 | 3.1875 | 3 | [] | no_license | <?php
namespace baofeng\Demo\Route;
class Route implements RouteInterface
{
private static $get = [];
private static $post = [];
private static $any = [];
/**
* method get
* @param string $route
* @param string $controller
*/
public static function get(string $route , string $controller ):void
{
static::$get[trim($route,"/")] = $controller;
}
/**
* method post
* @param string $route
* @param string $controller
*/
public static function post (string $route , string $controller):void
{
static::$post[trim($route,"/")] = $controller;
}
/**
* method any
* @param string $route
* @param string $controller
*/
public static function any (string $route , string $controller):void
{
static::$any[trim($route,"/")] = $controller;
}
public static function getGET($name)
{
if (!isset(static :: $get[trim($name , "/")])){
throw new \Exception("This route ".$name ." dont't find ");
}
return static :: $get[trim($name , "/")];
}
public static function getPOST($name)
{
if (!isset(static :: $post[trim($name , "/")])){
throw new \Exception("This route ".$name ." dont't find ");
}
return static :: $post[trim($name , "/")];
}
public static function getANY($name)
{
if (!isset(static :: $any[trim($name , "/")])){
throw new \Exception("This route ".$name ." dont't find ");
}
return static :: $any[trim($name , "/")];
}
} | true |
f0e573ef4e9a8c071e5e57698c4e870e1869e04c | PHP | dotmailer/dotmailer-magento2-extension | /Model/Config/Configuration/Fontpicker.php | UTF-8 | 1,719 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace Dotdigitalgroup\Email\Model\Config\Configuration;
class Fontpicker implements \Magento\Framework\Data\OptionSourceInterface
{
/**
* Options getter. web safe fonts.
*
* @return array
*/
public function toOptionArray()
{
return [
[
'value' => 'Arial, Helvetica, sans-serif',
'label' => 'Arial, Helvetica',
],
[
'value' => "'Arial Black', Gadget, sans-serif",
'label' => 'Arial Black, Gadget',
],
[
'value' => "'Courier New', Courier, monospace",
'label' => 'Courier New, Courier',
],
[
'value' => 'Georgia, serif',
'label' => 'Georgia',
],
[
'value' => "'MS Sans Serif', Geneva, sans-serif",
'label' => 'MS Sans Serif, Geneva',
],
[
'value' => "'Palatino Linotype', 'Book Antiqua', Palatino, serif",
'label' => 'Palatino Linotype, Book Antiqua',
],
[
'value' => 'Tahoma, Geneva, sans-serif',
'label' => 'Tahoma, Geneva',
],
[
'value' => "'Times New Roman', Times, serif",
'label' => 'Times New Roman, Times',
],
[
'value' => "'Trebuchet MS', Helvetica, sans-serif",
'label' => 'Trebuchet MS, Helvetica',
],
[
'value' => 'Verdana, Geneva, sans-serif',
'label' => 'Verdana, Geneva',
],
];
}
}
| true |
c42a9da2c16fad3c185b890e976095a5867a3b82 | PHP | prash1987/GamifyWebsite | /manage_groups.php | UTF-8 | 7,398 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
include("header.php");
if(isset($_SESSION['login_user'])) {
if(isset($_GET["group_id"])){
$userLoggedIn = $_SESSION['login_user'];
$user_obj = new UserClass($con, $userLoggedIn);
$group_id=$_GET["group_id"];
$sqlAdmin = mysqli_query($con, "SELECT * FROM groups WHERE group_id = '$group_id';");
while($row_admin = mysqli_fetch_array($sqlAdmin)) {
$group_admin = $row_admin['admin'];
$group_name = $row_admin['group_name'];
$group_members = $row_admin['members'];
$new_members = $group_members . ",";
}
if($group_admin !== $userLoggedIn)
{
header("Location: homepage.php");
}
}
else{
header("Location: groups.php");
}
}
else
{
header("Location: login.php");
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if (isset($_POST['btnRemove'])){
$user_id = $userLoggedIn;
$member_to_delete = '';
foreach($_POST['current_members'] as $vals) {
if($vals!==$user_id){
$member_to_delete = $vals . ',';
$new_members = str_replace($member_to_delete, "", $new_members);
}
}
if(substr($new_members, -1) === "," ){
$new_members = substr($new_members, 0, strlen($new_members)-1);
}
$sql = "UPDATE groups SET members='$new_members' WHERE group_id='$group_id';";
if ($con->query($sql) === TRUE) {
header('Location: manage_groups.php');
}
else {
echo "Something went wrong. Error: " . $sql . "<br>" . $con->error;
}
}
///Below is the code that will be executed if the user is trying to add more members
if (isset($_POST['btnUpdate'])){
if(isset($_POST['members'])){
$members= $_POST["members"];
$members = substr($members, 0, strlen($members)-1);
$sql = "UPDATE groups SET members= CONCAT('" . $group_members . "', " . "','" . " '" . $members . "') WHERE group_id='$group_id';";
if ($con->query($sql) === TRUE) {
header('Location: manage_groups.php');
}
else {
echo "Something went wrong. Error: " . $sql . "<br>" . $con->error;
}
}
else{
echo "No members to add.";
}
}
}
?>
<head>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<link href="css/styles.css" rel="stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src = "js/search.js"></script>
<script type="text/javascript">
function getUsers(value, user){
$.post("handlers/ajax_grp_member_search.php", {query:value, userLoggedIn:user}, function (data){
$(".results").html(data);
});
document.getElementById("results").style.display = "block";
}
function selectUser(selectedUser){
var test = "";
selectedUser += ",";
document.getElementById('members').value += selectedUser;
document.getElementById("results").style.display = "none";
document.getElementById('search_text_input').value = test;
}
</script>
</head>
<br><br><br><br>
<div class="col-md-2 column col-md-offset-0-5">
<img class="img-circle" height='126' width='126' src="<?php echo $user_obj->getProPic(); ?>">
<br><br>
<div class="user_details_left_right">
<b><?php echo $user_obj->getFirstAndLastName(); ?></b>
<br>
<?php echo "Location: " . $user_obj->getUserLocation() . "<br>";
echo "Contact: " . $user_obj->getUserContact() ; ?>
</div>
</div>
<div class="col-md-6 column col-md-offset-0-5">
<h3>Manage Group - <?php echo $group_name; ?> </h3><hr>
<form action="" method="post" class="form-horizontal" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Current Members:</label>
<div class="col-sm-10">
<select multiple class="form-control" id="current_members" name="current_members[]">
<?php
$members_arr = explode(",", $group_members);
for ($i = 0; $i < count($members_arr); $i++) {
$member_obj = new UserClass($con, $members_arr[$i]);
$member_name = $member_obj->getFirstAndLastName();
echo "<option value='" . $members_arr[$i] . "'>" . $member_name . "</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Select the members and click Remove</label>
<div class="col-sm-10">
<input type="submit" name="btnRemove" class="btn btn-primary signup" value="Remove"/><br/>
</div>
</div>
<hr>
<div class="form-group">
<label class="col-sm-2 control-label">Members to be added</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="members" id="members" required readonly>
</div>
</div>
<br>
Select the friend you would like to add to your group<br>
<input type="search" onkeyup='getUsers(this.value, "<?php echo $userLoggedIn; ?>")' name='q' placeholder='Name' autocomplete='off' id='search_text_input' onsearch="getUsers('','')">
<div class='results' id='results'></div>
<br>
<div class="col-sm-10">
<div class="action">
<input type="submit" name="btnUpdate" class="btn btn-primary signup" value="Update"/><br/>
</div></div>
</form>
</div>
<div class="col-md-3 ads">
<div style="max-width: 500px;">
<a target="_blank" href="https://www.ebay.com/b/Mens-Fitness-Running-Shoes/158952/bn_1965202">
<img class="mySlides" src="images/ads/ad_ebay.jpg" style="width:100%"></a>
<a target="_blank" href="http://www.indianavolleyballcamps.com/index.html">
<img class="mySlides" src="images/ads/ad_volleyball.jpg" style="width:100%"></a>
<a target="_blank" href="http://northamericasports.blogspot.ca/2012/09/new-nike-epl-match-ball-maxim-for.html">
<img class="mySlides" src="images/ads/ad_nike.jpg" style="width:100%"></a>
<a target="_blank" href="https://www.anytimefitness.com/gyms/2822/bloomington-in-47401/">
<img class="mySlides" src="images/ads/ad_gym.jpg" style="width:100%"></a>
<a target="_blank" href="https://www.pinterest.com/pin/316659417526781056/">
<img class="mySlides" src="images/ads/ad_adidas.jpg" style="width:100%"></a>
<a target="_blank" href="https://www.amazon.com/Best-Sellers-Health-Personal-Care-Sports-Nutrition-Protein/zgbs/hpc/6973704011/ref=zg_bs_unv_hpc_3_6973717011_2">
<img class="mySlides" src="images/ads/ad_protein.jpg" style="width:100%"></a>
</div>
</div>
<script>
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000); // Change image every 3 seconds
}
</script>
</body>
</html> | true |
7e61beb6383a47630fac34e5dae542caf1ce6378 | PHP | apetushok/push-notifications | /src/Push/IosService.php | UTF-8 | 3,332 | 2.6875 | 3 | [] | no_license | <?php
namespace Push;
use Push\Service;
class IosService implements Service {
private $config;
private $url_service = 'ssl://gateway.sandbox.push.apple.com:2195';
private $instance;
public function __construct($config){
if ( empty($this->instance) ) {
if(!is_string($config) || !file_exists($config)){
throw new \Exception("Has the wrong path to the ssl-certificate.");
}else{
$this->config = $config;
$result = $this->connect('test','test');
if($result !== false ){
$this->instance = $this;
}else{
throw new \Exception("Unable to authenticate, check certificate");
}
}
}
return $this->instance;
}
public function sendMessages($device_ids,$message){
if(empty($device_ids)){
throw new \Exception("Not empty device ids");
}elseif(empty($message)){
throw new \Exception("Not empty message");
}elseif(!is_string($message)){
throw new \Exception("Get type string for message, ". gettype($message)." given");
}else{
if(!is_array($device_ids) && !is_string($device_ids)){
throw new \Exception("Get type string or array for device ids, ". gettype($device_ids)." given");
}else{
$result = $this->connect($device_ids,$message);
if($result === false ){
throw new \Exception("Unable to authenticate, check certificate");
}else{
return $result;
}
}
}
}
private function connect($device_ids,$message){
if(is_string($device_ids))
$device_ids = (array)$device_ids;
$streamContext = stream_context_create();
@stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->config);
$fp = @stream_socket_client($this->url_service, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $streamContext);
@stream_set_blocking ($fp, 0);
if (!$fp) {
return false;
}
if($device_ids[0] != "test"){
$load = array(
'aps' => array(
'alert' => $message,
'badge' => 1,
'sound' => 'chime'
)
);
$payload = json_encode($load);
$apnsMessage = null;
foreach ($device_ids as $token) {
@$apnsMessage = chr (0) . chr (0) . chr (32) . pack ('H*', str_replace(' ', '', $token)) . pack ('n', strlen ($payload)) . $payload;
}
fwrite($fp, $apnsMessage);
usleep(500000);
$ivalidToken = $this->pullMessage($fp);
fclose($fp);
return $ivalidToken;
}
return true;
}
private function pullMessage($fp){
$responseBinary = fread($fp, 6);
if ($responseBinary !== false && strlen($responseBinary) == 6)
{
$response = unpack('Ccommand/Cstatus_code/Nidentifier', $responseBinary);
return $response;
}
return true;
}
private function __clone(){}
private function __wakeup(){}
} | true |
c1d298541d47f6c251a64eca6a64ff7542d16c1b | PHP | OpenSeaMap/tidal-scale | /experimental/code/classes/util.class.php | WINDOWS-1252 | 9,049 | 3.40625 | 3 | [] | no_license | <?php
/*
erstellt von Tim Reinartz im Rahmen der Bachelor-Thesis
letzte nderung 11.05.11 12:15 Uhr
alle wichtigen Funktionen in einer hilfsklasse zusammengefasst
*/
class Util {
/*
* Format fr Datum und Zeitangaben
* (wie bei date()-Funktion)
*/
const DATETIME_FORMAT = 'd.m.y H:i';
/*
* Singleton
*/
private static $singleton = null;
public static function getInstance() {
if (!self::$singleton instanceof Util) {
self::$singleton = new Util();
}
return self::$singleton;
}
function __constuct() {
}
/*
* ersetzt alle , durch einen punkt in dem string
* @param $string
* @retrun $string
*/
public static function getDotString($string) {
$string = str_replace(',','.', $string);
return $string;
}
/*
* entfernt alle . aus einem string
* @param $string
* @retrun $string
*/
public static function removeDotString($string) {
$string = str_replace('.','', $string);
return $string;
}
/*
* Wandelt die Tendenz in Worte um
* @param $tendenz zahl
* @return $tendenz string
*/
public static function convertTendenz($tendenz){
if($tendenz == 1) {
$tendenz = 'Steigend';
}
elseif($tendenz == -1) {
$tendenz = 'Fallend';
}
else {
$tendenz = 'Gleich';
}
return $tendenz;
}
/*
* zu utf-8 umwandlung
* @param $str
* @retrun $str
*/
public static function fix_text($str) {
return htmlspecialchars(utf8_decode($str));
}
/*
* fsock funktion
* baut eine verbindung auf und holt den inhalt und speichert diesen in einer variablen
* erstellt mithilfe von [ST09]
* @param $url
* @retrun $content
*/
public static function get_document($url) {
$content = '';
$is_header = TRUE;
$base_url = parse_url($url);
if ($fp = @fsockopen($base_url['host'], 80, $errno, $errstr, 5)) {
if (!empty($base_url['query'])) {
$query = '?'.$base_url['query'];
} else {
$query = '';
}
$data = 'GET '.$base_url['path'].$query." HTTP/1.0\r\n".
'Host: '.$base_url['host']."\r\n".
"Connection: Close\r\n\r\n";
stream_set_timeout($fp, 5);
fputs($fp, $data);
while(!feof($fp)) {
$line = fgets($fp, 4096);
if (!$is_header) {
$content .= $line;
} else {
if (strlen(trim($line)) == 0) {
$is_header = FALSE;
}
}
}
fclose($fp);
return $content;
} else {
return FALSE;
}
}
/*
* wert anzeige, wenn != '' sonst fehler meldung
* @param $wert
* @retrun $wert oder meldung
*/
public static function echo_wert($wert) {
if($wert != '') {
echo $wert;
}else{
echo 'achtung keine daten vorhanden';
}
return;
}
/*
* aus der php doku
* in cases when "0" is not intended to be empty, here is a simple function to safely test for an empty string (or mixed variable)
* da messwerte und pnp 0 sein knnen, dann aber nicht leer sind
* @param $string
* @retrun $string oder bool
*/
public static function my_empty($string){
$string = trim($string);
if(!is_numeric($string)) return empty($string);
return FALSE;
}
/*
* Liefert die Nanosekunden aus einem microtime() String
* @param $string - Der String vom microtime aufruf, falls leer aktuelle microtime
* @return float - aktuelle Zeit mit nanosekunden
*/
public static function getNanoSeconds($string = '') {
if (empty($string)) {
$string = microtime();
}
$zeittemp = explode(" ",$string);
$zeitmessung = $zeittemp[0] + $zeittemp[1]; // Timestamp + Nanosek
return $zeitmessung;
}
/*
* datei entfernen geht so nur bei linux
* @param $datei
* @retrun meldung
*/
public static function rm_datei($datei) {
if(file_exists($datei)) {
$escape = escapeshellarg($datei);
exec("rm " . $escape);
echo '<p>Die Datei '. $datei .' wurde entfernt</p>';
} else {
echo '<p>Die Datei '. $datei .' ist nicht vorhanden</p>';
}
return;
}
/*
* fuer linux , fuer windows wget installieren oder eine andere methode nutzen
* @param $datei
*/
public static function wget_datei($datei) {
//escapeshellarg Maskiert eine Zeichenkette (String), um sie als Shell-Argument benutzen zu knnen
$escape = escapeshellarg($datei);
//exec Fhrt ein externes Programm aus
exec("wget " . $escape);
return;
}
/*
* Wandelt DATE_W3C in ein "normales" Datum um
* http://php.net/manual/en/class.datetime.php
* Die if abfrage ist um kompatiblitt mit php versionen kleiner 5.3 herzustellen,
* allerdings so nur abwrtskompatibel bis 5.1
* @param $datew3c
* @return $date
*/
public static function convertTime($datew3c){
$localTimezone = new DateTimeZone("Europe/Berlin");
$date = new DateTime($datew3c, $localTimezone);
//http://de3.php.net/manual/de/function.phpversion.php
if (strnatcmp(phpversion(),'5.2.0') >= 0)
{
$date->setTimezone($localTimezone);
}
else
{
//$date->setTimezone($localTimezone);
}
return $date;
}
/*
* Wandelt einen nur aus GROSSBUCHSTABEN bestehenden String um
* http://php.net/manual/de/function.ucfirst.php
* @param $string
* @return $string
*/
public static function convertUpperString($string){
//$string = ucfirst(strtolower($string));
$string = ucwords(strtolower($string));
return $string;
}
/*
* Wandelt die Tendenz in Pfeile um
* Idee von Markus Brlocher
* @param $tendenz
* @return $tendenz
*/
public static function convertArrow($tendenz){
if($tendenz == 'Steigend') {
$tendenz = '↑';
}
elseif($tendenz == 'Fallend') {
$tendenz = '↓';
}
else {
$tendenz = '↔';
}
/*
↔ ↔ gleich
↓ ↓ fallend
↑ ↑ steigend
*/
return $tendenz;
}
/*
* Wandelt die Tendenz in Pfeile um fr OSM angepasst
* Idee von Markus Brlocher
* @param $tendenz
* @return $tendenz
*/
public static function convertArrow_osm($tendenz){
if($tendenz == 'Steigend') {
$tendenz = '\u2191';
}
elseif($tendenz == 'Fallend') {
$tendenz = '\u2193';
}
else {
$tendenz = '\u2194';
}
/*
name nummer wort hexwert
↔ ↔ gleich \u2194
↓ ↓ fallend \u2193
↑ ↑ steigend \u2191
*/
return $tendenz;
}
/*
* Stellt Informationen zu den Fehlern dar
* @param $daten_fehler
* @return $string
*/
public static function show_daten_fehler($fehler){
//bei 0 gibt es keine fehlerhaften daten
//bei 1 liegen unvollstaendige / fehlerhafte daten vor
//bei 2 ist der pnp nicht vorhanden
//bei 3 fehlen koordinaten informationen
if($fehler == 0) {
$fehler = '<br>';
}
elseif($fehler == 1) {
$fehler = '<br><font color="red"><b>Ausser Betrieb</b></font><br>';
}
elseif($fehler == 2) {
$fehler = '<br><font color="red">Kein PnP Wert vorhanden</font><br>';
}
else {
$fehler = '<br>';
}
return $fehler;
}
/*
* Stellt Informationen zu den Fehlern dar fr OSM angepasst
* @param $daten_fehler
* @return $string
*/
public static function show_daten_fehler_osm($fehler){
//bei 0 gibt es keine fehlerhaften daten
//bei 1 liegen unvollstaendige / fehlerhafte daten vor
//bei 2 ist der pnp nicht vorhanden
//bei 3 fehlen koordinaten informationen
if($fehler == 0) {
$fehler = '';
}
elseif($fehler == 1) {
$fehler = '<font color="red"><b>Ausser Betrieb</b></font>';
}
elseif($fehler == 2) {
$fehler = '<font color="red">Kein PnP Wert vorhanden</font>';
}
else {
$fehler = '';
}
return $fehler;
}
/*
* Liefert einen "fehlerfreien" String
* @param fstring - Name
* @return String - verbesserter Name
*/
public static function getCleanString($string) {
$umlaute = array("Ö","Ä","Ü");
$replace = array('Ä','Ö','Ü');
//Umlaute ersetzen
$string2 = str_replace($umlaute, $replace, $string);
return $string2;
}
/*
* Liefert einen "fehlerfreien" String fr OSM angepasst
* es werden direkt kleinbuchstaben eingesetzt da die php strtolower funktion die escaped zeichen ignoriert
* @param fstring - Name
* @return String - verbesserter Name
*/
public static function getCleanString_osm($string) {
$umlaute = array("Ö","Ä","Ü");
$replace = array('\u00E4','\u00F6','\u00FC');
//Umlaute ersetzen
$string2 = str_replace($umlaute, $replace, $string);
return $string2;
}
}
?> | true |
51fac40c3a6f54f709de538b0a61fffa96b23730 | PHP | sminuwa/lexington | /filter_faculty.php | UTF-8 | 1,011 | 2.5625 | 3 | [] | no_license | <?php
require "config.php";
require "functions.php";
if(isset($_POST['filter_school']))
{
if($_POST['filter_school'] != "")
{
$school_name = $_POST['filter_school'];
// fetching the school id
$query_school_id = $conn->query("SELECT * FROM lib_schools WHERE school_name = '$school_name' ") or die("Error");
if($query_school_id->num_rows > 0)
{
$row_school_id = $query_school_id->fetch_assoc();
$school_id = $row_school_id['school_id'];
// selecting the faculties
$query_faculty = $conn->query("SELECT * FROM lib_faculties WHERE school_id = '$school_id' ORDER BY faculty_name ASC") or die("Error 2");
if($query_faculty->num_rows > 0)
{
echo '<option value=""> --select faculty-- </option>';
while($row_faculty = $query_faculty->fetch_assoc())
{
echo '<option value="'.$row_faculty['faculty_name'].'">'.$row_faculty['faculty_name'].'</option>';
}
}
}
else
{
echo '<option value=""> --no faculty-- </option>';
}
}
}
?> | true |
cb818feaf1e9b5ce8565962f78c4145a7af3c1bc | PHP | kidcobain/atencion | /database/factories/UserFactory.php | UTF-8 | 4,674 | 2.640625 | 3 | [] | no_license | <?php
use Faker\Generator as Faker;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
//'user_id' => App\User::all()->random()->id,
//'created_at' => $faker->dateTimeBetween('-3 years', 'now'),
//randomElement($array = array ('a','b','c'))
$factory->define(App\usuarios::class, function (Faker $faker) {
static $password;
return [
'usuario' => $faker->unique()->userName,
'password' => $password ?: $password = bcrypt('secret'),
'rol' => $faker->word,
'remember_token' => str_random(10),
'created_at' => $faker->dateTimeThisDecade,
'updated_at' => $faker->dateTimeThisDecade,
];
});
$factory->define(App\personas::class, function (Faker $faker) {
static $password;
//$tipo = $faker->randomElement($array = array ('natural','juridico'));
return [
'nombre' => $faker->firstName,
'apellido' => $faker->lastName,
'sexo' => $faker->randomElement($array = array ('m','f')),
'rif' =>$faker->randomNumber($nbDigits = 9, $strict = false),
'tipo' =>$faker->randomElement($array = array ('natural','juridica')),
'cedula' => $faker->randomNumber($nbDigits = 8, $strict = false),
'representante' =>$faker->firstName,
'nivel_educativo' =>$faker->randomElement($array = array ('bachiller','universitario')),
'municipio' => $faker->word,
'parroquia' => $faker->word,
'sector' => $faker->word,
'direccion' => $faker->address,
'unidad_produccion' => $faker->word,
'organizacion' => $faker->word,
'telefono' => $faker->phoneNumber,
'email' => $faker->unique()->safeEmail,
'created_at' => $faker->dateTimeThisDecade,
'updated_at' => $faker->dateTimeThisDecade,
/*
$faker->randomElement($array = array ('v','j')) .
$table->string('cedula');
$table->primary('cedula');
$table->string('nombre');
$table->string('apellido');
$table->enum('sexo', ['f', 'm']);
$table->string('tipo');
$table->string('rif');
$table->string('representante');
$table->string('nivel_educativo');
$table->string('municipio');
$table->string('parroquia');
$table->string('sector');
$table->string('direccion');
$table->string('unidad_produccion');
$table->string('organizacion');
$table->string('telefono');
$table->string('email')->unique();
*/
];
});
$factory->define(App\solicitudes::class, function (Faker $faker) {
static $password;
return [
/*
$table->increments('id');
$table->string('lugar');
$table->string('tipo');
$table->string('solicitud');
$table->string('observaciones');
$table->string('fundo');
$table->timestamps();
$table->softDeletes(); //deleted_at
$table->string('persona_Cedula');
$table->string('funcionario_Cedula');
*/
'lugar' => $faker->state,
'tipo' => $faker->state,
'solicitud' => $faker->sentence(3, true),
'observaciones' => $faker->sentence(6, true),
'fundo' => $faker->name,
'fecha' => $faker->dateTimeThisDecade->format('Y-m-d'),
'created_at' => $faker->dateTimeThisDecade,
'updated_at' => $faker->dateTimeThisDecade,
];
});
$factory->define(App\funcionarios::class, function (Faker $faker) {
static $password;
return [
/*
$table->string('cedula');
$table->primary('cedula');
$table->string('email')->unique();
$table->string('nombre');
$table->string('apellido');
$table->enum('sexo', ['f', 'm']);
$table->string('telefono');
$table->string('direccion');
$table->string('cargo');
$table->string('departamento');
*/
'cedula' => $faker->randomNumber($nbDigits = 8, $strict = false),
'nombre' => $faker->firstName,
'apellido' => $faker->lastName,
'email' => $faker->unique()->safeEmail,
'sexo' => $faker->randomElement($array = array ('m','f')),
'direccion' => $faker->address,
'telefono' => $faker->phoneNumber,
'cargo' => $faker->jobTitle,
'departamento' => $faker->company,
'created_at' => $faker->dateTimeThisDecade,
'updated_at' => $faker->dateTimeThisDecade,
];
});
| true |
d14e2783ca9872187f53465018e1657ca3b17640 | PHP | ATouhou/wiki-kamus-al-quran-kata-per-kata | /utils/php/quran-rename-words-to-simple-clean-(access-from-db)2.php | UTF-8 | 1,980 | 2.59375 | 3 | [] | no_license | <?php
set_time_limit(999999);
?>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body onload_XXX='next()'>
<?php
$surat = $_GET['surat'];
if($surat=='') $surat = 1;
?>
<?php
$conn = mysql_connect("localhost", "webuser", "bismillah");
mysql_set_charset('utf8',$conn);
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("quran")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT t.*
FROM `terjemah_kata` t
WHERE t.quran_simple_clean!=t.arab
";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
$dir = 'D:/dropbox/projects/kamus-al-quran/kamus-al-quran.local/var/pages/';
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
// $content = $row["arab_harokat"] . ' = ' . $row['indonesia'];
$i = $i + 1;
$oldname = $dir . $row['arab'] . '.txt';
$newname = $dir . $row['quran_simple_clean'] . '.txt';
if ( file_exists($oldname) && !file_exists($newname)) {
echo $i . ": Renaming " . $oldname . " to " . $newname . "<br>\n";
$content = file_get_contents($oldname);
$content = str_replace($row['arab'] . ' = ', $row['quran_simple_clean'] . ' = ', $content);
file_put_contents($oldname, $content);
@rename($oldname, $newname);
}
}
mysql_free_result($result);
echo 'Done!';
?>
</body>
<script lang='javascript'>
function next() {
document.location.href ='<?php echo $_SERVER["SCRIPT_NAME"]; ?>?surat=<?php echo $surat+1 ?>';
}
</script>
</html>
| true |
ecf1a6c87fd9322431f0a606a0bf13ab5d5598af | PHP | cristianbb98/ProyectoSoftware | /Pruebas/prueba1.php | UTF-8 | 1,329 | 3.171875 | 3 | [] | no_license | <?php
$n = 2;
function polinomioLegendre($n){
if($n==0){
return "1";
}else if($n==1){
return '$x';
}else{
return (1/$n).'*'.((2*$n-1).'*$x*'.polinomioLegendre($n-1).'-'.($n-1)*polinomioLegendre($n-2));
}
}
function f($x){
global $n;
eval('$f='.polinomioLegendre($n).';');
return $f;
}
function calcularDerivada1($x){
$delta_t = 0.1;
$derivada = 0;
do {
$derivada_anterior=$derivada;
$derivada=(f($x+$delta_t) - f($x-$delta_t))/(2*$delta_t);
} while (abs($derivada-$derivada_anterior) > pow(10, -8));
return $derivada;
}
function calcularDerivada($polinomio,$t){
$delta_t = 0.1;
$cont = 0;
$derivada = 0;
do{
$derivada_anterior = $derivada;
eval('$fun1 = '.str_replace('$x', '($t + $delta_t)', $polinomio).';');
eval('$fun2 = '.str_replace('$x', '($t - $delta_t)', $polinomio).';');
$derivada=($fun1 - $fun2)/(2*$delta_t);
$delta_t = $delta_t/2;
$cont++;
}while(abs($derivada-$derivada_anterior) > pow(10, -8));
return $derivada;
}
echo calcularDerivada(polinomioLegendre(2),2)."<br>";
echo calcularDerivada1(2);
//echo calcularDerivada(polinomioLegendre(2),2);
//echo polinomioValor();
/*$hola=3;
$frase= 'es un $hola como estas';
echo $frase."<br>";
eval('$fun1 = '.'$hola+4'.';');
echo $fun1;*/
?>
| true |
a054b7a6c65acc181c04817d7fa3315c461dedb7 | PHP | n00bsaiboth/LAMP-messaging-system | /messages.php | UTF-8 | 1,848 | 2.703125 | 3 | [
"MIT"
] | permissive | <?php
session_start();
include("__/php/functions.php");
include("__/php/config.php");
include("__/php/header.php");
if(isset($_SESSION["id"]) && !empty($_SESSION["id"])) {
$id = validate($_SESSION["id"]);
$id = filter_var($id, FILTER_VALIDATE_INT);
// this settype seems to mess something up, because
// the id number is not updating into profile file.
// $id = settype($id, "integer");
// try another way to do it, see if it works
$id = (int) $id;
}
if(empty($_SESSION["id"])) {
$_SESSION["error"] = "Not so fast, it looks like you have not logged in yet. You need to be logged in to send new message. ";
header("Location: error.php");
} else {
?>
<section class="container" id="messages">
<h2>Welcome to messages</h2>
<?php
if(isset($id) && !empty($id)) {
getNewMessages($dbh, $id);
} else {
echo "<p>No new messages. </p>";
}
?>
</section>
<section class="container" id="sendnewmessage">
<h2>Send message to</h2>
<form action=<?php echo htmlspecialchars("process_sendmessage.php"); ?> method="post">
<div class="form-group">
<label for="username">Username: </label>
<input type="text" class="form-control" name="username" id="username">
</div>
<div class="form-group">
<label for="header">Header: </label>
<input type="text" class="form-control" name="header" id="header">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" id="message" name="message" id="message" rows="3"></textarea>
</div>
<input type="submit" class="btn btn-primary" name="submit" id="submit" value="Send">
</form>
</section>
<?php
}
include("__/php/footer.php");
?> | true |
70d7a79bf0f42c6d5a023d346e26509d36ba2454 | PHP | sozgat/LaravelMarketPlace | /tests/Unit/SumTwoNumbersTest.php | UTF-8 | 519 | 2.921875 | 3 | [
"MIT"
] | permissive | <?php
namespace Tests\Unit;
use App\Http\Controllers\SumTwoNumbersController;
use PHPUnit\Framework\TestCase;
class SumTwoNumbersTest extends TestCase
{
/**
* A basic unit test example.
*
* @return void
*/
public function test_sum_two_numbers()
{
$sumTwoNumbers = new SumTwoNumbersController();
$result = $sumTwoNumbers->sumTwoNumbers(1,5);
$this->assertEquals($result,6);
$this->assertTrue(is_int($result),'Function return type is int');
}
}
| true |
1515a2f2d6969b86b9f8761a23e8e68832f72f72 | PHP | silvapasache/inventario | /app/Http/Controllers/Auth/RegisterController.php | UTF-8 | 3,276 | 2.515625 | 3 | [] | no_license | <?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Roles;
use Illuminate\Http\Request;
use Illuminate\Auth\Events\Registered;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* @var string
*/
protected $redirectTo = '/usuario';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*'dni' => ['requerid','string', 'max:8'],
* @param array $data
* @return \Illuminate\Contracts\Validation\Validator
*/
public function showRegistrationForm()
{
$roles=Roles::orderBy('id','asc')->paginate(10);
return view('auth.register',compact('roles'));
}
protected function validator(array $data)
{
return Validator::make($data, [
'nombre' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'dni'=>['required','string','unique:users'],
'telefono'=>['string','max:15'],
'direccion'=>['string','max:100'],
'usuario'=>['required','string','unique:users',],
'password' => ['required', 'string', 'min:5', 'confirmed'],
'idrol' => ['required', 'string'],
'estado'=>['string'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return \App\User
*/
protected function create(array $data)
{
$request=app('request');
if ($request->hasFile('imagen')) {
$fileNameCompleto=$request->file('imagen')->getClientOriginalName();
$fileName=pathinfo($fileNameCompleto,PATHINFO_FILENAME);
$fileExtension=$request->file('imagen')->guessClientExtension();
$fileNameToStore=time().'.'.$fileExtension;
$path=$request->file('imagen')->storeAs('public/img/user/',$fileNameToStore);
}else{$fileNameToStore='noimagen.png';}
return User::create([
'nombre' => $data['nombre'],
'email' => $data['email'],
'dni' => $data['dni'],
'telefono' => $data['telefono'],
'direccion' => $data['direccion'],
'imagen'=>$fileNameToStore,
'usuario' => $data['usuario'],
'password' => Hash::make($data['password']),
'idrol' => $data['idrol'],
'estado'=>$data['estado'],
]);
}
}
| true |
1fca08254e34d08a7ad9f37f7148de8b4f1b5f99 | PHP | sekys/php-collection | /protected/classes/BASE/class.ObjectArray.php | UTF-8 | 1,831 | 3.203125 | 3 | [
"MIT"
] | permissive | <?
class ObjectArray {
protected $childs, $activechild, $lastchild;
public $data;
public function __contruct() {
$this->childs = NULL;
$this->data = NULL;
$this->activechild = false;
$this->lastchild = NULL;
}
public function add($data) {
if($this->IsActive()) {
$this->lastchild->add($data);
return;
}
$this->childs[] = new ObjectArray();
$this->lastchild = &$this->childs[count($this->childs)-1];
$this->lastchild->data = $data;
}
public function next() {
if($this->IsActive()) {
$this->lastchild->next();
return;
}
$this->activechild = true;
}
public function back() {
if($this->IsActive()) {
if($this->lastchild->activechild == true) {
$this->lastchild->back();
return;
}
}
$this->activechild = false;
}
/*public function find($data) {
if($this->lastchild != NULL ) {
$this->lastchild->find($data);
return;
}
foreach($this->data as $a) {
if($a == $data) return true;
}
return false;
} */
public function GenerateArray() {
$out = $this->data;
if($this->lastchild != NULL) {
$data = array();
foreach($this->childs as $ch) {
$data[] = $ch->GenerateArray();
}
$out['data'] = $data;
}
return $out;
}
public function DataGenerateArray() {
// Len oprava maleho bugu
$data = $this->GenerateArray();
return $data['data'];
}
protected function IsActive() {
return ($this->lastchild != NULL and $this->activechild);
}
}
?>
| true |
7f106df72401a75053656b53e2fd147a881481c6 | PHP | vavavr00m/noserub | /app/models/services/youtube.php | UTF-8 | 1,711 | 2.703125 | 3 | [] | no_license | <?php
class YoutubeService extends AbstractService {
public function init() {
$this->name = 'YouTube';
$this->url = 'http://youtube.com/';
$this->service_type = 6;
$this->icon = 'youtube.gif';
$this->has_feed = true;
}
public function detectService($url) {
return $this->extractUsername($url, array('#youtube.com/user/(.+)#'));
}
public function getAccountUrl($username) {
return 'http://www.youtube.com/user/' . $username;
}
public function getDatetime($feeditem, $format = 'Y-m-d H:i:s') {
$pubDate = $feeditem->get_item_tags('', 'pubDate');
$pubDate = @$pubDate[0]['data'];
return date($format, strtotime($pubDate));
}
public function getContent($feeditem) {
$content = array();
$raw_content = $feeditem->get_content();
if(preg_match('/watch\?v=(.*)[&"]/iU', $raw_content, $matches)) {
$content['id'] = $matches[1];
$content['url'] = 'http://www.youtube.com/watch?v=' . $content['id'];
$content['thumb'] = 'http://i.ytimg.com/vi/' . $content['id'] . '/default.jpg';
$content['embedd'] = '<object width="560" height="340"><param name="movie" value="http://www.youtube.com/v/' . $content['id'] . '&hl=de&fs=1&"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' . $content['id'] . '&hl=de&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="560" height="340"></embed></object>';
}
return $content;
}
public function getFeedUrl($username) {
return 'http://www.youtube.com/rss/user/' . $username . '/videos.rss';
}
} | true |
5043455802b0f2a6fbec9aeb97e1601e85de5503 | PHP | vubla/core | /search/faststringfilter.php | UTF-8 | 5,491 | 2.828125 | 3 | [] | no_license | <?php
if(!defined('DB_METADATA')){
echo "No config";
exit;
}
class FastStringFilter extends ConjunctiveStringFilter {
function __construct($wid,$search,$fullSearch = null){
parent::__construct($wid,$search,$fullSearch);
}
protected function filter(array $product_ids){
if(is_null($this->original)){
return array();
}
/// If full search we search amoung everything, which here is equivalent to null.
$searchAmong = $this->getFullSearch() ? null : $product_ids;
/// If empty query we just search right away.
if($this->original == '')
{
return $this->result = $this->search(array(),$searchAmong);
}
/// Takes the words remove the ends and put them in the words to process array
$this->original_search_array = $this->prepareWords($this->original);
/// Initial search
$this->result = $this->search($this->original_search_array,$searchAmong);
return $this->result;
}
/**
* @words Array of strings to search for
* if empty array is inserted, everything is found
* if non-array is inserted, nothing is found
* @minOptions Array of strings which names the options to search for
*/
protected function search($words,$product_ids = null,$fuzzyThres = 0) {
################## BUILDING RANKING QUERY ##################
################## BUILDING RANKING QUERY ##################
################## BUILDING RANKING QUERY ##################
################## BUILDING RANKING QUERY ##################
$qs = array();
$productIdsWhere = '';
if(is_array($product_ids))
{
if(empty($product_ids)) // No point in searching among nothing
{
return array();
}
$productIdsWhere = ' and ' . $this->generateWhereClauseFromProductIds($product_ids,'p','id');
}
if(!is_array($words)) // If some one puts in a string or object or something crazy, we just return empty array
{
return array();
}
$limit = Settings::get('suggestions',$this->getWid());
$limitString = '';
if($limit > 0) {
$limitString = " LIMIT $limit";
}
if(empty($words)) // means that every product should be found
{
/**
* Please notice that the order of arguments of this select actually matters!
* p.pid have been placed later, which resulted in no image link when grouping later on
*/
$query =
'(SELECT
p.id as product_id, 0 as boosted, 0 as inname , 0 as indesc, 0 as incategory
FROM
products p
WHERE
1 = 1
'.
$productIdsWhere. ')';
$qs[] = $query;
}
else
{
foreach($words as $word) {
$this->words_i_search_for[] = $word;
/**
* Please notice that the order of arguments of this select actually matters!
* p.pid have been placed later, which resulted in no image link when grouping later on
*/
$query =
'(SELECT
p.id as product_id, MAX(p.boosted) as boosted, SUM(inname) * ' .$word->getMultiplyer() .' as inname , SUM(indesc) * ' .$word->getMultiplyer() .' as indesc, SUM(incategory) * ' . $word->getMultiplyer() . ' as incategory
FROM
products p
inner join word_relation wr
on wr.product_id = p.id
inner join words w
on w.id = wr.word_id
WHERE
wr.inname > 0 and
w.word LIKE ' .$this->vdo->quote($word->short.'%').
$productIdsWhere. '
GROUP BY p.id)';
$qs[] = $query;
}
}
# Le grande Finale
$this->query =
'SELECT product_id FROM
(SELECT
product_id as product_id, MAX(boosted) as boosted, SUM(inname) as inname, SUM(indesc) as indesc, SUM(incategory) as incategory '.
' FROM (' .
implode( "\n UNION ALL \n", $qs) . ') AS innermost
GROUP BY product_id HAVING count(*) >= '.sizeof($words).' ORDER BY boosted desc, inname desc, incategory desc, indesc desc ) AS middle '.
$limitString;
############# STOP BUILDING RANKING QUERY ###############
############# STOP BUILDING RANKING QUERY ###############
############# STOP BUILDING RANKING QUERY ###############
############# STOP BUILDING RANKING QUERY ###############
############# STOP BUILDING RANKING QUERY ###############
### Makes sure DB hasen't changed
$this->vdo->exec('USE '.DB_PREFIX.(int)$this->getWid());
### The actual execution
$result = $this->vdo->getTableList($this->query, '');
if(is_null($result)) {
return array();
}
$out = array();
foreach ($result as $item) {
$out[] = (int)$item->product_id;
}
return $out;
}
public function query() {
return $this->query;
}
} | true |
b9f55cc80e1558437bbd7a4e11a455114fbf1548 | PHP | ahmed-hassan-sadek/courses | /backend/auther.php | UTF-8 | 2,801 | 3.015625 | 3 | [] | no_license | <?php
include("connect.php");
class Auther
{
/**
* get data from form and encrept password by use SHA1()
* get value of role
* check if email or password found
*/
public static function login()
{
global $cont;
$email = $_POST['email'];
$password = SHA1($_POST['password']);
$admin = $cont->prepare("SELECT `role` FROM `users` WHERE `email` = ? AND `password` = ? LIMIT 1");
$admin->execute([$email , $password]);
$adminData = $admin->fetchObject();
session_start();
if(empty($adminData))
{
$_SESSION['error'] = "Email or Password is Invaliad";
header("location:../admin/login.php");
}
else
{
$_SESSION['role'] = $adminData->role;
header("location:../admin/index.php");
}
}
/**
* get data from form and encrept password by use SHA1()
* insert data into users table
* session with message
* header location
*/
public static function signUp()
{
global $cont;
$name = $_POST['name'];
$email = $_POST['email'];
$password = SHA1($_POST['password']);
$signup = $cont->prepare("INSERT INTO users(`name`, `email`, `password` , `role`) VALUES (? , ? , ? , ?) ");
$signup->execute([$name , $email , $password , 0]);
session_start();
$_SESSION['message'] = "Data entering correctly";
header("location:../login.php");
}
/**
* get data from form and encrept password by use SHA1()
* get value of email
* check if email or password found
*/
public static function checkLogin()
{
global $cont;
$email = $_POST['email'];
$password = SHA1($_POST['password']);
$user = $cont->prepare("SELECT `email` FROM `users` WHERE `email` = ? AND `password` = ? LIMIT 1");
$user->execute([$email , $password]);
$adminData = $user->fetchObject();
session_start();
if(empty($adminData))
{
$_SESSION['error'] = "Email or Password is Invaliad";
header("location:../login.php");
}
else
{
$_SESSION['email'] = $adminData->email;
header("location:../index.php");
}
}
}
/**
* check if press to button or not
* go to function login at class Auther
*/
if(isset($_POST['submit']))
{
Auther::login();
}
/**
* check if press to button or not
* go to function checkLogin at class Auther
*/
if(isset($_POST['submit']))
{
Auther::checkLogin();
}
/**
* check if press to button or not
* go to function signUp at class Auther
*/
if (isset($_POST['sign-submit']))
{
Auther::signUp();
} | true |
22c554c5591528dc0ce95501169bac04f838a35a | PHP | freelaxdeveloper/laravel-store | /app/Console/Commands/ImportImage.php | UTF-8 | 2,268 | 2.671875 | 3 | [] | no_license | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\{Product,Category};
use Storage;
use File;
class ImportImage extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'ImportImage';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// Product::query()->delete();
// Storage::deleteDirectory('public');
// dd();
$categoriesID = $this->ask('В какие категории добавить? (перечислите ID или названия категорий через запятую)');
$categoriesID = explode(',', $categoriesID);
$categories = Category::whereIn('id', $categoriesID)->orWhereIn('name', $categoriesID)->get();
if (!$categories->count()) {
return $this->error('Категории не найдены');
}
$this->comment('Продукты будут добавлены в:');
$this->info(implode(', ', $categories->pluck('name')->toArray()));
if (!$this->confirm('Продолжить? (Yes/no)')) {
return;
}
$files = Storage::allFiles('images');
$bar = $this->output->createProgressBar(count($files) - 1);
foreach ( $files as $file ) {
$ext = File::extension($file);
if ( 'gitkeep' == $ext) {
continue;
}
$title = File::name($file);
$product = new Product;
$product->title = $title;
$product->save();
Storage::copy(($file), "public/uploads/products/{$product->id}/" . time() . md5(microtime()) . '.' . $ext);
$product->categories()->attach($categories->pluck('id')->toArray());
$bar->advance();
}
$bar->finish();
$this->info('Finish!');
}
}
| true |
f8837172837dc09748d74cb712ce853f52c8375d | PHP | tremor-od/pizza.loc | /app/controllers/AuthController.php | UTF-8 | 3,637 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php
/**
* Created by PhpStorm.
* User: oleg
* Date: 29.01.15
* Time: 14:44
*/
class AuthController extends HomeController {
/*
* Construct
* @author Tremor
*/
public function __construct(){
parent::__construct();
}
/**
* Регистрация нового пользователя
* @return
* @author Tremor
*/
public function registration(){
if(Request::isMethod('post')){
$post = Input::all();
$rules = array(
'email' => 'required|email|unique:user,email',
'password' => 'required',
);
$validator = Validator::make($post, $rules);
if($validator->fails()){
$this->setMessage($validator->messages()->all(), 'error');
return Redirect::route('registration')->withInput();
}else{
$user = new User;
$user->email = Input::get('email');
$user->password = Hash::make(Input::get('password'));
$user->save();
Auth::loginUsingId($user->id);
return Redirect::intended('/');
}
}
return View::make('auth.signup')->with($this->data);
}
/**
*
* @return nothing
* @author Tremor
*/
public function login(){
if(Request::isMethod('post')){
$post = Input::all();
$rules = [
'email' => 'required|email',
'password' => 'required',
];
$validator = Validator::make($post, $rules);
if($validator->fails()){
$this->setMessage($validator->messages()->all(), 'error');
return Redirect::route('login')->withInput();
}else{
$email = trim(Input::get('email'));
$password = trim(Input::get('password'));
$remember = (Input::get('remember') == 1) ? true : false;
if (Auth::attempt(array('email' => $email, 'password' => $password, 'is_admin' => 1))) {
return Redirect::route('admin');
} elseif (Auth::attempt(array('email' => $email, 'password' => $password))) {
return Redirect::route('home');
} else {
$this->setMessage('failed login', 'error');
return Redirect::route('login')->withInput();
}
}
}
return View::make('auth.signin')->with($this->data);
}
/**
*
* @param $some
* @return nothing
* @author Tremor
*/
public function generatePassword(){
// Символы, которые будут использоваться в пароле.
$chars="qazxswedcvfrtgbnhyujmkiolp1234567890QAZXSWEDCVFRTGBNHYUJMKIOLP";
// Количество символов в пароле.
$max = 10;
// Определяем количество символов в $chars
$size = StrLen($chars)-1;
// Определяем пустую переменную, в которую и будем записывать символы.
$password = null;
// Создаём пароль.
while($max--)
$password .= $chars[rand(0, $size)];
return $password;
}
/**
* Logout
* @return
* @author Tremor
*/
public function logout(){
Session::flush();
Auth::logout();
return Redirect::to('/');
}
} | true |
c684b029890a55f40a931daf5556fe5078465399 | PHP | jworksuk/extra-pdo | /tests/ExtraPDOTest.php | UTF-8 | 5,010 | 2.65625 | 3 | [
"MIT"
] | permissive | <?php
namespace JWorksUK;
use JWorksUK\Acme\Model;
use PDO;
use PHPUnit\Framework\Assert;
use PHPUnit\Framework\TestCase;
class ExtraPDOTest extends TestCase
{
public function extraPdoProvider()
{
return [
[ExtraPDO::createSqliteConnection(__DIR__.'/test.db')],
[ExtraPDO::createMySqlConnection($_ENV['DB_NAME'], $_ENV['DB_HOST'], $_ENV['DB_USER'], $_ENV['DB_PASS'])],
[ExtraPDO::createSqliteMemoryConnection()],
];
}
/**
* @test
*/
public function createSqliteMemoryConnection()
{
$connection = ExtraPDO::createSqliteMemoryConnection();
Assert::assertInstanceOf(PDO::class, $connection);
Assert::assertInstanceOf(ExtraPDO::class, $connection);
Assert::assertEquals('sqlite', $connection->getAttribute(PDO::ATTR_DRIVER_NAME));
}
/**
* @test
*/
public function createSqliteConnection()
{
$connection = ExtraPDO::createSqliteConnection(__DIR__.'/test.db');
Assert::assertInstanceOf(PDO::class, $connection);
Assert::assertInstanceOf(ExtraPDO::class, $connection);
Assert::assertEquals('sqlite', $connection->getAttribute(PDO::ATTR_DRIVER_NAME));
}
/**
* @test
*/
public function createMySqlConnection()
{
$connection = ExtraPDO::createMySqlConnection(
$_ENV['DB_NAME'],
$_ENV['DB_HOST'],
$_ENV['DB_USER'],
$_ENV['DB_PASS']
);
Assert::assertInstanceOf(PDO::class, $connection);
Assert::assertInstanceOf(ExtraPDO::class, $connection);
Assert::assertEquals('mysql', $connection->getAttribute(PDO::ATTR_DRIVER_NAME));
}
/**
* @test
*/
public function createWithOptions()
{
$pdo = ExtraPDO::createSqliteMemoryConnection([
PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT
]);
Assert::assertInstanceOf(ExtraPDO::class, $pdo);
Assert::assertEquals(PDO::ERRMODE_SILENT, $pdo->getAttribute(PDO::ATTR_ERRMODE));
Assert::assertEquals(PDO::FETCH_ASSOC, $pdo->getAttribute(PDO::ATTR_DEFAULT_FETCH_MODE));
Assert::assertEquals([ExtraPDOStatement::class], $pdo->getAttribute(PDO::ATTR_STATEMENT_CLASS));
}
/**
* @dataProvider extraPdoProvider
* @test
* @param ExtraPDO $pdo
*/
public function extraPdoStatement(ExtraPDO $pdo)
{
$pdo->exec(file_get_contents(__DIR__.'/test.sql'));
$row = $pdo
->executeStatement('SELECT * FROM todos WHERE id=:id', [
'id' => '15983acf-022f-303a-bfef-a096eaebbf7c'
])
->fetchAndMap(function ($row) {
return new Model(
$row['id'],
$row['name'],
$row['list_id'],
new \DateTime($row['updated_at']),
new \DateTime($row['created_at'])
);
});
Assert::assertInstanceOf(Model::class, $row);
Assert::assertEquals('amet', $row->getName());
$rows = $pdo
->executeStatement('SELECT * FROM todos WHERE list_id=:listId', [
'listId' => '05aab6f6-e991-3c59-a980-832cca75c578'
])
->fetchAllAndMap(function ($row) {
return new Model(
$row['id'],
$row['name'],
$row['list_id'],
new \DateTime($row['updated_at']),
new \DateTime($row['created_at'])
);
});
Assert::assertTrue(is_array($rows));
Assert::assertCount(10, $rows);
}
/**
* @dataProvider extraPdoProvider
* @test
* @param ExtraPDO $pdo
*/
public function extraPdoStatementNoResults(ExtraPDO $pdo)
{
$pdo->exec(file_get_contents(__DIR__.'/test.sql'));
$noRow = $pdo
->executeStatement('SELECT * FROM todos WHERE id=:id', [
'id' => 'IdNotInDatabase'
])
->fetchAndMap(function ($row) {
return new Model(
$row['id'],
$row['name'],
$row['list_id'],
new \DateTime($row['updated_at']),
new \DateTime($row['created_at'])
);
});
Assert::assertFalse($noRow);
$noRows = $pdo
->executeStatement('SELECT * FROM todos WHERE list_id=:listId', [
'listId' => 'YouWontFindAnything'
])
->fetchAllAndMap(function ($row) {
return new Model(
$row['id'],
$row['name'],
$row['list_id'],
new \DateTime($row['updated_at']),
new \DateTime($row['created_at'])
);
});
Assert::assertTrue(is_array($noRows));
Assert::assertEmpty($noRows);
}
}
| true |
4ad55f4ec6e5d1d297e11e40d45889ab2d1c73ba | PHP | thaerfayyad/adminLte-js | /app/Http/Controllers/UserController.php | UTF-8 | 3,097 | 2.546875 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Symfony\Component\HttpFoundation\Response;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
//
$data = User::withCount('permissions')->get();
return response()->view('cms.users.index',['users'=>$data]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
//
return response()->view('cms.users.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
$validator = Validator($request->all(),[
'name' => 'required|string|min:3|max:45',
'email' => 'required|email|string|unique:users,email',
'mobile'=>'required|numeric|digits:8|unique:users,mobile'
]);
if(!$validator->fails()) {
$user =new User();
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->mobile = $request->input('mobile');
$user->password = Hash::make('12345');
$isSave = $user->save();
return response()->json([
'message' => $isSave ? 'Created successfully' : 'Create Failed'
], $isSave ? Response::HTTP_CREATED : Response::HTTP_BAD_REQUEST);
} else {
return response()->json([
'message' => $validator->getMessageBag()->first()
],Response::HTTP_BAD_REQUEST);
}
}
/**
* Display the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function show(User $user)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function edit(User $user)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function update(Request $request, User $user)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\User $user
* @return \Illuminate\Http\Response
*/
public function destroy(User $user)
{
//
$isDelete = $user->delete();
return response()->json([
'icon' => $isDelete ? 'success' : 'error',
'title' => $isDelete ? 'Delete successfully' : 'Delete Failed'
], $isDelete ? Response::HTTP_OK :Response::HTTP_BAD_REQUEST );
}
}
| true |
b1fc4b780af35053a6f03ef38e872e62fc060222 | PHP | Sprovider90/PhpDesignPatterns | /IMooc/Database/IDatabase.php | UTF-8 | 252 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020-06-30
* Time: 15:49
*/
namespace IMooc\Database;
interface IDatabase{
function connect($host,$user,$pwd,$dbname);
function query($sql);
function close();
} | true |
604fb756b75014995390608fde5d75fbf6ab48ad | PHP | tesav/ParallelComputing | /classes/Begotten.php | UTF-8 | 3,883 | 2.84375 | 3 | [] | no_license | <?php
defined('R') or die('Доступ запрещен !!!');
/**
* Begotten
*
* Создает объект взаимодействия с порождающим скриптом
*
* @author Тесминецкий Александр <tesav@yandex.ru>
*/
class Begotten extends Communication implements IBegotten {
/**
* Ключ выхода
*
* @var boolean
*/
public $stop = false;
/**
* Цвет вывода сообщений
*
* @var string
*/
public $e_color = '#055';
/**
* Конструктор класса Begotten
*/
public function __construct() {
// Проверяем входные параметры
!isset($_POST['id']) and die('Отсутствует идентификатор !');
!isset($_POST['time']) and die('Отсутствует параметр времени !');
// Устанавливаем опорное время
Begotten::$_timeAbout = microtime(true) - $_POST['time'];
// Создаем потоки
// Входящий: ~~
// Исходящий: ~
//
parent::__construct($this->_prefix . $_POST['id'], $_POST['id']);
// Устанавливаем обработчик для возможности
// перехвата некритических ошибок и предупреждений
set_error_handler(array('Begotten', 'error_handler'));
// Фиксируем и отправляем время старта
$this->_report = Begotten::timer();
$this->_send();
}
/**
* Метод ожидает поступления, обрабатывает и отсылает данные
*/
final public function run() {
try {
try {
// Получаем и обрабатываем
$this->_report = $this->_waitAcceptHandler();
//
} catch (Exception_Begotten $e) {
$this->_report = Begotten::decor($e, $this->e_color);
}
// Отправляем
$this->_send();
//
} catch (Exception_Communication $e) {
$this->_closeOut();
echo $this->_exit();
}
}
/**
* Обрабатывает поступившие данные
*
* @return mixed
*/
protected function _handler() {
// Выходим
if ($this->_report === Begotten::EXIT_)
return $this->_exit();
// Читаем инструкцию
return $this->_e(Begotten::_manual());
}
/**
* Если уровень соответствующих ошибок установлен,
* бросает исключение,
* иначе возвращает false
*
* @param string
* @param integer
* @return boolean
* @throws Exception_Begotten
*/
protected function _e($text, $code = E_WARNING) {
if (error_reporting() & $code) {
throw new Exception_Begotten($text, $code);
}
return false;
}
/**
* Метод останавливает работу скрипта
*
* @return float
*/
private function _exit() {
//
$this->stop = true;
//
return Begotten::timer();
}
/**
* Обработчик ошибок
*
* @param integer
* @param string
* @return boolean
* @throws Exception_Begotten
*/
public static function error_handler($code, $error) {
if (error_reporting() & $code) {
throw new Exception_Begotten($error, $code);
}
return true;
}
} | true |
2b87e5d9bc504976878d51346ec8b8b3889b4067 | PHP | mayconbordin/laragen | /src/Mayconbordin/Laragen/Generator/LangGenerator.php | UTF-8 | 2,428 | 2.828125 | 3 | [
"MIT"
] | permissive | <?php namespace Mayconbordin\Laragen\Generator;
use Mayconbordin\Laragen\Exceptions\InvalidFormatException;
use Mayconbordin\Laragen\Helpers\FieldValidationHelper;
use Mayconbordin\Laragen\Parsers\SchemaParser;
class LangGenerator extends Generator
{
/**
* Get stub name.
*
* @var string
*/
protected $stub = 'lang';
/**
* @var string
*/
protected $language;
/**
* @var string
*/
protected $translations;
/**
* ModelGenerator constructor.
*
* @param array $options [ fillable=List of fillable fields, comma separated;
* fields=List of fields (with its descriptions), comma separated;
* table_name=The name of the table, if different than the model name ]
*/
public function __construct(array $options = array())
{
parent::__construct('lang', $options);
$this->language = array_get($options, 'language', 'en');
$this->translations = array_get($options, 'translations', null);
}
/**
* Get destination path for generated file.
*
* @return string
*/
public function getFileName()
{
return $this->language.'/'.strtolower($this->getName());
}
/**
* Get array replacements.
*
* @return array
*/
public function getReplacements()
{
return array_merge(parent::getReplacements(), [
'translations' => $this->getTranslations()
]);
}
/**
* Get the fillable attributes.
*
* @return string
* @throws InvalidFormatException
*/
public function getTranslations()
{
if (!$this->translations) {
return '';
}
// match key='value' pairs
$matches = preg_match_all('/(\w+)\s*=\s*(["\'])((?:(?!\2).)*)\2/', $this->translations, $translations, PREG_SET_ORDER);
if (strlen($this->translations) > 0 && $matches == 0) {
throw new InvalidFormatException("Translations should follow the format: <key1>='<value1>', <key2>='<value2>'.");
}
$results = '';
foreach ($translations as $translation) {
if (sizeof($translation) != 4) continue; //should throw an exception here
$results .= str_repeat(" ", 4) . "'{$translation[1]}' => '{$translation[3]}'," . PHP_EOL;
}
return $results;
}
}
| true |
20e6e25aa40b2e1f58d6bb29111654abb0ba4381 | PHP | dimaoag/teachme | /shop/repositories/shop/StatusRepository.php | UTF-8 | 662 | 3.015625 | 3 | [
"BSD-3-Clause"
] | permissive | <?php
namespace shop\repositories\shop;
use shop\entities\shop\Status;
use shop\repositories\NotFoundException;
class StatusRepository
{
public function get($id): Status
{
if (!$status = Status::findOne($id)) {
throw new NotFoundException('Status is not found.');
}
return $status;
}
public function save(Status $status): void
{
if (!$status->save()) {
throw new \RuntimeException('Saving error.');
}
}
public function remove(Status $status): void
{
if (!$status->delete()) {
throw new \RuntimeException('Removing error.');
}
}
} | true |
d3a4a384ecb608eb2af29bbe1b93c67467a3dc63 | PHP | basbrouwers/dino | /Http/Controllers/AnimalController.php | UTF-8 | 922 | 2.59375 | 3 | [] | no_license | <?php
/**
* Created by PhpStorm.
* User: bas
* Date: 10/05/18
* Time: 20:58
*/
namespace Modules\Shelter\Http\Controllers;
use Illuminate\Http\Request;
use Modules\Core\Http\Controllers\BasePublicController;
use Modules\Shelter\Repositories\AnimalRepository;
use Modules\Shelter\Repositories\BreedRepository;
class AnimalController extends BasePublicController
{
private $animals;
private $breeds;
public function __construct(AnimalRepository $animal, BreedRepository $breeds){
$this->animals = $animal;
$this->breeds = $breeds;
}
public function index(Request $request)
{
return view('shelter::animals.index', ['animals' => $this->animals->all()]);
}
public function view(Animal $animal)
{
return view('shelter::animals.view', ['animal' => $animal, 'breeds' => $this->breeds->all()->sortBy('name')->pluck('name', 'id')->toArray()]);
}
} | true |
fb7fef351b25669e0341da6300455aef6a9b9206 | PHP | matirosero/rachel | /includes/overrides.php | UTF-8 | 1,065 | 2.546875 | 3 | [] | no_license | <?php
// if ( ! function_exists( 'sydney_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog
*
* @see sydney_custom_header_setup().
*/
function sydney_header_style() {
if ( get_header_image() && ( get_theme_mod('front_header_type') == 'image' && is_front_page() || get_theme_mod('site_header_type', 'image') == 'image' && !is_front_page() ) ) {
?>
<?php
if ( has_post_thumbnail() ) :
$page_object = get_queried_object();
$page_id = get_queried_object_id();
$image_array = wp_get_attachment_image_src( get_post_thumbnail_id( $page_id ), 'full' );
$header_image = $image_array[0];
else :
$header_image = get_header_image();
endif;
?>
<style type="text/css">
.header-image {
background-image: url(<?php echo $header_image; ?>);
display: block;
}
@media only screen and (max-width: 1024px) {
.header-inner {
display: block;
}
.header-image {
background-image: none;
height: auto !important;
}
}
</style>
<?php
}
}
// endif; // sydney_header_style | true |
ba4437b8b46ffc7698405d51ca3398a773d2d45b | PHP | tylerhall/Rockwell | /www/share.php | UTF-8 | 2,201 | 2.53125 | 3 | [] | no_license | <?PHP
require 'includes/master.inc.php';
if(isset($_POST['btnShare']))
{
$Auth->requireUser();
$letters = 'abcdefghjkmnpqrstuvwxyz23456789';
$slug = '';
for($i = 0; $i < 5; $i++)
$slug .= substr($letters, rand(0, strlen($letters) - 1), 1);
$s = new Share();
$s->user_id = $Auth->id;
$s->slug = $slug;
$s->nickname = $_POST['nickname'];
$s->format = $_POST['format'];
$s->accuracy = $_POST['accuracy'];
$s->dt = gmdate('Y-m-d H:i:s');
$s->insert();
redirect('share.php?id=' . $s->slug);
}
if(isset($_GET['id']))
{
$db = Database::getDatabase();
$share = $db->getRow("SELECT * FROM shares WHERE slug = " . $db->quote($_GET['id']));
if($share === false) exit;
$update = $db->getRow("SELECT * FROM updates WHERE user_id = '" . $share['user_id'] . "' ORDER BY dt DESC LIMIT 1");
if($update === false) exit;
if($share['accuracy'] == 0)
{
if($share['format'] == 'text')
echo $update['latitude'] . ',' . $update['longitude'];
if($share['format'] == 'json')
echo json_encode(array('dt' => $update['dt'], 'latitude' => $update['latitude'], 'longitude' => $update['longitude']));
exit;
}
$results_str = geturl("http://where.yahooapis.com/geocode?location=" . $update['latitude'] . "+" . $update['longitude'] . "&gflags=R&appid=aKMt.vjV34G5RhPhDrQcKU3gcmqyIKn_AvAAyfwCLQo3_yyuZneprghFfgC98LAhLg--&flags=J");
$results = json_decode($results_str);
$loc_data = $results->ResultSet->Results[0];
if($share['format'] == 'text')
{
if($share['accuracy'] == 10)
echo $loc_data->city . ', ' . $loc_data->state;
if($share['accuracy'] == 20)
echo $loc_data->state;
if($share['accuracy'] == 30)
echo $loc_data->country;
}
if($share['format'] == 'json')
{
if($share['accuracy'] == 10)
echo json_encode(array('dt' => $update['dt'], 'city' => $loc_data->city, 'state' => $loc_data->state, 'country' => $loc_data->country));
if($share['accuracy'] == 20)
echo json_encode(array('dt' => $update['dt'], 'state' => $loc_data->state, 'country' => $loc_data->country));
if($share['accuracy'] == 30)
echo json_encode(array('dt' => $update['dt'], 'country' => $loc_data->country));
}
}
| true |
ba0fc3ae371889d13a38c561004314fd23c6d9d2 | PHP | atrifonoff/My-code | /myself/Codebase.class.php | UTF-8 | 8,572 | 2.546875 | 3 | [] | no_license | <?php
/**
* Анализа кода по брой редове, брой празни редове,
* зареждащи се пакети, брой функции и др.
*
* @category bgerp
* @package myself
* @author Angel Trifonov angel.trifonoff@gmail.com
* @copyright 2006 - 2017 Experta OOD
* @license GPL 3
* @since v 0.1
* @title Анализ » Анализ на кода
*/
class myself_Codebase extends core_Manager
{
public $title = "Анализ";
public $loadList = 'plg_Created,plg_Modified';
public $listFields = 'id,path,lines,modifiedOn=Модифициране';
protected function description()
{
$this->FLD('path', 'varchar','caption=Път');
$this->FLD('code', 'text(1000000)', 'caption=Код,column=none');
$this->FLD('lines', 'int', 'caption=Брой линии');
$this->setDbUnique('path');
}
/**
* Преди показване на листовия тулбар
*
* @param core_Manager $mvc
* @param stdClass $data
*/
public static function on_AfterPrepareListToolbar($mvc, &$res, $data)
{
$data->toolbar->addBtn('Анализ', array($mvc, 'ReadFiles'));
}
/**
* @return string
*/
function act_ReadFiles()
{
/**
* Установява необходима роля за да се стартира екшъна
*/
requireRole('admin');
//В $root запомняме директорията от която трябва да стартира екшъна.
//В случая __DIR__ намира директорията на текущия файл и след това
// DIRECTORY_SEPARATOR.'..' връща една dir назад//
/**
* Директория за стартиране
*/
$root = realpath(__DIR__ . DIRECTORY_SEPARATOR. '..' );
$files = array();
$methods = array();
$usesMetods = array();
$onMethods = array();
$couldntLoadsClasses = array();
$onMethodsString = " ";
$totalLines = 0;
$totalLoadClasses = 0;
$filesCounter = 0;
$emptyLineCounter = 0;
$totalMethods = 0;
self::readFiles($root, $files);
foreach($files as $f) {
$filesCounter++;
if(self::loadClasses($root, $f, $methods,$couldntLoadsClasses, $onMethods)) {
$totalLoadClasses++;
$usesMetods = array_merge($usesMetods, $methods);
$totalMethods += count($methods);
}
$exRec = self::fetch("#path = '{$f}'");
$rec = new stdClass();
if(isset($exRec)) {
$rec->id = $exRec->id;
}
$rec->path = $f;
$ext = fileman_Files::getExt($f);
if(in_array($ext, array('php', 'js', 'shtml', 'scss'))) {
$rec->code = file_get_contents($f);
$rec->lines = substr_count($rec->code, "\n");
$totalLines += $rec->lines;
}
$emptyLineCounter+=self::emptyLineCounter($f);
self::save($rec);
}
arsort($onMethods);
$onMethodsCount = count($onMethods);
$idicatorsTable = "<table style='width: 50%; border: solid 1px'>
<tr>
<td style='border: solid black 1px;height: 20px;' >Общо файлове</td>
<td style='border: solid black 1px;height: 20px;'>$filesCounter</td>
</tr>
<tr>
<td style='border: solid black 1px;height: 20px;'>Брой линии</td>
<td style='border: solid black 1px;height: 20px;'>$totalLines</td>
</tr>
<tr>
<td style='border: solid black 1px;height: 20px;'>Брой празни редове </td>
<td style='border: solid black 1px;height: 20px;'>$emptyLineCounter</td>
</tr>
<tr>
<td style='border: solid black 1px;height: 20px;'>Брой заредени класове</td>
<td style='border: solid black 1px;height: 20px;'>$totalLoadClasses</td>
</tr>
<tr>
<td style='border: solid black 1px;height: 20px;'>Брой методи</td>
<td style='border: solid black 1px;height: 20px;'>$totalMethods</td>
</tr>
<tr>
<td style='border: solid black 1px;height: 20px;'>Брой '_on'- методи</td>
<td style='border: solid black 1px;height: 20px;'>$onMethodsCount</td>
</tr>
</table>";
$onMethodsString = "<table>";
foreach ($onMethods as $key=>$value){
$onMethodsString.="<tr><td>$key</td>
<td>$value</td></tr>";
}
$onMethodsString.="</table>";
return"$idicatorsTable $onMethodsString";
// return 'Общо файлове :'.$filesCounter.'<br>'.'Брой линии : '.$totalLines."<br>".'Брой празни редове :'.$emptyLineCounter
// .'<br>'.' Брой заредени класове : '.$totalLoadClasses."<br>".'Не успях да заредя следните PHP-класове :'.$couldntLoadsClasses
// ."<br>".'Брой методи : '.$totalMethods."<br>".'on_Methods :'.count($onMethods).'<br>'.'<br>'.$onMethodsString;
}
/**
* @param $root
* @param array $files
*/
static function readFiles($root, &$files = array())
{
if ($handle = opendir($root)) {
while (FALSE !== ($entry = readdir($handle))) {
if ($entry == "." || $entry == ".." || $entry == "unit") continue;
$entry = $root . DIRECTORY_SEPARATOR . $entry;
if(is_dir($entry)) {
self::readFiles($entry, $files);
continue;
}
$files[$entry] = $entry;
}
closedir($handle);
}
}
/**
* @param $root
* @param $f
* @param array $methods
* @return bool
*/
static function loadClasses($root, $f, &$methods=array(),&$couldntLoadsClasses=array(),&$onMethods=array())
{
// return array('isLoaded' => TRUE, 'methods' => array(...));
$ext = fileman_Files::getExt($f);
$classLoadResult = FALSE;
if(($ext === 'php') && (bool)strpos($f,'.class.php')) {
$className = str_replace($root, '', $f);
$className = str_replace(DIRECTORY_SEPARATOR, '_', trim($className, DIRECTORY_SEPARATOR));
$className = str_replace(".class.php", '', $className);
if (@cls::load($className,TRUE)) {
;
$classLoadResult = TRUE;
$class = new ReflectionClass($className);
$methods = $class->getMethods();
foreach ($methods as $id => $m) {
if (strtolower(trim($m->class)) != strtolower(trim($className))) {
unset($methods[$id]);
}else{ if(substr($m->name,0,3) == 'on_'){
// $onMethods[substr($m->name,3)] = $m->name;
$onMethods[$m->name]++;
}
}
}
} else {
$couldntLoadsClasses[] = $className;
}
}
return $classLoadResult;
}
/**
* @param string $f
* @return int
*/
static function emptyLineCounter ($f)
{
$emptyLines = 0;
$handle = fopen("$f", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
if((trim($line) == NULL)){
$emptyLines++;
}
}
fclose($handle);
} else {
return 'Error opening file';
}
return $emptyLines;
}
} | true |
ccfe382690a95d854e1f01b73970aebe1f5e15bd | PHP | hnromante/karlaFolio | /registrar.php | UTF-8 | 5,756 | 2.8125 | 3 | [] | no_license | <?php
#Crear cuenta en el perfil
require_once 'core/init.php';
include 'extend/header.php';
//Acá vamos a ingresar datos
// echo '<h1>Acá vamos a hacer las pruebas de INSERT</h1>';
// $user = DB::getInstance()->insertar(
// 'usuarios',
// array(
// 'nombreusuario' => 'miguel2',
// 'email' => 'mcastilosobarzo@gmail.com',
// 'password' => '123456',
// 'salt' => 'salt',
// 'nombre' => 'Miguel Castillo Sobarzo'
// )
// );
?>
<?php
//PRUEBA DE INPUT
// if (Input::existe('get')){
// echo 'Se ingresó data por GET';
// }
//-----------CHECK DE TOKEN Y SESION
//var_dump(Token::check(Input::get('token'))); RETORNA BOOL (FALSE)SI SE INTENTA PASAR PARAMETROS POR FUERA DE LA PÁGINA.
//PRUEBA DE INPUT
if (Input::existe('post')){
if (Token::check(Input::get('token'))){
//VALIDACION DE CAMPOS, la estructura es:
//1.- Crear instancia de la clase Validar.
$validar = new Validar();
//2.- Ocupar el metodo comprobar() de la clase Validar. Este método recibe la FUENTE (get o post) y los CAMPOS (username,password,email,etc)
$validacion = $validar->comprobar($_POST,array(
//3.- Los campos tienen asociados otro array, donde van cada una de las reglas.
'nombreusuario' => array(
'nombre' => 'Nombre de usuario',
'required' => true,
'min' => 4,
'max' => 20,
//Esta regla dice: el 'Nombre de usuario' debe ser único en la tabla 'usuarios'. Se checkea con la BD.
'unico' => 'usuarios'
),
'email' => array(
'nombre' => 'Email',
'required' => true,
'max' => 30
),
'password' => array(
'nombre' => 'Password',
'required' => true,
'min' => 6,
),
'password_r' => array(
'nombre' => 'Repetir contraseña ',
'required' => true,
//Esta regla dice que debe coincidir con la contraseña.
'coincide' => 'password'
),
'nombre' => array(
'nombre' => 'Nombre',
'required' => true,
'min' => 5,
'max' =>50
)
));
if ($validacion->correcta()){
//Registrar usuario
// echo 'VALIDACION CORRECTA';
// Session::flash('exito',"Se ha registrado correctamente!.");
// header('Location: index.php');
$usu = new Usuario();
$salt = Hash::salt(32);
try {
$usu->crear(
array(
'nombreusuario' => Input::get('nombreusuario'),
'email' => Input::get('email'),
'password' => Hash::crear(Input::get('password'),$salt),
'salt' => $salt,
'nombre' => Input::get('nombre'),
'ingreso' => date('Y-m-d H:i:s'),
'grupo' => 1
)
);
//Ahora flashiamos!
Session::flash('home','Haz sido registrado y te puedes loguear!');
Redirect::to('index.php');
}catch(Exception $e){
//ESTO DEBERÍA SER UNA REDIRECCIÓN, CON UN MENSAJE. ES DECIR, UN FLASH.
die($e->getMessage());
}
}else {
//Mostrar los errores
foreach ($validacion->errores() as $error) {
echo "{$error} <br>";
}
}
}else{
echo 'Debe ingresar los datos a través del formulario.';
}
}
?>
<div class="container">
<div class="row">
<div class="col s12 m4 l6">
<form action="" method="post">
<!-- INPUT NOMBRE DE USUARIO -->
<div class="input-field col s12 l6">
<input type="text" id="nombreusuario" name="nombreusuario" value="<?php echo escape(Input::get('nombreusuario')); ?>">
<label for="nombreusuario">Nombre de usaurio</label>
</div>
<!-- INPUT EMAIL -->
<div class="input-field col s12 l6">
<input type="email" id="email" name="email" class="validate" value="<?php echo escape(Input::get('email')); ?>">
<label for="email" data-error="wrong" data-success="right">Email</label>
</div>
<!-- INPUT PASSWORD -->
<div class="input-field col s12">
<input type="password" id="password" name="password" >
<label for="password" >Contraseña</label>
</div>
<!-- INPUT REPETIR PASSWORD -->
<div class="input-field col s12">
<input type="password" id="password_R" name="password_r" >
<label for="password_r" data-error="wrong" data-success="right">Repetir contraseña</label>
</div>
<!-- INPUT NOMBRE COMPLETO -->
<div class="input-field col s12">
<input type="text" id="nombre" name="nombre" value="<?php echo escape(Input::get('nombre')); ?>" >
<label for="nombre">Nombre completo</label>
</div>
<!-- BOTON-->
<div class="input-field col s12">
<input type="hidden" name="token" value="<?php echo Token::generar();?>">
<button id="guardar" name="guardar" type="submit" class="btn">Guardar <i class="material-icons small">send</i></button>
</div>
</form>
</div>
</div>
</div>
<?php include 'extend/footer.php'; ?> | true |
a8471c11b7a9acfcbdaf6677a21e849871211c7d | PHP | anirudhv/Culinary-Clicks-Image-Gallery | /doAddCat.php | UTF-8 | 4,328 | 2.984375 | 3 | [] | no_license | <?php
session_start(); //start new or resume existing session
if (preg_match('/[\'^£$%&*()}{@#~?><>,|=_+¬-]/', $_POST["category"]))
{ //if the user entered a cuisine name with special characters
$_SESSION["badInput"] = "No special characters, numbers or spaces allowed. If a cuisine you would like to enter is multiple words, do not include spaces between the words. For example, 'Saudi Arabian' would be represented as 'SaudiArabain'."; //create an error message that tells them this is not allowed.
header("Location:supAdminCuisine.php"); //redirect to cuisine category manager page
exit; //exit current page
}
else if (preg_match('~[0-9]+~', $_POST["category"])) { //if user entered a cuisine name with numbers
$_SESSION["badInput"] = "No special characters, numbers or spaces allowed. If a cuisine you would like to enter is multiple words, do not include spaces between the words. For example, 'Saudi Arabian' would be represented as 'SaudiArabain'."; //create an error message that tells them this is not allowed.
header("Location:supAdminCuisine.php"); //redirect to cuisine category manager page
exit; //exit current page
}
else if ( preg_match('/\s/',$_POST["category"]) ) { //if the user entered a cuisine name with spaces
$_SESSION["badInput"] = "No special characters, numbers or spaces allowed. If a cuisine you would like to enter is multiple words, do not include spaces between the words. For example, 'Saudi Arabian' would be represented as 'SaudiArabain'."; //create an error message that tells them this is not allowed.
header("Location:supAdminCuisine.php"); //redirect to cuisine category manager page
exit; //exit current page
}
else if(empty($_POST["category"])) { //if the user didn't enter any name at all
$_SESSION["badInput"] = "Please enter a cuisine name."; //create error message telling them to enter one
}
else {
$_SESSION["badInput"] = ""; //if the user entered a name that met all the guidlines, make the badInput session variable blank.
}
include("includes/OpenDBConn.php"); //include OpenDBConn.php to connect to database.
$sql = "SELECT * FROM Categories"; //select all elements from Categories Table
$result = $conn->query($sql); //process query for my database
if($result->num_rows > 0) { //if more than 0 rows of results come up
$num_results = $result->num_rows; //set $num_results to num_rows
}
else {
$num_results = 0; //otherwise set $num_results to 0
}
if($num_results > 0) { //if $num_results > 0
while ($row = $result->fetch_assoc()) { //while there are still rows of elements left in the associative array $result
if($row["cuisine"] == $_POST["category"]) { //if the cuisine that the user entered is already in the database
if($row["available"] == "No") { //if the cuisine is disabled
$sql2 = "UPDATE Categories SET available = 'Yes' WHERE cuisine = '" . $_POST["category"] . "'"; //sql statement to re-enable that category by changing available from No to Yes
$result2 = $conn->query($sql2); //process query for my database.
$_SESSION["badInput"] = $_POST["category"] . " Cuisine successfully added."; //set badInput session variable to let user know that cuisine was added.
header("Location:supAdminCuisine.php"); //go back to super admin cuisine category manager.
exit; //exit page
}
else { //otherwise, if Available is Yes
$_SESSION["badInput"] = "Cuisine " . $_POST["category"] . " already exists."; //set badInput session variable to tell the user that the category they entered already exists.
header("Location:supAdminCuisine.php"); //go to supAdminCuisine.php
exit; //exit page
}
}
}
} //if the category is not already in the database
$ans = "Yes";
$sql3 = "INSERT INTO Categories(cuisine, available) VALUES ('". $_POST["category"] . "', '" . $ans."')"; //create sql statement to add it to database and make it available
$result3 = $conn->query($sql3); //process query for my database
$_SESSION["badInput"] = $_POST["category"] . " Cuisine successfully added."; //set badInput session variable to success message
header("Location:supAdminCuisine.php"); //go to supAdminCuisine.php
include("includes/CloseDBConn.php"); //include closeDBConn.php which closes database connection
exit; //exit page
?> | true |
74e9deab57847f0d59bca0c6b3937dbbf8a1a846 | PHP | ambuilding/LevelUp | /oop/solidPrinciples/dependencyInversion/passwordReminder.php | UTF-8 | 316 | 2.78125 | 3 | [] | no_license | <?php
interface ConnectionInterface {
public function connect();
}
class DbConnection implements ConnectionInterface {
public function connect() {
//
}
}
class PasswordReminder {
private $dbConnection;
function __construct(ConnectionInterface $dbConnection)
{
$this->dbConnection = $dbConnection;
}
} | true |
eed2e4b03aa492fff8df7bb9ab5915fa5eda7527 | PHP | spencerfinnell/curbside | /wp-content/plugins/curbside/includes/class-location.php | UTF-8 | 552 | 2.765625 | 3 | [] | no_license | <?php
class Curbside_Location {
public function __construct( $location ) {
$this->location = $location;
return $this->location;
}
public function get_date() {
return $this->location->post_date;
}
public function get_street() {
return $this->location->geolocation_street;
}
public function get_formatted_address() {
return $this->location->geolocation_formatted_address;
}
public function get_coordinates() {
return array(
'lng' => $this->location->geolocation_long,
'lat' => $this->location->geolocation_lat
);
}
} | true |
86f88e8b5f1d1d96994052bc2d551ffd5827a77c | PHP | shadowdestiny/dockenizacion | /src/tests/unit/LowBalanceEmailTemplateUnitTest.php | UTF-8 | 2,986 | 2.59375 | 3 | [] | no_license | <?php
namespace EuroMillions\tests\unit;
use EuroMillions\web\emailTemplates\EmailTemplate;
use EuroMillions\web\emailTemplates\LowBalanceEmailTemplate;
use Money\Currency;
use Money\Money;
use Prophecy\Argument;
use EuroMillions\tests\base\UnitTestBase;
class LowBalanceEmailTemplateUnitTest extends UnitTestBase
{
protected $lotteryService;
public function setUp()
{
parent::setUp();
$this->lotteryService = $this->getServiceDouble('LotteryService');
}
/**
* method loadVars
* when called
* should returnArrayWithProperData
*/
public function test_loadVars_called_returnArrayWithProperData()
{
$expected = $this->getArrayContentTemplate();
$emailTemplate = new EmailTemplate();
$this->lotteryService->getNextJackpot('EuroMillions')->willReturn(new Money(10000,new Currency('EUR')));
$this->lotteryService->getNextDateDrawByLottery('EuroMillions')->willReturn(new \DateTime());
$next_draw_day = new \DateTime();
$emailTemplateDataStrategy_double = $this->getInterfaceWebDouble('IEmailTemplateDataStrategy');
$emailTemplateDataStrategy_double->getData(Argument::type('EuroMillions\web\interfaces\IEmailTemplateDataStrategy'))->willReturn([]);
$data = [
'jackpot_amount' => 100,
'draw_day_format_one' => $next_draw_day->format('l'),
'draw_day_format_two' => $next_draw_day->format('j F Y')
];
$emailTemplateDataStrategy_double->getData($emailTemplateDataStrategy_double->reveal())->willReturn($data);
$sut = new LowBalanceEmailTemplate($emailTemplate, $emailTemplateDataStrategy_double->reveal());
$actual = $sut->loadVars($emailTemplateDataStrategy_double->reveal());
$this->assertEquals($expected,$actual);
}
private function getArrayContentTemplate()
{
$next_draw_day = new \DateTime();
$jackpot= new Money(10000, new Currency('EUR'));
$draw_day_format_one = $next_draw_day->format('l');
$draw_day_format_two = $next_draw_day->format('j F Y');
$vars = [
'template' => '1188463',
'subject' => 'Low balance',
'vars' =>
[
[
'name' => 'jackpot',
'content' => number_format((float) $jackpot->getAmount() / 100,2,".",",")
],
[
'name' => 'draw_day_format_one',
'content' => $draw_day_format_one
],
[
'name' => 'draw_day_format_two',
'content' => $draw_day_format_two,
],
[
'name' => 'url_add_funds',
'content' => 'https://localhost/account/wallet'
]
]
];
return $vars;
}
} | true |
f1f6be9a4a5d3eab58c157032a4f54a35faa8bb6 | PHP | chiiya/tmdb-api-php | /src/Responses/TvCreditsResponse.php | UTF-8 | 508 | 2.734375 | 3 | [] | no_license | <?php
namespace Chiiya\Tmdb\Responses;
use Chiiya\Tmdb\Models\Person\TvCastMember;
use Chiiya\Tmdb\Models\Person\TvCrewMember;
/**
* Class TvCreditsResponse.
*
* @method TvCastMember[] getCast()
* @method TvCrewMember[] getCrew()
*/
class TvCreditsResponse extends CreditsResponse
{
public function addCastMember(TvCastMember $credit): void
{
$this->cast[] = $credit;
}
public function addCrewMember(TvCrewMember $credit): void
{
$this->crew[] = $credit;
}
}
| true |
8f3d5c49e53e77f35b383fa7d79489e47b019e71 | PHP | PGB-LIV/php-ms-example | /src/inc/protein_digest.php | UTF-8 | 3,618 | 2.6875 | 3 | [
"Apache-2.0"
] | permissive | <?php
use pgb_liv\php_ms\Utility\Digest\DigestFactory;
use pgb_liv\php_ms\Reader\FastaReader;
use pgb_liv\php_ms\Core\Tolerance;
use pgb_liv\php_ms\Utility\Filter\FilterMass;
set_time_limit(600);
define('FORM_FILE', 'fasta');
if (! empty($_FILES) && $_FILES[FORM_FILE]['error'] == 0) {
header('Content-type: text/plain;');
header('Content-Disposition: attachment; filename="' . $_FILES[FORM_FILE]['name'] . '.csv"');
$fastaFile = $_FILES[FORM_FILE]['tmp_name'];
$reader = new FastaReader($fastaFile);
$digest = DigestFactory::getDigest($_POST['enzyme']);
$digest->setMaxMissedCleavage((int) $_POST['missedcleave']);
$digest->setNmeEnabled(false);
if (isset($_POST['nme']) && $_POST['nme'] == 1) {
$digest->setNmeEnabled(true);
}
$filter = null;
if (strlen($_POST['mass']) > 0 && $_POST['mass'] != 0) {
$tolerance = new Tolerance((float) $_POST['ppm'], Tolerance::PPM);
$minMass = $_POST['mass'] - $tolerance->getDaltonDelta((float) $_POST['mass']);
$maxMass = $_POST['mass'] + $tolerance->getDaltonDelta((float) $_POST['mass']);
$filter = new FilterMass($minMass, $maxMass);
}
foreach ($reader as $protein) {
$peptides = $digest->digest($protein);
foreach ($peptides as $peptide) {
if (! is_null($filter) && ! $filter->isValidPeptide($peptide)) {
continue;
}
echo $protein->getIdentifier() . ',' . $peptide->getSequence() . ',' . $peptide->getMass() . "\n";
}
}
exit();
}
?>
<h2>Protein Digestion</h2>
<?php
if (! empty($_FILES) && $_FILES[FORM_FILE]['error'] != 0) {
die('<p>An error occured. Ensure you included a file to upload.</p>');
}
?>
<p>This tool allows you to upload a FASTA file and to generate a list of
peptides as would be produced by the chosen enzyme. You may filter
the peptides to those within a certain mass. The output will be a
.csv file.</p>
<p>
The <abbr title="N-terminal Methionine Excision">NME</abbr> option
sets whether NME should be performed. When enabled any methionine at
the n-terminus of a protein will be removed. Both the excised and
non-excised peptide will be returned after digestion. Note, protein
sequence which do not contain a methionine at the n-terminus will be
unaffected.
</p>
<form enctype="multipart/form-data"
action="?page=protein_digest&txtonly=1" method="POST">
<fieldset>
<label for="fasta">FASTA File</label> <input
name="<?php echo FORM_FILE; ?>" type="file" id="fasta" />
</fieldset>
<fieldset>
<label for="enzyme">Enzyme</label> <select name="enzyme"
id="enzyme">
<?php
foreach (DigestFactory::getEnzymes() as $key => $enzyme) {
echo '<option value="' . $key . '">' . $enzyme . '</option>';
}
?>
</select>
</fieldset>
<fieldset>
<label for="nme">N-terminal Methionine Excision</label><input type="checkbox" name="nme"
id="nme" value="1" />
</fieldset>
<fieldset>
<label for="missedCleave">Missed Cleavages</label><input
type="text" name="missedcleave" id="missedCleave" value="1" />
</fieldset>
<fieldset>
<label for="mass">Mass Value</label> <input type="text"
name="mass" id="mass" value="" /> Da ± <input
type="text" name="ppm" id="ppm" value="5" class="smallInput" />
ppm
</fieldset>
<input type="submit" value="Send File" />
</form> | true |
8485f084453992df06ffb762d4bba86e5b86ffc5 | PHP | lange-cc/Africa-SDG | /libs/controller_model.php | UTF-8 | 11,048 | 2.546875 | 3 | [] | no_license | <?php
/**
*
*/
class ControllermModel
{
function __construct()
{
$this->db = new database();
}
public function isYearExist($year){
$exist = $this->db->prepare("SELECT * FROM country WHERE year = :year ");
$exist->execute(array(
':year' => $year
));
if ($exist->rowCount() > 0) {
return true;
}else{
return false;
}
}
public function randomnumber($length = 15)
{
$characters = '3456013454563456345345634566734568962345634563445634563453445634563453456345664563456345345634566734568973456895634566734568953456345667345689';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
public function getRealIpAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
public function detectDevice()
{
$userAgent = $_SERVER["HTTP_USER_AGENT"];
$devicesTypes = array(
"computer" => array("msie 10", "msie 9", "msie 8", "windows.*firefox", "windows.*chrome", "x11.*chrome", "x11.*firefox", "macintosh.*chrome", "macintosh.*firefox", "opera"),
"tablet" => array("tablet", "android", "ipad", "tablet.*firefox"),
"mobile" => array("mobile ", "android.*mobile", "iphone", "ipod", "opera mobi", "opera mini"),
"bot" => array("googlebot", "mediapartners-google", "adsbot-google", "duckduckbot", "msnbot", "bingbot", "ask", "facebook", "yahoo", "addthis")
);
foreach ($devicesTypes as $deviceType => $devices) {
foreach ($devices as $device) {
if (preg_match("/" . $device . "/i", $userAgent)) {
$deviceName = $deviceType;
}
}
}
return ucfirst($deviceName);
}
public function statistic($page)
{
$xml = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=" . $this->getRealIpAddr());
$country = $xml->geoplugin_countryName;
$city = $xml->geoplugin_city;
$device = $this->detectDevice();
if (isset($_SERVER['HTTP_REFERER'])) {
$referrer = $_SERVER['HTTP_REFERER'];
} else {
$referrer = 'Direct';
}
if (isset($_COOKIE['user_id'])) {
//setcookie("user_id", "", time() - (96400 * 30), "/");
$cookie = $_COOKIE['user_id'];
$exist = $this->db->prepare("SELECT * FROM mvc_status WHERE user_id=:user_id AND page=:page");
$exist->execute(array(
':user_id' => $cookie,
':page' => $page
));
if ($exist->rowCount() > 0) {
$update = $this->db->prepare("UPDATE `mvc_status` SET `views` = views+1, `time` = now() WHERE `mvc_status`.`page` = :page AND `user_id` = :user_id");
$update->execute(array(
':user_id' => $cookie,
':page' => $page
));
} else {
$insert = $this->db->prepare("INSERT into mvc_status(`user_id`, `country`, `city`, `time`, `device`, `page`, `ip`, `views`, `referrer`) VALUES (:user_id, :country, :city, now(), :device, :page, :ip, :views, :referrer)");
$insert->execute(array(
':user_id' => $cookie,
':country' => $country,
':city' => $city,
':device' => $device,
':page' => $page,
':ip' => $this->getRealIpAddr(),
':views' => 1,
':referrer' => $referrer
));
}
} else {
$cookie_name = "user_id";
$cookie_value = 'User_' . $this->randomnumber(10);
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
$insert = $this->db->prepare("INSERT into mvc_status(`user_id`, `country`, `city`, `time`, `device`, `page`, `ip`, `views`, `referrer`) VALUES (:user_id, :country, :city, now(), :device, :page, :ip, :views, :referrer)");
$insert->execute(array(
':user_id' => $cookie_value,
':country' => $country,
':city' => $city,
':device' => $device,
':page' => $page,
':ip' => $this->getRealIpAddr(),
':views' => 1,
':referrer' => $referrer
));
}
}
public function SelectLanguage($abrev, $key, $mainKeyword)
{
$command = $this->db->prepare("SELECT * FROM `mvc_lang_keywords` WHERE keytext = :key AND abreviation = :abrev");
$command->execute(array(':key' => $key, ':abrev' => $abrev));
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$keyword = $row['keyword'];
}
return $keyword;
} else {
$langId = $this->GetLangId('en');
$this->Addnewkeyword($mainKeyword, $key, 'en', $langId);
return $mainKeyword;
}
}
public function GetLangId($abrev)
{
$command = $this->db->prepare("SELECT * FROM `mvc_language` WHERE abreviation = :abrev");
$command->execute(array(':abrev' => $abrev));
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
}
return $id;
}
}
public function Addnewkeyword($keyword, $key, $abrev, $langId)
{
$proced = new \stdClass();
$status = $this->Checkifkeyexist($key, $keyword, $abrev);
if ($status == 1) {
} else if ($status == 0) {
$command = $this->db->prepare("INSERT INTO `mvc_lang_keywords` (`id`, `lang_id`, `keyword`, `keytext`, `abreviation`) VALUES (NULL, :langId, :keyword, :key, :abrev)");
if ($command->execute(array(
':langId' => $langId,
':keyword' => $keyword,
':key' => $key,
':abrev' => $abrev
))) {
} else {
}
}
}
public function Checkifkeyexist($key, $keyword, $abrev)
{
$command = $this->db->prepare("SELECT * FROM `mvc_lang_keywords` WHERE abreviation = :abrev AND keytext = :key AND keyword =:keyword");
$command->execute(array(':abrev' => $abrev, ':key' => $key, ':keyword' => $keyword));
if ($command->rowCount() > 0) {
return 1;
} else {
return 0;
}
}
public function Showlanguage()
{
$command = $this->db->prepare("SELECT * FROM `mvc_language`");
$command->execute();
$json_response = array(); //Create an array
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$row_array = array();
$row_array['id'] = $row['id'];
$row_array['name'] = $row['name'];
$row_array['abrev'] = $row['abreviation'];
$row_array['type'] = $row['type'];
$abrev = $row['abreviation'];
$command1 = $this->db->prepare("SELECT * FROM `mvc_lang_keywords` WHERE abreviation = :abrev");
$command1->execute(array(':abrev' => $abrev));
if ($command1->rowCount() > 0) {
$row_array['keywordNumber'] = $command1->rowCount();
} else {
$row_array['keywordNumber'] = 0;
}
array_push($json_response, $row_array);
}
return json_encode($json_response);
}
}
public function CurrencyData()
{
$command = $this->db->prepare("SELECT * FROM `mvc_currency`");
$command->execute();
$json_response = array(); //Create an array
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$row_array = array();
$row_array['id'] = $row['id'];
$row_array['name'] = $row['name'];
$row_array['logo'] = $row['logo'];
$row_array['rates'] = $row['rates'];
array_push($json_response, $row_array);
}
return json_encode($json_response);
}
}
public function SelectCarrency($curr, $price)
{
$command = $this->db->prepare("SELECT * FROM `mvc_currency` WHERE name = :name ");
$command->execute(array(':name' => $curr));
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$logo = $row['logo'];
$rates = $row['rates'];
}
$total = $rates * $price;
return strtoupper($logo . ' ' . number_format($total, 1));
}
}
public function FindContent($id)
{
$command = $this->db->prepare("SELECT * FROM `mvc_section` WHERE id = :id ");
$command->execute(array(':id' => $id));
$json_response = array(); //Create an array
if ($command->rowCount() > 0) {
while ($row = $command->fetch(PDO::FETCH_ASSOC)) {
$row_array = array();
$row_array['article'] = array();
$row_array['title'] = $row['title'];
$row_array['content'] = $row['discription'];
$section_index = $row['section_index'];
$command2 = $this->db->prepare("SELECT * FROM `mvc_article` WHERE section_index = :index AND lang = :lang");
$command2->execute(array(':index' => $section_index, ':lang' => LANG));
if ($command2->rowCount() > 0) {
while ($row2 = $command2->fetch(PDO::FETCH_ASSOC)) {
$row_array['article'][] = array(
'id' => $row2['id'],
'title' => $row2['title'],
'subtitle' => $row2['subtitle'],
'content' => $row2['content'],
'article_index' => $row2['article_index'],
'logo' => $row2['logo'],
'section_index' => $row2['section_index']
);
}
}
array_push($json_response, $row_array);
}
return json_encode($json_response);
}
}
}
?> | true |
3568ac9240c23cce35c0f803ced77d8ab462061d | PHP | Metrashev/Getlokal | /lib/task/countyRomaniaTask.class.php | UTF-8 | 5,819 | 2.53125 | 3 | [] | no_license | <?php
class CountyRomaniaTask extends sfBaseTask
{
protected function configure()
{
// // add your own arguments here
// $this->addArguments(array(
// new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
// ));
$this->addOptions(array(
new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
// add your own options here
));
$this->namespace = 'county';
$this->name = 'Romania';
$this->briefDescription = '';
$this->detailedDescription = <<<EOF
The [countyRomania|INFO] task does things.
Call it with:
[php symfony countyRomania|INFO]
EOF;
}
protected function execute($arguments = array(), $options = array())
{
$databaseManager = new sfDatabaseManager ( $this->configuration );
$connection = $databaseManager->getDatabase ( $options ['connection'] ? $options ['connection'] : null )->getConnection ();
$connection->setAttribute ( Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true );
echo "County translation Romania".PHP_EOL;
$skipped = 0;
$wrongs = Doctrine_Query::create()
->select('co.id')
->from('County co')
->where('co.id > 0 AND co.id < 43')
->andWhere('co.country_id = 2')
->fetchArray();
foreach ($wrongs as $w) {
$city = Doctrine_Query::create()
->select('c.lat as lat, c.lng as long, co.id as countyId, cp.id, count(cp.id) as cnt')
->from('City c')
->innerJoin('c.Company cp')
->innerJoin('c.County co')
->where('c.county_id = ?', $w['id'])
->groupBy('c.id')
->orderBy('count(cp.id) DESC')
->fetchOne();
//$latlng = $city->getLat().','.$city->getLong();
//$url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $latlng . "&sensor=false&language=en";
$address = urlencode($city->getLocation('en').',Romania');
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&sensor=false&language=en";
$geocode = json_decode (file_get_contents($url), true );
if ($geocode['status'] != 'OK') {
$skipped++;
echo "SKIPPED ".$city->getCountyId().PHP_EOL;
continue;
}
$_types = array(
'city' => array('locality'),
'county' => array(
'administrative_area_level_1',
'administrative_area_level_2',
'administrative_area_level_3'
),
'country' => array('country')
);
$results = $geocode['results'][0];
$components = $results['address_components'];
$data = array(
'latitude' => $results['geometry']['location']['lat'],
'longitude' => $results['geometry']['location']['lng']
);
foreach ($components as $c) {
foreach ($_types as $field => $types) {
if (array_intersect($types, $c['types'])) {
$data[$field] = $c['long_name'];
}
if (in_array('country', $c['types'])) {
$data['language'] = strtolower($c['short_name']);
}
}
}
/*
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $address . "&sensor=false&language=en";
$geocode = json_decode (file_get_contents($url), true );
if ($geocode['status'] != 'OK') {
$skipped++;
fputcsv($file, array(iconv('UTF-8', 'UTF-8',$city->getCountyId())));
continue;
}
$_types = array(
'city_en' => array('locality'),
'county_en' => array(
'administrative_area_level_1',
'administrative_area_level_2',
'administrative_area_level_3'
),
'country_en' => array('country')
);
$results = $geocode['results'][0];
$components = $results['address_components'];
foreach ($components as $c) {
foreach ($_types as $field => $types) {
if (array_intersect($types, $c['types'])) {
$data[$field] = $c['long_name'];
}
if (in_array('country', $c['types'])) {
$data['language'] = strtolower($c['short_name']);
}
}
}
*/
$con = Doctrine::getConnectionByTableName('county_translation');
//$con->execute("UPDATE `county_translation` SET name='".mb_strtoupper($data['county'], 'utf-8')."' WHERE id='".$city->getCountyId()."' AND lang = 'bg';");
$con->execute("UPDATE `county_translation` SET name='".$data['county']."' WHERE id='".$city->getCountyId()."' AND lang = 'en';");
echo "UPDATED ". $city->getCountyId().PHP_EOL;
}
echo "SKIPPED ".$skipped.PHP_EOL;
}
}
| true |
85521a9d392375c89f22aae615d618a54671cb4b | PHP | SigaSmart/WcTable | /_ajax/config/demo.php | UTF-8 | 1,135 | 2.75 | 3 | [] | no_license | <?php
// DB table to use
$table = 'd_demo';
// Table's primary key
$primaryKey = 'd_id';
// Array of database columns which should be read and sent back to DataTables.
// The `db` parameter represents the column name in the database, while the `dt`
// parameter represents the DataTables column identifier. In this case simple
// indexes
$columns = array(
array('db' => 'd_first_title', 'dt' => 0),
array('db' => 'd_last_title', 'dt' => 1),
array('db' => 'd_position', 'dt' => 2),
array('db' => 'd_office', 'dt' => 3),
array(
'db' => 'd_date',
'dt' => 4,
'formatter' => function( $d, $row ) {
return dt_date($d);
}
),
array(
'db' => 'd_salary',
'dt' => 5,
'formatter' => function( $d, $row ) {
return '$' . number_format($d);
}
),
array(
'db' => 'd_id',
'dt' => 6,
'formatter' => function( $d, $row ) {
return dt_edit($d,"custom/table");
}
)
); | true |
e61bdaff865f06cb2de782ae6a7287d8d0cffebb | PHP | thephpleague/container | /src/Argument/ResolvableArgument.php | UTF-8 | 333 | 2.828125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | <?php
declare(strict_types=1);
namespace League\Container\Argument;
class ResolvableArgument implements ResolvableArgumentInterface
{
protected $value;
public function __construct(string $value)
{
$this->value = $value;
}
public function getValue(): string
{
return $this->value;
}
}
| true |
feee5ec4aeb1558b4372a1c2f91d9a844d0acdef | PHP | horvathi/php-cmis-client | /src/VersioningServiceInterface.php | UTF-8 | 7,736 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace Dkd\PhpCmis;
/*
* This file is part of php-cmis-client.
*
* (c) Sascha Egerer <sascha.egerer@dkd.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Dkd\PhpCmis\Data\AclInterface;
use Dkd\PhpCmis\Data\ExtensionDataInterface;
use Dkd\PhpCmis\Data\ObjectDataInterface;
use Dkd\PhpCmis\Data\PropertiesInterface;
use Dkd\PhpCmis\Enum\IncludeRelationships;
use GuzzleHttp\Stream\StreamInterface;
/**
* Versioning Service interface.
*
* See the CMIS 1.0 and CMIS 1.1 specifications for details on the operations,
* parameters, exceptions and the domain model.
*/
interface VersioningServiceInterface
{
/**
* Reverses the effect of a check-out.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId the identifier for the PWC
* @param ExtensionDataInterface|null $extension
*/
public function cancelCheckOut($repositoryId, & $objectId, ExtensionDataInterface $extension = null);
/**
* Checks-in the private working copy (PWC) document.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId input: the identifier for the PWC,
* output: the identifier for the newly created version document
* @param boolean $major indicator if the new version should become a major (<code>true</code>) or minor
* (<code>false</code>) version
* @param PropertiesInterface|null $properties the property values that must be applied to the
* newly created document object
* @param StreamInterface|null $contentStream the content stream that must be stored
* for the newly created document object
* @param string|null $checkinComment a version comment
* @param string[] $policies a list of policy IDs that must be applied to the newly created document object
* @param AclInterface|null $addAces a list of ACEs that must be added to the newly created document object
* @param AclInterface|null $removeAces a list of ACEs that must be removed from the newly created document object
* @param ExtensionDataInterface|null $extension
* @return string|null Versioned object ID of original source if succesful, null otherwise
*/
public function checkIn(
$repositoryId,
& $objectId,
$major = true,
PropertiesInterface $properties = null,
StreamInterface $contentStream = null,
$checkinComment = null,
array $policies = [],
AclInterface $addAces = null,
AclInterface $removeAces = null,
ExtensionDataInterface $extension = null
);
/**
* Create a private working copy of the document.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId input: the identifier for the document that should be checked out,
* output: the identifier for the newly created PWC
* @param ExtensionDataInterface|null $extension
* @param boolean|null $contentCopied output: indicator if the content of the original
* document has been copied to the PWC
* @return string|null Versioned object ID of PWC if succesful, null otherwise
*/
public function checkOut(
$repositoryId,
& $objectId,
ExtensionDataInterface $extension = null,
$contentCopied = null
);
/**
* Returns the list of all document objects in the specified version series,
* sorted by the property "cmis:creationDate" descending.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId The identifier for the object
* @param string $versionSeriesId the identifier for the object
* @param string|null $filter a comma-separated list of query names that defines which properties must be
* returned by the repository (default is repository specific)
* @param boolean $includeAllowableActions if <code>true</code>, then the repository must return the allowable
* actions for the objects (default is <code>false</code>)
* @param ExtensionDataInterface|null $extension
* @return ObjectDataInterface[] the complete version history of the version series
*/
public function getAllVersions(
$repositoryId,
$objectId,
$versionSeriesId,
$filter = null,
$includeAllowableActions = false,
ExtensionDataInterface $extension = null
);
/**
* Get the latest document object in the version series.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId The identifier for the object
* @param string $versionSeriesId
* @param boolean $major If <code>true</code>, then the repository MUST return the properties for the latest major
* version object in the version series.
* If <code>false</code>, the repository MUST return the properties for the latest
* (major or non-major) version object in the version series.
* @param string|null $filter a comma-separated list of query names that defines which properties must be
* returned by the repository (default is repository specific)
* @param boolean $includeAllowableActions if <code>true</code>, then the repository must return the allowable
* actions for the objects (default is <code>false</code>)
* @param IncludeRelationships|null $includeRelationships indicates what relationships in which the objects
* participate must be returned (default is <code>IncludeRelationships::NONE</code>)
* @param string $renditionFilter indicates what set of renditions the repository must return whose kind
* matches this filter (default is "cmis:none")
* @param boolean $includePolicyIds if <code>true</code>, then the repository must return the policy ids for
* the object (default is <code>false</code>)
* @param boolean $includeAcl
* @param ExtensionDataInterface|null $extension
* @return ObjectDataInterface
*/
public function getObjectOfLatestVersion(
$repositoryId,
$objectId,
$versionSeriesId,
$major = false,
$filter = null,
$includeAllowableActions = false,
IncludeRelationships $includeRelationships = null,
$renditionFilter = Constants::RENDITION_NONE,
$includePolicyIds = false,
$includeAcl = false,
ExtensionDataInterface $extension = null
);
/**
* Get a subset of the properties for the latest document object in the version series.
*
* @param string $repositoryId the identifier for the repository
* @param string $objectId The identifier for the object
* @param string $versionSeriesId The identifier for the version series.
* @param boolean $major If <code>true</code>, then the repository MUST return the properties for the latest major
* version object in the version series.
* If <code>false</code>, the repository MUST return the properties for the latest
* (major or non-major) version object in the version series.
* @param string|null $filter a comma-separated list of query names that defines which properties must be
* returned by the repository (default is repository specific)
* @param ExtensionDataInterface|null $extension
* @return PropertiesInterface
*/
public function getPropertiesOfLatestVersion(
$repositoryId,
$objectId,
$versionSeriesId,
$major = false,
$filter = null,
ExtensionDataInterface $extension = null
);
}
| true |