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
c7bc031a15f6a14f87389b500082e4e9725720d6
PHP
xqueue/maileon-php-api-client
/src/mailings/DispatchLogic.php
UTF-8
9,956
2.8125
3
[ "MIT" ]
permissive
<?php namespace de\xqueue\maileon\api\client\mailings; use de\xqueue\maileon\api\client\xml\AbstractXMLWrapper; /** * The wrapper class for a dispatch logic. This class wraps the XML structure. * * @author Andreas Lange */ class DispatchLogic extends AbstractXMLWrapper { /** * @var DispatchLogicType type * The type of the trigger mail dispatch plan, this can be one of 'SINGLE' or 'MULTI' */ public $type; /** * @var int event * The ID of the transaction event that is used to either start the instant mailing or to controll the mass mailing */ public $event; /** * @var DispatchLogicTarget target * Defines the target group of a intervall mailing. This can either be 'EVENT', 'CONTACTFILTER', or 'RSS' */ public $target; /** * @var DispatchLogicSpeedLevel speedLevel * Valid values are 'LOW', 'MEDIUM', and 'HIGH' */ public $speedLevel; /** * @var DispatchLogicInterval interval * This defines the interval in which the mailing is sent. This can be one of 'HOUR', 'DAY', 'WEEK', or 'MONTH' */ public $interval; /** * @var int dayOfMonth * Sets the day of the month the mailing will be sent. Range: [1..31] If you set a larger number than the month has days, the last day in the month will be used. */ public $dayOfMonth; /** * @var int dayOfWeek * Sets the day of the week the mailing will be sent. Range: [1..7] 1 = Sunday 2 = Monday 3 = Tuesday 4 = Wednesday 5 = Thursday 6 = Friday 7 = Saturday */ public $dayOfWeek; /** * @var int hours * Sets the tour of the day the mailing will be sent. Range: [0..23] */ public $hours; /** * @var int minutes * Sets the minute of the hour the mailing will be sent. Range: [0..59] */ public $minutes; /** * @var int contactFilterId * Sets contact filter ID */ public $contactFilterId; /** * @var bool startTrigger * If set to true, the trigger will be instantly activated after setting the dispatching options. */ public $startTrigger; /** * @var DispatchLogicRSSUniqueFeature rssUniqueFeature * Defines the features that define an item as unique. Valid values are 'DEFAULT', 'PUBDATE', 'TITLE', and 'LINK'. */ public $rssUniqueFeature; /** * @var string rssFeedUrl * The URL of the RSS feed. */ public $rssFeedUrl; /** * @var DispatchLogicRSSOrderBy rssOrderBy * Defines the attribute to order elements by. Valid are 'PUBDATE', 'TITLE', and 'LINK' */ public $rssOrderBy; /** * @var bool rssOrderAsc * Defines if the order direction is ASC or DESC. If 'true' elements are handled in ascending order. */ public $rssOrderAsc; /** * @var int rssMinNewEntries * The minimal number of new entries to trigger the RSS2Email mailing. */ public $rssMinNewEntries; /** * @var int deliveryLimit * The maximum of mailings a repeipient should receive in a given period. Default is 0, which means unlimited. */ public $deliveryLimit; /** * @var DispatchLogicDeliveryLimitUnit deliveryLimitUnit * The time period for the delivery limit. Can be one of 'DAY', 'WEEK', 'MONTH', or 'YEAR'. */ public $deliveryLimitUnit; /** * Initialization of the schedule from a simple xml element. * * @param \SimpleXMLElement $xmlElement * The xml element that is used to parse the schedule from. */ public function fromXML($xmlElement) { if (isset($xmlElement->type)) { $this->type = DispatchLogicType::getObject($xmlElement->type); } if (isset($xmlElement->event)) { $this->event = (int) $xmlElement->event; } if (isset($xmlElement->target)) { $this->target = DispatchLogicTarget::getObject($xmlElement->target); } if (isset($xmlElement->speed_level)) { $this->speedLevel = DispatchLogicSpeedLevel::getObject($xmlElement->speed_level); } if (isset($xmlElement->interval)) { $this->interval = DispatchLogicInterval::getObject($xmlElement->interval); } if (isset($xmlElement->day_of_month)) { $this->dayOfMonth = (int) $xmlElement->day_of_month; } if (isset($xmlElement->day_of_week)) { $this->dayOfWeek = (int) $xmlElement->day_of_week; } if (isset($xmlElement->hours)) { $this->hours = (int) $xmlElement->hours; } if (isset($xmlElement->minutes)) { $this->minutes = (int) $xmlElement->minutes; } if (isset($xmlElement->contact_filter_id)) { $this->contactFilterId = (int) $xmlElement->contact_filter_id; } if (isset($xmlElement->start_trigger)) { $this->startTrigger = filter_var($xmlElement->start_trigger, FILTER_VALIDATE_BOOLEAN); } if (isset($xmlElement->rss_unique_feature)) { $this->rssUniqueFeature = DispatchLogicRSSUniqueFeature::getObject($xmlElement->rss_unique_feature); } if (isset($xmlElement->rss_feed_url)) { $this->rssFeedUrl = (string) $xmlElement->rss_feed_url; } if (isset($xmlElement->rss_order_by)) { $this->rssOrderBy = DispatchLogicRSSOrderBy::getObject($xmlElement->rss_order_by); } if (isset($xmlElement->rss_order_asc)) { $this->rssOrderAsc = filter_var($xmlElement->rss_order_asc, FILTER_VALIDATE_BOOLEAN); } if (isset($xmlElement->rss_min_new_entries)) { $this->rssUniqueFeature = DispatchLogicRSSUniqueFeature::getObject($xmlElement->rss_unique_feature); } if (isset($xmlElement->delivery_limit)) { $this->rssUniqueFeature = DispatchLogicRSSUniqueFeature::getObject($xmlElement->rss_unique_feature); } if (isset($xmlElement->delivery_limit_unit)) { $this->rssUniqueFeature = DispatchLogicRSSUniqueFeature::getObject($xmlElement->rss_unique_feature); } } /** * Serialization to a simple XML element. * * @param bool $addXMLDeclaration * * @return \SimpleXMLElement * Generate a XML element from the contact object. */ public function toXML($addXMLDeclaration = true) { $xmlString = $addXMLDeclaration ? "<?xml version=\"1.0\"?><mailing></mailing>" : "<mailing></mailing>"; $xml = new \SimpleXMLElement($xmlString); if (isset($this->type)) { $xml->addChild("type", $this->type->getValue()); } if (isset($this->event)) { $xml->addChild("event", $this->event); } if (isset($this->target)) { $xml->addChild("target", $this->target->getValue()); } if (isset($this->speedLevel)) { $xml->addChild("speed_level", $this->speedLevel->getValue()); } if (isset($this->interval)) { $xml->addChild("interval", $this->interval->getValue()); } if (isset($this->dayOfMonth)) { $xml->addChild("day_of_month", $this->dayOfMonth); } if (isset($this->dayOfWeek)) { $xml->addChild("day_of_week", $this->dayOfWeek); } if (isset($this->hours)) { $xml->addChild("hours", $this->hours); } if (!empty($this->minutes)) { $xml->addChild("minutes", $this->minutes); } if (isset($this->contactFilterId)) { $xml->addChild("contact_filter_id", $this->contactFilterId); } if (isset($this->startTrigger)) { $xml->addChild("start_trigger", $this->startTrigger ? 'true' : 'false'); } if (isset($this->rssUniqueFeature)) { $xml->addChild("rss_unique_feature", $this->rssUniqueFeature->getValue()); } if (isset($this->rssFeedUrl)) { $xml->addChild("rss_feed_url", $this->rssFeedUrl); } if (isset($this->rssOrderBy)) { $xml->addChild("rss_order_by", $this->rssOrderBy->getValue()); } if (isset($this->rssOrderAsc)) { $xml->addChild("rss_order_asc", $this->rssOrderAsc ? 'true' : 'false'); } if (isset($this->rssMinNewEntries)) { $xml->addChild("rss_min_new_entries", $this->rssMinNewEntries); } if (isset($this->deliveryLimit)) { $xml->addChild("delivery_limit", $this->deliveryLimit); } if (isset($this->deliveryLimitUnit)) { $xml->addChild("delivery_limit_unit", $this->deliveryLimitUnit->getValue()); } return $xml; } /** * Serialization to a simple XML element as string * * @return string * The string representation of the XML document for this mailing. */ public function toXMLString() { return $this->toXML()->asXML(); } /** * Human readable representation of this wrapper. * * @return string * A human readable version of the dispatch logic. */ public function toString() { return "Dispatch Logic [type={$this->type}, event={$this->event}, target={$this->target}, speedLevel={$this->speedLevel}, interval={$this->interval}, ". "dayOfMonth={$this->dayOfMonth}, dayOfWeek={$this->dayOfWeek}, hours={$this->hours}, minutes={$this->minutes}, contactFilterId={$this->contactFilterId}, ". "startTrigger={($this->startTrigger)?'true':'false'}, rssUniqueFeature={$this->rssUniqueFeature}, rssFeedUrl={$this->rssFeedUrl}, rssOrderBy={$this->rssOrderBy}, ". "rssOrderAsc={($this->rssOrderAsc)?'true':'false'}, rssMinNewEntries={$this->rssMinNewEntries}, deliveryLimit={$this->deliveryLimit}, deliveryLimitUnit={$this->deliveryLimitUnit}]"; } }
true
cae026f774f418f2aaf9c0047cc8e2d3ed751413
PHP
foxcodenine/tutorials
/ice_malta/mysuccess_web_dev/PHP/studies/pages_21_29.php
UTF-8
2,107
3.046875
3
[]
no_license
<?php include './my_print_functions.php'; ppp('A'); //____________________________________________________________ // ----- Yoda Condition, Constant on the left: $w = 'world'; if ($w = 'worlds') { // <- mistake echo 'match <br>'; } else { echo 'does not matcho <br>'; } // if ('worlds' = $w ) { // <- will give an error // echo 'match <br>'; // } else { // echo 'does not matcho <br>'; // } ppp('B'); //____________________________________________________________ // ----- backtick echo `whoami` . '<br>'; ppp('C'); //____________________________________________________________ $aaaa = <<<ENDING hello world ENDING; echo $aaaa; ppp('D'); //____________________________________________________________ // ----- md5() -----rand() echo md5(rand(), true) . '<br>'; echo md5(rand()) . '<br>'; echo rand(10, 20) . '<br>'; ppp('E'); //____________________________________________________________ for ($i = 0; $i < 5; $i++) { echo $i . '<br>'; } echo 'After loop ends $i is still ' . $i; ppp('F'); //____________________________________________________________ $n = 0; do { $n++; if (0 !== $n % 2) continue; if (10 === $n) break; echo $n . '<br>'; } while ($n <= 20); ppp('G'); //____________________________________________________________ // ----- Namespace include './NamespaceA.php'; use function NamespaceA\aaaa; use NamespaceA\AA as myAA; use const NamespaceA\AAA; aaaa(); $AA = new myAA(); echo AAA; echo '<br><br>'; // ________________________________ include './NamespaceB.php'; NamespaceB\bbbb(); $BB = new NamespaceB\BB(); echo NamespaceB\BBB; ppp('H'); //____________________________________________________________ echo '<br>'; echo php_ini_scanned_files() . '<br>'; ppp('H'); //____________________________________________________________ $array = ['a', 'b', 'c', 'd', 'e']; while (current($array) == true) { echo current($array); next($array); } ppp('i'); //____________________________________________________________ echo $_SERVER['DOCUMENT_ROOT'] . '<br>'; echo __DIR__ . '<br>'; echo `pwd` . '<br>';
true
c115cd7c7124a96a79f5ddfcce059b0079fd7dea
PHP
Solweigdev/PHP-System-Login
/index.php
UTF-8
898
2.671875
3
[]
no_license
<?php /** * @author Solweigdev * @link https://github.com/Solweigdev/-PHP-System-Login */ // Include auto loader to call class require ("vendor/autoload.php"); // Include configuration to connection in your database require_once("app/config/config.php"); // Include class login $User = new App\classes\User; // Verifier si l'utilisateur est déjà identifier ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>System login php</title> <link rel="stylesheet" type="text/css" href="app/css/style.css"> </head> <body> <?php if(App\classes\Session::exists('user')): ?> <?php require("app/home.php"); ?> <?php else: ?> <?php require("app/login.php"); ?> <?php endif ?> </body> </html>
true
9d51c7085867251cc72c5b1c1972c431f8bd06e5
PHP
nilsonjrsilva1997/lp-trane
/app/Models/State.php
UTF-8
491
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use App\Models\User; class State extends Model { use HasFactory; protected $connection= 'mysql'; protected $fillable = ['state_id', 'state_country_id', 'state_code', 'state_name', 'state_active']; protected $table = 'tb_states'; public function users() { return $this->belongsTo(User::class, 'usu_state_id', 'state_id'); } }
true
ebde550b6fc1d09398e4666f5d2239cb7d1050e1
PHP
ImtiH/BAPWD
/www/php-fundamentals/part14.php
UTF-8
754
3.125
3
[]
no_license
<?php function durjoy(){ $name = 'durjoy'; // Local scope echo $name; } durjoy(); echo "<br>"; $location ="Dhaka"; function place(){ global $location; // etake global korar jonno amra er age global likhlam. echo $location; } place(); echo "<br>"; $location ="Dhaka"; function location(){ echo $GLOBALS["location"]; // evabe super global koreo kaj kora jay. but amra uporter niyomei likhbo. } location(); echo "<br>"; function name(){ global $name; // ekhane nice je local variable ta likhbo take amra function er baire use kroar jonno age gloval kore nilam. $name = "Imtiaz"; // local variable } name(); // function take age execute kore nilam echo $name; // varibale ke echo korlam and now it will work.
true
a4580d2dadffa2d7b60b0c26cf9b95a023a43de4
PHP
Guillaume-RICHARD/cli-env-PHP
/app/sql/mysql.php
UTF-8
830
3.234375
3
[ "MIT" ]
permissive
<?php namespace App\sql; class mysql { protected $db; /** * sql constructor. * @param string $host * @param string $dbname * @param string $username * @param string $password */ public function __construct(string $host, string $dbname, string $username, string $password) { try { $this->db = new \PDO('mysql:host='.$host.';dbname='.$dbname,$username,$password, array(\PDO::ATTR_ERRMODE => \PDO::ERRMODE_WARNING)) or die(print_r($this->db->errorInfo())); $this->db->exec('SET NAMES utf8'); } catch(Exeption $e){ die('Erreur:'.$e->getMessage()); } } /** * @return \PDO */ public function getDb() { if ($this->db instanceof \PDO) { return $this->db; } } }
true
de2d37abd14f792edaf1e2d3a1b6fecd9a94f115
PHP
OrigamiStructures/foldingTime
/src/View/Helper/CrudViewResources/DecorationFactory.php
UTF-8
2,196
2.609375
3
[]
no_license
<?php namespace App\View\Helper\CrudViewResources; use CrudViews\View\Helper\CRUD\Decorator\BasicDecorationFactory; use CrudViews\View\Helper\CRUD\Decorator; use Cake\Utility\Text; //use CrudViews\View\Helper\CRUD\CrudFields; use App\View\Helper\CrudViewResources\ColumnOutput; use CrudViews\View\Helper\CRUD\Decorator\TableCellDecorator; use CrudViews\View\Helper\CRUD\Decorator\BelongsToDecorator; use CrudViews\View\Helper\CRUD\Decorator\BelongsToSelectDecorator; use CrudViews\View\Helper\CRUD\Decorator\LiDecorator; use CrudViews\View\Helper\CRUD\Decorator\LinkDecorator; /** * DecorationSetups are your custom output configurations * * The method name is the the name you'll invoke them by. * They should return some CrudFields sub-class possibly * decorated with sub-classes of FieldDecorator. * * return new BelongsToDecorator(new ColumnTypeHelper($helper)); * * They should all take one argument, $helper, which is an instance of CrudHelper * * The methods index(), view(), edit(), add() are reserved. * If you implement them, they will never be called. * * @author dondrake */ class DecorationFactory extends BasicDecorationFactory { public function __construct($helper) { return parent::__construct($helper); } /** * Return the decorated output for the menuIndex method * * This example method 'status' returns the same as the 'index' base action. * It is provided as an example of what you can do with alternate actions. * * @param type $helper * @return \App\View\Helper\CRUD\Decorator\TableCellDecorator */ public function menuIndex($helper) { return new TableCellDecorator( // new Decorator\LabelDecorator( new BelongsToSelectDecorator( new ColumnOutput($helper) )); } public function liLink($helper) { return new LiDecorator( new LinkDecorator( new ColumnOutput($helper) )); } /** * This is a standard index page setup * Repurposed for the embedded index of Time in a Project view CRUD. * @param type $helper * @return \App\View\Helper\CrudViewResources\TableCellDecorator */ public function projectTime($helper) { return $this->index($helper); } }
true
35b20c6cea2d36e6a9e5d89268f65d73696e3c0f
PHP
PomeloProductions/easy-products
/classes/Admin/ViewProduct.php
UTF-8
4,865
2.640625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: bryce * Date: 3/10/17 * Time: 3:00 AM */ namespace EasyProducts\Admin; use EasyProducts\Model\Product; use EasyProducts\Model\Region; use EasyProducts\Model\ShippingOption; use WordWrap\Admin\TaskController; use WordWrap\Assets\Template\Mustache\MustacheTemplate; use WordWrap\Assets\View\Editor; class ViewProduct extends TaskController { /** * @var Product the template data needed */ protected $product; /** * @var ShippingOption the default shipping rate for this product */ private $defaultRate; /** * override this to setup anything that needs to be done before * @param $action string the action the user is trying to complete */ public function processRequest($action = null) { if (isset ($_GET['id'])) { $this->product = Product::find_one($_GET['id']); } else { $this->product = new Product(); } for ($i = 0; $i < count($this->product->shippingOptions); $i++) { $shippingOption = $this->product->shippingOptions[$i]; if (!$shippingOption->region_id) { $this->defaultRate = $shippingOption; } } if (!$this->defaultRate) { $this->defaultRate = new ShippingOption(); } if ($action == 'save') { $this->product->name = $_POST['name']; $this->product->description = $_POST['description']; $this->product->weight = $_POST['weight']; $this->product->cost = $_POST['cost']; $this->product->image_url = $_POST['image_url']; $this->product->active = $_POST['active'] == 'on'; $this->product->save(); $this->defaultRate->primary_rate = $_POST['default_primary_rate']; $this->defaultRate->add_on_rate = $_POST['default_add_on_rate']; $this->defaultRate->product_id = $this->product->id; $this->defaultRate->save(); for ($i = 0; $i < count($_POST['shipping_rate']['id']); $i++) { $id = $_POST['shipping_rate']['id'][$i]; if ($id) { foreach ($this->product->shippingOptions as $shippingOption) { if ($id == $shippingOption->id) { $shippingOption->primary_rate = $_POST['shipping_rate']['primary_rate'][$i]; $shippingOption->add_on_rate = $_POST['shipping_rate']['add_on_rate'][$i]; $shippingOption->region_id = $_POST['shipping_rate']['region'][$i]; $shippingOption->save(); } } } else if (is_numeric($_POST['shipping_rate']['region'][$i])) { $shippingOption = new ShippingOption(); $shippingOption->product_id = $this->product->id; $shippingOption->primary_rate = $_POST['shipping_rate']['primary_rate'][$i]; $shippingOption->add_on_rate = $_POST['shipping_rate']['add_on_rate'][$i]; $shippingOption->region_id = $_POST['shipping_rate']['region'][$i]; $shippingOption->save(); $this->product->shippingOptions[] = $shippingOption; } } } } /** * override to render the main page */ protected function renderMainContent() { $editor = new Editor($this->lifeCycle, 'description', $this->product->description, 'Description'); $regions = Region::fetchAll(); $shippingOptions = []; foreach ($this->product->shippingOptions as $shippingOption) { if ($shippingOption->region_id) { $shippingOption->regions = []; foreach ( $regions as $region) { $shippingOption->regions[] = clone $region; } foreach ($shippingOption->regions as $region) { if ($region->id == $shippingOption->region_id) { $region->selected = true; } } $shippingOptions[] = $shippingOption; } } $data = [ 'regions' => $regions, 'shipping_options' => $shippingOptions, 'product' => $this->product, 'description' => $editor->export(), 'default_rate' => $this->defaultRate ]; $template = new MustacheTemplate($this->lifeCycle, 'admin/view_product', $data); return $template->export(); } /** * override to render the main page */ protected function renderSidebarContent() { // TODO: Implement renderSidebarContent() method. } }
true
564b7b6657d61061290285747e16b17d35bce7f3
PHP
tauronik/dokuwiki-abbrlist
/syntax.php
UTF-8
3,510
2.6875
3
[]
no_license
<?php /** * DokuWiki Plugin abbrlist (Syntax Component) * * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html * @version 2021-08-12 * @author Michael Schatz <m.schatz@tauronik.de> * * @author (Original by) Andreas Böhler <dev@aboehler.at> */ class syntax_plugin_abbrlist extends DokuWiki_Syntax_Plugin { /** * What kind of syntax are we? */ function getType(){ return 'substition'; } /** * What about paragraphs? */ function getPType(){ return 'normal'; } /** * Where to sort in? */ function getSort(){ return 163; } /** * Connect pattern to lexer */ function connectTo($mode) { $this->Lexer->addSpecialPattern('\{\{abbrlist>[^}]*\}\}',$mode,'plugin_abbrlist'); } /** * Handle the match */ function handle($match, $state, $pos, Doku_Handler $handler){ global $ID; $options = trim(substr($match,11,-2)); $options = explode(',', $options); $data = array( 'nointernal' => false, 'sort' => false, 'acronyms' => array() ); foreach($options as $option) { switch($option) { case 'nointernal': $data['nointernal'] = true; break; case 'sort': $data['sort'] = true; break; } } // Only parse the local config file if we should omit built-in ones if($data['nointernal'] === true) { global $config_cascade; if (!is_array($config_cascade['acronyms'])) trigger_error('Missing config cascade for "acronyms"',E_USER_WARNING); if (!empty($config_cascade['acronyms']['local'])) { foreach($config_cascade['acronyms']['local'] as $file) { if(file_exists($file)) { $data['acronyms'] = array_merge($data['acronyms'], confToHash($file)); } } } } // otherwise, simply use retrieveConfig to fetch all acronyms else { $data['acronyms'] = retrieveConfig('acronyms', 'confToHash'); } // Sort the array, if requested if($data['sort'] === true) { ksort($data['acronyms']); } return $data; } /** * Create output */ function render($format, Doku_Renderer $R, $data) { if($format == 'metadata') { if(!isset($renderer->meta['abbrlist'])) p_set_metadata($ID, array('abbrlist' => array())); return true; } if(($format != 'xhtml') && ($format != 'odt')) return false; $R->table_open(); $R->tablethead_open(); $R->tableheader_open(); $R->doc .= $this->getLang('key'); $R->tableheader_close(); $R->tableheader_open(); $R->doc .= $this->getLang('value'); $R->tableheader_close(); $R->tablethead_close(); foreach($data['acronyms'] as $key => $val) { $R->tablerow_open(); $R->tablecell_open(); $R->doc .= $key; $R->tablecell_close(); $R->tablecell_open(); $R->doc .= $val; $R->tablecell_close(); $R->tablerow_close(); } $R->table_close(); } }
true
774d43d396cedddf5736c81bea705effe778d2d3
PHP
ezreum/phpTraining
/clase/t1/ejer06.php
UTF-8
231
2.75
3
[]
no_license
<?php /* $tiempo = time(); $tiempo = date('D d M Y',$tiempo); echo $tiempo."\n"; $tiempo = '20-3-1993'; $t = strtotime($tiempo); */ setlocale(LC_ALL, "es_ES"); $ts = mktime(0,0,0,10,20,1993); $r = strftime("%B, $ts"); echo $r; ?>
true
aa5763f0cf48c92882c8b24abe1e543723d7bfd9
PHP
jogs78/sslab
/app/Models/Prestador.php
UTF-8
857
2.65625
3
[ "MIT" ]
permissive
<?php namespace App\Models; class Prestador extends User { /** * The table associated with the model. * * @var string */ protected $table = 'users'; /** * Obtener el proyecto en el cuál el usuario hace o hizo su servicio. */ public function proyecto() { return $this->hasOne('App\Models\Proyecto', 'prestador'); } /** * Obtener el horario en el cuál el usuario hace o hizo su servicio. * Establece el tipo de relacion "tiene un"... */ public function horario() { return $this->hasOne('App\Models\Horario','prestador'); } public function asistencia() { return $this->hasOne('App\Models\Asistencia','prestador'); } public function incidencia() { return $this->hasOne('App\Models\Incidencia','prestador'); } }
true
c8afcb2a368c2d9199c94520799489db410a9a04
PHP
marlihams/clinique-v-t-rinaire
/dossierPHP/RDV.php
UTF-8
1,449
2.59375
3
[]
no_license
<div id="nouveau_rdv"> <div class="entete"> Prendre un rendez-vous: </div> <?php $vSql1 = "SELECT intitule FROM Prestation"; $vSql2 = "SELECT id, nom, prenom FROM vveterinaire"; $vQuery1=pg_query($vConn, $vSql1) or die("Requete 1 incomprise"); $vQuery2=pg_query($vConn, $vSql2) or die("Requete 2 incomprise"); echo" <form action='NouveauRDV.php' method='POST'> <table> <tr> <td>Type de prestation <select name='prestation'>"; while ($row=pg_fetch_array($vQuery1, null, PGSQL_ASSOC)) { echo"<option>$row[intitule]</option>"; } echo"</select></td> </tr> <tr> <td>Quel Vétérinaire souhaitez vous? <select id='vet' name='veterinaire'>"; while ($row=pg_fetch_array($vQuery2, null, PGSQL_ASSOC)) { echo"<option>$row[id] . $row[nom] $row[prenom]</option>"; } echo"</select></td> </tr> <tr> <td>Date: <input type='date' name='date' id='datepicker' class='idatepicker' align='left'>"; echo "<select id='heure' name='heure'>"; for ($h = 8; $h < 18; $h++) { if ($h !=12 && $h !=13){ echo '<option value="'.$h.'h">'.$h.'h'.' 00</option>'; } } echo "</select></td></tr>; </table> <input name='Valider' type='submit' value='Réserver'></td></tr> </form>"; ?> </div> </div>
true
e6501402375eaeaa0a221d82351901929002d92d
PHP
trijayadigital/tripay-php
/src/Transaction.php
UTF-8
6,109
3.203125
3
[ "MIT" ]
permissive
<?php namespace Tripay; class Transaction extends Base { private $transactionType; private $returnUrl; private $customerName; private $customerEmail; private $customerPhone; private $expiresAfter; private $items = []; /** * Konstruktor. * * @param int $environment */ public function __construct($environment) { // default expiry: 24 hours. $this->expiresAfter(1440); parent::__construct($environment); } /** * Set operasi untuk open payment. * * @return Transaction */ public function forOpenPayment() { $this->transactionType = 'open'; return $this; } /** * Set operasi untuk closed payment. * * @return Transaction */ public function forClosedPayment() { $this->transactionType = 'closed'; return $this; } /** * Tambahakan item ke list request. * * @param string $name * @param int $price * @param int $quantity * @param string $sku * * @return Transaction */ public function addItem($name, $price, $quantity, $sku = null) { $this->items[] = [ 'sku' => (string) $sku, 'name' => (string) $name, 'price' => (int) $price, 'quantity' => (int) $quantity, ]; return $this; } /** * Set nama customer. * * @param string $name * * @return Transaction */ public function customerName($name) { $this->customerName = (string) $name; return $this; } /** * Set email customer. * * @param string $email * * @return Transaction */ public function customerEmail($email) { $this->customerEmail = (string) $email; return $this; } /** * Set nomor telepon customer. * * @param string $phone * * @return Transaction */ public function customerPhone($phone) { $this->customerPhone = (string) $phone; return $this; } /** * Set return URL. * * @param string $url * * @return Transaction */ public function returnUrl($url) { if (! filter_var($url, FILTER_VALIDATE_URL)) { throw new Exceptions\InvalidRedirectException(sprintf('Invalid URL fornat: %s', $url)); } $this->returnUrl = $url; return $this; } /** * Set waktu kedaluwarsa invoice (dalam menit). * * @param int $minutes * * @return Transaction */ public function expiresAfter($minutes) { $this->expiresAfter = time() + ((int) $minutes * 60); return $this; } /** * Proses data transaksi. * * @return \stdClass */ public function process() { switch ($this->transactionType) { case 'open': $signature = hash_hmac( 'sha256', $this->merchantCode.$this->channelCode.$this->merchantRef, $this->privateKey ); $payloads = [ 'method' => $this->channelCode, 'merchant_ref' => $this->merchantRef, 'customer_name' => $this->customerName, 'signature' => $signature, ]; return $this->request('post', 'open-payment/create', $payloads); case 'closed': $amount = 0; for ($i = 0; $i < count($this->items); $i++) { $amount += (int) $this->items[$i]['price'] * (int) $this->items[$i]['quantity']; } $signature = hash_hmac( 'sha256', $this->merchantCode.$this->merchantRef.$amount, $this->privateKey ); $payloads = [ 'method' => $this->channelCode, 'merchant_ref' => $this->merchantRef, 'amount' => $amount, 'customer_name' => $this->customerName, 'customer_email' => $this->customerEmail, 'customer_phone' => $this->customerPhone, 'order_items' => $this->items, 'return_url' => $this->returnUrl, 'expired_time' => $this->expiresAfter, 'signature' => $signature, ]; return $this->request('post', 'transaction/create', $payloads); default: throw new Exceptions\InvalidTransactionTypeException(sprintf( 'Only OPEN and CLOSED transaction are supported, got: %s', $this->transactionType )); } } public function detail($uuid) { if (! is_string($uuid) || strlen(trim($uuid)) <= 0) { throw new Exceptions\InvalidTransactionUuidException('Transaction UUID should be a non empty string.'); } switch ($this->transactionType) { case 'open': $payloads = []; return $this->request('get', 'open-payment/'.$uuid.'/detail', $payloads); case 'closed': $payloads = ['reference' => $uuid]; // TODO: apakah reference sama dengan uuid? return $this->request('get', 'transaction/detail', $payloads); default: throw new Exceptions\InvalidTransactionTypeException(sprintf( 'Only OPEN and CLOSED transaction types are supported, got: %s', $this->transactionType )); } } public function payments($uuid) { if (! is_string($uuid) || strlen(trim($uuid)) <= 0) { throw new Exceptions\InvalidTransactionUuidException('Transaction UUID should be a non-empty string.'); } $payloads = []; return $this->request('get', 'open-payment/'.$uuid.'/transactions', $payloads); } }
true
20708098b0926b81642c63f2dccac7ecaf57ef34
PHP
lazaroness/cursos-e-exemplos-extras
/facu/php/obras/painel/exportar_xls_tipo_produto.php
UTF-8
2,127
2.625
3
[]
no_license
<?php include ('seguranca.php'); include '../librarys/phpexcel/Classes/PHPExcel.php'; $tipos_produto = TipoProduto::find('all'); $arquivo = "exportar_tipo_produto_".date('d/m/Y').".".date('H:i:s').".xls"; // Instanciamos a classe $objPHPExcel = new PHPExcel(); // Criamos as colunas $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A1', $config->empresa ) ->setCellValue('B1', $online->nome ) ->setCellValue("C1", date('d/m/Y') ) ->setCellValue("D1", date('H:i:s') ); // Definimos o estilo da fonte $objPHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true); $objPHPExcel->getActiveSheet()->getStyle('A3')->getFont()->setBold(true); // Criamos as colunas $objPHPExcel->setActiveSheetIndex(0) ->setCellValue('A3', 'DESCRICAO' ); // Podemos configurar diferentes larguras paras as colunas como padrão $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(50); // Também podemos escolher a posição exata aonde o dado será inserido (coluna, linha, dado); $count = 4; foreach ($tipos_produto as $tipo_produto): $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $count, $tipo_produto->descricao); $count++; endforeach; // Podemos renomear o nome das planilha atual, lembrando que um único arquivo pode ter várias planilhas $objPHPExcel->getActiveSheet()->setTitle('exportar_tipo_produto'); // Cabeçalho do arquivo para ele baixar header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$arquivo.'"'); header('Cache-Control: max-age=0'); // Se for o IE9, isso talvez seja necessário header('Cache-Control: max-age=1'); // Acessamos o 'Writer' para poder salvar o arquivo $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); // Salva diretamente no output, poderíamos mudar arqui para um nome de arquivo em um diretório ,caso não quisessemos jogar na tela $objWriter->save('php://output'); exit; ?>
true
26861867203c67d4eadcd3dd33956c29858c1277
PHP
iulyanp/battle
/src/Entity/Skill.php
UTF-8
3,084
3.390625
3
[]
no_license
<?php namespace Iulyanp\Battle\Entity; /** * Class Skill * @package Iulyanp\Battle\Entity */ class Skill { const SKILL_TYPES = [self::ATTACK, self::DEFENCE]; const ATTACK = 'onAttack'; const DEFENCE = 'onDefence'; private $name; private $type; private $probability; private $formula; private $status; private $used = false; /** * Skill constructor. * * @param $name * @param $type * @param $probability * @param $formula */ public function __construct($name, $type, $probability, $formula) { $this->validate($type, $probability, $formula); $this->name = $name; $this->type = $type; $this->probability = $probability; $this->formula = str_replace('damage', '%s', $formula); } /** * @return mixed */ public function getName() { return $this->name; } /** * @return mixed */ public function getType() { return $this->type; } /** * @return mixed */ public function getProbability() { return $this->probability; } /** * @return mixed */ public function getFormula() { return $this->formula; } public function wasUsed() { return $this->used; } /** * @return bool */ public function isActive() { $this->status = mt_rand(1, 100) <= $this->probability; return $this->status; } /** * @param $defaultDamage * * @return float|int */ public function getDamageWithActiveSkills($defaultDamage) { $damage = 0; $this->used = false; if ($this->isActive()) { $this->used = true; $formula = sprintf($this->getFormula(), $defaultDamage); list($a, $operator, $b) = explode(' ', $formula); switch ($operator) { case '*': $damage = $a * $b; break; case '/': $damage = $a / $b; break; } } return $damage; } /** * @param $type * @param $probability * @param $formula * * @throws \Exception */ protected function validate($type, $probability, $formula) { if (!in_array($type, self::SKILL_TYPES)) { throw new \Exception(sprintf('Skill can be only of type %s or %s', self::ATTACK, self::DEFENCE)); } if (!is_numeric($probability) || 0 > $probability || 100 < $probability) { throw new \Exception('Skill probability can be only numeric from 0 to 100.'); } if (!preg_match('/^([0-9]|damage)+\s[\*\/]{1}\s(damage|[0-9])+$/m', $formula)) { throw new \Exception( "Skill formula can be only in the following forms: [number] [operator] damage OR damage [operator] [number] eg. 2 * damage" ); } } }
true
6851bc90dbd45933be0c810ac4eb27bea25d6b83
PHP
oksuz/github-resume
/tests/Services/DeveloperCvBuilderTest.php
UTF-8
841
2.640625
3
[]
no_license
<?php namespace App\Tests\Services; use App\Services\DeveloperCvBuilder; use PHPUnit\Framework\TestCase; class DeveloperCvBuilderTest extends TestCase { public function testBuildException() { $instance = new DeveloperCvBuilder(); $this->expectException(\Exception::class); $this->expectExceptionMessage('user not defined'); $instance->build(); } public function testBuild() { $instance = new DeveloperCvBuilder(); $user = json_decode(file_get_contents(__DIR__ . '/user.json'), true); $repos = json_decode(file_get_contents(__DIR__ . '/repos.json'), true); $instance->setUser($user); $instance->setRepositories($repos); $cv1 = $instance->build(); $cv2 = $instance->build(); $this->assertEquals($cv1, $cv2); } }
true
be389b8d071e56d018c423b97ac3dec24b7dc160
PHP
adrianowead/cep-gratis
/tests/WS/ApiCEPTest.php
UTF-8
3,066
2.8125
3
[]
no_license
<?php namespace Wead\ZipCode\Tests\WS; use PHPUnit\Framework\TestCase; use Wead\ZipCode\WS\ApiCEP; class ApiCEPTest extends TestCase { /** * @dataProvider getCepDefaultWithOutput */ public function testGetAddressFromApiCEPDefaultUsage(string $zipCode, array $expected) { $cep = new ApiCEP(); $out = $cep->getAddressFromZipcode($zipCode); // must be qual structure and values self::assertEquals($expected, $out); } /** * @dataProvider getCepEmptyDefaultWithOutput */ public function testGetAddressEmptyFromApiCEPDefaultUsage(string $zipCode, array $expected) { $cep = new ApiCEP(); $out = $cep->getAddressFromZipcode($zipCode); // must be qual structure and values self::assertEquals($expected, $out); } /** * @dataProvider getMockInputOutput */ public function testNormalizeResponseApiCEPDefaultUsage(array $address, array $expected) { $cep = new ApiCEP(); $reflect = new \ReflectionObject($cep); $method = $reflect->getMethod('normalizeResponse'); $method->setAccessible(true); // turns private method accessible $out = $method->invoke($cep, $address); // must be qual structure and values self::assertEquals($expected, $out); } /** * Returns all data to be used on tests */ public function getCepDefaultWithOutput() { return [ "Dados esperados Luís Asson" => [ "03624010", [ "status" => true, "address" => "Rua Luís Asson", "district" => "Vila Buenos Aires", "city" => "São Paulo", "state" => "SP", "api" => "ApiCEP" ] ] ]; } /** * Returns all data to be used on tests */ public function getCepEmptyDefaultWithOutput() { return [ "Dados esperados vazio" => [ "00000000", [ "status" => false, "address" => null, "district" => null, "city" => null, "state" => null, "api" => "ApiCEP" ] ] ]; } public function getMockInputOutput() { return [ "Input e Output Luís Asson" => [ [ "logradouro" => "Rua Luís Asson", "bairro" => "Vila Buenos Aires", "localidade" => "São Paulo", "uf" => "SP", ], [ "status" => true, "address" => "Rua Luís Asson", "district" => "Vila Buenos Aires", "city" => "São Paulo", "state" => "SP", "api" => "ViaCep" ] ] ]; } }
true
cc1a575cb81443d4f733b01f833027de414b2e75
PHP
jbirch8865/Twilio
/SendSMS.php
UTF-8
3,726
3.015625
3
[]
no_license
<?php require_once 'vendor/autoload.php'; use Twilio\Rest\Client; require_once 'ValidatePhoneNumber.php'; class IniConfigError Extends \Exception{} class MessageBodyTooLong Extends \Exception{} class MessageNotReadyToSend Extends \Exception{} class ThisIsADuplicateMessage Extends \Exception{} class TextMessage { private $message_body; private $send_to; private $sid; private $token; private $send_from; function __construct() { $this->LoadConfigs(); } private function LoadConfigs() { try { $ini = parse_ini_file('SMS_config.ini'); $this->sid = $ini['SID']; $this->token = $ini['Token']; $this->send_from = $ini['From']; } catch (Exception $e) { throw new IniConfigError("Error loading ini configurations"); } } public function Set_To_Number($send_to) { try { $this->send_to = new PhoneNumber($send_to); } catch (InvalidPhoneNumber $e) { throw new InvalidPhoneNumber('This is not a valid phone number'); } catch (\Exception $e) { throw new \Exception("There was an error setting this phone number"); } } public function Set_Message_Body($message_body) { try { $this->message_body = $message_body; $sms_string_analyzer = new \Instasent\SMSCounter\SMSCounter(); $analyze_results = $sms_string_analyzer->count($message_body); if($analyze_results->messages > 1){throw new MessageBodyTooLong("This message is too long to send");} } catch (MessageBodyTooLong $e) { throw new MessageBodyTooLong("This message is too long to send"); } catch (\Exception $e) { throw new \Exception("Error validating the message body"); } } public function Send_Message() { if($this->Is_Message_Ready_To_Send()) { try { $twilio = $this->Twilio_Client_Object(); $message = $twilio->messages->create($this->send_to->Print_Number(),array("body" => $this->message_body,"from" => $this->send_from)); } catch (\Exception $e) { throw new \Exception("There was an error sending this message"); } }else{ throw new MessageNotReadyToSend("This message is either missing a body or to number"); } } public function Twilio_Client_Object() { try { $twilio = new Client($this->sid, $this->token); return $twilio; } catch (\Exception $e) { throw new \Exception("Error loading twilio"); } } public function Is_Message_Ready_To_Send() { if($this->send_to && $this->message_body) { return true; } else { return false; } } public function Print_Send_To() { return $this->send_to->Print_Number(); } public function Print_Message_Body() { return $this->message_body; } } class SMSMessageWithChecks extends TextMessage { function __construct() { parent::__construct(); } private function Is_This_A_Duplicate_Message() { $twilio = $this->Twilio_Client_Object(); $date = date_create(); date_sub($date, date_interval_create_from_date_string('1 days')); $messages = $twilio->messages->read(array("dateSent" => $date,"to" => $this->Print_Send_To()),20); foreach($messages as $record) { if($record->body == $this->Print_Message_Body()) { return true; } } return false; } public function Send_SMS() { if($this->Is_This_A_Duplicate_Message()) { throw new ThisIsADuplicateMessage("This message was already sent today"); }else { $this->Send_Message(); } } } /* sample of how to use this class try { $sms = new SMSMessageWithChecks(); $sms->Set_To_Number("1".$_GET['phone']); $sms->Set_Message_Body($_GET['body']); $sms->Send_SMS(); echo 'Message Sent'; } catch (ThisIsADuplicateMessage $e) { echo 'Sorry this message was already sent today'; } catch (\Exception $e) { echo 'Unknown Error'; } */ ?>
true
b99647d9da79c69d4a25ea08cfdcc58a3435cf71
PHP
shafqatali/code-signal
/fileNaming/file_naming.php
UTF-8
269
3.03125
3
[]
no_license
<?php function fileNaming($names) { foreach($names as $i=>$name){ $c = 1; $newNames = array_slice($names, 0, $i); while(in_array($names[$i], $newNames)){ $names[$i] = $name.'('.$c++.')'; } } return $names; }
true
7b0321cc04a67b2bad9c8ac3d1d74395dad2fa71
PHP
yonykikok/TercerCuatrimestre-DesarrolloWeb-
/Programacion/primer parcial3/Funciones/cargarProveedor.php
UTF-8
2,039
2.703125
3
[]
no_license
<?php include "./Clases/proveedor.php"; include "./Clases/dao.php"; if(isset($_POST['id'])) { if(isset($_POST['nombre'])) { if(isset($_POST['email'])) { if(isset($_FILES['foto'])) { $id=$_POST['id']; $nombre=$_POST['nombre']; $email=$_POST['email']; $foto=$_FILES['foto']['name']; $proveedor = new proveedor(); $arraNombre=array("nombre"=>$nombre,"id"=>$id); $proveedor->cargarFoto($arraNombre);// hacer que sea mas generico $params=array("id"=>$id,"nombre"=>$nombre,"email"=>$email,"foto"=>$foto); $proveedor->miConstructorGenerico($params); $path="./Archivos/proveedores.txt"; $arrayProveedores=array(); if(file_exists($path)) { $arrayProveedores=dao::LeerObjetosJson($path,$proveedor); if(!dao::verificarExistenciaDelObjeto($arrayProveedores,$id,'id')) { dao::GuardarObjetoJson($path,$proveedor); echo "Guardamos el proveedor"; } else { echo "El proveedor con el id: ".$id." ya esta en la lista"; } } else { dao::GuardarObjetoJson($path,$proveedor); echo "Guardamos el proveedor"; } } else { echo "falta el campo foto en POST"; } } else { echo "falta el campo email en POST"; } } else { echo "falta el campo nombre en POST"; } } else { echo "falta el campo id en POST"; } ?>
true
809eb073a87f90cb89f984ad0570c91ca9b1dce0
PHP
razaman2/AccountOnline
/interfaces/format.php
UTF-8
107
2.671875
3
[]
no_license
<?php namespace AccountOnline\interfaces; interface format { public function format(array $data); }
true
5d97359b1583290c493b234bbc24ae7c545e8690
PHP
nasimul007/Internship-Project
/app/Http/Resources/Semester.php
UTF-8
626
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; class Semester extends JsonResource { /** * Transform the resource into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ 'semester_id' => $this->semester_id, 'semester_name' => $this->semester_name, 'start_date' => $this->start_date, 'end_date' => $this->end_date, 'created_date' => $this->created_date, 'status' => $this->status ]; } }
true
99bb433ec009e93dbabe8341d7b7c0e3b8c4b7aa
PHP
luigif/WsdlToPhp
/samples/amazon-ec2/Describe/Type/AmazonEc2TypeDescribeInstanceAttributeType.php
UTF-8
7,335
2.953125
3
[]
no_license
<?php /** * Class file for AmazonEc2TypeDescribeInstanceAttributeType * @date 10/07/2012 */ /** * Class AmazonEc2TypeDescribeInstanceAttributeType * @date 10/07/2012 */ class AmazonEc2TypeDescribeInstanceAttributeType extends AmazonEc2WsdlClass { /** * The instanceId * @var string */ public $instanceId; /** * The instanceType * @var AmazonEc2TypeEmptyElementType */ public $instanceType; /** * The kernel * @var AmazonEc2TypeEmptyElementType */ public $kernel; /** * The ramdisk * @var AmazonEc2TypeEmptyElementType */ public $ramdisk; /** * The userData * @var AmazonEc2TypeEmptyElementType */ public $userData; /** * The disableApiTermination * @var AmazonEc2TypeEmptyElementType */ public $disableApiTermination; /** * The instanceInitiatedShutdownBehavior * @var AmazonEc2TypeEmptyElementType */ public $instanceInitiatedShutdownBehavior; /** * The rootDeviceName * @var AmazonEc2TypeEmptyElementType */ public $rootDeviceName; /** * The blockDeviceMapping * @var AmazonEc2TypeEmptyElementType */ public $blockDeviceMapping; /** * The sourceDestCheck * @var AmazonEc2TypeEmptyElementType */ public $sourceDestCheck; /** * The groupSet * @var AmazonEc2TypeEmptyElementType */ public $groupSet; /** * The productCodes * @var AmazonEc2TypeEmptyElementType */ public $productCodes; /** * Constructor * @param string instanceId * @param AmazonEc2TypeEmptyElementType instanceType * @param AmazonEc2TypeEmptyElementType kernel * @param AmazonEc2TypeEmptyElementType ramdisk * @param AmazonEc2TypeEmptyElementType userData * @param AmazonEc2TypeEmptyElementType disableApiTermination * @param AmazonEc2TypeEmptyElementType instanceInitiatedShutdownBehavior * @param AmazonEc2TypeEmptyElementType rootDeviceName * @param AmazonEc2TypeEmptyElementType blockDeviceMapping * @param AmazonEc2TypeEmptyElementType sourceDestCheck * @param AmazonEc2TypeEmptyElementType groupSet * @param AmazonEc2TypeEmptyElementType productCodes * @return AmazonEc2TypeDescribeInstanceAttributeType */ public function __construct($_instanceId = null,$_instanceType = null,$_kernel = null,$_ramdisk = null,$_userData = null,$_disableApiTermination = null,$_instanceInitiatedShutdownBehavior = null,$_rootDeviceName = null,$_blockDeviceMapping = null,$_sourceDestCheck = null,$_groupSet = null,$_productCodes = null) { parent::__construct(array('instanceId'=>$_instanceId,'instanceType'=>$_instanceType,'kernel'=>$_kernel,'ramdisk'=>$_ramdisk,'userData'=>$_userData,'disableApiTermination'=>$_disableApiTermination,'instanceInitiatedShutdownBehavior'=>$_instanceInitiatedShutdownBehavior,'rootDeviceName'=>$_rootDeviceName,'blockDeviceMapping'=>$_blockDeviceMapping,'sourceDestCheck'=>$_sourceDestCheck,'groupSet'=>$_groupSet,'productCodes'=>$_productCodes)); } /** * Set instanceId * @param string instanceId * @return string */ public function setInstanceId($_instanceId) { return ($this->instanceId = $_instanceId); } /** * Get instanceId * @return string */ public function getInstanceId() { return $this->instanceId; } /** * Set instanceType * @param EmptyElementType instanceType * @return EmptyElementType */ public function setInstanceType($_instanceType) { return ($this->instanceType = $_instanceType); } /** * Get instanceType * @return AmazonEc2TypeEmptyElementType */ public function getInstanceType() { return $this->instanceType; } /** * Set kernel * @param EmptyElementType kernel * @return EmptyElementType */ public function setKernel($_kernel) { return ($this->kernel = $_kernel); } /** * Get kernel * @return AmazonEc2TypeEmptyElementType */ public function getKernel() { return $this->kernel; } /** * Set ramdisk * @param EmptyElementType ramdisk * @return EmptyElementType */ public function setRamdisk($_ramdisk) { return ($this->ramdisk = $_ramdisk); } /** * Get ramdisk * @return AmazonEc2TypeEmptyElementType */ public function getRamdisk() { return $this->ramdisk; } /** * Set userData * @param EmptyElementType userData * @return EmptyElementType */ public function setUserData($_userData) { return ($this->userData = $_userData); } /** * Get userData * @return AmazonEc2TypeEmptyElementType */ public function getUserData() { return $this->userData; } /** * Set disableApiTermination * @param EmptyElementType disableApiTermination * @return EmptyElementType */ public function setDisableApiTermination($_disableApiTermination) { return ($this->disableApiTermination = $_disableApiTermination); } /** * Get disableApiTermination * @return AmazonEc2TypeEmptyElementType */ public function getDisableApiTermination() { return $this->disableApiTermination; } /** * Set instanceInitiatedShutdownBehavior * @param EmptyElementType instanceInitiatedShutdownBehavior * @return EmptyElementType */ public function setInstanceInitiatedShutdownBehavior($_instanceInitiatedShutdownBehavior) { return ($this->instanceInitiatedShutdownBehavior = $_instanceInitiatedShutdownBehavior); } /** * Get instanceInitiatedShutdownBehavior * @return AmazonEc2TypeEmptyElementType */ public function getInstanceInitiatedShutdownBehavior() { return $this->instanceInitiatedShutdownBehavior; } /** * Set rootDeviceName * @param EmptyElementType rootDeviceName * @return EmptyElementType */ public function setRootDeviceName($_rootDeviceName) { return ($this->rootDeviceName = $_rootDeviceName); } /** * Get rootDeviceName * @return AmazonEc2TypeEmptyElementType */ public function getRootDeviceName() { return $this->rootDeviceName; } /** * Set blockDeviceMapping * @param EmptyElementType blockDeviceMapping * @return EmptyElementType */ public function setBlockDeviceMapping($_blockDeviceMapping) { return ($this->blockDeviceMapping = $_blockDeviceMapping); } /** * Get blockDeviceMapping * @return AmazonEc2TypeEmptyElementType */ public function getBlockDeviceMapping() { return $this->blockDeviceMapping; } /** * Set sourceDestCheck * @param EmptyElementType sourceDestCheck * @return EmptyElementType */ public function setSourceDestCheck($_sourceDestCheck) { return ($this->sourceDestCheck = $_sourceDestCheck); } /** * Get sourceDestCheck * @return AmazonEc2TypeEmptyElementType */ public function getSourceDestCheck() { return $this->sourceDestCheck; } /** * Set groupSet * @param EmptyElementType groupSet * @return EmptyElementType */ public function setGroupSet($_groupSet) { return ($this->groupSet = $_groupSet); } /** * Get groupSet * @return AmazonEc2TypeEmptyElementType */ public function getGroupSet() { return $this->groupSet; } /** * Set productCodes * @param EmptyElementType productCodes * @return EmptyElementType */ public function setProductCodes($_productCodes) { return ($this->productCodes = $_productCodes); } /** * Get productCodes * @return AmazonEc2TypeEmptyElementType */ public function getProductCodes() { return $this->productCodes; } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } } ?>
true
2596b9efc31d5d5e515cbd6374237b20b4b093b4
PHP
hypermoon/waterMonitors
/frontend/controllers/Socketserver.php
GB18030
2,674
2.78125
3
[]
no_license
<?php namespace res\waterMonitor\frontend\controllers; use Yii; class Socketserver{ private $_port='9000'; private $_address='127.0.0.1'; private $_client_socket_list=array(); public function __set($name,$val){ $this->$name=$val; } private function _showError($error){ exit($error); } /** * ʼsocket˼˿ */ public function start(){ // ˿ if (($sock = socket_create ( AF_INET, SOCK_STREAM, SOL_TCP )) === false) { $this->_showError("socket_create() failed :reason:" . socket_strerror ( socket_last_error () )); } // if (socket_bind ( $sock, $this->_address, $this->_port ) === false) { $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) )); } // if (socket_listen ( $sock, 5 ) === false) { $this->_showError("socket_bind() failed :reason:" . socket_strerror ( socket_last_error ( $sock ) ) ); } do { //һͻӵʱ if ($client_socket=socket_accept ( $sock )) { $count = count ( $this->_client_socket_list ) + 1; //û ͻ $this->_client_socket_list[]=$client_socket; echo "new connection:\r\n";//ǰӵĿͻ echo "current connection:{$count}\r\n"; //ܿͻ˴ַ $msg=$this->read($client_socket); echo "client:{$msg}\r\n"; //ͻ˴ֵ $my_msg="I am fine,think you\r\n"; $this->send($client_socket,$my_msg); } /** * δο,жǷпͻʧȥ else{ foreach ( $this->_client_socket_list as $socket ) { $len = socket_recv ($socket, $buffer, 2048, 0 ); // һ¿ͻϢ,Ϊ0Ͽ if ($len < 7) { //дȥӵĿͻҵ } } } */ }while(true); } /** * ݸͻ */ public function send($client_socket,$str){ return socket_write ( $client_socket,$str, strlen ( $str ) ); } /** * ӿͻ˽ */ public function read($client_socket){ return socket_read ( $client_socket, 8192 );//8192ʵʴĽܳ,819292ʾһ,һַҲԽܵ,8192Ҳûϵ,Զʶ } } //$socket_server =new SocketServer(); //$socket_server->start();//ʼ
true
eb9184cd15c53cd138925af41df840806fe747e3
PHP
Cell-V/laravel-posts
/src/Http/Requests/UpdatePostRequest.php
UTF-8
642
2.703125
3
[ "MIT" ]
permissive
<?php namespace CellV\LaravelPosts\Http\Requests; use Auth; use CellV\LaravelPosts\Models\Post; use Illuminate\Foundation\Http\FormRequest; class UpdatePostRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { $post = $this->post; return Auth::check() && $post && $post->user_id==$this->user()->getKey();//$this->user()->can('update', $post); } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'title' => 'required', 'body' => 'required', ]; } }
true
3df6892bf0f694d834e47b344769d2e075432e88
PHP
threeel/Clarifai
/src/ClarifaiClient.php
UTF-8
4,490
2.953125
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * User: threeel * Date: 6/28/16 * Time: 12:38 AM */ namespace Threeel\Clarifai; use Threeel\Clarifai\Exceptions\AuthorizationException; class ClarifaiClient { private $url; protected $request; private $token; private $tokenRequest = false; public function __construct(array $options = []) { $this->url = new ClarifaiUrl($options); } /** * Get the Token to be used for the consecutive requests */ public function getToken() { $url = $this->url->get('token'); $this->tokenRequest = true; $tokenResult = $this->post($url, $this->url->credentials()); if (isset($tokenResult['access_token'])) { $this->token = $tokenResult['access_token']; $this->tokenRequest = false; return $this->token; } throw new AuthorizationException($tokenResult['error']); } public function getAuthorizationHeader() { if (!$this->tokenRequest) { $header = 'Authorization: Bearer '; if (!$this->hasToken()) { $this->getToken(); } return [(string) $header . $this->token]; } } public function hasToken() { return isset($this->token); } public function url() { return $this->url; } public function onModel($name) { } /** * Prepares the Curl Resource to be Executed * @param $url * @param string $method * @param array $data */ private function setup($url, $method = 'GET', array $data = [], $headers = []) { try { $this->request = curl_init($url); curl_setopt($this->request, CURLOPT_CUSTOMREQUEST, $method); curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true); curl_setopt($this->request, CURLOPT_SSL_VERIFYPEER, false); if ($method === 'POST') { curl_setopt($this->request, CURLOPT_POST, count($data)); curl_setopt($this->request, CURLOPT_POSTFIELDS, $data); } if ($headers !== null) { curl_setopt($this->request, CURLOPT_HTTPHEADER, $headers); } } catch (\Exception $ex) { throw $ex; } } public function isAuthorized() { return ($this->token !== null) ; } /** * Disposes the Curl Resource Handle * @param $curl_resource */ private function destroy($curl_resource) { return curl_close($curl_resource); } public function request($url, $method = 'GET', array $data = []) { $header = $this->getAuthorizationHeader(); // dd($header); $this->setup($url, $method, $data, $header); try { $curl_response = curl_exec($this->request); $response = json_decode($curl_response, true); $this->destroy($this->request); return $response; } catch (\Exception $ex) { throw $ex; } } /** * Make a GET Request to Clarifai * @return mixed */ public function get($url = null) { if (!$url) { return $this->request($this->url->get(), 'GET'); } return $this->request($url, 'GET'); } /** * Make a POST Request to Clarifai * @param array $data * @return mixed */ public function post($url, array $data) { return $this->request($url, 'POST', $data); } /** * The Endpoint to Call * @param $name * @return KitelyClient */ public function onService($name) { $this->url->onService($name); return $this; } /** * The Array of Query Parameters * @param array $parameters * @return KitelyClient */ public function withParameters(array $parameters) { foreach ($parameters as $key => $value) { $this->withParameter($key, $value); } return $this; } /** * Add a query parameter * @param string $key * @param string $value * @return KitelyClient */ public function withParameter($key, $value) { $this->url->withParameter($key, $value); return $this; } /** * The Url that will be Called * @return string */ public function __toString() { return (string) $this->url; } }
true
4f8f8339a4d144332475001aa5595a92f2cc9b73
PHP
bintangputera/ws-web-kelompok4
/idabatik-web/admin/action/blog-post.php
UTF-8
2,464
2.53125
3
[ "MIT" ]
permissive
<?php include '../../db/connection.php'; $judul = $_POST['judul_blog']; $thumbnail = $_FILES['gambar']['name']; $kategori = $_POST['select_kategori']; $editorContent = $_POST['contentEditor']; $str = str_replace(" ", "-", $judul); $slug = strtolower($str); $date = date("d-m-Y"); var_dump($date); if (!empty($thumbnail)) { $allowed_ext = array('png', 'jpg'); $x = explode('.', $thumbnail); $ext = strtolower(end($x)); $file_tmp = $_FILES['gambar']['tmp_name']; $angka_acak = rand(1, 999); $nama_gambar_baru = $angka_acak.'-'.$thumbnail; if (in_array($ext, $allowed_ext) == true) { move_uploaded_file($file_tmp, '../../uploaded-images/blog/'. $nama_gambar_baru); $query = "INSERT INTO blog(id_kategori, judul, slug, thumbnail, konten_blog, created_at) VALUES ('".$kategori."', '".$judul."', '".$slug."', '".$nama_gambar_baru."', '".$editorContent."', '".$date."')"; $result = mysqli_query($mysqli, $query); if(!$result){ die ("Query gagal dijalankan: ".mysqli_errno($mysqli). " - ".mysqli_error($mysqli)); } else { //tampil alert dan akan redirect ke halaman index.php //silahkan ganti index.php sesuai halaman yang akan dituju echo "<script>alert('Data berhasil ditambah.');window.location='../pages/blog/daftar-blog';</script>"; } }else { echo "<script>alert('Ekstensi gambar yang boleh hanya jpg atau png.');window.location='../pages/blog/cms-blog';</script>"; } }else { $query = $mysqli->query("INSERT INTO blog(id_kategori, judul, thumbnail, konten_blog, created_at) VALUES ('".$kategori."', '".$judul."', '".$nama_gambar_baru."', '".$editorContent."', '".$date."')") or die (mysqli_error($mysqli)); $result = mysqli_query($mysqli, $query); if(!$result){ die ("Query gagal dijalankan: ".mysqli_errno($mysqli). " - ".mysqli_error($mysqli)); } else { //tampil alert dan akan redirect ke halaman index.php //silahkan ganti index.php sesuai halaman yang akan dituju } } // header("location:../pages/blog/daftar-blog"); if($insert){ $statusMsg = "The editor contect has been inserted"; echo $statusMsg; }else { $statusMsg = "Error"; echo $statusMsg; } ?>
true
c313e3a249773693b01569f76324477c7b557274
PHP
aolaniran21/weekly_report
/weekly_rep/scripts/remark.php
UTF-8
6,522
2.53125
3
[]
no_license
<?php include('connect.php'); if (isset($_GET['id'])) { $id = $_GET['id']; $query = "SELECT * FROM week_report WHERE id ='$id'"; $result = mysqli_query($conn, $query); $row = mysqli_fetch_array($result); } if (isset($_POST['submit'])) { $id = $_POST['id']; $name = $_POST['fullname']; $date = $_POST['date']; $username = $_POST['username']; $department = $_POST['department']; $position = $_POST['position']; $month = $_POST['month']; $week = $_POST['week']; $activity = $_POST['activity']; $addinfo = $_POST['addinfo']; $status = $_POST['status']; $score = $_POST['score']; $remark = $_POST['remark']; $update_query = mysqli_query($conn, "UPDATE week_report SET name ='$name', username ='$username', department ='$department', position ='$position', month ='$month', week ='$week', activity ='$activity', additional_info ='$addinfo', status ='$status', score ='$score', remark ='$remark' WHERE id ='$id'"); if (!$update_query) { echo 'error description' . mysqli_error($conn); } else { header("location: ../scripts/retrieve.php?username=$username&date=$date&id=$id"); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Automated weekly activities report</title> <link rel="stylesheet" href="../css/bootstrap.min.css"> <link rel='stylesheet' href='../css/style.css'> </head> <body style="background-color: black;"> <div class="container h-100"> <div class="row h-100 justify-content-center align-items-center" style="padding-top: 40px"> <div class="col-md-4"> <h1 style="padding-bottom: 30px; color: #17a2b8; text-align: center;">Edit Report Sheet</h1> <form action=" remark.php" method="post"> <div class="form-group"> <input class="form-control" type="text" name="username" value="<?php echo $row['username']; ?>" readonly> </div> <div class="form-group"> <input class="form-control" type="date" name="date" value="<?php echo $row['date']; ?>" readonly> </div> <div class="form-group"> <input class="form-control" type="hidden" name="id" value="<?php echo $id; ?>" readonly> </div> <div class="form-group"> <label for="fullname">Full Name</label> <input type="text" class="form-control" id="fullname" name="fullname" value="<?php echo $row['name']; ?>" readonly> <small id="emailHelp" class="form-text text-muted">Surname should be in capital letter.</small> </div> <div class="form-group"> <label for="department">Department</label> <select class="form-control" id="department" name="department" readonly> <option value="<?php echo $row['department']; ?>"><?php echo $row['department']; ?></option> </select> </div> <div class="form-group"> <label for="position">Position</label> <input type="text" class="form-control" id="position" name="position" value="<?php echo $row['position']; ?>" readonly> </div> <div class="form-group"> <label for="month">Month</label> <select class="form-control" id="month" name="month" readonly> <option value="<?php echo $row['month']; ?>"><?php echo $row['month']; ?></option> </select> </div> <div class="form-group"> <label for="week">Week</label> <select class="form-control" id="week" name="week" readonly> <option value="<?php echo $row['week']; ?>"><?php echo $row['week']; ?></option> </select> </div> <div class="form-group"> <label for="department">Activity</label> <textarea class="form-control" id="activity" rows="3" name="activity" readonly><?php echo $row['activity']; ?></textarea> </div> <div class="form-group"> <label for="department">Additional Information</label> <textarea class="form-control" id="addinfo" rows="3" name="addinfo" readonly><?php echo $row['additional_info']; ?></textarea> </div> <div class="form-group"> <label for="status">Status</label> <select class="form-control" id="status" name="status" readonly> <option value="<?php echo $row['status']; ?>"><?php echo $row['status']; ?></option> </select> </div> <div class="form-group"> <label for="score">Score</label> <select class="form-control" id="score" name="score"> <option value="<?php echo $row['score']; ?>"><?php echo $row['score']; ?></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> <div class="form-group"> <label for="remark">Remark</label> <textarea class="form-control" id="remark" rows="3" name="remark"><?php echo $row['remark']; ?></textarea> </div> <div class="text-center"> <button type="submit" name="submit" class="btn btn-primary">Update</button> </div> </form> </div> </div> </div> <script src="../js/jquery.min.js"></script> <script src="../js/bootstrap.min.js"></script> </body> </html>
true
ae5606409fd125da3383032a9944a0e5eaecc398
PHP
monoulou/meslunettes
/src/MA/MainBundle/Service/FileUploader.php
UTF-8
2,687
2.859375
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php namespace MA\MainBundle\Service; use MA\MainBundle\Entity\Annonce; use MA\UserBundle\Entity\User; use Symfony\Component\HttpFoundation\File\File; use Symfony\Component\Form\FormInterface; use Symfony\Component\HttpFoundation\File\UploadedFile; class FileUploader { private $targetDir; public function __construct($targetDir) { $this->targetDir = $targetDir; } /* * Upload une image. */ public function upload(UploadedFile $file, User $user) { $fileName = $user->getId().'_'.rand(1, 1000).'.'.$file->guessExtension(); $file->move($this->getTargetDir(), $fileName); return $fileName; } /* * Effectue un upload des images si annonce editée. */ public function editFiles(Annonce $annonce, User $user, FormInterface $editForm) { //Récupère l'image soumis au formulaire $imagePrincipale = $editForm->get('imagePrincipale')->getData(); if (!empty($imagePrincipale)) { //Effectue l'upload de l'image. $annonce->setImagePrincipale($this->upload($imagePrincipale, $user)); } $imageBis = $editForm->get('imageBis')->getData(); if (!empty($imageBis)) { $annonce->setImageBis($this->upload($imageBis, $user)); } $imageTer = $editForm->get('imageTer')->getData(); if (!empty($imageTer)) { $annonce->setImageTer($this->upload($imageTer, $user)); } } /* * Supprime les images déjà liées à une Annonce * avant mise à jour. */ public function deleteAllImages(Annonce $annonce) { $imagePrincipale = $annonce->getImagePrincipale(); if (!empty($imagePrincipale)) { $this->deleteOneImage($imagePrincipale); } $imageBis = $annonce->getImageBis(); if (!empty($imageBis)) { $this->deleteOneImage($imageBis); } $imageTer = $annonce->getImageTer(); if (!empty($imageTer)) { $this->deleteOneImage($imageTer); } } /* * Supprime l'image passée en paramètre */ public function deleteOneImage($image) { $directory = scandir($this->getTargetDir()); foreach ($directory as $index => $file) { if ($file != '.' && $file !='..') { if ($file == $image) { unlink($this->getTargetDir().'/'.$file); } } } } public function getTargetDir() { return $this->targetDir; } }
true
5e93835ea8f514ebbfb96bde32ec97b96748c201
PHP
peterlembke/laravel_keyvalue
/src/Console/Commands/Read.php
UTF-8
2,505
2.65625
3
[]
no_license
<?php /** * Copyright (C) 2020 Peter Lembke, CharZam soft * the program is distributed under the terms of the GNU General Public License * * Test.php is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Test.php 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 Test.php. If not, see <https://www.gnu.org/licenses/>. */ namespace PeterLembke\KeyValue\Console\Commands; use Illuminate\Console\Command; use PeterLembke\KeyValue\Repositories\KeyValueRepositoryInterface; use PeterLembke\KeyValue\Helper\Base; /** * Class Read * @package PeterLembke\KeyValue\Console\Commands * Read from the key value table * Example: dox laravel keyvalue:read config background/color */ class Read extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'keyvalue:read {resource_name} {key}'; /** * The console command description. * * @var string */ protected $description = 'Read a key'; /** @var KeyValueRepositoryInterface */ protected $keyValueRepository; /** @var Base */ protected $base; /** * Read constructor. * @param KeyValueRepositoryInterface $keyValueRepository */ public function __construct( KeyValueRepositoryInterface $keyValueRepository, Base $base ) { $this->keyValueRepository = $keyValueRepository; $this->base = $base; parent::__construct(); // Classes that extend another class should call the parent constructor. } /** * Execute the console command. * dox laravel keyvalue:read config background/color */ public function handle(): void { $resourceName = $this->argument('resource_name'); $key = $this->argument('key'); $response = $this->keyValueRepository->read($resourceName, $key); if ($response['answer'] === false) { echo $response['message']; return; } echo $this->base->_JsonEncode($response['value_array']); } }
true
c03314cb25e4309942ab049e0e6fc838bd4c8598
PHP
junaidbhura/gumponents
/inc/rest-api/relationship/class-taxonomies-controller.php
UTF-8
3,564
2.640625
3
[ "MIT" ]
permissive
<?php /** * Posts Rest API Controller. * * @package gumponents */ namespace JB\Gumponents\RestApi\Relationship; use WP_REST_Request; use WP_REST_Response; use WP_Query; /** * Class Rest. */ class TaxonomiesController extends Controller { /** * Register the routes for the objects of the controller. */ public function register_routes() { // Initialize route. register_rest_route( $this->namespace, '/taxonomies/initialize', array( 'methods' => 'POST', 'callback' => array( $this, 'get_initial_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array( 'items' => array( 'required' => true, 'type' => 'array', 'description' => __( 'Items', 'gumponents' ), 'items' => array( 'type' => 'integer', 'sanitize_callback' => 'sanitize_text_field', ), 'default' => [], ), ), ) ); // Query route. register_rest_route( $this->namespace, '/taxonomies/query', array( 'methods' => 'POST', 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'get_items_permissions_check' ), 'args' => array( 'search' => array( 'required' => true, 'type' => 'string', 'description' => __( 'Search Term', 'gumponents' ), 'sanitize_callback' => 'sanitize_text_field', 'default' => '', ), 'taxonomies' => array( 'required' => false, 'type' => 'array', 'description' => __( 'Taxonomies', 'gumponents' ), 'default' => [], ), 'filter' => array( 'required' => false, 'type' => 'string', 'description' => __( 'Custom Filter', 'gumponents' ), 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); } /** * Initialize taxonomy items. * * @param array $params API params. * @return WP_REST_Response */ public function get_initial_items( $params ) { $results = get_terms( array( 'include' => $params['items'], 'orderby' => 'include', 'hide_empty' => false, ) ); if ( empty( $results ) || is_wp_error( $results ) ) { return rest_ensure_response( [] ); } $result_terms = []; foreach ( $results as $result ) { $result_terms[] = array( 'id' => $result->term_id, 'value' => $result, 'label' => $result->name, ); } return rest_ensure_response( $result_terms ); } /** * API: Get items query. * * @param WP_REST_Request $request API Request. * @return WP_REST_Response */ public function get_items( $request ) { $params = $request->get_params(); $filter = ! empty( $params['filter'] ) ? '_' . $params['filter'] : ''; $args = apply_filters( 'gumponents_taxonomies_relationship_query' . $filter, array( 'taxonomy' => $params['taxonomies'], 'name__like' => $params['search'], 'hide_empty' => false, ) ); $results = get_terms( $args ); if ( empty( $results ) || is_wp_error( $results ) ) { return rest_ensure_response( [] ); } $result_terms = []; foreach ( $results as $result ) { $result_terms[] = array( 'id' => $result->term_id, 'value' => $result, 'label' => $result->name, ); } return rest_ensure_response( apply_filters( 'gumponents_relationship_results' . $filter, $result_terms, $params ) ); } }
true
f80982b1fe2702ead500fb340b801b5231c96ef1
PHP
ESUCC/Maximd
/application/forms/LanguageSelector.php
UTF-8
2,091
2.796875
3
[]
no_license
<?php /** * * @author sbennett * */ class Form_LanguageSelector extends Zend_Form { /** * * @var Zend_Translate */ protected $translate; /** * * @var string locale */ protected $locale; /** * * @param Zend_Translate $translate */ public function __construct(Zend_Translate $translate, $locale) { $this->setTranslate($translate); $this->setLocale($locale); parent::__construct(); } /** * (non-PHPdoc) * @see App_Form::init() */ public function init() { $this->languages = new Zend_Form_Element_Select('languages', array('multiOptions' => $this->getLanguageOptions()) ); $this->languages->setDecorators(array( 'ViewHelper', array('Description', array('tag' => 'span')), array('Label', array('tag' => 'span')), array (array ('data' => 'HtmlTag' ), array ('tag' => 'span')) )); $this->languages->setValue($this->locale); } /** * * @param Zend_Translate $translate * @return mixed $options */ protected function getLanguageOptions() { $options = array(); foreach ($this->translate->getList() AS $l) $options[$l] = $this->getLanguageFromLocale($l); return $options; } /** * Setter for translation * * @param Zend_Translate $translate */ protected function setTranslate(Zend_Translate $translate) { $this->translate = $translate; } /** * Settor for locale * * @param string $locale */ protected function setLocale($locale) { $this->locale = $locale; } /** * * @param string $locale * @return string $language */ protected function getLanguageFromLocale($locale) { $languages = array( 'en' => 'English', 'es' => 'Spanish', ); return $languages[$locale]; } }
true
baefdd47decf7a54a07069a2a0d0f2710a7961c5
PHP
bdougherty/sonic
/lib/Sonic/Collection.php
UTF-8
2,345
3.140625
3
[ "Apache-2.0" ]
permissive
<?php namespace Sonic; use \ArrayObject; /** * Collection * * @category Sonic * @package Collection * @author Craig Campbell */ class Collection extends ArrayObject { /** * @var array */ protected $_ids; /** * @var string */ protected $_object_name; /** * @var Pager */ protected $_pager; /** * @var bool */ protected $_filled = false; /** * constructor * * @param string $object_name * @param array $ids * @param Pager $pager * @return void */ public function __construct($object_name = null, $ids = array(), Pager $pager = null) { $this->_object_name = $object_name; $this->_ids = $ids; $this->_pager = $pager; if ($pager instanceof Pager) { $this->_pager->setTotal(count($ids)); } unset($ids); } /** * gets the count of this collection * * @return int */ public function count() { // if there is a parent count that means this collection is being used as a normal ArrayObject if (parent::count() && empty($this->_ids)) { return parent::count(); } return count($this->_ids); } /** * overrides parent getIterator method * used to lazy load collection and not actually retrieve it until you go to loop over it * * @return Iterator */ public function getIterator() { if (parent::count()) { return parent::getIterator(); } $this->_fillCollection(); return parent::getIterator(); } /** * fills the collection if it hasn't already been fille * * @return void */ protected function _fillCollection() { if ($this->_filled) { return; } $ids = $this->_ids; if ($this->_pager instanceof Pager) { $ids = array_slice($ids, $this->_pager->getOffset(), $this->_pager->getPageSize()); } $object_name = $this->_object_name; $objects = $object_name::get($ids); $this->exchangeArray($objects); $this->_filled = true; } /** * gets the pager object * * @return Pager */ public function getPager() { return $this->_pager; } }
true
de2767eb9577261661dbbd37ea315b1b6e9d3ca0
PHP
IvayloIV/PHP-Web-Basics
/PHP-Web-Basics-May-2019/Exercise-Introduction_to_PHP/13.Lazy_Sundays.php
UTF-8
279
3.15625
3
[ "MIT" ]
permissive
<?php $month = date('m', strtotime(readline())); $totalDays = cal_days_in_month(CAL_GREGORIAN, $month, 2019); for ($i = 1; $i <= $totalDays; $i++) { if (date('N', strtotime(2018 . '-' . $month . '-' . $i)) == 7) { echo $i . "rd " . $month . ", " . "2018\n"; } }
true
7b862a44d8a096d3a4c5086a132d79ba3eb2ee0b
PHP
znframework/fullpack-edition
/Internal/package-console/UndoUpgrade.php
UTF-8
581
2.65625
3
[ "MIT" ]
permissive
<?php namespace ZN\Console; /** * ZN PHP Web Framework * * "Simplicity is the ultimate sophistication." ~ Da Vinci * * @package ZN * @license MIT [http://opensource.org/licenses/MIT] * @author Ozan UYKUN [ozan@znframework.com] */ use ZN\ZN; /** * @command undo-upgrade * @description undo-upgrade [last|version-number] */ class UndoUpgrade { protected static $lang; /** * Magic constructor * * @param void * * @return void */ public function __construct($command) { new Result(ZN::undoUpgrade($command ?? 'last')); } }
true
95f0df1160886ab629305cbe843b4cf2a08d5166
PHP
1314jiajia/redis
/class/Model.class.php
UTF-8
1,048
3.078125
3
[]
no_license
<?php /* @return 获取所有数据 @return 链接redis @return array() */ class Model { public $pdo; public $redis; public $key; public function __construct() { $this->redis = new Redis(); // 连接redis $this->redis->connect("localhost",6379); } public function get($sql) { // 判断 $this->key = md5($sql); // 获取缓存服务器的数据 ,json_decode()字符串转换数组,给true(转成数组)要不然他默认转的是对象, $data=json_decode($this->redis->get($this->key),true); // 判断 if(empty($data)){ $this->pdo = new PDO("mysql:host=localhost;port=3307;charset=utf8;dbname=movie","root",""); //执行sql语句 $list = $this->pdo->query($sql); //获取结果集 $data = $list->fetchAll(PDO::FETCH_ASSOC); //给redis一份 ,数组转字符串 $this->redis->set($this->key,json_encode($data)); } return $data; } }
true
bfbd3e1a44e4466511819b6b07f7e58b76946e61
PHP
Contedantignano/php6
/moviesite/header.php
UTF-8
994
2.84375
3
[]
no_license
<div style="text-align: center"> <?php date_default_timezone_set('America/New_York'); if (date ('G') >= 5 && date ('G') <= 11) { echo '<p>Welcome to my movie site !<br/></p><h2>Good Moring!</h2>'; } else if (date ('G') >= 12 && date ('G') <= 18) { echo '<h2>Good Afthernoon!</h2>'; } else if (date ('G') >= 19 && date ('G') <= 4) { echo '<h2>Good Night!</h2>'; } echo 'Today is '; echo date('F d'); echo ', '; ?> <?php function display_times($num) { echo '<p>You have viewed this page ' . $num . ' time(s) <p/>'; } //recupera il valore del cookie $num_times = 1; if (isset($_COOKIE['num_times'])) { $num_times = $_COOKIE['num_time'] + 1; setcookie('num_times', $num_times, time(), + 60); } ?> <br/> <?php display_times($num_times); ?> </p> </div>
true
b1d072aa8be6adce3ec4b832b02d777c08067bee
PHP
paulomendesdigital/lm-cursos-de-transito
/app/Lib/IntegracaoDetrans/IntegracaoDetransService.php
UTF-8
37,519
2.59375
3
[]
no_license
<?php /** * Integracao Service * Faz a interface entre o sistema e as integrações com os órgãos de trânsito * * @author Douglas Gomes de Souza <douglas@dsconsultoria.com.br> * @copyright LM Cursos de Transito */ App::uses('IntegracaoRetorno', 'IntegracaoDetrans'); App::uses('IntegracaoParams', 'IntegracaoDetrans'); App::uses('IntegracaoException', 'IntegracaoDetrans'); App::uses('Course', 'Model'); App::uses('CourseType', 'Model'); App::uses('OrderCourse', 'Model'); App::uses('StatusDetran', 'Model'); App::uses('Payment', 'Model'); App::uses('UserCertificate', 'Model'); App::uses('UserModuleLog', 'Model'); App::uses('UserQuestion', 'Model'); App::uses('UserModuleSummary', 'Model'); class IntegracaoDetransService { const HORA_INICIO_AULAS = 6; const HORA_FIM_AULAS = 22; /** * @var IntegracaoRetorno */ private $retorno = null; /** * Origem da Transmissão * @var string */ private $origem; /** * Valida junto ao Sistema do Órgão de Trânsito se o condutor é publico alvo do referido curso. * * @param int $courseId Id do Curso * @param int|null $stateId Id do Estado * @param int|null $cityId Id da Cidade * @param array $parametros Parâmetros para serem validados pelo Órgão de Trânsito * @return boolean * @throws Exception|IntegracaoException */ public function validar($courseId, $stateId = null, $cityId = null, array $parametros = null) { $arrCurso = $this->getDadosCurso($courseId); $objIntegracao = $this->getIntegracao($arrCurso['Course'], $stateId, $cityId); if ($objIntegracao) { try { return $objIntegracao->validar(IntegracaoParams::createFromArray(array_merge($arrCurso, $parametros))); } catch (Exception $exception) { throw $exception; } finally { $this->retorno = $objIntegracao->getRetorno(); } } else { $this->retorno = new IntegracaoRetorno('OK', 'Curso não integrado'); return true; } } /** * Consulta junto ao Sistema do Órgão de Trânsito se o condutor é publico alvo do referido curso. * * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @return IntegracaoRetorno * @throws Exception */ public function consultar($orderId, $courseId) { $arrMatricula = $this->getDadosMatricula($orderId, $courseId); $arrOrderCourse = $arrMatricula['OrderCourse']; $objIntegracao = $this->getIntegracao($arrMatricula['Course'], $arrOrderCourse['state_id'], $arrOrderCourse['citie_id']); if ($objIntegracao) { return $objIntegracao->consultar(IntegracaoParams::createFromArray($arrMatricula)); } else { return new IntegracaoRetorno('OK', 'Curso não integrado'); } } /** * Valida, Matricula e Conclui junto ao Sistema do Órgão de Trânsito de acordo com a situação do aluno * * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @throws Exception|IntegracaoException */ public function reprocessar($orderId, $courseId) { $this->matricular($orderId, $courseId); $this->concluir($orderId, $courseId); } /** * Matricula o Condutor no Órgão de Trânsito * * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @throws Exception|IntegracaoException * @return boolean */ public function matricular($orderId, $courseId) { $arrMatricula = $this->getDadosMatricula($orderId, $courseId); $arrOrderCourse = $arrMatricula['OrderCourse']; $objIntegracao = $this->getIntegracao($arrMatricula['Course'], $arrOrderCourse['state_id'], $arrOrderCourse['citie_id']); if ($objIntegracao) { try { //VALIDA. SE AINDA NÃO FOI VALIDADO if ($arrOrderCourse['status_detran_id'] == StatusDetran::NAO_VALIDADO || $arrOrderCourse['status_detran_id'] == StatusDetran::ERRO) { $bolValido = $objIntegracao->validar(IntegracaoParams::createFromArray($arrMatricula)); $arrOrderCourse['status_detran_id'] = $bolValido ? StatusDetran::VALIDADO : StatusDetran::ERRO; $arrOrderCourse['codigo_retorno_detran'] = $objIntegracao->getRetorno()->getCodigo(); $arrOrderCourse['mensagem_retorno_detran'] = $objIntegracao->getRetorno()->getMensagem(); $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['retry_count_detran'] = $bolValido ? 0 : ($arrOrderCourse['retry_count_detran'] + 1); $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); } //EFETUA A MATRICULA se foi validado anterioremente e o pagamento for Aprovado ou Disponivel if ($arrOrderCourse['status_detran_id'] == StatusDetran::VALIDADO && ($arrMatricula['Order']['order_type_id'] == Payment::APROVADO || $arrMatricula['Order']['order_type_id'] == Payment::DISPONIVEL)) { if ($objIntegracao->matricular(IntegracaoParams::createFromArray($arrMatricula))) { $arrOrderCourse['status_detran_id'] = StatusDetran::MATRICULADO; $arrOrderCourse['codigo_retorno_detran'] = $objIntegracao->getRetorno()->getCodigo(); $arrOrderCourse['mensagem_retorno_detran'] = $objIntegracao->getRetorno()->getMensagem(); $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['data_matricula_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['retry_count_detran'] = 0; $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); return true; } else { $arrOrderCourse['codigo_retorno_detran'] = $objIntegracao->getRetorno()->getCodigo(); $arrOrderCourse['mensagem_retorno_detran'] = $objIntegracao->getRetorno()->getMensagem(); $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['retry_count_detran']++; $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); } } return false; } catch (Exception $ex) { $this->retorno = $objIntegracao->getRetorno(); $arrOrderCourse['status_detran_id'] = StatusDetran::ERRO; $arrOrderCourse['codigo_retorno_detran'] = $objIntegracao->getRetorno()->getCodigo(); $arrOrderCourse['mensagem_retorno_detran'] = $objIntegracao->getRetorno()->getMensagem(); $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['retry_count_detran']++; $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); throw $ex; } } $this->retorno = new IntegracaoRetorno('OK', 'Curso não é integrado, aluno já foi matriculado ou não consultado.'); return true; } /** * Comunica a Conclusão do Curso no Órgão de Trânsito * * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @throws Exception|IntegracaoException * @return boolean */ public function concluir($orderId, $courseId) { $arrMatricula = $this->getDadosMatricula($orderId, $courseId); $arrOrderCourse = &$arrMatricula['OrderCourse']; $objIntegracao = $this->getIntegracao($arrMatricula['Course'], $arrOrderCourse['state_id'], $arrOrderCourse['citie_id']); if ($objIntegracao) { //deve estar Matriculado ou Aguardando Conclusão para processar if ($arrOrderCourse['status_detran_id'] == StatusDetran::MATRICULADO || $arrOrderCourse['status_detran_id'] == StatusDetran::AGUARDANDO_CONCLUSAO) { $bolSave = false; try { $arrCertificado = $this->getCertificado($orderId, $courseId); //se já tem o certificado, altera o status para Aguardando Conclusão if ($arrCertificado && $arrOrderCourse['status_detran_id'] == StatusDetran::MATRICULADO) { $arrOrderCourse['status_detran_id'] = StatusDetran::AGUARDANDO_CONCLUSAO; $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $bolSave = true; } //só faz a comunicação da conclusão enviou todos os créditos de aula e tem certificado if ($this->creditar($orderId, $courseId, $arrMatricula) && $arrCertificado) { $bolSave = true; if ($objIntegracao->concluir(IntegracaoParams::createFromArray(array_merge($arrMatricula, $arrCertificado)))) { $arrOrderCourse['status_detran_id'] = StatusDetran::CONCLUIDO; $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); $arrOrderCourse['retry_count_detran'] = 0; return true; } else { $arrOrderCourse['retry_count_detran']++; //tentará novamente pelo cron return false; } } } catch (Exception $ex) { $arrOrderCourse['retry_count_detran']++; $bolSave = true; throw $ex; } finally { $this->retorno = $objIntegracao->getRetorno(); if ($bolSave) { if ($this->retorno) { $arrOrderCourse['codigo_retorno_detran'] = $this->retorno->getCodigo(); $arrOrderCourse['mensagem_retorno_detran'] = $this->retorno->getMensagem(); $arrOrderCourse['data_status_detran'] = date('Y-m-d H:i:s'); } $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); } } } } $this->retorno = new IntegracaoRetorno('OK', 'Curso não é integrado'); return true; } /** * Envia o Crédito de Aula para o Órgão de Trânsito * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @param array $arrMatricula Dados da Matricula * @return bool * @throws Exception|IntegracaoException */ public function creditar($orderId, $courseId, $arrMatricula = []) { if (empty($arrMatricula)) { $arrMatricula = $this->getDadosMatricula($orderId, $courseId); } $arrOrderCourse = $arrMatricula['OrderCourse']; $objIntegracao = $this->getIntegracao($arrMatricula['Course'], $arrOrderCourse['state_id'], $arrOrderCourse['citie_id']); if ($objIntegracao) { //só faz a comunicação de crédito de aula se estiver com status de Matriculado ou Aguardando Conclusão if ($arrOrderCourse['status_detran_id'] == StatusDetran::MATRICULADO || $arrOrderCourse['status_detran_id'] == StatusDetran::AGUARDANDO_CONCLUSAO) { //CURSOS SERGIPE TEM CREDITO DE HORAS if ($arrOrderCourse['state_id'] == State::SERGIPE) { $bolSave = false; try { $arrCreditoHoras = $this->getDadosCreditoHoras($orderId); $bolRetry = false; $intCountModules = count($arrCreditoHoras); $intCountSentModules = 0; foreach ($arrCreditoHoras as $arrHorasModulo) { $arrModulo = $arrHorasModulo['Module']; //Se o total de horas executadas for maior ou igual a carga horária do módulo if ($arrHorasModulo['total'] > 0 && $arrHorasModulo['total'] >= $arrModulo['value_time'] * 60) { foreach ($arrHorasModulo['dates'] as $strData => $arrDisciplines) { if ($strData <= date('Y-m-d')) { //não processa datas futuras foreach ($arrDisciplines as $arrDiscipline) { if ($arrDiscipline['count_sent'] < $arrDiscipline['count_total']) { $arrParams = IntegracaoParams::createFromArray(array_merge($arrMatricula, $arrModulo, $arrDiscipline)); if ($objIntegracao->creditar($arrParams)) { if (isset($arrDiscipline['is_exam'])) { $objUserQuestion = new UserQuestion(); $objUserQuestion->id = $arrDiscipline['id']; if (!$objUserQuestion->saveField('sent_to_detran', 1)) { throw new Exception('Erro ao salvar flag de envio paro detran'); } } else { $objModuleLog = new UserModuleLog(); if (!$objModuleLog->updateAll(['UserModuleLog.sent_to_detran' => 1], ['UserModuleLog.id' => $arrDiscipline['logs']])) { throw new Exception('Erro ao salvar flag de envio paro detran'); } } } else { $bolRetry = true; break 3; } } } } else { $bolRetry = true; break 2; } } $intCountSentModules++; //modulo concluído e enviado } else { break; } } //se todos os módulos foram enviados, altera o status if ($intCountModules > 0 && $intCountSentModules == $intCountModules) { $arrOrderCourse['retry_count_detran'] = 0; $bolSave = true; return true; } else { if ($bolRetry) { $arrOrderCourse['retry_count_detran']++; $bolSave = true; } elseif ($arrOrderCourse['retry_count_detran'] != 0) { $arrOrderCourse['retry_count_detran'] = 0; $bolSave = true; } } return false; } catch (Exception $ex) { $arrOrderCourse['retry_count_detran']++; $bolSave = true; throw $ex; } finally { $this->retorno = $objIntegracao->getRetorno(); if ($bolSave) { $arrOrderCourse['last_exec_detran'] = date('Y-m-d H:i:s'); $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->save(['OrderCourse' => $arrOrderCourse]); } } //CURSOS RJ NÃO TEM CRÉDITOS DE HORAS } else { return true; } } return false; } $this->retorno = new IntegracaoRetorno('OK', 'Curso não é integrado'); return true; } /** * Retorno da Última Chamada * @return IntegracaoRetorno */ public function getRetorno() { return $this->retorno; } /** * Integração Factory * Retorna a classe concreta de integração de acordo com o tipo de curso, estado e cidade * * @param array $arrCourse * @param null $stateId * @param null $cityId * @return IntegracaoBase|null * @throws Exception|IntegracaoException */ public function getIntegracao(array $arrCourse, $stateId = null, $cityId = null) { try { if (!array_key_exists('course_type_id', $arrCourse)) { throw new Exception('Não foi possível identificar o tipo de curso.'); } if (!array_key_exists('detran_validation', $arrCourse)) { throw new Exception('Não foi possível identificar a validação do curso.'); } if (!$arrCourse['detran_validation']) { return null; //CURSO NÃO TEM INTEGRAÇÃO } $courseTypeId = $arrCourse['course_type_id']; //CURSOS DE RECICLAGEM RJ if ($courseTypeId == CourseType::RECICLAGEM && $stateId == State::RIO_DE_JANEIRO) { App::uses('IntegracaoDetranRj', 'IntegracaoDetrans'); return new IntegracaoDetranRj($this->origem); //CURSOS DE RECICLAGEM E ESPECIALIZADOS SERGIPE } elseif (($courseTypeId == CourseType::RECICLAGEM || $courseTypeId == CourseType::ESPECIALIZADOS) && $stateId == State::SERGIPE) { App::uses('IntegracaoDetranSe', 'IntegracaoDetrans'); return new IntegracaoDetranSe($this->origem); //CURSOS DE RECICLAGEM ALAGOAS } elseif ($courseTypeId == CourseType::RECICLAGEM && $stateId == State::ALAGOAS) { App::uses('IntegracaoDetranAl', 'IntegracaoDetrans'); return new IntegracaoDetranAl($this->origem); //CURSOS DE RECICLAGEM PARANÁ } elseif ($courseTypeId == CourseType::RECICLAGEM && $stateId == State::PARANA) { App::uses('IntegracaoDetranPr', 'IntegracaoDetrans'); return new IntegracaoDetranPr($this->origem); //CURSOS DE RECICLAGEM OU ESPECIALIZADOS DE OUTROS ESTADOS } elseif ($courseTypeId == CourseType::RECICLAGEM || $courseTypeId == CourseType::ESPECIALIZADOS) { throw new IntegracaoException('Este curso ainda não está disponível na sua região.'); } else { return null; //Se o curso não tem integração, não deve retornar nada, nem exception } } catch (Exception $ex) { $this->retorno = new IntegracaoRetorno('Erro', $ex->getMessage()); throw $ex; } } /** * Retorna os Dados do Curso para a integração * @param int $courseId Id do Curso * @return array */ private function getDadosCurso($courseId) { $objCourseModel = new Course(); $objCourseModel->Behaviors->load('Containable'); return $objCourseModel->find('first', [ 'recursive' => false, 'conditions' => ['Course.id' => $courseId], 'fields' => ['id', 'course_type_id', 'detran_validation', 'course_code_id'], 'contain' => [ 'CourseCode' => [ 'fields' => ['id', 'code as course_code', 'name'] ] ] ]); } /** * Retorna os Dados da Matrícula para a integração * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @return array * @throws Exception */ private function getDadosMatricula($orderId, $courseId) { $objOrderCourseModel = new OrderCourse(); $objOrderCourseModel->Behaviors->load('Containable'); $result = $objOrderCourseModel->find('first', [ 'conditions' => ['OrderCourse.order_id' => $orderId, 'OrderCourse.course_id' => $courseId], 'fields' => ['id', 'order_id', 'course_id', 'citie_id', 'state_id', 'status_detran_id', 'codigo_retorno_detran', 'mensagem_retorno_detran', 'data_matricula_detran', 'retry_count_detran', 'renach', 'cnh', 'cnh_category'], 'contain' => [ 'Course' => [ 'fields' => ['id', 'course_type_id', 'detran_validation', 'max_time', 'course_code_id'], 'CourseCode' => [ 'fields' => ['id', 'code as course_code', 'name'] ] ], 'Order' => [ 'fields' => ['id', 'order_type_id', 'user_id'], 'User' => [ 'fields' => ['id', 'cpf'], 'School' => [ 'fields' => ['id', 'cod_cfc'] ], 'Student' => [ 'fields' => ['id', 'birth'] ] ] ] ] ]); if (empty($result)) { throw new Exception('Não foi possível encontrar os dados referente a matrícula'); } $result['OrderCourse']['order_courses_id'] = $result['OrderCourse']['id']; return $result; } /** * Retorna os Dados do Certificado para a integração * @param int $orderId Id do Pedido * @param int $courseId Id do Curso * @return array */ private function getCertificado($orderId, $courseId) { $objModelUserCertificate = new UserCertificate(); $objModelUserCertificate->Behaviors->load('Containable'); $arrCertificate = $objModelUserCertificate->find('first', [ 'fields' => ['id as num_certificado', 'start as data_inicio', 'finish as data_fim'], 'contain' => [ 'UserCertificateModule' ], 'conditions' => [ 'UserCertificate.order_id' => $orderId, 'UserCertificate.course_id' => $courseId ] ]); if ($arrCertificate) { $arrCertificate['workload'] = $objModelUserCertificate->__getTotalWorkload($arrCertificate['UserCertificateModule']); } return $arrCertificate; } private function getDateGroupTimes($arrGroup, $arrRow) { if (isset($arrGroup['start'])) { $intStart = $arrGroup['start']; $intTime = $arrGroup['total_time'] + $arrRow['time']; } else { $intStart = $arrRow['datetime']; $intTime = $arrRow['time']; } $intFinish = $intStart + $intTime * 60; return [$intTime, $intStart, $intFinish]; } /** * Retorna os Dados para Crédito de Horas com base nos registros de UserModuleLog * @param $orderId * @return array */ public function getDadosCreditoHoras($orderId) { $objSummary = new UserModuleSummary(); $objSummary->Behaviors->load('Containable'); //recupera todos os módulos da grade de estudos e agrupa por módulo e disciplina $arrModules = $objSummary->find('all', [ 'recursive' => false, 'contain' => [ 'Module' => ['fields' => ['id', 'name', 'value_time']], 'ModuleDiscipline' => [ 'fields' => ['id', 'name', 'discipline_code_id', 'value_time', 'module_discipline_slider_count', 'module_discipline_player_count'], 'DisciplineCode' ] ], 'conditions' => ['UserModuleSummary.order_id' => $orderId, 'Module.is_introduction' => 0], ]); $arrResult = []; foreach ($arrModules as $arrRow) { if (isset($arrRow['ModuleDiscipline']['DisciplineCode']['id'])) { $arrGroupModule = &$arrResult[$arrRow['Module']['id']]; $arrGroupModule['Module'] = $arrRow['Module']; $arrGroupModule['total'] = 0; $arrGroupModule['dates'] = []; $arrGroupDiscipline = &$arrGroupModule['disciplines'][$arrRow['ModuleDiscipline']['id']]; $arrGroupDiscipline['ModuleDiscipline'] = $arrRow['ModuleDiscipline']; $arrGroupDiscipline['value_count'] = $arrRow['ModuleDiscipline']['module_discipline_slider_count'] + $arrRow['ModuleDiscipline']['module_discipline_player_count']; $arrGroupDiscipline['logs'] = []; } } if (isset($arrGroupDiscipline)) { unset($arrGroupDiscipline); unset($arrGroupModule); } //recupera o log de estudos $objModuleLog = new UserModuleLog(); $objModuleLog->Behaviors->load('Containable'); $arrLogs = $objModuleLog->find('all', [ 'recursive' => false, 'conditions' => ['UserModuleLog.order_id' => $orderId], 'fields' => ['id', 'module_id', 'module_discipline_id', 'time', 'created', 'sent_to_detran'], 'order' => ['created'] ]); //associa o log a disciplina foreach ($arrLogs as $arrRow) { $intModuleId = $arrRow['UserModuleLog']['module_id']; $intDisciplineId = $arrRow['UserModuleLog']['module_discipline_id']; if (isset($arrResult[$intModuleId]['disciplines'][$intDisciplineId])) { $arrResult[$intModuleId]['disciplines'][$intDisciplineId]['logs'][] = $arrRow['UserModuleLog']; } } //agrupa por carga horária $intLastFinish = null; foreach ($arrResult as $intModuleId => &$arrModule) { $arrDates = &$arrModule['dates']; foreach ($arrModule['disciplines'] as &$arrDiscipline) { if (count($arrDiscipline['logs']) >= $arrDiscipline['value_count']) { //SE COMPLETOU TODOS OS SLIDES $arrFirstLog = $arrDiscipline['logs'][0]; $strDate = substr($arrFirstLog['created'], 0, 10); $intDate = strtotime($strDate); $intMinTime = $intDate + self::HORA_INICIO_AULAS * 3600; $intMaxTime = $intDate + self::HORA_FIM_AULAS * 3600; $intNextDate = $intDate + 86400; $intNextTime = $intNextDate + self::HORA_INICIO_AULAS * 3600; $arrRow['datetime'] = strtotime(substr($arrFirstLog['created'], 0, 16)); $arrRow['time'] = $arrDiscipline['ModuleDiscipline']['value_time'] * 60; //se o registro for antes do horário inicial, altera para o horário inicial if ($arrRow['datetime'] < $intMinTime) { $arrRow['datetime'] = $intMinTime; } if ($arrRow['datetime'] <= $intLastFinish) { $arrRow['datetime'] = $intLastFinish + 60; } $strGroupKey = $strDate . '-' . $arrDiscipline['ModuleDiscipline']['DisciplineCode']['id']; $arrGroup = &$arrDates[$strDate][$strGroupKey]; list($intTime, $intStart, $intFinish) = $this->getDateGroupTimes($arrGroup, $arrRow); $intLimiter = 0; while ($intFinish > $intMaxTime && $intLimiter < 7) { if (empty($arrGroup)) { unset($arrDates[$strDate][$strGroupKey]); } $arrGroup = &$arrDates[date('Y-m-d', $intNextDate)][$strGroupKey]; $arrRow['datetime'] = $intNextTime; if ($arrRow['datetime'] <= $intLastFinish) { $arrRow['datetime'] = $intLastFinish + 60; } list($intTime, $intStart, $intFinish) = $this->getDateGroupTimes($arrGroup, $arrRow); $intDate = $intNextDate; $strDate = date('Y-m-d', $intDate); $intNextDate = $intDate + 86400; $intNextTime = $intNextDate + self::HORA_INICIO_AULAS * 3600; $intMaxTime = $intDate + self::HORA_FIM_AULAS * 3600; $intLimiter++; } $intLastFinish = $intFinish; $arrGroup['start'] = $intStart; $arrGroup['finish'] = $intFinish; $arrGroup['total_time'] = $intTime; $arrGroup['discipline_code'] = $arrDiscipline['ModuleDiscipline']['DisciplineCode']['code']; $arrGroup['discipline_name'] = $arrDiscipline['ModuleDiscipline']['DisciplineCode']['name']; $arrGroup['inicio_aula'] = $intStart; $arrGroup['fim_aula'] = $intFinish; $arrGroup['time'] = $intTime; foreach ($arrDiscipline['logs'] as $arrLog) { $intOriginalTimeCreated = strtotime($arrLog['created']); $arrGroup['real_inicio_aula'] = isset($arrGroup['real_inicio_aula']) ? min($arrGroup['real_inicio_aula'], $intOriginalTimeCreated) : $intOriginalTimeCreated; $arrGroup['real_fim_aula'] = isset($arrGroup['real_fim_aula']) ? max($arrGroup['real_fim_aula'], $intOriginalTimeCreated) : $intOriginalTimeCreated; $arrGroup['logs'][$arrLog['id']] = ['id' => $arrLog['id'], 'sent_to_detran' => $arrLog['sent_to_detran']]; } if (empty($arrDates[$strDate])) { //limpa bloco vazio unset($arrDates[$strDate]); } unset($arrGroup); } } unset($arrDiscipline); unset($arrModule['disciplines']); //insere a prova por último if (!empty($arrDates)) { $arrProva = $this->getQtdAcertosProva($orderId, $intModuleId); if ($arrProva) { end($arrDates); $strLastDate = key($arrDates); $intDate = strtotime($strLastDate); $intMaxTime = $intDate + self::HORA_FIM_AULAS * 3600; $intNextDate = $intDate + 86400; $intNextTime = $intNextDate + self::HORA_INICIO_AULAS * 3600; $arrLastDiscipline = end($arrDates[$strLastDate]); $intStart = $arrLastDiscipline['finish'] + 60; $intFinish = $intStart + $arrProva['time'] * 60; if ($intFinish > $intMaxTime) { $strLastDate = date('Y-m-d', $intNextDate); $intStart = $intNextTime; } $arrProva['inicio_aula'] = $intStart; $arrProva['fim_aula'] = $intFinish; $arrDates[$strLastDate][] = $arrProva; } } unset($arrDates); } unset($arrModule); //formata a saida foreach ($arrResult as &$arrModule) { $arrModule['total'] = 0; foreach ($arrModule['dates'] as &$arrDisciplines) { foreach ($arrDisciplines as &$arrDiscipline) { $arrModule['total'] += $arrDiscipline['time']; //date time foreach (['inicio_aula', 'fim_aula', 'real_inicio_aula', 'real_fim_aula'] as $key) { if (isset($arrDiscipline[$key])) { $arrDiscipline[$key] = date('Y-m-d H:i:s', $arrDiscipline[$key]); } } //contagem transmitidos $intCountSent = 0; if (isset($arrDiscipline['logs'])) { foreach ($arrDiscipline['logs'] as &$arrLog) { if ($arrLog['sent_to_detran']) { $intCountSent++; } $arrLog = $arrLog['id']; } $arrDiscipline['count_sent'] = $intCountSent; $arrDiscipline['count_total'] = count($arrDiscipline['logs']); } elseif (array_key_exists('sent_to_detran', $arrDiscipline)) { $arrDiscipline['count_sent'] = $arrDiscipline['sent_to_detran'] ? 1 : 0; $arrDiscipline['count_total'] = 1; } unset($arrDiscipline); } unset($arrDisciplines); } unset($arrModule); } return $arrResult; } /** * Recupera a Quantidade de Acertos na Prova de um módulo * @param $orderId * @param $moduleId * @return mixed */ private function getQtdAcertosProva($orderId, $moduleId) { $objUserQuestion = new UserQuestion(); $arrResult = $objUserQuestion->query("SELECT uq.id, dc.code, dc.name, dc.hours, uq.sent_to_detran, uq.created, COUNT(qu.id) as acertos FROM user_questions uq INNER JOIN user_question_options uqo ON uqo.user_question_id = uq.id INNER JOIN question_alternative_option_users qu ON qu.id = uqo.question_alternative_option_user_id INNER JOIN question_alternatives qa ON qu.question_alternative_id = qa.id INNER JOIN modules m ON qa.module_id = m.id INNER JOIN discipline_codes dc ON dc.id = m.exam_discipline_code_id WHERE uq.order_id = '$orderId' AND qa.module_id = '$moduleId' AND uq.model = 'Module' AND uq.result = 1 AND qu.correct = 1 GROUP BY qa.module_id ORDER BY uq.id DESC LIMIT 1"); if (isset($arrResult[0]['dc'])) { return [ 'id' => $arrResult[0]['uq']['id'], 'discipline_code' => $arrResult[0]['dc']['code'], 'discipline_name' => $arrResult[0]['dc']['name'], 'time' => $arrResult[0]['dc']['hours'] * 60, 'real_inicio_aula' => strtotime($arrResult[0]['uq']['created']), 'real_fim_aula' => strtotime($arrResult[0]['uq']['created']) + $arrResult[0]['dc']['hours'] * 3600, 'acertos' => $arrResult[0][0]['acertos'], 'is_exam' => true, 'sent_to_detran' => $arrResult[0]['uq']['sent_to_detran'] ]; } else { return null; } } /** * @return string */ public function getOrigem() { return $this->origem; } /** * @param string $origem */ public function setOrigem($origem) { $this->origem = $origem; } }
true
81b1eba3405f56c479444dbbf6fc02bcda630495
PHP
rohan-pat/dos-iot
/edge/LEDEdge.php
UTF-8
4,389
2.546875
3
[]
no_license
<?php /* Authors: Parth Rampal, Pushparaj Britto, Harsh Shah, Prashant Mishra, Rohan Patil * Last Modified: 26-Nov-2016 * Purpose: Prepared for COP5615 DOS IOT Project * Description: * * This script defines the IoT Edge with which forms the bridge between the * cloud and the IoT End Devices (Beagle Bone Black) with LED * */ header('Access-Control-Allow-Origin: *'); //Reduce errors error_reporting(~E_WARNING); date_default_timezone_set('America/New_York'); /* Open Log File */ $log = fopen("LED_Edge.log", "a+") or die("Unable to open file!"); fwrite($log, "\n=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n"); fwrite($log,date("Y-F-d H:i:s",time())." > Edge Called.\n"); /* BBB will be sent the LED Code */ /* Get Value of LED Code */ $ledt = $_GET["LED"]; fwrite($log,date("Y-F-d H:i:s",time())." > LED Code: $ledt \n"); if($ledt <0 || $ledt >2) /* If LED value is invalid, reset to 0 */ { $ledt = 0; fwrite($log,date("Y-F-d H:i:s",time())." > LED Code Reset to 0.\n"); } /* Read configuration file */ $conffile = "LEDEdge-BBBLED.json"; fwrite($log,date("Y-F-d H:i:s",time())." > Reading conf file.\n"); $conf = file_get_contents($conffile); $conf2 = file_get_contents($conffile); $confarrayr =json_decode($conf2,true); $ledoff = $confarrayr['parameters'][0]['name']; fwrite($log,date("Y-F-d H:i:s",time())." > ledoff: $ledoff.\n"); $ledred = $confarrayr['parameters'][1]['name']; fwrite($log,date("Y-F-d H:i:s",time())." > ledred: $ledred.\n"); $ledblue = $confarrayr['parameters'][2]['name']; fwrite($log,date("Y-F-d H:i:s",time())." > ledblue: $ledblue.\n"); $BBBip = $confarrayr['ip']; fwrite($log,date("Y-F-d H:i:s",time())." > BBBip: $BBBip.\n"); $BBBport = $confarrayr['port']; fwrite($log,date("Y-F-d H:i:s",time())." > BBBport: $BBBport.\n"); if($ledt==0) { $led = $ledoff; } if($ledt==1) { $led = $ledred; } if($ledt==2) { $led = $ledblue; } /* Create a UDP socket */ if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0))) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); fwrite($log,date("Y-F-d H:i:s",time())." > Couldn't create socket: [$errorcode] $errormsg .\n"); curl_close($curl); fwrite($log,date("Y-F-d H:i:s",time())." > Curl Closed.\n"); socket_close($sock); fwrite($log,date("Y-F-d H:i:s",time())." > Socket Closed.\n"); fwrite($log,date("Y-F-d H:i:s",time())." > =-EOE-=\n"); fclose($log); die("Couldn't create socket: [$errorcode] $errormsg \n"); } fwrite($log,date("Y-F-d H:i:s",time())." > Socket Created.\n"); echo "Socket created <br>"; /* Bind the source address to localost port 33100 */ if( !socket_bind($sock, "0.0.0.0" , 33100) ) { $errorcode = socket_last_error(); $errormsg = socket_strerror($errorcode); fwrite($log,date("Y-F-d H:i:s",time())." > Socket Already bound. Continuing...\n"); } fwrite($log,date("Y-F-d H:i:s",time())." > Socket bind OK.\n"); echo "Socket bind OK <br>"; $y=poll(); /* Poll BBB */ /* Poll() sends UDP packet to BBB to get the temperature value and receives the value from the BBB. */ function poll() { $remote_ip =$GLOBALS['BBBip']; /* IP Address of BBB */ $remote_port = $GLOBALS['BBBport']; /* Port number of BBB */ $rip = ''; $rport = 0; fwrite($GLOBALS['log'],date("Y-F-d H:i:s",time())." > Polling BBB...\n"); socket_sendto($GLOBALS['sock'], $GLOBALS['led'], 100 , 0 , $remote_ip , $remote_port); /* Send UDP packet to BBB */ echo $GLOBALS['led']." <br>"; fwrite($GLOBALS['log'],date("Y-F-d H:i:s",time())." > UDP ".$GLOBALS['led']." sent to BBB.\n"); /* Blocking Receive for UDP packet from BBB */ $r = socket_recvfrom($GLOBALS['sock'], $buf, 2, 0, $rip, $rport); echo "$buf received with size $r<br> from IP: $rip , port: $rport"; if(!strcmp($buf,"OK")) { echo "<br>LED OK<br>"; fwrite($GLOBALS['log'],date("Y-F-d H:i:s",time())." > LED OK.\n"); } else { echo "<br>LED Fail<br>"; fwrite($GLOBALS['log'],date("Y-F-d H:i:s",time())." > LED Fail.\n"); } } /* Close Socket */ socket_close($sock); fwrite($log,date("Y-F-d H:i:s",time())." > Socket Closed.\n"); fwrite($log,date("Y-F-d H:i:s",time())." > =-EOE-=\n"); /* Close Log file */ fclose($log); ?>
true
40e1aa81f41dcf2994432ab75b95294de25c8ffa
PHP
nabilelmoudden/2015
/anaconda-project/businessCore/components/EMV/Exception.php
UTF-8
1,646
2.828125
3
[]
no_license
<?php /** * Exception * * @package EMV */ class EMV_Exception extends Exception { /** * Creates an exception from a SoapFault object * * @param SoapFault $soapFault * @return EMV_Exception */ public static function createFromSoapFault(SoapFault $soapFault) { if (isset($soapFault->detail->ExportServiceException)) { $detail = $soapFault->detail->ExportServiceException; $message = $detail->status . ': ' . $detail->description; return new EMV_Exception($message); } if (isset($soapFault->detail->BatchMemberServiceException)) { $detail = $soapFault->detail->BatchMemberServiceException; $fields = isset($detail->fields) ? ' [fields: ' . $detail->fields . ']' : ''; $message = $detail->status . $fields . ': ' . $detail->description; return new EMV_Exception($message); } return new EMV_Exception($soapFault->getMessage()); } /** * Adds class/method info to the exception message * * @return string */ public function getCustomMessage() { $trace = $this->getTrace(); $message = 'Exception in '; if (!empty($trace[0]['class'])) { if ($trace[0]['class'] != get_class()) { $idx = 0; } else if (isset($trace[1]['class'])) { $idx = 1; } if (isset($idx)) { $message .= $trace[$idx]['class'] . '->'; } } $message .= $trace[$idx]['function'] . '(): ' . $this->getMessage(); return $message; } }
true
630cfebbd677ea30add170aac7474c195aee9e27
PHP
boss59/first
/Es/sync.php
UTF-8
1,140
2.625
3
[]
no_license
<?php # 把 MYSQL 数据 同步到 Es 中 header('content-type:text/html;charset=utf-8'); $limit = 2; $goods_log = __DIR__.'/sync_goods.log'; if (file_exists($goods_log)){ $sync_id = file_get_contents($goods_log); }else{ $sync_id = 0; } // 连接数据库 $mysql = new Mysqli('127.0.0.1','root','root','new_blog'); $mysql -> query('set names utf8'); // 设置字符集 $sql = 'select * from goods where goods_id >'.$sync_id.' limit '.$limit; $goods_list = $mysql -> query($sql) -> fetch_all(MYSQLI_ASSOC); echo '<pre/>'; print_r($goods_list); if (empty($goods_list)){ exit('商品同步完成'); } # 将查询出来的数据 写入 Es 中 include_once __DIR__ .'/Es.class.php'; $es_obj = new Es(); foreach($goods_list as $k=>$v){ $add = $es_obj ->index('goods') ->save($v['goods_id'],$v); if ($add){ file_put_contents($goods_log,$v['goods_id'],FILE_USE_INCLUDE_PATH); }else{ exit('die'); } } ?>
true
274d7aeb7eb32f0a2f176bbad22c296fb979892d
PHP
StefanRHRO/CCCRM
/application/classes/html2.php
UTF-8
5,923
2.515625
3
[ "BSD-3-Clause" ]
permissive
<?php /** * * Copyright (c) 2010, SRIT Stefan Riedel <info@srit-stefanriedel.de> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - 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. * - Neither the name of the author 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR * CONTRIBUTORS 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. * * PHP version 5 * * $Id: html2.php 9 2010-08-12 20:31:38Z stefanriedel $ * $LastChangedBy: stefanriedel $ * * @author Stefan Riedel <info@srit-stefanriedel.de> * @copyright 2010 SRIT Stefan Riedel * @license http://www.opensource.org/licenses/bsd-license.php New BSD License */ defined('SYSPATH') or die('No direct script access.'); class HTML2 extends HTML { static protected $_javascript = array(); public static function errorBlock(array $errors) { $errorStrings = ''; foreach ($errors as $errorField => $errorsValue) { $errorStrings .= self::tag('p', array('id' => 'p' . $errorField), I18n::get($errorsValue)); } return self::tag('div', array('class' => 'message error closeable'), $errorStrings); } public static function tag($tag, array $htmlOptions = array(), $content = false, $closeTag = true) { $html = '<' . $tag . self::_renderAttributes($htmlOptions); if ($content === false) { return $closeTag ? $html . ' />' : $html . '>'; } else { return $closeTag ? $html . '>' . $content . '</' . $tag . '>' : $html . '>' . $content; } } public static function encode($text) { return htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); } protected static function _renderAttributes($htmlOptions) { if ($htmlOptions === array()) { return ''; } $html = ''; $raw = isset($htmlOptions ['encode']) && !$htmlOptions ['encode']; unset($htmlOptions ['encode']); if ($raw) { foreach ($htmlOptions as $name => $value) { $html .= ' ' . $name . '="' . $value . '"'; } } else { foreach ($htmlOptions as $name => $value) { $html .= ' ' . $name . '="' . self::encode($value) . '"'; } } return $html; } public static function orderAnchor($field, array $params = array(), $title = NULL, array $attributes = NULL, $protocol = NULL) { $request = Request::instance(); /* $uri = $request->uri; if (!empty($params)) { foreach ($params as $k => $p) { if ($k === 0) { $uri .= '?'; } else { $uri .= '&'; } $uri .= $p['name'] . '=' . $p['value']; } $uri .= self::_orderString($field, $request, true); } else { $uri .= self::_orderString($field, $request); } */ $base = URL::base(); $baseLength = strlen($base); $reqUri = Request::current()->uri; $uri = URL::site($reqUri) . URL::query(array('order' => $field, 'type' => self::_orderString($field, $request))); $uri = substr($uri, $baseLength); //var_dump($uri); return self::anchor($uri, $title, $attributes, $protocol); } protected static function _orderString($field, Request $request, $query=false) { $acStatusOfField = (isset($_GET['order'])) ? $_GET['order'] : null; $type = (isset($_GET['type'])) ? $_GET['type'] : null; if (!empty($acStatusOfField) && $field === $acStatusOfField) { switch (strtolower($type)) { case 'asc': $uri = 'DESC'; break; case 'desc': $uri = 'ASC'; break; } } else { $uri = 'ASC'; } return $uri; } public static function javascriptAnchor($title = null, array $attributes = array()) { return '<a href="javascript:void(0)"'.self::attributes($attributes).'>'.$title.'</a>'; } public static function addJavaScriptCode($code, $indexName=null, $oneDeklaration = false) { if (!is_string($code)) { throw new Kohana_Exception('Im Moment werden leider nur Strings unterstützt. Es ist für eine spätere Version vorgesehen auch Arrays übergeben zu können.'); } if(null !== $indexName && $oneDeklaration && isset(self::$_javascript[$indexName])) { return self::$_javascript[$indexName]; } $index = (empty($indexName)) ? (count(self::$_javascript)) : $indexName; self::$_javascript[$index] = $code; } public static function getJavaScriptCodes() { return self::$_javascript; } }
true
b5c14a1faab63188a7a84645ead1462c365002cf
PHP
a-ghasemi/algorithm-gaming
/markdown-parser-initial/Bold.php
UTF-8
235
2.953125
3
[]
no_license
<?php class Bold extends RegexRule implements RegexRuleInterface { public function rule() { return '/\*{2}(.*)\*{2}|\_{2}(.*)\_{2}/m'; } public function replacement() { return "<b>$1</b>"; } }
true
0b19890b71c922fa446f7cd5f08daa35bfeefcf5
PHP
antonsmolko/calipari.laravel
/app/Services/Sale/Repositories/CmsSaleRepository.php
UTF-8
1,564
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Services\Sale\Repositories; use App\Models\Sale; use App\Services\Base\Resource\Repositories\CmsBaseResourceRepository; use App\Services\Sale\Resources\ForListCmsCollection as SaleForListCollection; class CmsSaleRepository extends CmsBaseResourceRepository { /** * CmsSaleRepository constructor. * @param Sale $model */ public function __construct(Sale $model) { $this->model = $model; } /** * @param int $id * @return mixed */ public function getItemWithTexture(int $id) { return $this->model::where('id', $id) ->with('texture:id,name,width,seamless') ->firstOrFail(); } /** * @param array $requestData * @param string $status * @return SaleForListCollection */ public function getItemsByStatus(array $requestData, int $status) { return new SaleForListCollection($this->model::where('status', $status) ->orderBy($requestData['sort_by'], $requestData['sort_order']) ->paginate($requestData['per_page'], ['*'], '', $requestData['current_page'])); } /** * @param Sale $item * @param int $status * @return bool */ public function setStatus(Sale $item, int $status): bool { $item->status = $status; return $item->save(); } /** * @param Sale $item * @return bool */ public function onSale(Sale $item) { $item->status = $this->model::FOR_SALE; return $item->save(); } }
true
faf72d083e95a28d463275caecfb560d5288aa00
PHP
consumersketch/nilesh
/app/View/Helper/GeneralHelper.php
UTF-8
4,570
2.71875
3
[]
no_license
<?php /** * Created by JetBrains PhpStorm. * User: proses * Date: 1/1/14 * Time: 7:44 PM * To change this template use File | Settings | File Templates. */ class GeneralHelper extends AppHelper { public $helpers = array('Session'); public function first_letter_capitalized($text = null) { $result = ''; $sentence_text = ucwords(strtolower($text)); $result = preg_replace('#[.-][a-z]#e', 'strtoupper(\'$0\')', $sentence_text); return $result; } public function shortens_string_by_words($str, $number) { $array_str = explode(" ", $str); if (isset($array_str[$number])) { return implode(" ", array_slice($array_str, 0, $number)); } return $str; } public function getDateDiff($val1,$val2=DATECALCULATIONFORMEMBERS) { $dt1 = date("Y-m-d",strtotime($val1)); $dt2 = date($val2); $datetime1 = new DateTime($dt1); $datetime2 = new DateTime($dt2); return $datetime1->diff($datetime2)->y; } public function base64_to_jpeg($base64_string) { $src = 'data: image/png;base64,'.$base64_string; return $src; } public function file_size($size = '') { switch(strtolower($size)) { case "small": case "profile": return '<small><strong>Max Dimensions</strong>: 247(w) X 203(h),<br /> <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "banner": return '<small><strong>Max Dimensions</strong>: 800(w) X 120(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "committee": return '<small><strong>file Dimensions</strong>: 500(w) X 500(h) (must be square), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "content": return '<small><strong>file Dimensions</strong>: 800(w) X 200(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "event_select_file": return '<small><strong>file Dimensions</strong>: 800(w) X 200(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "event_sponsor_file": return '<small><strong>file Dimensions</strong>: 200(w) X 200(h)(must be square), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "event_architect_file": return '<small><strong>file Dimensions</strong>: 200(w) X 200(h) (must be square), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "event_gallery": return '<small><strong>file Dimensions</strong>: 500(w) X 500(h) (must be square), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "footer_image": return '<small><strong>file Dimensions</strong>: 800(w) X 170(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "pdf_upload_image": return '<small><strong>Max File Size:</strong> 1MB , <strong>Allowed File Extensions: </strong> (PDF)</small>'; break; case "product_image": return '<small><strong>file Dimensions</strong>: 800(w) X 150(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; case "small_banner": return '<small><strong>file Dimensions</strong>: 300(w) X 250(h), <strong>Max File Size:</strong> 1MB , <br /><strong>Allowed File Extensions: </strong> (JPEG,JPG,PNG)</small>'; break; } } public function showFormHelper($text = '') { switch(strtolower($text)) { case "restaurant_title": return '<small><strong>Please provide Restaurant Full Name</strong></small>'; break; case "restaurant_about": return '<small><strong>Please provide Restaurant Description</strong></small>'; break; } } public function showError($errors,$field) { if(isset($errors[$field][0]) && $errors[$field][0]!='') { echo '<div class="error-message">'.$errors[$field][0].'</div>'; } } public function db2date($date) { return date('d/m/Y',strtotime($date)); } // end of function public function getVars($key,$array) { if(isset($array[$key])) { return $array[$key]; } } }
true
afffd84492e3f7177ae18a70e9c2bca209645495
PHP
OsaAjani/cours-php-b2
/examples/oop/pokemon2.php
UTF-8
264
3.109375
3
[]
no_license
<?php class Pokemon { public $name = 'Carapuce'; public $life = 100; public $level = 5; public $type = 'eau'; public $strength = 10; } $pokemon = new Pokemon(); $pokemon2 = new Pokemon(); var_dump($pokemon2);
true
f7d3336babc4ce9fde1a23f2e20546e8358cec53
PHP
urbaniak62/exoLaravel
/app/article.php
UTF-8
1,687
3.015625
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class article extends Model { protected $_titre; protected $_contenu; protected $_date; protected $_name_auteur; protected $_categorie; protected $_nb_vue; public function __construct(array $donne){ $this->hydrate($donne); } // ---------------hydratation // ---------------------------- public function hydrate(array $donnes){ foreach ($donnes as $key => $value) { $method = 'set'.ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } } // settters // ------------------------------------ public function setTitre($titre){ $this->_titre=$titre; } public function setContenu($contenu){ $this->_contenu=$contenu; } public function setDate($date){ $this->_date=$date; } public function setName_Auteur($name){ $this->_name_Auteur=$name; } public function setCategorie($categorie){ $this->_categorie=$categorie; } public function setNb_vue($vue){ $this->_nb_vue=$vue; } // getters // ---------------------------------------- public function getTitre(){ return $this->_titre; } public function getContenu(){ return $this->_contenu; } public function getDate(){ return $this->_date; } public function getName_auteur(){ return $this->_name_auteur; } public function getCategorie(){ return $this->_categorie; } public function getVue(){ return $this->_vue; } }
true
42c1ed799fb46d60d6e283e8938d5c29593ff298
PHP
philsebastian/cs401
/web/app/models/students/StudentAppointmentModel.php
UTF-8
467
2.546875
3
[]
no_license
<?php class StudentAppointmentModel extends StudentsModel { public function __construct() { parent::__construct('appointments'); } public function GetData($content) { $data = parent::GetData($content); $tabcontent = array("tabs" => ["upcoming" => "appointments", "history" => "appointments/history", "schedule" => "appointments/schedule"]); $data = array_merge($data, $tabcontent); return $data; } }
true
b72136507d39ef3da3d04e8fdfc76c6c5a636846
PHP
Roave/BetterReflection
/test/core/ReflectionParameter_DefaultValueConstant_basic2.phpt
UTF-8
811
2.890625
3
[ "MIT" ]
permissive
--TEST-- ReflectionParameter::isDefaultValueConstant() && getDefaultValueConstantName() for namespace --FILE-- <?php namespace ReflectionTestNamespace { CONST TEST_CONST_1 = "Test Const 1"; class TestClass { const TEST_CONST_2 = "Test Const 2 in class"; } } namespace { function ReflectionParameterTest($test=ReflectionTestNamespace\TestClass::TEST_CONST_2, $test2 = ReflectionTestNamespace\CONST_TEST_1) { echo $test; } $reflect = new ReflectionFunction('ReflectionParameterTest'); foreach($reflect->getParameters() as $param) { if($param->isDefaultValueAvailable() && $param->isDefaultValueConstant()) { echo $param->getDefaultValueConstantName() . "\n"; } } echo "==DONE=="; } ?> --EXPECT-- ReflectionTestNamespace\TestClass::TEST_CONST_2 ReflectionTestNamespace\CONST_TEST_1 ==DONE==
true
a0ae3402392e8440b68e9abcd739f20e2d40ca75
PHP
edouardkombo/EkApiCallerBundle
/Helper/ApiCallerHelper.php
UTF-8
5,785
2.5625
3
[]
no_license
<?php /** * Main docblock * * PHP version 5 * * @category Handler * @package EkApiCallerBundle * @author Edouard Kombo <edouard.kombo@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php MIT License * @version GIT: 1.0.0 * @link http://creativcoders.wordpress.com * @since 0.0.0 */ namespace EdouardKombo\EkApiCallerBundle\Helper; /** * Api Caller Helper * * @category Helper * @package EkApiCallerBundle * @author Edouard Kombo <edouard.kombo@gmail.com> * @license http://www.opensource.org/licenses/mit-license.php MIT License * @link http://creativcoders.wordpress.com */ class ApiCallerHelper { /** * * @var object */ public $setGetContract; /** * * @var object */ public $firewall; /** * * @var object */ public $comm; /** * COnstructor * * @param \EdouardKombo\PhpObjectsContractBundle\Contract\SetGetCOntract $setGetContract SetGet Contrat * @param array $parameters EkApiCaller parameters config * @param \EdouardKombo\PhpObjectsContractBundle\Contract\FirewallContract $firewall Class that throws exceptions * @param \EdouardKombo\PhpObjectsContractBundle\Contract\CommunicationCOntract $comm Communication Contract */ public function __construct($setGetContract, $parameters, $firewall, $comm) { $this->comm = $comm; $this->firewall = $firewall; $this->firewall->isCurlEnabled(); $this->setGetContract = $setGetContract; $this->setGetContract->cursor = 'verifySSLCertificates'; $this->setGetContract->set($parameters['verify_ssl_certificates']); $this->setGetContract->cursor = 'cache'; $this->setGetContract->set($parameters['cache']); $this->setGetContract->cursor = 'timeout'; $this->setGetContract->set($parameters['timeout']); $this->setGetContract->cursor = 'connectTimeout'; $this->setGetContract->set($parameters['connect_timeout']); } /** * Encode datas * * @param array $data Url ldatas to encode * @param null|string $prefix Datas prefix * * @return string */ private function encodeDatas(array $data = array(), $prefix = null) { $parameters = []; foreach ($data as $key => $value) { if (is_null($value)) { continue; } if ($prefix !== null && $key && !is_int($key)) { $key = $prefix . '[' . $key . ']'; } else if ($prefix !== null) { $key = $prefix . '[]'; } if (is_array($value)) { $parameters[] = $this->encodeDatas($value, $key); } else { $parameters[] = urlencode($key) . '=' . urlencode($value); } } return implode('&', $parameters); } /** * Main method for sending curl request, needs curlMethodSetOpt * * @param string $method Http method * * @return mixed */ public function curlMethod($method) { $url = $this->setGetContract->url; $datas = $this->setGetContract->datas; $encodedDatas = $this->encodeDatas($datas); $handle = curl_init($url); $nUrl = $this->curlMethodSetopt($url, $datas, $encodedDatas, $handle, $method); $this->setGetContract->cursor = 'url'; $this->setGetContract->set($nUrl); $this->setGetContract->cursor = 'handle'; $this->setGetContract->set($handle); $this->comm->handle = $handle; list($response, $code, $errorNumber, $errorMessage) = $this->comm->send(); if (false === $response) { $this->firewall->handleCurlError($errorNumber, $errorMessage); } return $this->firewall->getResponse($response, $code); } /** * Method that sets curlSeptOpt requests * * @param string $url Url to target * @param array $datas Url params * @param string $encodedDatas Url params encoded * @param mixed $handle Curl url return * @param string $method Http method * * @return string */ private function curlMethodSetopt($url, $datas, $encodedDatas, $handle, $method) { $c = $this->setGetContract; if ($method === 'get') { curl_setopt($handle, CURLOPT_HTTPGET, 1); } else if ($method === 'post') { curl_setopt($handle, CURLOPT_POST, 1); curl_setopt($handle, CURLOPT_POSTFIELDS, $encodedDatas); } else if ($method === 'delete') { curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE'); } $newUrl = (count($datas) > 0) ? $url.'?'.$encodedDatas : $url; curl_setopt($handle, CURLOPT_FRESH_CONNECT, $c->cache); curl_setopt($handle, CURLOPT_URL, $newUrl); curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $c->connectTimeout); curl_setopt($handle, CURLOPT_TIMEOUT , $c->timeout); if (is_array($c->headers) && !empty($c->headers)) { curl_setopt($handle, CURLOPT_HTTPHEADER, $c->headers); } curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $c->verifySSLCertificates); return $newUrl; } }
true
bbe6f84a05a96492ddbaa53647e8fba1576b7950
PHP
srijib/Talentoon2
/talentoon/app/Http/GCMPushMessage.php
UTF-8
2,847
3.265625
3
[ "MIT" ]
permissive
<?php /* Class to send push notifications using Google Cloud Messaging for Android Example usage ----------------------- $an = new GCMPushMessage($apiKey); $an->setDevices($devices); $response = $an->send($message); ----------------------- $apiKey Your GCM api key $devices An array or string of registered device tokens $message The mesasge you want to push out @author Matt Grundy Adapted from the code available at: http://stackoverflow.com/questions/11242743/gcm-with-php-google-cloud-messaging */ class GCMPushMessage { // the URL of the GCM API endpoint private $url = 'https://android.googleapis.com/gcm/send'; // the server API key - setup on class init private $serverApiKey = ""; // array of devices to send to private $devices = array(); /* Constructor @param $apiKeyIn the server API key */ function GCMPushMessage($apiKeyIn){ $this->serverApiKey = $apiKeyIn; } /* Set the devices to send to @param $deviceIds array of device tokens to send to */ function setDevices($deviceIds){ if(is_array($deviceIds)){ $this->devices = $deviceIds; } else { $this->devices = array($deviceIds); } } /* Send the message to the device @param $message The message to send @param $data Array of data to accompany the message */ function send($message, $data = false){ if(!is_array($this->devices) || count($this->devices) == 0){ throw new GCMPushMessageArgumentException("No devices set"); } if(strlen($this->serverApiKey) < 8){ throw new GCMPushMessageArgumentException("Server API Key not set"); } $fields = array( 'registration_ids' => $this->devices, 'data' => array( "message" => $message ), ); if(is_array($data)){ foreach ($data as $key => $value) { $fields['data'][$key] = $value; } } $headers = array( 'Authorization: key=' . $this->serverApiKey, 'Content-Type: application/json' ); // Open connection $ch = curl_init(); // Set the url, number of POST vars, POST data curl_setopt( $ch, CURLOPT_URL, $this->url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) ); // Avoids problem with https certificate curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false); // Execute post $result = curl_exec($ch); // Close connection curl_close($ch); return $result; } } class GCMPushMessageArgumentException extends Exception { public function __construct($message, $code = 0, Exception $previous = null) { parent::__construct($message, $code, $previous); } public function __toString() { return __CLASS__ . ": [{$this->code}]: {$this->message}\n"; } }
true
de4db65f59b97d33029ee309dc20f7befd01ac00
PHP
mkostelcev/va_afl
/models/Flights/ops/BookingDelete.php
UTF-8
952
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * Created by PhpStorm. * User: Nikita Fedoseev * Date: 09.10.16 * Time: 0:54 */ namespace app\models\Flights\ops; use app\models\Booking; use app\models\Fleet; use app\models\Services\notifications\FlightOps; class BookingDelete { /** * @var Booking */ private $booking; /** * Construct * @param Booking $booking */ public function __construct(Booking $booking){ $this->booking = $booking; FlightOps::bookingDelete($booking); $this->fleet(); $this->booking(); } private function fleet(){ if($this->booking->fleet){ $this->booking->fleet->status = Fleet::STATUS_AVAIL; $this->booking->fleet->save(); } } private function booking(){ $this->booking->status = Booking::BOOKING_DELETED_BY_USER; $this->booking->g_status = Booking::STATUS_CANCELED_BY_COMPANY; $this->booking->save(); } }
true
88c093ee6bef72c5275a523de86e937c31cd5e18
PHP
Arvraepe/ohm
/general.php
UTF-8
8,747
2.9375
3
[]
no_license
<?php session_start(); /* Controlling the pages and making sure nobody sees things he don't want/needs to see */ // Using general in scripts need to set the $skip_page_control so // general skips this possible redirect and the SQL features and functions can be used if(!isset($skip_page_control)) { // Get the Current page $page = "home"; $page_type = "public"; if(isset($_GET['p'])){ $page = $_GET['p']; } else if(isset($_SESSION['uid'])) { // When no page is set but the user is logged in -> go to dashboard instead of home $page = "dashboard"; } // Login Required for this page? $public = array("home", "login", "register", "tour", "registred"); if (!in_array($page, $public)) { $page_type = "private"; // Session is needed to be set for this page ... but is it? if (!isset($_SESSION['uid'])) header("location: index.php?p=login&redirect=".$page); } else { // Logged in user tries to access public page if (isset($_SESSION['uid'])) header("location: index.php"); // Register with a running activation else if ($page == "register" && isset($_SESSION['activated'])) $page = "registred"; // Register with no activation else if ($page == "register" && !isset($_SESSION['activated'])) $page = "register"; // Registred without the $_SESSION var else if ($page == "registred" && !isset($_SESSION['activated'])) $page = "register"; } } function GetSubItem($default){ return isset($_GET['s']) ? $_GET['s'] : $default; } /* STARTING GENERAL */ $db = new mysqli("localhost", "root", "", "handball"); $ohm = FETCH_OR_NULL_SQL("SELECT * FROM `ohm`"); // -------------- QUERYING HELPERS function QUERY($sql){ global $db; $result = $db->query($sql) or die ($db->error); if($result){ while ($row = $result->fetch_object()){ $a[] = $row; } // Free result set $result->close(); $db->next_result(); return $a; } } function FETCH_ALL_OR_NULL_SQL($sql){ $r = QUERY($sql); if(count($r) > 0) return $r; return NULL; } function FETCH_OR_NULL_SQL($sql){ $r = QUERY($sql); if(count($r) > 0) return $r[0]; return NULL; } function FETCH_OR_NULL($table, $field, $value){ $r = QUERY("SELECT * FROM `".$table."` WHERE ".$field." = '".mysql_escape_string($value)."'"); if(count($r) > 0) return $r[0]; return NULL; } function FETCH_ALL_OR_NULL($table, $field, $value){ $r = QUERY("SELECT * FROM `".$table."` WHERE ".$field." = '".mysql_escape_string($value)."'"); if(count($r) > 0) return $r; return NULL; } // -------------- END QUERYING HELPERS function GetPlayerAge($birthday) { $cyear = date("Y"); $cmonth = date("m"); $cday = date("d"); $bdate = explode("-", $birthday); $age = $cyear - $bdate[0]; if ($bdate[1] > $cmonth || ($bdate[1] == $cmonth && $bdate[2] > $cday)) $age -= 1; return $age; } function GetTalentColorClass($talent){ $class = ""; switch ($talent) { case 1: $class = "important"; break; case 2: $class = "warning"; break; case 3: $class = "info"; break; case 4: $class = "success"; break; case 5: $class = "success"; break; } return $class; } function GetExperienceColorClass($exp){ $class = ""; switch ($exp) { case 0: $class = "important"; break; case 1: $class = "warning"; break; case 2: $class = "info"; break; case 3: $class = "success"; break; } return $class; } // ----- Get Functions -------- function GetUserById($uid){ return FETCH_OR_NULL("users", "id", $uid); } function GetUserByUsername($username){ return FETCH_OR_NULL("users", "username", $username); } function GetUserByEmail($email){ return FETCH_OR_NULL("users", "email", $email); } function GetPlayerById($pid){ return FETCH_OR_NULL("players", "id", $pid); } function GetPlayersByTeam($tid){ return FETCH_ALL_OR_NULL("players", "tid", $tid); } function GetTeamById($teamid){ return FETCH_OR_NULL("team", "id", $teamid); } function GetDivisionById($did){ return FETCH_OR_NULL("divisions", "id", $did); } function GetTeamsByDivision($did){ return FETCH_ALL_OR_NULL("team", "did", $did); } function GetStatusById($sid){ return FETCH_OR_NULL("player_status", "id", $sid); } function GetTransactionsByTeamId($tid, $amount){ return FETCH_ALL_OR_NULL_SQL("SELECT * FROM `transactions` WHERE tid = ".$tid." AND completed = 'y' ORDER BY `when` DESC LIMIT ".$amount); } function GetStaffOnList(){ return FETCH_ALL_OR_NULL_SQL("SELECT id, tid, name, salary, experience, typename as type FROM `staff`, `staff_type` WHERE staff.type = staff_type.typeid AND staff.tid is null"); } function GetStaffByTeamId($tid){ return FETCH_ALL_OR_NULL_SQL("SELECT id, tid, name, salary, experience, typename as type FROM `staff`, `staff_type` WHERE staff.type = staff_type.typeid AND staff.tid = ".$tid); } function GetStaffById($sid){ return FETCH_OR_NULL("staff", "id", $sid); } // ----- END Get Functions -------- function GetPlayerStatus($player){ if($player->status != 0){ $status = GetStatusById($player->status); return '<div class="img-player-info label label-'.$status->class.'">'.$status->text.'</div>'; } return ""; } function RestoreSession($uid){ // TODO //$user = GetUserById($uid); } function SetSessionVars($user){ $_SESSION['uid'] = $user->id; $_SESSION['tid'] = $user->tid; $_SESSION['username'] = $user->username; $team = GetTeamById($user->tid); $_SESSION['did'] = $team->did; } function RandomHash() { $stack = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; $length = 40; $str = ""; for ($i=0; $i < $length; $i++) { $in = rand(0, strlen($stack)-1); $str .= $stack[$in]; } return $str; } function GetRandomName($amount){ $lastnames = QUERY("SELECT * FROM `lastnames`"); $firstnames = QUERY("SELECT * FROM `firstnames`"); for ($i=0; $i < $amount; $i++) { $lrid = rand(0, count($lastnames)); $frid = rand(0, count($firstnames)); $names[$i] = $firstnames[$frid]->firstname." ".$lastnames[$lrid]->lastname; } return $names; } /* Creation functions */ function CreateStaff($name, $experience, $salary, $type){ global $db; $db->query("INSERT INTO `staff` (name, salary, experience, type) VALUES ( '".$name."', ".$salary.", ".$experience.", ".$type." )"); return $db->insert_id; } function CreateTransaction($amount, $message, $when, $extra, $class){ $db->query("INSERT INTO `transactions` (when, amount, completed, message, extra, class) VALUES ( '".$when."', ".$amount.", 'n', '".$message."', '".$extra."', '".$class."' )"); return true; } function HireStaff($staffid, $teamid){ global $db; $staff = GetStaffById($staffid); if($staff != NULL && $staff->tid == NULL){ $db->query("UPDATE `staff` SET tid = ".$teamid." WHERE id = ".$staffid) or die ($db->error); return true; } return false; } function FireStaff($staffid, $teamid){ global $db; $staff = GetStaffById($staffid); if($staff != NULL && $staff->tid == $teamid){ // Fire the staff member $db->query("UPDATE `staff` SET tid = NULL WHERE id = ".$staffid); // Add the transaction fire fee. } } ?>
true
1440d2c1fcb70c1bc33ddf06f8b6a98fed387187
PHP
Lacustris/Website
/app/User.php
UTF-8
911
2.78125
3
[]
no_license
<?php namespace App; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'role', ]; /** * Rules for validation */ const validationRules = [ 'name' => 'required|max:255', 'email' => 'required|email|max:255', 'role' => 'required', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function getRole() { return Role::getRole($this->role); } public function getRoleName() { return $this->getRole()['name']; } public function canManage() { return $this->getRole()['admin']; } }
true
2f0a2feb0d3911e4ae6a2f4502803ca7ce6037bc
PHP
danieljuniorce/mvcPhp
/Core/Controller.php
UTF-8
867
2.546875
3
[ "MIT" ]
permissive
<?php namespace Core; class Controller { public function view($viewPaste, $viewName, $viewData = array()) { extract($viewData); if ($viewPaste == '') { include 'App/View/' . $viewName . '.php'; } else { include 'App/View/'.$viewPaste.'/'. $viewName . '.php'; } } public function template($viewPaste, $viewName, $viewData = array()) { include 'App/View/template.php'; } public function LoadViewTemplate($viewPaste, $viewName, $viewData = array()) { extract($viewData); if ($viewPaste == '') { include 'App/View/' . $viewName . '.php'; } else { include 'App/View/'.$viewPaste.'/'. $viewName . '.php'; } } public function asset($dir) { global $config; echo $config['link'].$dir; } }
true
192c9f16d8a7f1dec23ddaa77d73da076bdb48be
PHP
adamhaley/anastasia
/types/article_desc.php
UTF-8
1,489
2.9375
3
[]
no_license
<?php //THIS IS THE SAME AS DESC BUT IT INSERTS LINE BREAKS IN GET_VALUE_FOR_WEB class article_desc extends type { public function article_desc($key, $value, $bp, $http_vars = '') { //constructor return $this->type($key, $value, $bp, $http_vars); } public function form_field() { $value = stripslashes($this->value); $key = $this->key; $length = $this->length; $cols = 90; $rows = ceil($length / 40); $label = $this->get_label(); $form = $label . ": (&lt;b&gt;<b>Bold</b>&lt;/b&gt; &lt;i&gt;<i>Italics</i>&lt;/i&gt; &lt;a href=\"URL\"&gt;<a href=\"#\">Link</a>&lt;/a&gt;)<br><textarea name = \"" . $key . "\" cols=\"" . $cols . "\" rows = \"" . $rows . "\" wrap=\"physical\">" . $value . "</textarea><br>"; return $form; } public function get_value_for_web() { $value = stripslashes($this->value); $value = str_replace("\n", "<br>", $value); $value = preg_replace("/\s\s\s/", "&nbsp;<img src=\"images/blank.gif\" width=\"10px\">", $value); if(strstr($value, '---')) { $array = explode('---', $value); $value = ''; for($i=0;$i<count($array);$i++) { $imgno = $i+1; $tag = '<%image' . $imgno . '%>'; $value .= $array[$i]; $value .= ($i == (count($array)-1)) ? '' : $tag; } } return $this->_wrap($value); } }
true
03354f7dff15455e6eabd5d63429142f9ad5b2c8
PHP
sobwoofer/simpleDocker
/public/index.php
UTF-8
254
2.859375
3
[]
no_license
<?php /** * Test php file */ $first = 'Hello '; $second = 'World!'; echo $first . $second . PHP_EOL; echo 'Congratulations, now you have your own a little docker machine for your big projects. ' . PHP_EOL; echo 'Configure it how you want' . PHP_EOL;
true
686e293356f275892b50fbb2140b6aecf80a8d74
PHP
garbetjie/http-request-logger
/src/Logger.php
UTF-8
7,110
2.84375
3
[ "MIT" ]
permissive
<?php namespace Garbetjie\RequestLogging\Http; use Garbetjie\RequestLogging\Http\Context\SafeRequestContext; use Garbetjie\RequestLogging\Http\Context\SafeResponseContext; use InvalidArgumentException; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; use SplObjectStorage; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; use function call_user_func; use function in_array; use function is_callable; use function microtime; use function strtolower; class Logger { /** * @var LoggerInterface */ protected $logger; /** * @var string|int */ protected $level; /** * @var callable[] */ protected $context = []; /** * @var callable[] */ protected $enabled = []; /** * @var callable[] */ protected $messages = []; /** * @var callable */ protected $id; /** * @var SplObjectStorage */ protected $startedAt; public const DIRECTION_IN = 'in'; public const DIRECTION_OUT = 'out'; /** * @param LoggerInterface $logger * @param string|int $level */ public function __construct(LoggerInterface $logger, $level = LogLevel::DEBUG) { // Set logger and level. $this->logger = $logger; $this->level = $level; // Create the map of startedAt timestamps. $this->startedAt = new SplObjectStorage(); // Set default extractors. $this->context(new SafeRequestContext(), new SafeResponseContext()); // Set default message handler. $this->message( function (RequestEntry $entry) { return [ Logger::DIRECTION_IN => 'http request received', Logger::DIRECTION_OUT => 'http request sent', ][$entry->direction()]; }, function (ResponseEntry $entry) { return [ Logger::DIRECTION_IN => 'http response received', Logger::DIRECTION_OUT => 'http response sent', ][$entry->direction()]; } ); // Enable request & response logging by default. $this->enabled(true, true); // Set default ID generation. $this->id( function() { return generate_id(); } ); } /** * Set the callable used to generate an ID to link requests & responses together. * * @param callable $handler * * @return $this */ public function id(callable $handler): Logger { $this->id = $handler; return $this; } /** * Set the function used to generate the log message. * * @param callable|null $request * @param callable|null $response * * @return $this */ public function message(?callable $request, ?callable $response): Logger { if ($request !== null) { $this->messages['requests'] = $request; } if ($response !== null) { $this->messages['responses'] = $response; } return $this; } /** * Set the functions to use to extract context for each request/response. * * @param callable|null $request * @param callable|null $response * * @return $this */ public function context(?callable $request, ?callable $response): Logger { if ($request !== null) { $this->context['requests'] = $request; } if ($response !== null) { $this->context['responses'] = $response; } return $this; } /** * Set the function to use to determine whether a request or response should be logged. * * @param null|bool|callable $requests * @param null|bool|callable $responses * * @return $this */ public function enabled($requests, $responses): Logger { // Determine whether requests are enabled. if ($requests !== null) { $this->enabled['requests'] = is_callable($requests) ? $requests : function() use ($requests) { return (bool)$requests; }; } // Determine whether responses are enabled. if ($responses !== null) { $this->enabled['responses'] = is_callable($responses) ? $responses : function() use ($responses) { return (bool)$responses; }; } return $this; } /** * @param RequestInterface|SymfonyRequest|ServerRequestInterface|string $request * @param string $direction * * @return RequestEntry */ public function request($request, string $direction): RequestEntry { $direction = strtolower($direction); // Ensure a valid direction is given. if (!in_array($direction, [Logger::DIRECTION_IN, Logger::DIRECTION_OUT])) { throw new InvalidArgumentException("Unexpected request direction '{$direction}'."); } // Create the request's log entry. $logEntry = new RequestEntry( $request, call_user_func($this->id), $direction ); // Only log the request if requests should be logged. if (call_user_func($this->enabled['requests'], $logEntry)) { $this->logger->log( $this->level, call_user_func($this->messages['requests'], $logEntry), call_user_func($this->context['requests'], $logEntry) ?: [] ); } // This is only populated here because we don't know how long the call to $this->logger->log() might take. // If the log() call takes 1s, this will misrepresent the duration of the request, hence why we only populate // it later. // It would be nice for the context extractors and togglers to receive the proper values, but ¯\_(ツ)_/¯ $this->startedAt[$logEntry] = microtime(true); return $logEntry; } /** * @param RequestEntry $request * @param ResponseInterface|SymfonyResponse|string $response * * @return void */ public function response(RequestEntry $request, $response): void { $duration = isset($this->startedAt[$request]) ? microtime(true) - $this->startedAt[$request] : null; $logEntry = new ResponseEntry($request, $response, $duration); // Ensure the reference in the object map is removed. unset($this->startedAt[$request]); // Only log the response if responses should be logged. if (call_user_func($this->enabled['responses'], $logEntry)) { $this->logger->log( $this->level, call_user_func($this->messages['responses'], $logEntry), call_user_func($this->context['responses'], $logEntry) ?: [] ); } } }
true
6a0230507e2ffa70bd2629e62c61b8934e7d9998
PHP
shefchenkornd/Oop_week_ElisDn
/lesson04/02/demo08/cart/cost/NewYearCost.php
UTF-8
1,474
3.390625
3
[]
no_license
<?php namespace lesson04\example02\demo08\cart\cost; /** * Эффективнее работать с классом \DateTime * потому что с его помощью можно складывать/вычитать даты, форматировать и использовать прочие плюшки */ class NewYearCost implements CalculatorInterface { private $next; private $month; private $percent; public function __construct(CalculatorInterface $next, \DateTime $month, $percent) { $this->next = $next; $this->month = $month; $this->percent = $percent; } /** * эта функция не совсем ЧИСТАЯ, ПОТОМУ ЧТО ОНА ЛЕЗЕТ ЕЩЕ ЗА ДАТОЙ * и для нас это будет проблемой протестировать этот функционал */ public function getCost(array $items) { $cost = $this->next->getCost($items); if (date('m') === $this->month->format('m')) { return (1 - $this->percent / 100 ) * $cost; } return $cost; } } $simple = new SimpleCost(); $newYear = new NewYearCost($simple, 12, 5); //... по скидкам можно дальше суммировать паровозиком =) // принцип такой: мы вкладываем объекты в друг друга передавай их следующему echo $newYear->getCost([]);
true
43878e18270a431b3f83023125868e23c71ba841
PHP
richardfullmer/rdfbot2
/src/RDF/GithubBotBundle/EventListener/GithubStatusListener.php
UTF-8
2,942
2.765625
3
[ "MIT" ]
permissive
<?php /* * This file is part of ONP * * Copyright (c) 2012 Farheap Solutions (http://www.farheap.com) * * The unauthorized use of this code outside the boundaries of * Farheap Solutions Inc. is prohibited. */ namespace RDF\GithubBotBundle\EventListener; use RDF\GithubBotBundle\Event\OnBuildStartedEvent; use RDF\GithubBotBundle\Event\OnBuildFinishedEvent; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Github\Client; use RDF\GithubBotBundle\Events; /** * @author Richard Fullmer <richard.fullmer@opensoftdev.com> */ class GithubStatusListener implements EventSubscriberInterface { /** * @var \Github\Client */ private $client; /** * @param \Github\Client $client */ public function __construct(Client $client) { $this->client = $client; } /** * @param \RDF\GithubBotBundle\Event\OnBuildStartedEvent $event */ public function onBuildStarted(OnBuildStartedEvent $event) { $build = $event->getBuild(); $this->updateGithub($build->getProject()->getUsername(), $build->getProject()->getRepository(), $build->getCommitSha(), $build->getStatusName()); } /** * @param \RDF\GithubBotBundle\Event\OnBuildFinishedEvent $event */ public function onBuildFinished(OnBuildFinishedEvent $event) { $build = $event->getBuild(); $this->updateGithub($build->getProject()->getUsername(), $build->getProject()->getRepository(), $build->getCommitSha(), $build->getStatusName()); } /** * @param $username * @param $repo * @param $commit * @param $status */ private function updateGithub($username, $repo, $commit, $status) { $this->client->api('repos')->statuses()->create( $username, $repo, $commit, array( 'state' => $status, 'description' => ucfirst($status) . ' at ' . date('m/d/y G:i:s T'), // 'target_url' => $url ) ); } /** * Returns an array of event names this subscriber wants to listen to. * * The array keys are event names and the value can be: * * * The method name to call (priority defaults to 0) * * An array composed of the method name to call and the priority * * An array of arrays composed of the method names to call and respective * priorities, or 0 if unset * * For instance: * * * array('eventName' => 'methodName') * * array('eventName' => array('methodName', $priority)) * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) * * @return array The event names to listen to * * @api */ public static function getSubscribedEvents() { return array( Events::BUILD_STARTED => 'onBuildUpdated', Events::BUILD_FINISHED => 'onBuildFinished' ); } }
true
20fcda07078a48a1a6d315e89d5fa5a0e2b7cbb2
PHP
Godfather27/FactoryBot
/tests/TestStrategies/JSONStrategy.php
UTF-8
852
2.734375
3
[]
no_license
<?php namespace FactoryBot\Tests\TestStrategies; use FactoryBot\Strategies\StrategyInterface; class JSONStrategy implements StrategyInterface { public static function beforeCompile($factory) { $factory->notify("before"); } public static function result($factory, $instance) { $factory->notify("after"); $result = self::getPropertiesArray($instance); return json_encode($result); } public static function getPropertiesArray($instance) { $instanceArray = (array) $instance; $result = []; foreach ($instanceArray as $keyWithVisibility => $value) { $keySegments = explode("\0", $keyWithVisibility); $keyWithoutVisibility = end($keySegments); $result[$keyWithoutVisibility] = $value; } return $result; } }
true
019e8c2e1cb4ae117b28bf39fefd22e8b0174961
PHP
Flowfly/Mudespacher_Florian_Travail_Diplome
/backend/tests/Unit/QuestionTest.php
UTF-8
2,077
2.546875
3
[]
no_license
<?php /* Florian Mudespacher * Quiz interactif - Diploma work * CFPT - T.IS-E2A - 2019 */ namespace Tests\Unit; use App\Proposition; use App\Question; use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase; class QuestionTest extends TestCase { public function is_question_created_and_deleted_correctly(){ $question = new Question(); $question->label = "test"; $question->points = 20; $question->type_id = 1; $question->tag_id = 1; $this->assertTrue($question->saveOrFail()); $id = $question->id; $this->assertEquals(1, Question::where('id', $id)->count()); $this->assertEquals(1, Question::destroy($id)); $this->assertEquals(0, Question::where('id', $id)->count()); } /** @test */ public function is_question_updated_correctly(){ $question = new Question(); $question->label = "test_update"; $question->points = 20; $question->type_id = 1; $question->tag_id = 1; $question->save(); $question->label = "test_update1"; $question->save(); $id = $question->id; $this->assertEquals("test_update1", Question::find($id)->label); Question::destroy($id); } /** @test */ public function are_propositions_deleted_when_questions_also_deleted(){ $question = new Question(); $question->label = "test_delete"; $question->points = 20; $question->type_id = 1; $question->tag_id = 1; $question->save(); $id = $question->id; for($i = 0; $i < 4; $i++){ $proposition = new Proposition(); $proposition->label = $i; $proposition->is_right_answer = 0; $proposition->question_id = $id; $proposition->save(); } $this->assertEquals(4, Proposition::where('question_id', $id)->count()); Question::destroy($id); $this->assertEquals(0, Proposition::where('question_id', $id)->count()); } }
true
66910cb02c5be8f21b19c9bf4196b0f51d3ccb5c
PHP
CWSBusiness/Webservant
/php/classes/ErrorCollector.php
UTF-8
2,028
3.296875
3
[]
no_license
<?php class ErrorCollector implements IteratorAggregate, Countable { private $level = 0; private $errors = array(); const INFO = 1; const SUCCESS = 2; const WARNING = 4; const DANGER = 8; private static $levels = array( self::INFO => "info", self::SUCCESS => "success", self::WARNING => "warning", self::DANGER => "danger", JSON_HEX_AMP ); public function addError($message, $level) { if (!is_int($level)) { try { $level = (int) $level; } catch (Exception $e) { throw new InvalidArgumentException("Expected int for error level, got " . gettype($level) . " instead."); } } if ($level <= 0 || ($level & ($level - 1)) != 0) { // using the constants above, the error level should be a power of two throw new InvalidArgumentException("Invalid error level supplied as argument."); } $count = array_push($this->errors, $message); // bitwise OR the error level. This way you can quickly tell the highest level set, but also if any given level is set $this->level = $this->level | $level; return $count - 1; } // public function removeError($index) { // if (array_key_exists($index, $this->errors)) { // // } else { // throw new BadMethodCallException("Attempt to remove non-existent error from collector."); // } // } public function reset() { $this->errors = array(); } public function hasErrors() { return (count($this->errors) > 0) ? true : false; } public function __toString() { if (count($this->errors) == 0) { return ""; } $str = "<div class=\"status-box " . self::$levels[$this->level] . "\">" . PHP_EOL; if (count($this->errors) == 1) { $str .= $this->errors[0]; } else { $str .= "<ul>" . PHP_EOL; foreach ($this->errors as $error) { $str .= "<li>" . $error . "</li>" . PHP_EOL; } $str .= "</ul>" . PHP_EOL; } $str .= "</div>" . PHP_EOL; return $str; } public function getIterator() { return new ArrayIterator($this->errors); } public function count() { return count($this->errors); } }
true
971e344e2e35a4960e98ad2a8c60f3614f4dcbb5
PHP
chaim1/Fetch-Words
/Backend/models/model.php
UTF-8
210
2.890625
3
[]
no_license
<?php interface IModel { public function getWord(); public function getScore(); public function setWord($data); public function setScore($data); } ?>
true
7adcd242b6807892cb71993494e1c551bcd78aeb
PHP
MyIceTea/http
/Response/Header.php
UTF-8
512
2.734375
3
[ "MIT" ]
permissive
<?php namespace EsTeh\Http\Response; use EsTeh\Contracts\Http\Response; class Header implements Response { private $headers = []; private $headerF = []; public function __construct($headerF) { $this->headerF = $headerF; } public function buildHeader() { $this->headers['X-EsTeh-Framework-Version'] = ESTEH_VERSION; } public function sendResponse() { http_response_code($this->headerF['http_response_code']); foreach ($this->headers as $key => $val) { header($key.": ".$val); } } }
true
4e531771d357476bde5ebc5bce3f684e4f5bb616
PHP
eddy147/oop-principles-exercises
/SingleResponsibility/TreatmentServiceInterface.php
UTF-8
204
2.5625
3
[]
no_license
<?php namespace SingleResponsibility; interface TreatmentService { public function create(array $treatmentData); public function update(Treatment $treatment); public function find($id); }
true
e2531607a7bdcd084ee1dab720fe7392dadd2daf
PHP
nisnaker/tu
/server/model/User.php
UTF-8
1,543
2.59375
3
[ "MIT" ]
permissive
<?php use Phalcon\Mvc\Model\Validator\Email as EmailValidator; class User extends Base { protected $_attrs = ['userid', 'name', 'avatar', 'email', 'status']; public function getSource() { return 'user'; } public function beforeCreate() { parent::beforeCreate(); $this->status = 2; // 未激活 $this->userid = $this->_uniqid(); $this->name = $this->userid; $hash = md5(strtolower(trim($this->email))); $this->avatar = 'http://cdn.v2ex.com/gravatar/' . $hash . '?d=retro'; } public function afterCreate() { // send comfirm mail } public function validation() { $this->validate(new EmailValidator([ 'field' => 'email' ])); if($this->validationHasFailed() == true) { return false; } } private function _uniqid() { $str = '0123456789abcdefghijklmnopqrstuvwxyz'; while(true) { $id = ''; for($i = 0; $i < 6; $i++) { $index = rand(0, 35); $id .= $str{$index}; } $user = self::findFirst([['userid' => $id]]); if(!$user) return $id; } } public function gen_token() { $time = dechex(time() - EPOCH); $val = $this->userid . $time; $token = sprintf('%s.%s.%s', $this->userid, $time, hash_hmac('sha256', $val, CRYPT_KEY) ); return $token; } public function check_token() { $token = arr_get($_COOKIE, 'token', ''); $info = explode('.', $token); if(3 != count($info)) return false; list($userid, $time, $hash) = $info; if($hash != hash_hmac('sha256', $userid . $time, CRYPT_KEY)) return false; return $userid; } }
true
22f0c81c303994ebea562ceecd5b633cd68c5808
PHP
GSushma11/TechAspect-Codeathon
/form.php
UTF-8
680
2.5625
3
[]
no_license
<?php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "MSA"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $a=$_REQUEST('t1'); $b=$_REQUEST('t2'); $c=$_REQUEST('t3'); $d=$_REQUEST('t4'); $e=$_REQUEST('t5'); $f=$_REQUEST('t6'); $sql = "INSERT INTO TABLE Studentinfo VALUES ('$a', '$b', '$c' , '$d','$e', '$f')"; if ($conn->query($sql) === TRUE) { echo "Inserted successfully"; } else { echo "Error "; } $conn->close(); <html> <body> echo "View all details"; <input type="submit" value="View"/> </body> </html> ?>
true
7d180ab5960c52dd7cf86cc65c3d2561234a6e38
PHP
benplummer/calendarful
/src/Event/InMemory/InMemoryEventRepository.php
UTF-8
1,283
2.8125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Plummer\Calendarful\Event\InMemory; use DateTimeImmutable; use Plummer\Calendarful\Event\EventCollection; use Plummer\Calendarful\Event\EventInterface; use Plummer\Calendarful\Event\EventRepositoryInterface; class InMemoryEventRepository implements EventRepositoryInterface { /** * @var array<int, EventInterface> */ protected array $events = []; public function add( EventInterface ...$events, ): void { $this->events = [ ...$this->events, ...array_values($events), ]; } public function withinDateRange( DateTimeImmutable $fromDate, DateTimeImmutable $toDate, ): EventCollection { return EventCollection::fromArray( array_filter( $this->events, function (EventInterface $event) use ($fromDate, $toDate) { if ( ($event->startDate() < $fromDate && $event->endDate() < $fromDate) || ($event->startDate() > $toDate && $event->endDate() > $toDate) ) { return false; } return true; } ), ); } }
true
2b310000bdbea44384757cfe123939918dd15d88
PHP
xuzhijian17/Yii2-backend
/common/lib/ErrorHandler.php
UTF-8
4,109
2.59375
3
[]
no_license
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace common\lib; use Yii; use yii\base\Exception; use yii\base\ErrorException; use yii\base\UserException; use yii\web\HttpException; /** * ErrorHandler handles uncaught PHP errors and exceptions. * * ErrorHandler is configured as an application component in [[\yii\base\Application]] by default. * You can access that instance via `Yii::$app->errorHandler`. * * @author Carsten Brandt <mail@cebe.cc> * @since 2.0 */ class ErrorHandler extends \yii\base\ErrorHandler { /** * Renders an exception using ansi format for console output. * @param \Exception $exception the exception to be rendered. */ protected function renderException($exception) { $error_arr = $this->convertExceptionToArray($exception); $log_path = Yii::$app->params['logPath']; if(array_key_exists('error',$log_path) && file_exists($log_path['error'])){ $log_500_path = $log_path['error']."500_".date("Y-m-d").".log"; }else{ $log_500_path = Yii::$app->basePath."/runtime/logs/500_".date("Y-m-d").".log"; } $msg = isset($error_arr['message']) ? $error_arr['message'] : ''; $fname = isset($error_arr['file']) ? $error_arr['file'] : ''; $line = isset($error_arr['line']) ? $error_arr['line'] : '';; $type = isset($error_arr['type']) ? $error_arr['type'] : '';; $randCode = $this->selfRand(); $errorinfo = array( 'ckcd'=>$randCode, 'type' => $type, 'error' => $msg, 'line' => $line, 'file' => $fname, 'requUrl' => isset(Yii::$app->request->url) ? Yii::$app->request->url : '', ); $error_str = "【ERROR】".date("Y-m-d H:i:s")." ".json_encode($errorinfo); $fp = fopen($log_500_path,'a+'); fwrite($fp,$error_str."\n"); fclose($fp); $returnarr = array('code'=>500, 'message'=>'Request error,try again later.', 'ckcd'=>$randCode); echo json_encode($returnarr); exit; } /* * 产生一个随机数 * */ private function selfRand() { list($usec, $sec) = explode(' ', microtime()); $hh = (float) $sec + ((float) $usec * 100000); mt_srand($hh); $randval = mt_rand(100,999); $randval = date('H').$randval; return $randval; } /** * Converts an exception into an array. * @param \Exception $exception the exception being converted * @return array the array representation of the exception. */ protected function convertExceptionToArray($exception) { if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) { $exception = new HttpException(500, 'There was an error at the server.'); } $array = [ 'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception', 'message' => $exception->getMessage(), 'code' => $exception->getCode(), ]; if ($exception instanceof HttpException) { $array['status'] = $exception->statusCode; } if (YII_DEBUG) { $array['type'] = get_class($exception); if (!$exception instanceof UserException) { $array['file'] = $exception->getFile(); $array['line'] = $exception->getLine(); $array['stack-trace'] = explode("\n", $exception->getTraceAsString()); if ($exception instanceof \yii\db\Exception) { $array['error-info'] = $exception->errorInfo; } } } if (($prev = $exception->getPrevious()) !== null) { $array['previous'] = $this->convertExceptionToArray($prev); } return $array; } }
true
f61528b50221dc4175792755974aab15cc992fac
PHP
Nushrat-Jahan/atpProject
/database/migrations/2021_03_11_191545_create_teacher_courses_table.php
UTF-8
936
2.578125
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTeacherCoursesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('teacher_courses', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('teacher_course_id',10)->unique(); $table->string('teacher_id',10); $table->foreign('teacher_id')->references('teacher_id')->on('teachers'); $table->string('course_id',10); $table->foreign('course_id')->references('course_id')->on('courses'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('teacher_courses'); } }
true
d189b508f371ecf78f56212d5ab430c09722d3e0
PHP
davbaster/php
/php_desde_cero/paginacursos/includes/Visitante.inc.php
UTF-8
332
2.828125
3
[]
no_license
<?php /** * */ class Visitante extends Persona { private $badge; public function __construct($nombre, $apellido, $email, $badge) { parent::__construct($nombre, $apellido, $email); $this->badge = $badge; } public function despedida(){ echo "Hola {$this->nombre} te esperamos en ED team."; } } ?>
true
b3b59f3d2fc8c5ffc54120e69c4480875a298317
PHP
rezieno/Tugas-RPL-revisi-
/barangmasuk_edit.php
UTF-8
2,958
2.546875
3
[]
no_license
<?php include_once 'include/class.php'; include_once 'include/lib.php'; // instansiasi objek user $user = new User(); // instansiasi objek nsb $bm = new Barangmasuk(); $iduser = $_SESSION['id']; if (!$user->get_sesi()) { header("location:index.php"); } // proses hapus data if (isset($_GET['aksi'])) { if ($_GET['aksi'] == 'hapus') { // baca id_detail dari parameter id_detail nasabah yang akan dihapus $kode_brg= $_GET['kode_brg']; // proses hapus data nasabah berdasarkan id_detail via method $bm->hapusBm($kode_brg); echo '<META HTTP-EQUIV="Refresh" Content="0; URL=?page=barangmasuk">'; } // proses edit data else if ($_GET['aksi'] == 'edit') { // baca id_detail nasabah yang akan diedit $kode_brg = $_GET['kode_brg']; // menampilkan form edit nasabah // untuk menampilkan data detil nasabah, gunakan method bacaDataNasabah() ?> <link rel="stylesheet" href="kalender/calendar.css" type="text/css"> <script type="text/javascript" src="kalender/calendar.js"></script> <script type="text/javascript" src="kalender/calendar2.js"></script> <script> function checkForm(formZ){ if(formZ.kode_brg.value==''){ alert('Kode Barang tidak boleh kosong.'); formZ.kode_brg.focus(); return false; } if(formZ.jum_brg.value==''){ alert('Jumlah barang tidak boleh kosong.'); formZ.jum_brg.focus(); return false; } } </script> <b>BARANG MASUK</b> <div class="subnav"> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="images/tabdata01.gif" /></td> <td class="tabsubnav"> <a href="?page=barangmasuk">DATA</a> &raquo; <b>EDIT BARANGMASUK</b> </td> <td><img src="images/tabdata03.gif" /></td> </tr> </table> </div> <table width="100%" border="0" cellspacing="0" cellpadding="3"> <form name="barangmasuk" action="?page=barangmasuk_edit&aksi=update" method="post" onsubmit="return checkForm(this)"> <tr> <td width="15%"><div class="tabtxt">Kode Barang</div></td> <td width="2%"><div class="tabtxt">:</div></td> <td width="83%"> <input name="kode_brg" style="width:200px" type="textfield" class="tfield" value="<?php echo $bm->bacaDataBm('kode_brg', $kode_brg); ?>"> </td> </tr> <tr> <td valign="top"><div class="tabtxt">Jumlah Barang</div></td> <td valign="top"><div class="tabtxt">:</div></td> <td> <input name="jum_brg" style="width:200px" type="number" class="tfield" value="<?php echo $bm->bacaDataBm('jum_brg', $kode_brg); ?>"> </td> </tr> <tr> <td colspan="2">&nbsp;</td> <td> <input name="submit" type="submit" class="button" value="Update">&nbsp;&nbsp; <input type="button" class="button" value="Batal" onclick=self.history.back()> </td> </tr> </form> </table> <?php } else if ($_GET['aksi'] == 'update') { // update data nasabah via method $bm->updateDataBm($_POST['kode_brg'], $_POST['jum_brg']); echo '<META HTTP-EQUIV="Refresh" Content="0; URL=?page=barangmasuk">'; } } ?>
true
fc0f6ba809b7091369552b51fbc447efbb62064e
PHP
SvenFlower/mightybattle_queue
/src/Match/MatchChance.php
UTF-8
1,393
3.203125
3
[]
no_license
<?php declare(strict_types=1); namespace MightyBattle\GameQueue\Match; use MightyBattle\GameQueue\Entity\WaitingPlayerInterface; class MatchChance { private WaitingPlayerInterface $waitingPlayer; private float $levelChance; private float $cardsCountChance; private float $deckPointsChance; public function __construct(WaitingPlayerInterface $waitingPlayer, float $levelChance, float $cardsCountChance, float $deckPointsChance) { $this->waitingPlayer = $waitingPlayer; $this->levelChance = $levelChance; $this->cardsCountChance = $cardsCountChance; $this->deckPointsChance = $deckPointsChance; } /** * @return WaitingPlayerInterface */ public function getWaitingPlayer(): WaitingPlayerInterface { return $this->waitingPlayer; } /** * @return float */ public function getLevelChance(): float { return $this->levelChance; } /** * @return float */ public function getCardsCountChance(): float { return $this->cardsCountChance; } /** * @return float */ public function getDeckPointsChance(): float { return $this->deckPointsChance; } public function chance(): float { return ($this->getCardsCountChance() + $this->getDeckPointsChance() + $this->getLevelChance()) / 3; } }
true
e8b28ac18014bb88cdf52369e061d054065b051e
PHP
serj271/shop33
/modules/acl/classes/Kohana/ACL/Auth/Interface.php
UTF-8
510
2.734375
3
[ "BSD-3-Clause", "MIT" ]
permissive
<?php defined('SYSPATH') OR die('No direct script access.'); interface Kohana_ACL_Auth_Interface extends ACL_Role_Interface { /** * Singleton pattern * * @return object of class */ public static function instance(); /** * Gets the currently logged in user from the session. * Returns NULL if no user is currently logged in. * * @param mixed $default Default value to return if the user is currently not logged in. * @return mixed */ public function get_user($default = NULL); }
true
9d3b8195cc48d5eaecca82ef1e6d01fed27d1619
PHP
JeckPikachan/Pancakes
/requires/adminPageGen.php
UTF-8
904
2.875
3
[]
no_license
<?php function showOrdersTable() { $mysqli = new mysqli("localhost", "root", "", "pancakesdb"); $mysqli->query("SET NAMES 'utf8'"); $orders = $mysqli->query("SELECT `id`, `pancakeName`, `fillings`, `done`, `totalPrice` FROM `orders` WHERE `show` = 1"); echo '<table class="table table-hover"> <thead><tr><th>№</th><th>Блин</th><th>Начинки</th><th>Цена</th><th>Готово</th><th>Забрать</th></tr></thead> <tbody>'; while ($row = $orders->fetch_assoc()) { $done = ""; if ($row["done"] == 1) $done = "success"; echo "<tr id='".$row["id"]."' class='pancake $done'><td>".$row["id"]."</td><td>".$row["pancakeName"]."</td><td>".$row["fillings"]."</td><td>".$row["totalPrice"]."</td><td><button class='readyBtn'>Готово</button></td><td><button class='getBtn'>Забрать</button></td></tr>"; } echo '</tbody> </table>'; $mysqli->close(); } ?>
true
81610ad3d58dc93f0cc707262f8881145b822fe0
PHP
truffo/ie-numbers
/src/ArrayDigit.php
UTF-8
1,558
3.59375
4
[]
no_license
<?php class ArrayDigit { private $digits; /** * ArrayDigit constructor. */ public function __construct() { $this->digits = []; } public static function createWithInteger(int $i): self { if ($i < 0) { throw new LogicException('Invalid value'); } $v = new ArrayDigit(); $v->digits = str_split((string) $i); return $v; } public static function createWithClassicalArray(array $v): self { foreach ($v as $value) { if (!is_integer($value) && $value / 10 > 1) { throw new LogicException('Invalid value'); } } $result = new ArrayDigit(); $result->digits = $v; return $result; } public function getIntValue(): int { $reverse = array_reverse($this->digits); $factor = 1; $result = 0; foreach ($reverse as $digit) { $result = $digit * $factor + $result; $factor *= 10; } return $result; } public static function increment(ArrayDigit $v): ArrayDigit { $reverse = array_reverse($v->digits); $result = $reverse; $curry = 1; foreach ($reverse as $key => $digit) { $digit += $curry; $curry = intdiv($digit, 10); $result[$key] = $digit % 10; } if (0 !== $curry) { $result[$key + 1] = $curry; } return self::createWithClassicalArray(array_reverse($result)); } }
true
abe9826c154137b5dc0f961a709c3963db84576e
PHP
ArtemBaranovsky/code-kata-php
/tests/SongTest.php
UTF-8
2,171
3
3
[]
no_license
<?php namespace App; use App\Song; use PHPUnit\Framework\TestCase; class SongTest extends TestCase { /** @test */ function ninety_nine_bottles_verse() { $expected = <<<EOT 99 bottles of beer on the wall 99 bottles of beer Take one down and pass it around 98 bottles of beer on the wall EOT; $result = (new Song)->verse(99); $this->assertEquals($expected, $result); } /** @test */ function ninety_eight_bottles_verse() { $expected = <<<EOT 98 bottles of beer on the wall 98 bottles of beer Take one down and pass it around 97 bottles of beer on the wall EOT; $result = (new Song)->verse(98); $this->assertEquals($expected, $result); } /** @test */ function forty_five_bottles_verse() { $expected = <<<EOT 45 bottles of beer on the wall 45 bottles of beer Take one down and pass it around 44 bottles of beer on the wall EOT; $result = (new Song)->verse(45); $this->assertEquals($expected, $result); } /** @test */ function two_bottles_verse() { $expected = <<<EOT 2 bottles of beer on the wall 2 bottles of beer Take one down and pass it around 1 bottle of beer on the wall EOT; $result = (new Song)->verse(2); $this->assertEquals($expected, $result); } /** @test */ function one_bottle_verse() { $expected = <<<EOT 1 bottle of beer on the wall 1 bottle of beer Take one down and pass it around No more bottles of beer on the wall EOT; $result = (new Song)->verse(1); $this->assertEquals($expected, $result); } /** @test */ function no_more_bottles_verse() { $expected = <<<EOT No more bottles of beer on the wall No more bottles of beer Go to the store and buy some more 99 bottles of beer on the wall EOT; $result = (new Song)->verse(0); $this->assertEquals($expected, $result); } /** @test */ function it_gets_the_lyrics() { $expected = file_get_contents(__DIR__ . '/stubs/lyrics.stub'); $result = (new Song)->sing(); $this->assertEquals($expected, $result); } }
true
dc1b0799728cdfbe51c179da9256f5837e2b3722
PHP
ckissane/HTML5
/Server/html5/rest/v0.2/dto/SetRotationStyleBrickDto.class.php
UTF-8
280
2.6875
3
[]
no_license
<?php class SetRotationStyleBrickDto extends BaseBrickDto { public $selected; //index public function __construct($selected = "1") { parent::__construct("SetRotationStyle"); $this->selected = $selected; //{0: left-right, 1: all around, 2: don't rotate} } }
true
7a3b56cf1311d190add7400abf814d5df0ced532
PHP
eonx-com/flowconfig-wrapper
/tests/Stubs/External/FlowConfig/CompositeConfigRepositoryStub.php
UTF-8
1,959
2.546875
3
[]
no_license
<?php declare(strict_types=1); namespace Tests\LoyaltyCorp\FlowConfig\Stubs\External\FlowConfig; use CodeFoundation\FlowConfig\Interfaces\EntityIdentifier; use CodeFoundation\FlowConfig\Interfaces\Repository\CompositeConfigRepositoryInterface; /** * Stub for providing the equivalent functionality of CascadeConfig. */ final class CompositeConfigRepositoryStub implements CompositeConfigRepositoryInterface { /** * @var string[] */ private $defaults; /** * @var string[][][] */ private $entityConfig; /** * @var string[] */ private $systemConfig; /** * CompositeConfigRepositoryStub constructor. * * @param string[]|null $defaults */ public function __construct(?array $defaults = null) { $this->defaults = $defaults ?? []; } /** * {@inheritdoc} */ public function canSet(): bool { return true; } /** * {@inheritdoc} */ public function canSetByEntity(): bool { return true; } /** * {@inheritdoc} */ public function get(string $key, $default = null) { return $this->systemConfig[$key] ?? $this->defaults[$key] ?? $default ?? null; } /** * {@inheritdoc} */ public function getByEntity(EntityIdentifier $entity, string $key, $default = null) { return $this->entityConfig[$entity->getEntityType()][$entity->getEntityId()][$key] ?? $this->systemConfig[$key] ?? $this->defaults[$key] ?? $default ?? null; } /** * {@inheritdoc} */ public function set(string $key, $value) { $this->systemConfig[$key] = $value; } /** * {@inheritdoc} */ public function setByEntity(EntityIdentifier $entity, string $key, $value) { $this->entityConfig[$entity->getEntityType()][$entity->getEntityId()][$key] = $value; } }
true
1c7e3610fed58bec2a123a52d4837d44a2bd3141
PHP
Team-Tea-Time/thaliak
/code/app/Http/Lodestone/FreeCompanyListing.php
UTF-8
816
2.8125
3
[ "MIT" ]
permissive
<?php namespace Thaliak\Http\Lodestone; /** * Convenience class used by the API when returning a list of free * companies. */ class FreeCompanyListing { public $id; // String public $crest; // Array (string) public $name; // String public $world; // String public $grandcompany; // String public $activemembers; // Int public $dateformed; // Int/Timestamp public $estate; // String public function __construct(Array $data = []) { foreach ($data as $property => $value) { if (property_exists($this, $property)) { $this->{$property} = $value; } } } public function __toString() { return $this->name; } }
true
bb3ab0c525fb274c242496336e2037d18d7e2d34
PHP
oidcphp/core
/src/Traits/Psr7ResponseBuilder.php
UTF-8
1,859
2.578125
3
[ "MIT" ]
permissive
<?php namespace OpenIDConnect\Traits; use MilesChou\Psr\Http\Client\HttpClientAwareTrait; use OpenIDConnect\Http\Query; use Psr\Http\Message\UriInterface; trait Psr7ResponseBuilder { use ConfigAwareTrait; use HttpClientAwareTrait; /** * Using form post * * @param string $uri * @param array $parameters * @return string */ protected function generateFormPostHtml(string $uri, array $parameters = []): string { $formInput = implode('', array_map(function ($value, $key) { return "<input type=\"hidden\" name=\"{$key}\" value=\"{$value}\"/>"; }, $parameters, array_keys($parameters))); return <<< HTML <!DOCTYPE html> <head><title>Requesting Authorization</title></head> <body onload="javascript:document.forms[0].submit()"> <form method="post" action="{$uri}">{$formInput}</form> </body> </html> HTML; } /** * @param string $key * @param array $parameters * @return string */ protected function generateFormPostHtmlWithProviderConfig(string $key, array $parameters = []): string { return $this->generateFormPostHtml($this->config->requireProviderMetadata($key), $parameters); } /** * @param string $uri * @param array $parameters * @return UriInterface */ protected function generateRedirectUri(string $uri, array $parameters = []): UriInterface { return $this->httpClient->createUri($uri) ->withQuery(Query::build($parameters)); } /** * @param string $key * @param array $parameters * @return UriInterface */ protected function generateRedirectUriWithProviderConfig(string $key, array $parameters = []): UriInterface { return $this->generateRedirectUri($this->config->requireProviderMetadata($key), $parameters); } }
true
e9b2eb8e230c85d9c5f595257a5137f9d13f0f38
PHP
SebiLob/Project_Insead
/src/inseadBundle/Entity/createTrip.php
UTF-8
1,442
2.71875
3
[]
no_license
<?php namespace inseadBundle\Entity; /** * createTrip */ class createTrip { /** * @var int */ private $id; /** * @var string */ private $place; /** * @var \DateTime */ private $start; /** * @var \DateTime */ private $end; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set place * * @param string $place * * @return createTrip */ public function setPlace($place) { $this->place = $place; return $this; } /** * Get place * * @return string */ public function getPlace() { return $this->place; } /** * Set start * * @param \DateTime $start * * @return createTrip */ public function setStart($start) { $this->start = $start; return $this; } /** * Get start * * @return \DateTime */ public function getStart() { return $this->start; } /** * Set end * * @param \DateTime $end * * @return createTrip */ public function setEnd($end) { $this->end = $end; return $this; } /** * Get end * * @return \DateTime */ public function getEnd() { return $this->end; } }
true
f07e05f4827626f426435072cc23ca327741bc13
PHP
DASPRiD/dagr
/src/Format/DateTimePrinterParserInterface.php
UTF-8
696
3.21875
3
[]
no_license
<?php declare(strict_types = 1); namespace Dagr\Format; interface DateTimePrinterParserInterface { /** * Prints the date-time object to the buffer. * * The context holds information to use during the format. It also contains the date-time information to be printed. */ public function format(DateTimePrintContext $context) : ?string; /** * Parses text into date-time information. * * The context holds information to use during parse. It is also used to store the parsed date-time information. */ public function parse(DateTimePrintContext $context, string $parseText, int $position) : int; public function __toString() : string; }
true
7b82069b901d0a618ca7dde03ebd70b0aca68f64
PHP
Rajilatha/Hall-Booking-Website-System
/hotel1/search.php
UTF-8
1,246
2.75
3
[]
no_license
<html> <body> <form action="home.php" method="post"> <label for="Date">Date</label> <input type="date" name="Date" ><br> <select name="Time"> <option value="morning">Morning</option> <option value="evening">Evening</option> </select> <input type="submit" name="submit" value="OK"> </form> <?php $connect =mysqli_connect("localhost","root","","jkhall"); if(isset($_POST['submit'])){ $Date=$_POST['Date']; $Time=$_POST['Time']; $sql="SELECT `hallname` FROM `hallbooking` WHERE hallname!=(SELECT `hallname` FROM `hallbooking` WHERE Date='$Date' && Time='$Time')"; if($result = mysqli_query($connect, $sql)){ if(mysqli_num_rows($result) > 0){ echo "<table>"; echo "<tr>"; echo "<th>hallname</th>"; echo "</tr>"; while($row = mysqli_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row['hallname'] . "</td>"; echo "</tr>"; } echo "</table>"; // Free result set mysqli_free_result($result); } else{ echo "No records matching your query were found."; }} else{ echo"no connect"; } ?> </body> </html>
true
1418d151461b4306edba51b9085970c1f1bc7d3d
PHP
ViktorOrda/PHP-school
/lesson4/diamond.php
UTF-8
496
3.53125
4
[]
no_license
<?php $argc !== 2 ? exit('Error! You\'ve not entered size') : $count = $argv[1]; if ($count % 2 === 0) { exit('Error! Size should be odd number!'); } $start = $end = ceil($count/2); for ($i = 1; $i <= $count ; $i++) { for ($j = 1; $j <= $count; $j++) { echo ($j >= $start && $j <= $end) ? "*" : " " ; } if ($i < ceil($count/2)) { $start--; $end++; } else { $start++; $end--; } echo ($i < $count) ? PHP_EOL : null; }
true
333c1c055c7545d0aeee9f8da74e38658a38733e
PHP
denzelsc1337/proyecto_inventario
/Modelo/Productos.php
UTF-8
2,383
2.6875
3
[]
no_license
<?php //include_once('../config/Conexion.php'); $listProducto; class pProductos { function __construct() { $this->listProducto = array(); $this->selectorProd = array(); } public function obtenerProducto() { $cnx = new conexion(); $cadena = $cnx->abrirConexion(); $query = 'SELECT secuence_prod, razon_social,cat.secuence_cat,cat.nom_categoria, marca_nom, nom_producto, cantidades, fecha_entrada FROM productos prod INNER JOIN categorias cat ON prod.id_categoria = cat.secuence_cat INNER JOIN usuario usu ON prod.id_usuario = usu.secuence_usu #where cantidades >0 ORDER BY 1 desc'; $resultado = mysqli_query($cadena, $query); while ($fila = mysqli_fetch_row($resultado)) { $this->listProducto[] = $fila; } $cnx->cerrarConexion($cadena); return $this->listProducto; } public function selectorProd(){ $cnx = new conexion(); $cadena = $cnx->abrirConexion(); $query = 'SELECT cantidades, secuence_prod , concat(nom_producto, " - Marca: " ,marca_nom , " (stock: " ,cantidades , ")") as Producto FROM productos'; $result = mysqli_query($cadena, $query); while ($fila = mysqli_fetch_row($result)) { $this->selectorProd[]=$fila; } $cnx->cerrarConexion($cadena); return $this->selectorProd; } function agregarProducto($data) { include_once('../config/Conexion.php'); $cnx = new Conexion(); $cadena = $cnx->abrirConexion(); /* $Query = "INSERT INTO `productos` (`secuence_prod`, `id_categoria`, `marca_nom`, `RUC`, `razon_social`, `id_usuario`, `nom_producto`, `cantidades`, `fecha_entrada`, `fecha_vencimento`, `descripcion`, `guia_remision`, `num_orden`, `num_pecosa`, `perecible`) VALUES (null,'".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."', '".$data[5]."','".$data[6] ."','".$data[7]."','".$data[8]."', '".$data[9]."','".$data[10]."','".$data[11]."','".$data[12]."', '".$data[13]."','".$data[14]."');"; */ $Query = "CALL agregarProducto('".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."', '".$data[5]."','".$data[6] ."','".$data[7]."','".$data[8]."', '".$data[9]."','".$data[10]."','".$data[11]."','".$data[12]."', '".$data[13]."','".$data[14]."');"; echo mysqli_query($cadena, $Query); $cnx->cerrarConexion($cadena); /*$result = mysqli_query($cadena, $Query); $cnx ->cerrarConexion($cadena); return $result;*/ } }
true
b03cad72d7d6eaf7cecb19bef9968e5cd247bc87
PHP
mecca2/bsrg
/includes/autoload/Property.php
UTF-8
4,774
2.59375
3
[ "MIT" ]
permissive
<?php namespace Crb; /** * Represent a property Entry * Used to display Property in Frontend */ class Property { protected $meta_keys = array( 'agent_id', 'api_id', 'price', 'neighborhood', 'street_number', 'street_prefix', 'street_name', 'unit_number', 'street_dir_suffix', 'street_suffix', 'city', 'state', 'postal_code', 'bedrooms', 'bathrooms', 'sqft', 'sale', 'lat', 'lng', 'year_built', 'garage_carport', 'features', 'schools', 'food', 'waterfront', 'water_sewer', 'equipment', 'basement', 'dryer', 'family_room', 'floors', 'roofing', 'shared_interest', 'walls', 'zoning', 'age', 'construction', 'exterior_extras', 'fireplace', 'foundation', 'heating', 'other_rooms', 'days_on_market', 'style', 'washer_connection', 'water_heater', ); protected $details_keys = array( 'bedrooms', 'bathrooms', 'sqft', ); protected $additional_details_keys = array( 'neighborhood', 'construction', 'days_on_market', 'year_built', 'shared_interest', 'waterfront', 'style', 'floors', 'roofing', 'foundation', 'heating', 'garage_carport', 'water_sewer', 'family_room', 'fireplace', 'equipment', 'dryer', 'exterior_extras', 'other_rooms', 'washer_connection', 'water_heater', 'basement', 'walls', 'zoning', 'age', 'api_id', ); function __construct( $property_id ) { $prefix = 'crb_property_'; $this->images = carbon_get_the_post_meta( $prefix . 'gallery' ); $image = ''; if ( ! empty( $this->images ) && ! empty( $this->images[0] ) && ! empty( $this->images[0]['url'] ) ) { $image = $this->images[0]['url']; } $post_metadata = get_post_meta( $property_id ); // API Meta $this->meta = array(); foreach ( $this->meta_keys as $key ) { $this->meta[ $key ] = $post_metadata[ '_' . $prefix . \Crb\Mapper::get( $key ) ][0]; } // Additional Meta $this->meta = array_merge( $this->meta, array( 'address' => $post_metadata[ '_' . $prefix . 'address' ][0], 'street' => $post_metadata[ '_' . $prefix . 'street' ][0], 'image' => $image, ) ); $this->address = $this->meta['address']; } function get_meta_from_keys( $keys ) { $keys = array_combine( $keys, $keys ); $meta = array(); foreach ( $keys as $key ) { $meta[$key] = $this->meta[$key]; } $meta = array_filter( $meta ); # $meta = $this->filter_meta( $meta ); $meta = $this->format_meta( $meta ); return $meta; } function filter_meta( $meta_array ) { foreach ( $meta_array as $key => $value ) { if ( strtolower( $value ) == 'no' ) { unset( $meta_array[$key] ); } } return $meta_array; } function format_meta( $meta_array ) { foreach ( $meta_array as $key => $value ) { // Add space after ",.;" when they are followed by letter $meta_array[$key] = preg_replace( '~([,.;])([a-zA-Z])~', '$1 $2', $value ); } return $meta_array; } function set_titles( $meta_array ) { foreach ( $meta_array as $key => $value ) { $meta_array[$key] = array( 'value' => $value, 'title' => \Crb\Mapper::get_field_title( $key ), ); } return $meta_array; } function get_images() { return $this->images; } function get_meta() { return $this->meta; } function get_address() { return $this->address; } function get_details() { if ( isset( $this->details ) ) { return $this->details; } $this->details = $this->get_meta_from_keys( $this->details_keys ); return $this->details; } function get_additional_details() { if ( isset( $this->additional_details ) ) { return $this->additional_details; } $this->additional_details = $this->get_meta_from_keys( $this->additional_details_keys ); $this->additional_details = $this->set_titles( $this->additional_details ); return $this->additional_details; } function get_price() { if ( empty( $this->meta['price'] ) ) { return ''; } return '$' . number_format( $this->meta['price'], 0 ); } function get_agent_api_id() { return $this->meta['agent_id']; } function get_agent_id() { if ( ! isset( $this->agent_id ) ) { $agents = get_posts( array( 'post_type' => 'crb_agent', 'post_status' => 'publish', 'posts_per_page' => 1, 'paged' => 1, 'meta_key' => '_crb_agent_id', 'meta_value' => $this->meta['agent_id'], ) ); $this->agent_id = 0; if ( ! empty( $agents ) && ! empty( $agents[0] ) && ! empty( $agents[0]->ID ) ) { $this->agent_id = $agents[0]->ID; } } return $this->agent_id; } }
true
f53c3f77937c9cb54ea3f2dd07e55dec091017d0
PHP
Profilan/apibasiclabel
/module/Webshop/src/Webshop/V1/Rest/Verkooporder/VerkooporderMapper.php
UTF-8
5,374
2.5625
3
[]
no_license
<?php namespace Webshop\V1\Rest\Verkooporder; use Doctrine\ORM\EntityManager; use Zend\Stdlib\Hydrator\ArraySerializable as ArraySerializableHydrator; use Zend\Stdlib\ArrayUtils; use Traversable; use InvalidArgumentException; use Doctrine\Common\Collections\ArrayCollection; use DoctrineModule\Paginator\Adapter\Collection; use Application\Entity\MapperInterface; use Zend\Filter\Word\UnderscoreToCamelCase; /** * Mapper implementation using a file returning PHP arrays */ class VerkooporderMapper implements MapperInterface { /** * * @var EntityManager */ var $entityManager; /** * @var ArraySerializableHydrator */ protected $hydrator; /** * * @param EntityManager $em */ public function __construct(EntityManager $em) { $this->entityManager = $em; $this->hydrator = new ArraySerializableHydrator(); } /** * @param array|Traversable|\stdClass $data * @return VerkooporderEntity */ public function create($data) { if ($data instanceof Traversable) { $data = ArrayUtils::iteratorToArray($data); } if (is_object($data)) { $data = (array) $data; } if (!is_array($data)) { throw new InvalidArgumentException(sprintf( 'Invalid data provided to %s; must be an array or Traversable', __METHOD__ )); } $item = new VerkooporderEntity(); $item = $this->hydrator->hydrate($data, $item); $this->entityManager->persist($item); $this->entityManager->flush(); return $item; } /** * @param string $id * @return VerkooporderEntity */ public function fetch($id) { $item = $this->entityManager->getRepository('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity')->findBy(array( 'ordernr' => $id ))[0]; return $item; } /** * @return VerkooporderCollection */ public function fetchAll($params = array()) { $filter = new UnderscoreToCamelCase(); $qb = $this->entityManager->createQueryBuilder(); $qb->select('o') ->from('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity', 'o'); if (count($params) > 0) { $conditions = array(); foreach ($params as $k => $v) { // $conditions[lcfirst($filter->filter(strtolower($k)))] = $v; if ($k == 'DATE_START' || $k == 'DATE_END') { $val = urldecode($v); if ($k == 'DATE_START') { $qb->andWhere('o.sysmodified >= :startdate')->setParameter('startdate', $val); } if ($k == 'DATE_END') { $qb->andWhere('o.sysmodified <= :enddate')->setParameter('enddate', $val); } $qb->orderBy('o.sysmodified'); } else { $key = lcfirst($filter->filter(strtolower($k))); $qb->andWhere('o.'.$key.' = :'.$key)->setParameter($key, $v); } } // $items = $this->entityManager->getRepository('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity')->findBy($conditions); } else { // $items = $this->entityManager->getRepository('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity')->findAll(); } // var_dump($qb->getDQL());die(); $query = $qb->getQuery(); $items = $query->getResult(); $collection = new ArrayCollection($items); return new VerkooporderCollection(new Collection($collection)); } /** * @param string $id * @param array|Traversable|\stdClass $data * @return VerkooporderEntity */ public function update($id, $data) { $item = $this->entityManager->find('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity', $id); $item = $this->hydrator->hydrate($data, $item); $this->entityManager->persist($item); $this->entityManager->flush(); return $item; } /** * @param string $id * @return bool */ public function delete($id) { $item = $this->entityManager->find('Webshop\\V1\Rest\Verkooporder\VerkooporderEntity', $id); $this->entityManager->remove($item); $this->entityManager->flush(); return true; } /** * Translates a string with underscores into camel case (e.g. first_name -&gt; firstName) * @param string $str String in underscore format * @param bool $capitalise_first_char If true, capitalise the first char in $str * @return string $str translated into camel caps */ protected function to_camel_case($str, $capitalise_first_char = false) { if($capitalise_first_char) { $str[0] = strtoupper($str[0]); } $func = create_function('$c', 'return strtoupper($c[1]);'); return preg_replace_callback('/_([a-z])/', $func, $str); } }
true
59071df8fc485d93246f2cb87e6154281489e08e
PHP
singee77/socket-io
/app/Component/ClientManager.php
UTF-8
2,541
2.609375
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); /** * * This is my open source code, please do not use it for commercial applications. * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code * * @author CodingHePing<847050412@qq.com> * @link https://github.com/Hyperf-Glory/socket-io */ namespace App\Component; use App\Helper\ArrayHelper; use Hyperf\Redis\RedisProxy; class ClientManager { public const HASH_UID_TO_SID_PREFIX = 'hash.socket_user_fd'; public const HASH_FD_TO_UID_PREFIX = 'hash.socket_fd_user'; public const ZSET_IP_TO_UID = 'zset.ip_to_uid_bind'; /** *存储fd,ip,uid. */ public static function put(RedisProxy $redis, string $uid, int $fd) { //bind key to fd $redis->hSet(self::HASH_UID_TO_SID_PREFIX, $uid, $fd); $redis->hSet(self::HASH_FD_TO_UID_PREFIX, $fd, $uid); } /** * 删除对应关系. */ public static function del(RedisProxy $redis, string $uid, int $fd = null) { //del key to fd $redis->hDel(self::HASH_UID_TO_SID_PREFIX, $uid); $redis->hDel(self::HASH_FD_TO_UID_PREFIX, $fd); } public static function disconnect(RedisProxy $redis, int $fd) { $uid = $redis->hGet(self::HASH_FD_TO_UID_PREFIX, $fd); if (empty($uid)) { return; } self::del($redis, $uid, $fd); } /** * @return null|int */ public static function fd(\Redis $redis, string $uid) { return (int) $redis->hGet(self::HASH_UID_TO_SID_PREFIX, $uid) ?? null; } /** * @return array */ public static function fds(RedisProxy $redis, array $uids = []) { if (empty($uids)) { return []; } return ArrayHelper::multiArrayValues($redis->hMGet(self::HASH_UID_TO_SID_PREFIX, $uids) ?? []); } /** * @return null|string */ public static function key(RedisProxy $redis, int $fd) { return $redis->hGet(self::HASH_FD_TO_UID_PREFIX, $fd) ?? null; } /** * @return array|void */ public static function getIpUid(RedisProxy $redis, string $ip = null) { if (empty($ip)) { return; } return $redis->sMembers(sprintf('%s.%s', self::ZSET_IP_TO_UID, $ip)); } /** * @return false|string */ public static function isOnline(RedisProxy $redis, int $uid) { return $redis->hGet(self::HASH_UID_TO_SID_PREFIX, $uid) ?? false; } }
true
d055c3a9758b43aa98ff16d31ad6d8f85842a358
PHP
gebe678/TCO-Web-Tool
/webtool/root/assets/PHP/getFuelCostData.php
UTF-8
5,506
2.5625
3
[]
no_license
<?php function getFuelID($index) { include "getID.php"; $costComponentQuery = "SELECT Fuel_ID FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Fuel_ID"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getFuelYearData($index) { include "getID.php"; $costComponentQuery = "SELECT Year FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Year"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getGasolineData($index) { // include "getID.php"; include "connectDatabase.php"; $costComponentQuery = "SELECT Gasoline FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Gasoline"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getDieselData($index) { include "getID.php"; $costComponentQuery = "SELECT Diesel FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Diesel"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getCNGData($index) { include "getID.php"; $costComponentQuery = "SELECT CNG FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["CNG"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getElectricData($index) { include "getID.php"; $costComponentQuery = "SELECT Electric FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Electric"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getGasElectricData($index) { include "getID.php"; $costComponentQuery = "SELECT Gas_Electric FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Gas_Electric"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getPremiumGasolineData($index) { include "getID.php"; $costComponentQuery = "SELECT Premium_Gasoline FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row["Premium_Gasoline"]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getFuelData($index) { include "getID.php"; $costComponentQuery = "SELECT $fuelType FROM aeo_fuel_prices"; $result = $connect->query($costComponentQuery); $output; $i = 0; while($row = $result->fetch_assoc()) { $output[$i] = $row[$fuelType]; $i++; } if($index < count($output) && $index >= 0) { return $output[$index]; } return -1; } function getEnergyUseData() { include "getID.php"; $vehicleSize = $_POST["vehicleClassSize"]; $fuelReference = $_POST["fuelReference"]; $costComponentQuery = "SELECT price FROM energy_use_task WHERE fuel LIKE '$fuelType' AND year LIKE $fuelYear AND vehicle_size LIKE '$vehicleSize' AND fuel_type LIKE '$fuelReference'"; // if($fuelType == "Hydrogen") // { // $hydrogenType = $fuelType . "_" . $hydrogenSuccess; // $costComponentQuery = "SELECT price FROM energy_use_task WHERE fuel LIKE '$hydrogenType' AND year LIKE $fuelYear"; // } $result = $connect->query($costComponentQuery); $result = $result->fetch_assoc(); $result = $result["price"]; return $result; } ?>
true
efbcf22f5d0db75168c364d0680e88d5bfd3e15c
PHP
chenqianfang/PHP-Python--Data-capture
/hello.php
UTF-8
2,258
2.765625
3
[]
no_license
<?php set_time_limit(0); //执行时间无限 ini_set('memory_limit', '-1'); //内存无限 ini_set("display_errors","On"); error_reporting(E_ALL); ob_end_flush(); ob_implicit_flush(1); $book_url = 'https://www.zwdu.com'; $url = 'https://www.zwdu.com/book/8167/'; $data = file_get_contents($url); //页面源是gbk的编码格式,需要进行转换 $data = iconv("gb2312", "utf-8//IGNORE",$data); //echo $data; $p = '/<div id="info">\s*<h1>(.*?)<\/h1>/';//书名 $m = '/<p>作&nbsp;&nbsp;&nbsp;&nbsp;者:(.*?)<\/p>/';//作者 preg_match($p, $data, $title); print_r($title[1]);echo '<br>'; $articleTitle = $title[1];//书名 if(!is_dir('book/')){ //判断是已存在该小说的文件夹,如果不存在,就新建一个 mkdir('book/',0777,true); } preg_match($m, $data, $author); print_r($author[1]);echo '<br>'; $articleAuthor = $author[1];//作者 preg_match_all('/<dd><a href="(.*?)"/', $data, $chapter); //print_r($chapter[1]);echo '<br>';die; $chapter_url = $chapter[1];//章节列表url数组 $len = count($chapter_url); $chapterTitle = []; $chapterText = []; $i = 590; do { $chapterData = file_get_contents($book_url.$chapter_url[$i]); $chapterData = iconv("gb2312", "utf-8//IGNORE",$chapterData); preg_match('/<div class="bookname">\s*<h1>(.*?)<\/h1>/', $chapterData, $chapterH); //print_r($chapterH[1]); $chapterTitle[$i] = $chapterH[1];//章节标题 preg_match('/<div id="content">(.*?)<\/div>/', $chapterData, $chapterT); $chapterT[1] = preg_replace('/八.*M/', '', $chapterT[1]); //print_r($chapterT[1]); $chapterText[$i] = $chapterT[1];//章节内容 echo $chapterH[1].'<br>'; $text = strip_tags($chapterT[1]);//去除html代码 $text = $chapterH[1]."\r\n".$text."\r\n";//插入章节标题 $text = str_replace('&nbsp;', '', $text); $fileName = 'book/'.$articleTitle.".txt"; //转换文件名编码格式,防止windows下乱码,linux系统下不用转码 $fileName = iconv('UTF-8', 'GBK', $fileName); //a+方式,向文本末尾写入新的章节 $chapterFile = fopen($fileName, "a+") or die("Unable to open file!"); fwrite($chapterFile, $text); fclose($chapterFile); sleep(1); //休眠一秒 $i = $i + 1; } while ($i < $len ); ?>
true
7801dcfcba468321d5945005a626ee80b7c82d3e
PHP
james-projet/partage
/src/Model/AccountManager.php
UTF-8
1,280
2.703125
3
[ "MIT" ]
permissive
<?php namespace Acme\Model; class AccountManager extends BddManager { public function accountById($id){ $accounts = array(); $bdd = $this->getBdd(); $req = $bdd->prepare('SELECT * FROM account WHERE account_groupe=:id'); $req->bindValue('id', $id); $req->execute(); while ($donnees = $req->fetch()) { $account = new Account(); $account->setId($donnees['id']); $account->setAccount_name($donnees['account_name']); $account->setIdentifiant($donnees['identifiant']); $account->setAccount_mdp($donnees['account_mdp']); $account->setAccount_groupe($donnees['account_groupe']); $accounts[] = $account; }; return $accounts; } public function decryptById($id){ $bdd = $this->getBdd(); $req = $bdd->prepare('SELECT account_mdp FROM account WHERE id=:id'); $req->bindValue('id', $id); $req->execute(); $donnees = $req->fetch(); $pass_hash = $donnees['account_mdp']; return $pass_hash; } public function pseudoById($id){ $bdd = $this->getBdd(); $req = $bdd->prepare('SELECT identifiant FROM account WHERE id=:id'); $req->bindValue('id', $id); $req->execute(); $donnees = $req->fetch(); $pseudo = $donnees['identifiant']; return $pseudo; } }
true
6c5ce298ad6ecdc5b31c81dee664e7e61dcae349
PHP
owenvoke/PHPTorrent
/src/Logger/Logger.php
UTF-8
2,090
3
3
[ "Zlib" ]
permissive
<?php namespace genaside\PHPTorrent\Logger; use genaside\PHPTorrent\Config\Config; /** * Class Logger * @package genaside\PHPTorrent\Logger */ class Logger { // Message types const STATUS = 1; const CRITICAL = 2; // exit program const WARNING = 3; const DEBUG = 4; /** * @param string $programName * @param int $type * @param string $message */ public static function logMessage($programName, $type, $message) { $dateTime = date('Y-m-d H:i:s'); switch ($type) { case self::STATUS: $type_str = 'Status'; break; case self::CRITICAL: $type_str = 'Critical'; break; case self::WARNING: $type_str = 'Warning'; break; case self::DEBUG: default: $type_str = 'Debug'; break; } $message_log = "[$dateTime][$programName][$type_str]: $message\n"; $report = function () use (&$message_log) { if (Config::ENABLE_LOGGING_ON_STDOUT) { // Output message to console echo $message_log; } // Log the message error_log($message_log, 3, Config::LOGFILE_LOCATION); }; //TODO CHECK file permissions if (Config::LOG_LEVEL == 1) { switch ($type) { case self::STATUS: case self::CRITICAL: case self::WARNING: $report(); break; default: break; } } else { if (Config::LOG_LEVEL == 2) { switch ($type) { case self::STATUS: case self::CRITICAL: case self::WARNING: case self::DEBUG: $report(); break; default: break; } } } } }
true
f9eb09bcbd4bc0078b5a6fd85e4c03fc9a1db447
PHP
felipecechin/company-system
/Class/Funcionario.class.php
UTF-8
664
3.1875
3
[]
no_license
<?php class Funcionario extends Pessoa { protected $profissao; public $salario; protected $empresa, $poupanca; function __construct($nome, $idade, $endereco, $profissao) { parent::__construct($nome, $idade, $endereco); $this->poupanca = 1000; $this->profissao = $profissao; } function Atuar($profissao, $salario, $empresa) { $this->profissao = $profissao; $this->salario = $salario; $this->empresa = $empresa; } function receberSalario($sal) { $this->poupanca += $sal; } function ver() { return var_dump($this); } } ?>
true
8cc885c15c8b58841c0cc7ae9df155253f0a543c
PHP
extremeframework/extremeframework
/library/external/PEAR/Image/Graph.php
WINDOWS-1252
26,800
2.734375
3
[ "MIT" ]
permissive
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Image_Graph - Main class for the graph creation. * * PHP versions 4 and 5 * * LICENSE: This library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or (at your * option) any later version. This library 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 Lesser * General Public License for more details. You should have received a copy of * the GNU Lesser General Public License along with this library; if not, write * to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * @category Images * @package Image_Graph * @author Jesper Veggerby <pear.nosey@veggerby.dk> * @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version CVS: $Id: Graph.php,v 1.58 2005/11/27 18:48:05 nosey Exp $ * @link http://pear.php.net/package/Image_Graph */ /** * Include PEAR.php */ require_once 'PEAR.php'; /** * Include file Image/Graph/Element.php */ require_once 'Image/Graph/Element.php'; /** * Include file Image/Graph/Constants.php */ require_once 'Image/Graph/Constants.php'; /** * Main class for the graph creation. * * This is the main class, it manages the canvas and performs the final output * by sequentialy making the elements output their results. The final output is * handled using the {@link Image_Canvas} classes which makes it possible * to use different engines (fx GD, PDFlib, libswf, etc) for output to several * formats with a non-intersecting API. * * This class also handles coordinates and the correct managment of setting the * correct coordinates on child elements. * * @category Images * @package Image_Graph * @author Jesper Veggerby <pear.nosey@veggerby.dk> * @copyright Copyright (C) 2003, 2004 Jesper Veggerby Hansen * @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1 * @version Release: @package_version@ * @link http://pear.php.net/package/Image_Graph */ class Image_Graph extends Image_Graph_Element { /** * Show generation time on graph * @var bool * @access private */ var $_showTime = false; /** * Display errors on the canvas * @var boolean * @access private */ var $_displayErrors = false; /** * Image_Graph [Constructor]. * * If passing the 3 parameters they are defined as follows:' * * Fx.: * * $Graph =& new Image_Graph(400, 300); * * or using the factory method: * * $Graph =& Image_Graph::factory('graph', array(400, 300)); * * This causes a 'png' canvas to be created by default. * * Otherwise use a single parameter either as an associated array or passing * the canvas along to the constructor: * * 1) Create a new canvas with the following parameters: * * 'canvas' - The canvas type, can be any of 'gd', 'jpg', 'png' or 'svg' * (more to come) - if omitted the default is 'gd' * * 'width' - The width of the graph * * 'height' - The height of the graph * * An example of this usage: * * $Graph =& Image_Graph::factory('graph', array(array('width' => 400, * 'height' => 300, 'canvas' => 'jpg'))); * * NB! In ths case remember the "double" array (see {@link Image_Graph:: * factory()}) * * 2) Use the canvas specified, pass a valid Image_Canvas as * parameter. Remember to pass by reference, i. e. &amp;$canvas, fx.: * * $Graph =& new Image_Graph($Canvas); * * or using the factory method: * * $Graph =& Image_Graph::factory('graph', $Canvas)); * * @param mixed $params The width of the graph, an indexed array * describing a new canvas or a valid {@link Image_Canvas} object * @param int $height The height of the graph in pixels * @param bool $createTransparent Specifies whether the graph should be * created with a transparent background (fx for PNG's - note: transparent * PNG's is not supported by Internet Explorer!) */ function Image_Graph($params, $height = false, $createTransparent = false) { parent::Image_Graph_Element(); $this->setFont(Image_Graph::factory('Image_Graph_Font')); if (defined('IMAGE_GRAPH_DEFAULT_CANVAS_TYPE')) { $canvasType = IMAGE_GRAPH_DEFAULT_CANVAS_TYPE; } else { $canvasType = 'png'; // use GD as default, if nothing else is specified } if (is_array($params)) { if (isset($params['canvas'])) { $canvasType = $params['canvas']; } $width = 0; $height = 0; if (isset($params['width'])) { $width = $params['width']; } if (isset($params['height'])) { $height = $params['height']; } } elseif (is_a($params, 'Image_Canvas')) { $this->_canvas =& $params; $width = $this->_canvas->getWidth(); $height = $this->_canvas->getHeight(); } elseif (is_numeric($params)) { $width = $params; } if ($this->_canvas == null) { include_once 'Image/Canvas.php'; $this->_canvas =& Image_Canvas::factory( $canvasType, array('width' => $width, 'height' => $height) ); } $this->_setCoords(0, 0, $width - 1, $height - 1); } /** * Gets the canvas for this graph. * * The canvas is set by either passing it to the constructor {@link * Image_Graph::ImageGraph()} or using the {@link Image_Graph::setCanvas()} * method. * * @return Image_Canvas The canvas used by this graph * @access private * @since 0.3.0dev2 */ function &_getCanvas() { return $this->_canvas; } /** * Sets the canvas for this graph. * * Calling this method makes this graph use the newly specified canvas for * handling output. This method should be called whenever multiple * 'outputs' are required. Invoke this method after calls to {@link * Image_Graph:: done()} has been performed, to switch canvass. * * @param Image_Canvas $canvas The new canvas * @return Image_Canvas The new canvas * @since 0.3.0dev2 */ function &setCanvas(&$canvas) { if (!is_a($this->_canvas, 'Image_Canvas')) { return $this->_error('The canvas introduced is not an Image_Canvas object'); } $this->_canvas =& $canvas; $this->_setCoords( 0, 0, $this->_canvas->getWidth() - 1, $this->_canvas->getHeight() - 1 ); return $this->_canvas; } /** * Gets a very precise timestamp * * @return The number of seconds to a lot of decimals * @access private */ function _getMicroTime() { list($usec, $sec) = explode(' ', microtime()); return ((float)$usec + (float)$sec); } /** * Gets the width of this graph. * * The width is returned as 'defined' by the canvas. * * @return int the width of this graph */ function width() { return $this->_canvas->getWidth(); } /** * Gets the height of this graph. * * The height is returned as 'defined' by the canvas. * * @return int the height of this graph */ function height() { return $this->_canvas->getHeight(); } /** * Enables displaying of errors on the output. * * Use this method to enforce errors to be displayed on the output. Calling * this method makes PHP uses this graphs error handler as default {@link * Image_Graph::_default_error_handler()}. */ function displayErrors() { $this->_displayErrors = true; set_error_handler(array(&$this, '_default_error_handler')); } /** * Sets the log method for this graph. * * Use this method to enable logging. This causes any errors caught * by either the error handler {@see Image_Graph::displayErrors()} * or explicitly by calling {@link Image_Graph_Common::_error()} be * logged using the specified logging method. * * If a filename is specified as log method, a Log object is created (using * the 'file' handler), with a handle of 'Image_Graph Error Log'. * * Logging requires {@link Log}. * * @param mixed $log The log method, either a Log object or filename to log * to * @since 0.3.0dev2 */ function setLog($log) { } /** * Factory method to create Image_Graph objects. * * Used for 'lazy including', i.e. loading only what is necessary, when it * is necessary. If only one parameter is required for the constructor of * the class simply pass this parameter as the $params parameter, unless the * parameter is an array or a reference to a value, in that case you must * 'enclose' the parameter in an array. Similar if the constructor takes * more than one parameter specify the parameters in an array, i.e * * Image_Graph::factory('MyClass', array($param1, $param2, &$param3)); * * Variables that need to be passed by reference *must* have the &amp; * before the variable, i.e: * * Image_Graph::factory('line', &$Dataset); * * or * * Image_graph::factory('bar', array(array(&$Dataset1, &$Dataset2), * 'stacked')); * * Class name can be either of the following: * * 1 The 'real' Image_Graph class name, i.e. Image_Graph_Plotarea or * Image_Graph_Plot_Line * * 2 Short class name (leave out Image_Graph) and retain case, i.e. * Plotarea, Plot_Line *not* plot_line * * 3 Class name 'alias', the following are supported: * * 'graph' = Image_Graph * * 'plotarea' = Image_Graph_Plotarea * * 'line' = Image_Graph_Plot_Line * * 'area' = Image_Graph_Plot_Area * * 'bar' = Image_Graph_Plot_Bar * * 'pie' = Image_Graph_Plot_Pie * * 'radar' = Image_Graph_Plot_Radar * * 'step' = Image_Graph_Plot_Step * * 'impulse' = Image_Graph_Plot_Impulse * * 'dot' or 'scatter' = Image_Graph_Plot_Dot * * 'smooth_line' = Image_Graph_Plot_Smoothed_Line * * 'smooth_area' = Image_Graph_Plot_Smoothed_Area * 'dataset' = Image_Graph_Dataset_Trivial * * 'random' = Image_Graph_Dataset_Random * * 'function' = Image_Graph_Dataset_Function * * 'vector' = Image_Graph_Dataset_VectorFunction * * 'category' = Image_Graph_Axis_Category * * 'axis' = Image_Graph_Axis * * 'axis_log' = Image_Graph_Axis_Logarithmic * * 'title' = Image_Graph_Title * * 'line_grid' = Image_Graph_Grid_Lines * * 'bar_grid' = Image_Graph_Grid_Bars * * 'polar_grid' = Image_Graph_Grid_Polar * * 'legend' = Image_Graph_Legend * * 'font' = Image_Graph_Font * * 'ttf_font' = Image_Graph_Font * * 'Image_Graph_Font_TTF' = Image_Graph_Font (to maintain BC with Image_Graph_Font_TTF) * * 'gradient' = Image_Graph_Fill_Gradient * * 'icon_marker' = Image_Graph_Marker_Icon * * 'value_marker' = Image_Graph_Marker_Value * * @param string $class The class for the new object * @param mixed $params The paramaters to pass to the constructor * @return object A new object for the class * @static */ function &factory($class, $params = null) { static $Image_Graph_classAliases = array( 'graph' => 'Image_Graph', 'plotarea' => 'Image_Graph_Plotarea', 'line' => 'Image_Graph_Plot_Line', 'area' => 'Image_Graph_Plot_Area', 'bar' => 'Image_Graph_Plot_Bar', 'smooth_line' => 'Image_Graph_Plot_Smoothed_Line', 'smooth_area' => 'Image_Graph_Plot_Smoothed_Area', 'pie' => 'Image_Graph_Plot_Pie', 'radar' => 'Image_Graph_Plot_Radar', 'step' => 'Image_Graph_Plot_Step', 'impulse' => 'Image_Graph_Plot_Impulse', 'dot' => 'Image_Graph_Plot_Dot', 'scatter' => 'Image_Graph_Plot_Dot', 'dataset' => 'Image_Graph_Dataset_Trivial', 'random' => 'Image_Graph_Dataset_Random', 'function' => 'Image_Graph_Dataset_Function', 'vector' => 'Image_Graph_Dataset_VectorFunction', 'category' => 'Image_Graph_Axis_Category', 'axis' => 'Image_Graph_Axis', 'axis_log' => 'Image_Graph_Axis_Logarithmic', 'title' => 'Image_Graph_Title', 'line_grid' => 'Image_Graph_Grid_Lines', 'bar_grid' => 'Image_Graph_Grid_Bars', 'polar_grid' => 'Image_Graph_Grid_Polar', 'legend' => 'Image_Graph_Legend', 'font' => 'Image_Graph_Font', 'ttf_font' => 'Image_Graph_Font', 'Image_Graph_Font_TTF' => 'Image_Graph_Font', // BC with Image_Graph_Font_TTF 'gradient' => 'Image_Graph_Fill_Gradient', 'icon_marker' => 'Image_Graph_Marker_Icon', 'value_marker' => 'Image_Graph_Marker_Value' ); if (substr($class, 0, 11) != 'Image_Graph') { if (isset($Image_Graph_classAliases[$class])) { $class = $Image_Graph_classAliases[$class]; } else { $class = 'Image_Graph_' . $class; } } include_once str_replace('_', '/', $class) . '.php'; $obj = null; if (is_array($params)) { switch (count($params)) { case 1: $obj =& new $class( $params[0] ); break; case 2: $obj =& new $class( $params[0], $params[1] ); break; case 3: $obj =& new $class( $params[0], $params[1], $params[2] ); break; case 4: $obj =& new $class( $params[0], $params[1], $params[2], $params[3] ); break; case 5: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4] ); break; case 6: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4], $params[5] ); break; case 7: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4], $params[5], $params[6] ); break; case 8: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4], $params[5], $params[6], $params[7] ); break; case 9: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4], $params[5], $params[6], $params[7], $params[8] ); break; case 10: $obj =& new $class( $params[0], $params[1], $params[2], $params[3], $params[4], $params[5], $params[6], $params[7], $params[8], $params[9] ); break; default: $obj =& new $class(); break; } } else { if ($params == null) { $obj =& new $class(); } else { $obj =& new $class($params); } } return $obj; } /** * Factory method to create layouts. * * This method is used for easy creation, since using {@link Image_Graph:: * factory()} does not work with passing newly created objects from * Image_Graph::factory() as reference, this is something that is * fortunately fixed in PHP5. Also used for 'lazy including', i.e. loading * only what is necessary, when it is necessary. * * Use {@link Image_Graph::horizontal()} or {@link Image_Graph::vertical()} * instead for easier access. * * @param mixed $layout The type of layout, can be either 'Vertical' * or 'Horizontal' (case sensitive) * @param Image_Graph_Element $part1 The 1st part of the layout * @param Image_Graph_Element $part2 The 2nd part of the layout * @param int $percentage The percentage of the layout to split at * @return Image_Graph_Layout The newly created layout object * @static */ function &layoutFactory($layout, &$part1, &$part2, $percentage = 50) { if (($layout != 'Vertical') && ($layout != 'Horizontal')) { return $this->_error('Layouts must be either \'Horizontal\' or \'Vertical\''); } if (!(is_a($part1, 'Image_Graph_Element'))) { return $this->_error('Part 1 is not a valid Image_Graph element'); } if (!(is_a($part2, 'Image_Graph_Element'))) { return $this->_error('Part 2 is not a valid Image_Graph element'); } if ((!is_numeric($percentage)) || ($percentage < 0) || ($percentage > 100)) { return $this->_error('Percentage has to be a number between 0 and 100'); } include_once "Image/Graph/Layout/$layout.php"; $class = "Image_Graph_Layout_$layout"; $obj =& new $class($part1, $part2, $percentage); return $obj; } /** * Factory method to create horizontal layout. * * See {@link Image_Graph::layoutFactory()} * * @param Image_Graph_Element $part1 The 1st (left) part of the layout * @param Image_Graph_Element $part2 The 2nd (right) part of the layout * @param int $percentage The percentage of the layout to split at * (percentage of total height from the left side) * @return Image_Graph_Layout The newly created layout object * @static */ function &horizontal(&$part1, &$part2, $percentage = 50) { $obj =& Image_Graph::layoutFactory('Horizontal', $part1, $part2, $percentage); return $obj; } /** * Factory method to create vertical layout. * * See {@link Image_Graph::layoutFactory()} * * @param Image_Graph_Element $part1 The 1st (top) part of the layout * @param Image_Graph_Element $part2 The 2nd (bottom) part of the layout * @param int $percentage The percentage of the layout to split at * (percentage of total width from the top edge) * @return Image_Graph_Layout The newly created layout object * @static */ function &vertical(&$part1, &$part2, $percentage = 50) { $obj =& Image_Graph::layoutFactory('Vertical', $part1, $part2, $percentage); return $obj; } /** * The error handling routine set by set_error_handler(). * * This method is used internaly by Image_Graph and PHP as a proxy for {@link * Image_Graph::_error()}. * * @param string $error_type The type of error being handled. * @param string $error_msg The error message being handled. * @param string $error_file The file in which the error occurred. * @param integer $error_line The line in which the error occurred. * @param string $error_context The context in which the error occurred. * @access private */ function _default_error_handler($error_type, $error_msg, $error_file, $error_line, $error_context) { switch( $error_type ) { case E_ERROR: $level = 'error'; break; case E_USER_ERROR: $level = 'user error'; break; case E_WARNING: $level = 'warning'; break; case E_USER_WARNING: $level = 'user warning'; break; case E_NOTICE: $level = 'notice'; break; case E_USER_NOTICE: $level = 'user notice'; break; default: $level = '(unknown)'; break; } $this->_error("PHP $level: $error_msg", array( 'type' => $error_type, 'file' => $error_file, 'line' => $error_line, 'context' => $error_context ) ); } /** * Displays the errors on the error stack. * * Invoking this method cause all errors on the error stack to be displayed * on the graph-output, by calling the {@link Image_Graph::_displayError()} * method. * * @access private */ function _displayErrors() { return true; } /** * Display an error from the error stack. * * This method writes error messages caught from the {@link Image_Graph:: * _default_error_handler()} if {@Image_Graph::displayErrors()} was invoked, * and the error explicitly set by the system using {@link * Image_Graph_Common::_error()}. * * @param int $x The horizontal position of the error message * @param int $y The vertical position of the error message * @param array $error The error context * * @access private */ function _displayError($x, $y, $error) { } /** * Outputs this graph using the canvas. * * This causes the graph to make all elements perform their output. Their * result is 'written' to the output using the canvas, which also performs * the actual output, fx. it being to a file or directly to the browser * (in the latter case, the canvas will also make sure the correct HTTP * headers are sent, making the browser handle the output correctly, if * supported by it). * * Parameters are the ones supported by the canvas, common ones are: * * 'filename' To output to a file instead of browser * * 'tohtml' Return a HTML string that encompasses the current graph/canvas - this * implies an implicit save using the following parameters: 'filename' The "temporary" * filename of the graph, 'filepath' A path in the file system where Image_Graph can * store the output (this file must be in DOCUMENT_ROOT scope), 'urlpath' The URL that the * 'filepath' corresponds to (i.e. filepath + filename must be reachable from a browser using * urlpath + filename) * * @param mixed $param The output parameters to pass to the canvas * @return bool Was the output 'good' (true) or 'bad' (false). */ function done($param = false) { $result = $this->_reset(); if (PEAR::isError($result)) { return $result; } return $this->_done($param); } /** * Outputs this graph using the canvas. * * This causes the graph to make all elements perform their output. Their * result is 'written' to the output using the canvas, which also performs * the actual output, fx. it being to a file or directly to the browser * (in the latter case, the canvas will also make sure the correct HTTP * headers are sent, making the browser handle the output correctly, if * supported by it). * * @param mixed $param The output parameters to pass to the canvas * @return bool Was the output 'good' (true) or 'bad' (false). * @access private */ function _done($param = false) { $timeStart = $this->_getMicroTime(); if ($this->_shadow) { $this->setPadding(20); $this->_setCoords( $this->_left, $this->_top, $this->_right - 10, $this->_bottom - 10); } $result = $this->_updateCoords(); if (PEAR::isError($result)) { return $result; } if ($this->_getBackground()) { $this->_canvas->rectangle( array( 'x0' => $this->_left, 'y0' => $this->_top, 'x1' => $this->_right, 'y1' => $this->_bottom ) ); } $result = parent::_done(); if (PEAR::isError($result)) { return $result; } if ($this->_displayErrors) { $this->_displayErrors(); } $timeEnd = $this->_getMicroTime(); if (($this->_showTime) || ((isset($param['showtime'])) && ($param['showtime'] === true)) ) { $text = 'Generated in ' . sprintf('%0.3f', $timeEnd - $timeStart) . ' sec'; $this->write( $this->_right, $this->_bottom, $text, IMAGE_GRAPH_ALIGN_RIGHT + IMAGE_GRAPH_ALIGN_BOTTOM, array('color' => 'red') ); } if (isset($param['filename'])) { if ((isset($param['tohtml'])) && ($param['tohtml'])) { return $this->_canvas->toHtml($param); } else { return $this->_canvas->save($param); } } else { return $this->_canvas->show($param); } } } ?>
true
62eee892dfee2858e9986aa9acf24ace5c7b1bd6
PHP
shrink0r/workflux
/src/Param/Input.php
UTF-8
1,222
2.84375
3
[ "MIT" ]
permissive
<?php namespace Workflux\Param; use Workflux\Param\InputInterface; use Workflux\Param\OutputInterface; use Workflux\Param\ParamHolderTrait; final class Input implements InputInterface { use ParamHolderTrait; /** * @var string $event */ private $event; /** * @param mixed[] $params * @param string $event */ public function __construct(array $params = [], string $event = '') { $this->params = $params; $this->event = $event; } /** * @return string */ public function getEvent(): string { return $this->event; } /** * @return boolean */ public function hasEvent(): bool { return !empty($this->event); } /** * @param string $event * @return InputInterface */ public function withEvent(string $event): InputInterface { $clone = clone $this; $clone->event = $event; return $clone; } /** * @param OutputInterface $output * * @return InputInterface */ public static function fromOutput(OutputInterface $output): InputInterface { return new static($output->toArray()['params']); } }
true
a0455531c1fcbd7947db11efbf34e7a5858455c9
PHP
riki1/smr2b_ricardo
/Else b.php
UTF-8
144
2.828125
3
[]
no_license
<?php $nota = 6.5; $r= 'PENDIENTE'; if ($nota>=5) $r= 'APROBADO'; if($nota>=7) $r='NOTABLE'; if ($nota>=8.5) $r= 'SOBRESALIENTE'; echo $r;
true
07735c4fa87e02e597ccf51a819291ca202fa9c7
PHP
punkstar/snake
/lib/snake.php
UTF-8
2,410
3.453125
3
[]
no_license
<?php class Snake { public static $NORTH = 2; public static $EAST = 3; public static $SOUTH = 4; public static $WEST = 5; protected $_length = 1; protected $_trail = null; protected $_head; public function __construct($length) { $this->_setLength($length); $this->_head = new Coord(0, 0); } protected function _setLength($length) { $this->_length = $length; if ($this->_trail == null) { $this->_trail = new Queue($length); } else { $this->_trail->setSize($length); } } public function getPosition() { return $this->_head; } public function grow() { $this->_setLength($this->_length + 1); } public function moveSouth() { $this->_trail->add(clone $this->_head); $this->_head->add(0, 1); } public function moveNorth() { $this->_trail->add(clone $this->_head); $this->_head->add(0, -1); } public function moveEast() { $this->_trail->add(clone $this->_head); $this->_head->add(1, 0); } public function moveWest() { $this->_trail->add(clone $this->_head); $this->_head->add(-1, 0); } public function move($direction) { switch ($direction) { case self::$NORTH: $this->moveNorth(); break; case self::$EAST: $this->moveEast(); break; case self::$SOUTH: $this->moveSouth(); break; case self::$WEST: $this->moveWest(); break; default: trigger_error("I've no idea which direction you want me to travel in!"); } } public function getRandomDirection() { return rand(self::$NORTH, self::$WEST); } public function clockwiseMoveDirection($direction) { return (((($direction - 2) + 1) % 4) + 2); } public function getOccupiedCells() { } public function toArray() { $trail_array = array(); return array( "head" => $this->_head->toArray(), "body" => array_map(function ($el) { return $el->toArray(); }, $this->_trail->toArray()) ); } }
true
f71c95999cc729769f7ce007ece315f8ddd264b1
PHP
leonardoivo/Trilhos-Do-Rio
/Acervo/Livros/TesteComSecao.php
UTF-8
234
2.875
3
[]
no_license
<?php session_start(); // store session data $_SESSION['views']=1; $_SESSION['name']="Leonardo Ivo"; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; echo "Nome:".$_SESSION['name']; ?> </body> </html>
true