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
163efb6e12b26032f12b38755bdded3327c02dbd
PHP
krampy7/Momoh
/session.php
UTF-8
370
2.75
3
[ "MIT" ]
permissive
<?php #Esta plantilla o pagina de código es para el inicio de sesión #Función para iniciar sesión session_start(); #Se pasan los datos (Nombre de usaurio) dados por el usuario a una variable $usuario=$_POST['USUARIO']; #Da bienvenida al usuario junto con su nombre echo "Bienvenido ".$usuario; #Variable de sesión $_SESSION['USUARIO']=$_usuario; ?>
true
83f38927ee39663f65545767303050dde2bb79a0
PHP
redrails/PHP
/DateDiff/index.php
UTF-8
4,485
3.171875
3
[]
no_license
<?php class Duration { public $date_1; public $date_2; function __construct($date_1, $date_2){ if(empty($date_1)){ $date = date("Y-m-d"); $time = date("h:i:s"); $this->datetime = $date ." ". $time; $this->date_1 = $this->datetime; } else { $this->date_1 = $date_1; } $this->date_2 = $date_2; } function DaysBetween(){ $this->date_1_class = new Datetime($this->date_1); $this->date_2_class = new Datetime($this->date_2); $this->result = $this->date_1_class->diff($this->date_2_class); return($this->result->format('%d days, %m months, %y years // %h hours, %i minutes, %s seconds')); } } if(isset($_POST['calculate'])){ $firstDay = $_POST['day1']; $firstMonth = $_POST['month1']; $firstYear = $_POST['year1']; $secondDay = $_POST['day2']; $secondMonth = $_POST['month2']; $secondYear = $_POST['year2']; if(!empty($firstDay)){ $constructDateOne = "$firstYear-$firstMonth-$firstDay"; } elseif(empty($firstDay) || empty($firstMonth)){ $constructDateOne = ""; } $constructDateTwo = "$secondYear-$secondMonth-$secondDay"; $constructClass = new Duration($constructDateOne, $constructDateTwo); $final = $constructClass->DaysBetween(); } ?> <html> <style type="text/css"> body{ background:#EEE; color:black; text-shadow:1px 1px 5px grey; font-family:Calibri; margin-top:10%; text-align:center; } #box{ width:100%; border:1px dashed Grey; padding-top: 20px; height:150px; } input.button{ color:#EEE; background:Grey; text-shadow:1px 1px 5px grey; font-family:Calibri; } input.button:hover{ color:#EEE; background:LightGrey; text-shadow:1px 1px 5px grey; font-family:Calibri; } </style> <body> <center> <h1>Duration calculator!</h1><hr /><br> <div id="box"> <table border="1" bordercolor="#FFCC00" style="background-color:#FFFFCC" width="" cellpadding="2" cellspacing="3"> <form action="#" method="post"> <tr> <td>Start Date (Day, Month, Year)(Leave empty for today's date): </td> <td><input type="text" name="day1"></td> <td><select name="month1"> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select></td> <td><input type="text" name="year1"> </tr> <tr> <td>End Date (Day, Month, Year): </td> <td><input type="text" name="day2"></td> <td><select name="month2"> <option value="01">January</option> <option value="02">February</option> <option value="03">March</option> <option value="04">April</option> <option value="05">May</option> <option value="06">June</option> <option value="07">July</option> <option value="08">August</option> <option value="09">September</option> <option value="10">October</option> <option value="11">November</option> <option value="12">December</option> </select></td> <td><input type="text" name="year2"></td> </tr> <tr><td><input type="submit" name="calculate" value="Find Distance!"></td></tr> </form> </table> </div> </center> <?php echo "<h1>". $final ."</h1>"; ?> </body> </html>
true
29de310e88af2a0ccb3171a65cc79e5ad897b103
PHP
anggymaryati/ecommerce_phpnative
/serviceforajax/showdatatshirtedit.php
UTF-8
626
2.515625
3
[]
no_license
<?php include("../config/config.php"); include("../classes/utility.php"); include("../classes/database.php"); include("../classes/t-shirt.php"); $tshirt_obj = new tshirt($_REQUEST["tshirt_id"],true); echo "{"; echo "\"tshirt_name\":" . "\"" . $tshirt_obj->tshirt_name() . "\","; echo "\"tshirt_id\":" . "\"" . $tshirt_obj->tshirt_id() . "\","; echo "\"brand_id\":" . "\"" . $tshirt_obj->brand_id() . "\","; echo "\"price\":" . "\"" . $tshirt_obj->price() . "\","; echo "\"stock\":" . "\"" .$tshirt_obj->stock() . "\","; echo "\"description\":" . "\"" .$tshirt_obj->description() . "\""; echo "}"; ?>
true
a42d801e1ee524fcd0113d0bc5a4601010478358
PHP
amrtgaber/MCED-Database
/load_contact_form.php
UTF-8
14,824
2.609375
3
[]
no_license
<?php /* File: load_contact_form.php * Author: Amr Gaber * Created: 02/10/2012 * Description: Returns the contact add/update form for KC99 database. */ include( "db_credentials.php" ); include( "common.php" ); /* Must be logged in for this to work */ if( !$_SESSION[ 'username' ] ) { header( "Location: login.php" ); exit; } /* Connect to database */ $mc = connect_to_database(); if( $_GET[ 'add' ] ) { $cinfo = Array(); } else { $id = mysql_real_escape_string( $_GET[ 'id' ] ); /* Get contact information */ $qs = "SELECT contacts.*, contact_email.*, workers.*, students.*, contact_action.* FROM contacts LEFT JOIN contact_email ON contacts.id = contact_email.cid LEFT JOIN workers ON contacts.id = workers.cid LEFT JOIN students ON contacts.id = students.cid LEFT JOIN contact_action ON contacts.id = contact_action.cid WHERE contacts.id = " . $id; $qr = execute_query( $qs, $mc ); $cinfo = mysql_fetch_array( $qr ); } ?> <div class="well" id="main"> <div class="row-fluid"> <div class="span1">First Name</div> <div class="span5"> <input type="text" name="firstName" class="span12" value="<?php echo( $cinfo[ 'first_name' ] ); ?>" placeholder="Type first name here"> </div> <div class="span1">Last Name</div> <div class="span5"> <input type="text" name="lastName" class="span12" value="<?php echo( $cinfo[ 'last_name' ] ); ?>" placeholder="Type last name here"> </div> </div> <div class="row-fluid"> <div class="span1">Address</div> <div class="span8"> <input type="text" name="address" class="span12" value="<?php echo( $cinfo[ 'street_no' ] ); ?>" placeholder="Type address here"> </div> <div class="span1">Apt. no.</div> <div class="span2"> <input type="text" name="aptNo" class="span12" value="<?php echo( $cinfo[ 'apt_no' ] ); ?>" placeholder="Type Apt. no. here"> </div> </div> <div class="row-fluid"> <div class="span1">City</div> <div class="span6"> <input type="text" name="city" class="span12" value="<?php echo( $cinfo[ 'city' ] ); ?>" placeholder="Type city here"> </div> <div class="span1">State</div> <div class="span1"> <input type="text" name="state" class="span12" value="<?php echo( $cinfo[ 'state' ] ); ?>" placeholder="State"> </div> <div class="span1">Zipcode</div> <div class="span2"> <input type="text" name="zipcode" class="span12" value="<?php echo( $cinfo[ 'zipcode' ] ); ?>" placeholder="Type zipcode here"> </div> </div> <div class="row-fluid"> <?php if( $_GET[ "id" ] ) { $qs = "SELECT contact_phone.* FROM contact_phone WHERE cid = " . $cinfo[ 'id' ] . " AND main = 1"; $pqr = execute_query( $qs, $mc ); $pinfo1 = mysql_fetch_array( $pqr ); } else { $pinfo1 = Array(); } ?> <div class="span1">Phone</div> <div class="span3"> <input type="text" name="phone1" class="span12" value="<?php echo( $pinfo1[ 'phone' ] ); ?>" placeholder="Type phone number here"> </div> <div class="span2"> <label class="checkbox inline">Cell</label> <input type="checkbox" name="cell1" value="true" <?php if( ord( $pinfo1[ 'cell' ] ) == 1 ) { echo( "checked" ); } ?>> </div> <div class="span2"> <label class="checkbox inline">Text</label> <input type="checkbox" name="text1" value="true" <?php if( ord( $pinfo1[ 'text_updates' ] ) == 1 ) { echo( "checked" ); } ?>> </div> </div> <div class="row-fluid"> <div class="span1">Email</div> <div class="span5"> <input type="text" name="email" class="span12" value="<?php echo( $cinfo[ 'email' ] ); ?>" placeholder="Type email here"> </div> </div> <div class="row-fluid"> <h5>Workplaces</h5> </div> <div class="row-fluid"> <?php if( $_GET[ "id" ] ) { $qs = "SELECT workers.wid, workers.wage, workplaces.wname FROM workers LEFT JOIN workplaces ON workers.wid = workplaces.wid WHERE workers.cid = " . $id . " ORDER BY workplaces.wname"; $cwqr = execute_query( $qs, $mc ); while( $winfo = mysql_fetch_array( $cwqr ) ) { ?> <div class="row-fluid"> <div class="span1"></div> <div class="span5"> <select id="workplace" class="span12 workplace-select"> <option>&lt; select a workplace &gt;</option> <?php $qs = "SELECT wid, wname, street_no FROM workplaces ORDER BY wname"; $wqr = execute_query( $qs, $mc ); while( $workplace = mysql_fetch_array( $wqr ) ) { ?> <option data-wid="<?php echo( $workplace[ 'wid' ] ); ?>" <?php if( $workplace[ "wid" ] == $winfo[ "wid" ] ) { echo( "selected" ); $wid = $winfo[ "wid" ]; $wage = $winfo[ "wage" ]; } ?>> <?php echo( $workplace[ "wname" ] . " " . $workplace[ "street_no" ] ); ?> </option> <?php } ?> </select> </div> <div class="span1">Wage</div> <div class="span1 input-prepend"> <span class="add-on">$</span><input type="text" class="span12 wage" data-wid="<?php echo( $wid ); ?>" value="<?php echo( $wage ); ?>"> </div> </div> <?php } ?> <?php } ?> <div class="row-fluid"> <div class="span1"></div> <div class="span5"> <select id="workplace" class="span12 workplace-select" data-last="true"> <option>&lt; select a workplace &gt;</option> <?php $qs = "SELECT wid, wname, street_no FROM workplaces ORDER BY wname"; $wqr = execute_query( $qs, $mc ); while( $workplace = mysql_fetch_array( $wqr ) ) { ?> <option data-wid="<?php echo( $workplace[ 'wid' ] ); ?>"> <?php echo( $workplace[ "wname" ] . " " . $workplace[ "street_no" ] ); ?> </option> <?php } ?> </select> </div> <div class="span1">Wage</div> <div class="span1 input-prepend"> <span class="add-on">$</span><input type="text" class="span12 wage" data-wid=""> </div> </div> </div> <div class="row-fluid"> <h5>Actions</h5> </div> <?php if( $_GET[ "id" ] ) { $qs = "SELECT aid FROM contact_action WHERE cid = " . $id; $caqr = execute_query( $qs, $mc ); while( $cainfo = mysql_fetch_array( $caqr ) ) { ?> <div class="row-fluid"> <div class="span1"></div> <div class="span5"> <select id="action" class="span12 action-select"> <option>&lt; select an action &gt;</option> <?php $qs = "SELECT aid, aname FROM actions ORDER BY aname"; $aqr = execute_query( $qs, $mc ); while( $action = mysql_fetch_array( $aqr ) ) { ?> <option data-aid="<?php echo( $action[ 'aid' ] ); ?>" <?php if( $action[ "aid" ] == $cainfo[ "aid" ] ) { echo( "selected" ); } ?>> <?php echo( $action[ "aname" ] ); ?> </option> <?php } ?> </select> </div> </div> <?php } ?> <?php } ?> <div class="row-fluid"> <div class="span1"></div> <div class="span5"> <select id="action" class="span12 action-select" data-last="true"> <option>&lt; select an action &gt;</option> <?php $qs = "SELECT aid, aname FROM actions ORDER BY aname"; $aqr = execute_query( $qs, $mc ); while( $action = mysql_fetch_array( $aqr ) ) { ?> <option data-aid="<?php echo( $action[ 'aid' ] ); ?>"> <?php echo( $action[ "aname" ] ); ?> </option> <?php } ?> </select> </div> </div> </div> <div class="well"> <?php if( $_GET[ "id" ] ) { $qs = "SELECT contact_phone.* FROM contact_phone WHERE cid = " . $cinfo[ 'id' ] . " AND main = 0"; $pqr = execute_query( $qs, $mc ); $pinfo2 = mysql_fetch_array( $pqr ); $pinfo3 = mysql_fetch_array( $pqr ); $pinfo4 = mysql_fetch_array( $pqr ); } ?> <div class="row-fluid"> <div class="span1">Phone 2</div> <div class="span3"> <input type="text" name="phone2" class="span12" value="<?php echo( $pinfo2[ 'phone' ] ); ?>" placeholder="Type phone number here"> </div> <div class="span2"> <label class="checkbox inline">Cell</label> <input type="checkbox" name="cell2" value="true" <?php if( ord( $pinfo2[ 'cell' ] ) == 1 ) { echo( "checked" ); } ?>> </div> <div class="span2"> <label class="checkbox inline">Text</label> <input type="checkbox" name="text2" value="true" <?php if( ord( $pinfo2[ 'text_updates' ] ) == 1 ) { echo( "checked" ); } ?>> </div> </div> <div class="row-fluid"> <div class="span1">Phone 3</div> <div class="span3"> <input type="text" name="phone3" class="span12" value="<?php echo( $pinfo3[ 'phone' ] ); ?>" placeholder="Type phone number here"> </div> <div class="span2"> <label class="checkbox inline">Cell</label> <input type="checkbox" name="cell3" value="true" <?php if( ord( $pinfo3[ 'cell' ] ) == 1 ) { echo( "checked" ); } ?>> </div> <div class="span2"> <label class="checkbox inline">Text</label> <input type="checkbox" name="text3" value="true" <?php if( ord( $pinfo3[ 'text_updates' ] ) == 1 ) { echo( "checked" ); } ?>> </div> </div> <div class="row-fluid"> <div class="span1">Phone 4</div> <div class="span3"> <input type="text" name="phone4" class="span12" value="<?php echo( $pinfo4[ 'phone' ] ); ?>" placeholder="Type phone number here"> </div> <div class="span2"> <label class="checkbox inline">Cell</label> <input type="checkbox" name="cell4" value="true" <?php if( ord( $pinfo4[ 'cell' ] ) == 1 ) { echo( "checked" ); } ?>> </div> <div class="span2"> <label class="checkbox inline">Text</label> <input type="checkbox" name="text4" value="true" <?php if( ord( $pinfo4[ 'text_updates' ] ) == 1 ) { echo( "checked" ); } ?>> </div> </div> <div class="row-fluid"> <div class="span1">School</div> <div class="span4"> <input type="text" name="school" class="span12" value="<?php echo( $cinfo[ 'school' ] ); ?>" placeholder="Type school here"> </div> <div class="span1">Year</div> <div class="span1 input-prepend"> <span class="add-on">20</span><input type="text" name="syear" class="span12" value="<?php echo( $cinfo[ 'syear' ] ); ?>" placeholder="year"> </div> </div> <div class="row-fluid"> <div class="span1">Notes</div> <div class="span11"> <textarea name="notes" class="span12" placeholder="Type notes here"><?php echo( $cinfo[ 'notes' ] ); ?></textarea> </div> </div> <div class="row-fluid"> <div class="span1">WIT Organizer</div> <div class="span3"> <select id="wit-organizer" class="span12"> <option>&lt; select an organizer &gt;</option> <?php $qs = "SELECT id, username FROM users ORDER BY username"; $oqr = execute_query( $qs, $mc ); while( $organizer = mysql_fetch_array( $oqr ) ) { ?> <option data-oid="<?php echo( $organizer[ 'id' ] ); ?>" <?php if( $organizer[ 'id' ] == $cinfo[ 'wit_oid' ] ) { echo( "selected" ); } ?>> <?php echo( $organizer[ "username" ] ); ?> </option> <?php } ?> </select> </div> </div> <div class="row-fluid"> <div class="span1">Contact Type</div> <div class="span2"> <select id="contactType" class="span12"> <?php $contact_type = $cinfo[ "contact_type" ]; if( !$_GET[ 'id' ] ) { $contact_type = 1; } ?> <option data-ctype="1" <?php if( $contact_type == 1 ) { echo( "selected" ); } ?>>Worker</option> <option data-ctype="2" <?php if( $contact_type == 2 ) { echo( "selected" ); } ?>>Student</option> <option data-ctype="3" <?php if( $contact_type == 3 ) { echo( "selected" ); } ?>>Supporter</option> <option data-ctype="0" <?php if( $contact_type == 0 ) { echo( "selected" ); } ?>>Other</option> </select> </div> <div class="span2"> <span class="span4">Date</span> <input type="text" name="date" id="date" class="span8" value="<?php echo( $cinfo[ 'cdate' ] ); ?>"> </div> </div> </div> <div class="row-fluid"> <div id="contact-form-status" class="alert alert-error hide"> </div> </div> <div class="row-fluid"> <?php if( $_GET[ 'add' ] ) { ?> <button type="submit" id="save-button" class="btn btn-primary btn-large">Add Contact</button> <?php } else { ?> <button type="submit" id="save-button" class="btn btn-primary btn-large">Save Changes</button> <?php } ?> <button type="button" id="cancel-button" class="btn btn-inverse btn-large">Cancel</button> <?php if( !$_GET[ 'add' ] ) { ?> <button type="button" id="delete-button" class="btn btn-danger btn-large pull-right" data-toggle="modal" data-target="#delete-modal">Delete</button> <?php } ?> </div> <div id="delete-modal" class="modal hide fade"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h3>Are you sure?</h3> </div> <div class="modal-body"> This action cannot be undone. Clicking delete will permanently remove this contact from the database. </div> <div class="modal-footer"> <button type="button" id="delete-confirm-button" class="btn btn-primary btn-danger">Delete</button> <button type="button" class="btn btn-inverse" data-dismiss="modal">Cancel</button> </div> </div>
true
e1e1fc0c0e146754599ede57807251e91931f79d
PHP
treehouselabs/queue
/src/TreeHouse/Queue/Amqp/EnvelopeInterface.php
UTF-8
3,384
2.65625
3
[ "MIT" ]
permissive
<?php namespace TreeHouse\Queue\Amqp; interface EnvelopeInterface { /** * Get the application id of the message. * * @return string The application id of the message. */ public function getAppId(); /** * Get the body of the message. * * @return string The contents of the message body. */ public function getBody(); /** * Get the content encoding of the message. * * @return string The content encoding of the message. */ public function getContentEncoding(); /** * Get the message content type. * * @return string The content type of the message. */ public function getContentType(); /** * Get the message correlation id. * * @return string The correlation id of the message. */ public function getCorrelationId(); /** * Get the delivery mode of the message. * * @return int The delivery mode of the message. */ public function getDeliveryMode(); /** * Get the delivery tag of the message. * * @return string The delivery tag of the message. */ public function getDeliveryTag(); /** * Get the exchange name on which the message was published. * * @return string The exchange name on which the message was published. */ public function getExchangeName(); /** * Get the expiration of the message. * * @return string The message expiration. */ public function getExpiration(); /** * Get a specific message header. * * @param string $headerKey Name of the header to get the value from. * * @return string|bool The contents of the specified header or false if not set. */ public function getHeader($headerKey); /** * Get the headers of the message. * * @return array An array of key value pairs associated with the message. */ public function getHeaders(); /** * Get the message id of the message. * * @return string The message id */ public function getMessageId(); /** * Get the priority of the message. * * @return string The message priority. */ public function getPriority(); /** * Get the reply-to address of the message. * * @return string The contents of the reply to field. */ public function getReplyTo(); /** * Get the routing key of the message. * * @return string The message routing key. */ public function getRoutingKey(); /** * Get the timestamp of the message. * * @return string The message timestamp. */ public function getTimestamp(); /** * Get the message type. * * @return string The message type. */ public function getType(); /** * Get the message user id. * * @return string The message user id. */ public function getUserId(); /** * Whether this is a redelivery of the message. * * If this message has been delivered and `nack()` was called, the message will be put back on the queue to be * redelivered, at which point the message will always return true when this method is called. * * @return bool true if this is a redelivery, false otherwise. */ public function isRedelivery(); }
true
e73b0c4f2e6a7ba780b8cc6fbf420bd12ca255b7
PHP
webignition/simplytestable.com
/src/Model/Plan/DistinctionDecorator.php
UTF-8
2,219
3.078125
3
[ "MIT" ]
permissive
<?php namespace App\Model\Plan; class DistinctionDecorator implements DistinctionInterface { const NUMBER_RANGE_SEPARATOR = '-'; /** * @var DistinctionInterface */ private $distinction; /** * @param DistinctionInterface $distinction */ public function __construct(DistinctionInterface $distinction) { $this->distinction = $distinction; } /** * {@inheritdoc} */ public function getId() { return $this->distinction->getId(); } /** * {@inheritdoc} */ public function getValue() { return $this->distinction->getValue(); } /** * {@inheritdoc} */ public function isInt() { return $this->distinction->isInt(); } /** * {@inheritdoc} */ public function isInfinity() { return $this->distinction->isInfinity(); } /** * {@inheritdoc} */ public function isBool() { return $this->distinction->isBool(); } /** * @return string */ public function __toString() { $value = $this->getValue(); if ($this->isInt()) { return number_format($value); } if (gettype($value) === 'string' && $this->isNumberRange($value)) { return $this->numberFormatRangeString($value); } if ($this->isInfinity()) { return 'Unlimited'; } if (is_null($value)) { return '&mdash;'; } return (string)$value; } /** * @param $value * @return bool */ private function isNumberRange($value) { return preg_match('/[0-9]+\s' . self::NUMBER_RANGE_SEPARATOR . '\s[0-9]+/', $value) > 0; } /** * @param $rangeString * * @return string */ private function numberFormatRangeString($rangeString) { $parts = array_map( 'trim', explode(self::NUMBER_RANGE_SEPARATOR, $rangeString) ); foreach ($parts as $index => $part) { $parts[$index] = number_format($part); } return implode($parts, ' ' . self::NUMBER_RANGE_SEPARATOR . ' '); } }
true
049afec6ad769d9a180e75355572f6fe14e3633d
PHP
ronalLeiva/curso_php_oo
/10_final_class.php
UTF-8
1,455
3.640625
4
[]
no_license
<?php /** * En ocasiones, no deseamos que una funcionalidad sea heredada, * por lo que queremos limitar la herencia para dicha clase. * * Esto se hace con el fin de evitar herencias ridículas del tipo de los * tatarabuelos, bisabuelo, abuelo, etc. * * La flexibidad que le podemos dar a nuestro código viene de una buena * abstracción, no de la herencia. */ trait myUtilities{ function sayMyName(){ echo "mi nombre es: " . $this->name . "\n"; } } abstract class Animal{ abstract public function makeSound(); public function run(){ echo "Corriendo \n"; } } class Dog extends Animal{ private $name = "Perro"; // Con esto ya tenemos acceso al trait myUlitities y acceso al método // syMyName que hará uso del atributo $name declarado aqui, localmente. use myUtilities; public function makeSound(){ echo "Guau \n"; } } class Cat extends Animal{ private $name = "Gato"; // Con esto ya tenemos acceso al trait MyUtilities y acceso al método // syMyName que hará uso del atributo $name declarado aqui, localmente. use myUtilities; public function makeSound(){ echo "Miau \n"; } } // Esta clase ya no es heredable, por que ya le colocamos que es la final // esta será la última clase que se va a instanciar. final class Schnauzer extends Dog{ public function __construct(){ $this->breed = "Shnauzer"; } } class anotherDog extends Schnauzer{ } $insSh = new Schnauzer; echo "\n";
true
47059d05b2cc025962fc51f4ff16abe63b7e54ef
PHP
ElionUser/Zaphira_Ecommerce
/route.php
UTF-8
1,860
2.6875
3
[]
no_license
<?php require_once './core/helpers.php'; class Route { public function __construct( $url , $web ) { // separa la ruta por los slashes y analiza si hay un id $id_ = $this->analyze( explode( '/' , $url ) ); if( empty( $id_ ) ) { $url = $this->replace( $url ); $this->callController( $web , $url ); } else { $url = $this->replace( $url ) .'id'; $this->callController( $web , $url , $id_); } } // devuelve el id si obtuvo uno. public function analyze( $_evaluate_id_ ) { for( $f = 0 ; $f < count ( $_evaluate_id_ ) ; $f++ ) { if ( is_numeric( $_evaluate_id_[ $f ] ) ) { return $_evaluate_id_[ $f ]; } } } // borra los numeros de la ruta public function replace( $_url_replace ) { return preg_replace( "/[0-9]+/" , '' , $_url_replace ); } // Llama al controlador y a los metodos public function callController( $_web_ , $_url_ , $_id_method = NULL) { foreach ( $_web_ as $paths ) { if ( $paths['path'] == $_url_ ) { $controller = $paths['controller']; $method = $paths['method']; include 'controller/'.$controller.'.php'; $Controller = new $controller(); $Controller->$method( $_id_method ); exit(); } } header('Location:'.helper::base_path().'/web/Error'); } } $route = new Route( $_GET['url'] , include 'web.php'); ?>
true
c1540b430726cf7ce8859ce4e6f62cc0eefcb831
PHP
EvertRdrgz/everodriguez
/hw/hw2/inc/functions.php
UTF-8
2,354
3.265625
3
[]
no_license
<?PHP function displaySymbol($randomvalue,$pos){ $symbols = array("android","apple","css","html","instagram","linux","otter","php","twitter","windows"); $randomSymbol = $symbols[$randomvalue]; echo "<img id='reel$pos' src='img/$randomSymbol.png' width='70' alt='$randomSymbol' title=\"$randomSymbol\"/>"; } function displayPoints($randomvalue1, $randomvalue2, $randomvalue3){ echo "<div id='output'>"; if ($randomvalue1 == $randomvalue2 && $randomvalue2 == $randomvalue3){ switch ($randomvalue1) { case '0': $toalPoints = 100; //android echo "<h1>Jackpot!</h1>"; break; case '1': $toalPoints = 250; //apple echo "<h1>Jackpot!</h1>"; break; case '2': $toalPoints = 500;//css echo "<h1>Jackpot!</h1>"; break; case '3': $toalPoints = 750;//html echo "<h1>Jackpot!</h1>"; break; case '4': $toalPoints = 1000;//instagram echo "<h1>Jackpot!</h1>"; break; case '5': $toalPoints = 10000;//linux echo "<h1>Jackpot!</h1>"; break; case '6': $toalPoints = 100000000;//otter echo "<h1>Jackpot!</h1>"; break; case '7': $toalPoints = 50000;//php echo "<h1>Jackpot!</h1>"; break; case '8': $toalPoints = 100000;//titter echo "<h1>Jackpot!</h1>"; break; case '9': $toalPoints = 1000000;//windows echo "<h1>Jackpot!</h1>"; break; } echo "<h2>You won $toalPoints points!</h2>"; }else{ echo "<h3>Try again!</h3>"; } echo "</div>"; } function play(){ for ($i=1; $i<4; $i++){ ${"randomValue" . $i} = rand(0,9);//# of pic - 1 displaySymbol(${"randomValue" . $i},$i); } displayPoints($randomValue1,$randomValue2,$randomValue3); } ?>
true
0337f6b1848efedee1bfc70cd0ad4229756c0fbf
PHP
eliasuardi/Registro-Virtuale
/src/DBEdit/DBEManagerSql.1.0.php
UTF-8
7,562
3.28125
3
[]
no_license
<?php // TODO // // * remove $query_result and $num_rows /** * Gestione di query SQL */ class ManagerSql { // messaggio di errore public $errore; private $hostname; private $user_name; private $user_pswd; private $user_db; // connessione a mysql server private $link; // query eseguita private $sql; // risultato della query private $query_result; private $debug; /** * Crea nuovo Manager. * * @param $config configurazione di DBEdit */ public function __construct( & $config ) { $this->hostname = $config["hostname"]; $this->user_name = $config["user_name"]; $this->user_pswd = $config["user_pswd"]; $this->user_db = $config["user_db"]; $this->debug = @$config["debug"]; $this->init(); } /** * Getters e setters */ public function get_num_fields( $query_result) { return mysql_num_fields( $query_result); } public function get_field( $query_result, $i) { return mysql_fetch_field( $query_result, $i);; } public function get_row_assoc( $query_result) { return mysql_fetch_assoc( $query_result); } public function get_row_array( $query_result) { return mysql_fetch_array( $query_result); } public function get_num_rows( $query_result) { return mysql_num_rows( $query_result); } /** * All information about a table columns * * @return array di nomi di colonne e relative info in formato mysql */ public function get_table_metadata( $table_name) { $metadata = null; $list_fields = mysql_list_fields($this->user_db, $table_name); if (! $list_fields) { $this->set_error( "DB Error, could not get metadata." ); return $metadata; } $num_fields = mysql_num_fields($list_fields); for ($i=0; (($i<$num_fields) && ($info_field = mysql_fetch_field($list_fields, $i))); $i++) { // aggiungi field flags e salva table metadata $info_field->field_flags = mysql_field_flags($list_fields, $i); $metadata[$info_field->name] = $info_field; } return $metadata; } /** * Esegui SQL select * * @return int risultato di mysql_query() */ public function query( $sql) { $this->errore = null; $this->sql = $sql; $this->query_result = mysql_query($this->sql, $this->link); if (! $this->query_result) { $this->set_error( "DB Error, could not query the database." ); } if ($this->debug) { echo "<HR>".$this->sql; } return $this->query_result; } /** * Esegui SQL select * * @return array con l'intero risultato */ public function query_all( $sql) { $this->errore = null; $this->sql = $sql; $query_result = mysql_query($this->sql, $this->link); if (! $query_result) { $this->set_error( "DB Error, could not query the database." ); return $query_result; } // costruisci risultato $result_set = array(); while ($row = mysql_fetch_array( $query_result)) { $result_set[] = $row; } return $result_set; } /** * Aggiungi LIMIT to SQL */ public function sql_select_limit( $sql, $offset, $row_count) { if($row_count) { $this->sql = $sql . " LIMIT ".$offset.",".$row_count; } return $this->sql; } /** * Aggiungi filtri to SQL */ public function sql_select_filter( $sql, $filter_expression, $filter_value) { // split sql at the level of main clauses $sql_parts = $this->sql_split_at_where_end($sql); $sql_parts[0] .= substr_count($sql_parts[0], "WHERE") ? " AND " : " WHERE "; $sql_parts[0] .= $filter_expression . " LIKE '%".$filter_value."%'"; // rebuild full SQL $sql = $sql_parts[0] . " " . $sql_parts[1]; return $sql; } /** * Aggiungi where expression to SQL */ public function sql_select_where( $sql, $where_expression) { // split sql at the level of main clauses $sql_parts = $this->sql_split_at_where_end($sql); $sql_parts[0] .= substr_count($sql_parts[0], "WHERE") ? " AND " : " WHERE "; $sql_parts[0] .= $where_expression; // rebuild full SQL $sql = $sql_parts[0] . " " . $sql_parts[1]; return $sql; } /** * Estrae SELECT clause from SQL */ public function sql_split_select( $sql) { // extract the SELECT clause $sql_upper = strtoupper($sql); $pos_select = strpos( $sql_upper, "SELECT"); $pos_from = strpos( $sql_upper, "FROM"); $sql_select = substr( $sql, $pos_select+6, $pos_from-$pos_select-6); return $sql_select; } /** * Genera WHERE col IN ( ... ) */ public function sql_where_col_in( $col_name, $col_numeric, $value_array) { $sql = $col_name . " IN ("; foreach ($value_array as $value) { $sql .= $col_numeric ? "$value," : "'$value',"; } return rtrim($sql, ",") . ")"; } /** * Salva errore. * * @param $err messaggio di errore */ private function set_error( $err ) { $this->errore = "DBEManagerSql: $err"; if(mysql_errno()) { $this->errore .= ' [' . mysql_error() . ']'; } if($this->sql) { $this->errore .= ' [[' . $this->sql . ']]'; } if($this->debug) { echo $this->errore; } } /** * Inizializza connessione a database e metadata */ private function init() { // connessione al mysql server if (!$this->link = mysql_connect( $this->hostname , $this->user_name , $this->user_pswd)) { $this->set_error( 'Could not connect to mysql' ); return; } // seleziona il database if (!mysql_select_db($this->user_db, $this->link)) { $this->set_error( 'Could not select database' ); return; } } /** * Split SQL at WHERE */ private function sql_split_at_where_end( $sql) { // split sql at the level of main clauses $sql_upper = strtoupper($sql); $pos_groupby = strpos( $sql_upper, "GROUP BY"); $pos_having = strpos( $sql_upper, "HAVING"); $pos_orderby = strpos( $sql_upper, "ORDER BY"); $split_pos = $pos_orderby ? $pos_orderby : 0; $split_pos = $pos_groupby ? ($split_pos > 0 ? min($pos_groupby, $split_pos) : $pos_groupby) : $split_pos ; $split_pos = $pos_having ? ($split_pos > 0 ? min($pos_having, $split_pos) : $pos_having) : $split_pos ; $sql_part1 = $split_pos ? substr( $sql, 0, $split_pos-1) : $sql; $sql_part2 = $split_pos ? substr( $sql, $split_pos, strlen($sql)) : ""; return array($sql_part1, $sql_part2); } } ?>
true
b196651a59006d245b16636be071bccab23d980f
PHP
KintoLef/WF3-Lokisalle
/ajax.php
UTF-8
4,936
2.640625
3
[ "MIT" ]
permissive
<?php require_once("inc/init.inc.php"); // On crée le tableau array $tab = array(); $tab['resultat'] = ""; $capacite = (isset($_POST['capacite'])) ? $_POST['capacite'] : ""; $prix = (isset($_POST['prix'])) ? $_POST['prix'] : ""; if(!empty($_POST['capacite'])) { $filtre_capacite = $_POST['capacite']; $contenu = $pdo->prepare("SELECT * FROM salle s, produit p WHERE p.id_salle = s.id_salle AND capacite = :capacite"); $contenu->bindParam(":capacite", $filtre_capacite, PDO::PARAM_STR); $contenu->execute(); $compteur = 0; while($ligne = $contenu->fetch(PDO::FETCH_ASSOC)) { // On crée l'objet date instanciée par la classe DateTime $date_arrivee = new DateTime($ligne['date_arrivee']); $date_depart = new DateTime($ligne['date_depart']); if($compteur % 3 == 0) { $tab['resultat'] .= '</div><div class="row">'; } $tab['resultat'] .= '<div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"><img src="' . URL . 'photo/' . $ligne['photo'] . '" class="img-responsive" /></div> <div class="panel-body"> <div class="row"> <div class="col-sm-6"> <p>' . $ligne['titre'] . '</p> </div> <div class="col-sm-6"> <p class="text-right"><strong>' . $ligne['prix'] . ' €</strong></p> </div> </div> <p>' . substr_replace($ligne['description'], ' ...', 30) . '</p> <p><span class="glyphicon glyphicon-calendar"></span> ' . date_format($date_arrivee, 'd/m/Y') . ' au ' . date_format($date_depart, 'd/m/Y') . '</p> <div class="row"> <div class="col-sm-6"> </div> <div class="col-sm-6"> <a href="fiche_produit.php?id_produit=' . $ligne['id_produit'] . '" class="pull-right"><span class="glyphicon glyphicon-search" style="font-size: 1em;"></span> Voir</a> </div> </div> </div> </div> </div>'; // On incrémente le compteur dans la boucle while $compteur++; } } elseif(!empty($_POST['prix'])) { $filtre_prix = $_POST['prix']; $contenu = $pdo->prepare("SELECT * FROM salle s, produit p WHERE p.id_salle = s.id_salle AND prix <= :prix"); $contenu->bindParam(":prix", $filtre_prix, PDO::PARAM_STR); $contenu->execute(); $compteur = 0; while($ligne = $contenu->fetch(PDO::FETCH_ASSOC)) { // On crée l'objet date instanciée par la classe DateTime $date_arrivee = new DateTime($ligne['date_arrivee']); $date_depart = new DateTime($ligne['date_depart']); if($compteur % 3 == 0) { $tab['resultat'] .= '</div><div class="row">'; } $tab['resultat'] .= '<div class="col-sm-4"> <div class="panel panel-default"> <div class="panel-heading"><img src="' . URL . 'photo/' . $ligne['photo'] . '" class="img-responsive" /></div> <div class="panel-body"> <div class="row"> <div class="col-sm-6"> <p>' . $ligne['titre'] . '</p> </div> <div class="col-sm-6"> <p class="text-right"><strong>' . $ligne['prix'] . ' €</strong></p> </div> </div> <p>' . substr_replace($ligne['description'], ' ...', 30) . '</p> <p><span class="glyphicon glyphicon-calendar"></span> ' . date_format($date_arrivee, 'd/m/Y') . ' au ' . date_format($date_depart, 'd/m/Y') . '</p> <div class="row"> <div class="col-sm-6"> </div> <div class="col-sm-6"> <a href="fiche_produit.php?id_produit=' . $ligne['id_produit'] . '" class="pull-right"><span class="glyphicon glyphicon-search" style="font-size: 1em;"></span> Voir</a> </div> </div> </div> </div> </div>'; // On incrémente le compteur dans la boucle while $compteur++; } } // NE JAMAIS FAIRE D'echo avant l'encodage JSON sinon celui-ci ne s'effectue pas et la requête ajax ne reçoit pas de réponse echo json_encode($tab);
true
bb8d2b5f93bc2d7643c02afa35827324fa7d576b
PHP
MerlinWT/lifetracker
/lib/ViewApi.php
UTF-8
291
2.5625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: kov * Date: 21.07.18 * Time: 13:39 */ class ViewApi { /** * @param \ModelApi $model * @return string */ public static function render($model) { header('Content-Type: application/json'); return json_encode($model->getData()); } }
true
5b568d8df211557a52f9eb9f29376e1c8dec2753
PHP
aiyolk/dang-php-framework
/libs/Dang/Dmemcache.php
UTF-8
1,625
2.828125
3
[]
no_license
<?php namespace Dang; use Memcache as MemcacheResource; class Dmemcache { protected $memcache; public function __construct() { $servers = \Dang\Quick::config("memcache"); $memcache = new MemcacheResource(); for($i=0;$i<count($servers);$i++){ $config = $servers[$i]; $memcache->addServer($config->host, $config->port); } $this->memcache = $memcache; } public function getItem(& $normalizedKey, & $success = null, & $flags = null) { $memc = $this->memcache; if (func_num_args() > 2) { $result = $memc->get($normalizedKey, $flags); } else { $result = $memc->get($normalizedKey); } $success = true; if ($result === false || $result === null) { $success = false; } return $result; } public function delItem($normalizedKey) { $memc = $this->memcache; if (!$memc->delete($normalizedKey)) { return false; } return true; } public function setItem(& $normalizedKey, & $value, $expiration = 0) { $memc = $this->memcache; $flag = MEMCACHE_COMPRESSED; if (!$memc->set($normalizedKey, $value, $flag, $expiration)) { return false; } return true; } public function incrementItem(& $normalizedKey, $offset = 1) { $memc = $this->memcache; if (!$memc->increment($normalizedKey, $offset)) { $memc->set($normalizedKey, $offset); } return true; } }
true
651256e938a4178165e335d8d7709e9353df6b75
PHP
Vutov/SoftUni
/PHP/Exams/Exam-03-May/codeAnalysis.php
UTF-8
1,027
2.828125
3
[]
no_license
<?php $code = $_GET['code']; //var_dump($code); $data = ['variables' => [], 'loops' => ['while' => [], 'for' => [], 'foreach' => []], 'conditionals' => []]; $varRegex = '/(\$.+?)[\W]/'; preg_match_all($varRegex, $code, $vars); //var_dump($vars); foreach ($vars[1] as $variable) { $data['variables'][$variable]++; } $whileRegex = '/(while\s*\([\w\W]*?\))\s*{/'; preg_match_all($whileRegex, $code, $whiles); //var_dump($whiles); foreach ($whiles[1] as $while) { $data['loops']['while'][] = $while; } $forRegex = '/(for\s*\([\s\S]*?\))\s*{/'; preg_match_all($forRegex, $code, $fors); foreach ($fors[1] as $for) { $data['loops']['for'][] = $for; } $foreachRegex = '/(foreach\s*\([\w\W]*?\))\s*{/'; preg_match_all($foreachRegex, $code, $each); foreach ($each[1] as $ea) { $data['loops']['foreach'][] = $ea; } //var_dump($data); $ifRegex = '/((?:else\s+if|if)\s*\([\w\W]*?\))\s*{/'; preg_match_all($ifRegex, $code, $if); foreach ($if[1] as $else) { $data['conditionals'][] = $else; } echo json_encode($data);
true
cd34079d2e84803e6a0cada08d3da17aadd9ce85
PHP
yivi/prueba_tecnica_2018_03_18
/src/PuppyService/PuppyQuery.php
UTF-8
1,442
3.328125
3
[]
no_license
<?php namespace App\PuppyService; class PuppyQuery { /** * @var string */ protected $title; /** * @var array */ protected $ingredients; /** * @var int */ protected $page; public function __construct(string $title, array $ingredients = [], int $page = 1) { $this->title = $title; $this->ingredients = $ingredients; $this->page = $page; } /** * @return string */ public function getTitle(): string { return $this->title; } /** * @param string $title * @return $this */ public function setTitle(string $title) { $this->title = $title; return $this; } /** * @return array */ public function getIngredients(): array { return $this->ingredients; } /** * @param array $ingredients * * @return $this */ public function setIngredients(array $ingredients) { $this->ingredients = $ingredients; return $this; } /** * @return int */ public function getPage(): int { return $this->page; } /** * @param int $page * @return $this */ public function setPage(int $page) { $this->page = $page; return $this; } public function nextPage() { $this->page++; return $this; } }
true
aeb0211efea024462669bb8c8562897c6cc62263
PHP
XetaIO/Xetaravel
/app/Models/Permission.php
UTF-8
832
2.609375
3
[ "MIT" ]
permissive
<?php namespace Xetaravel\Models; use Ultraware\Roles\Contracts\PermissionHasRelations as PermissionHasRelationsContract; use Ultraware\Roles\Traits\PermissionHasRelations; class Permission extends Model implements PermissionHasRelationsContract { use PermissionHasRelations; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'slug', 'description', 'model', 'is_deletable' ]; /** * The attributes that should be cast has a certain type. * * @var array */ protected $cast = [ 'is_deletable' => 'boolean' ]; /** * Return the field to slug. * * @return string */ public function slugStrategy(): string { return 'name'; } }
true
21a9fff6662468081cddb43bfe098e405a4a9eb9
PHP
OKTOTV/FLUX2
/src/AppBundle/Entity/Repository/EpisodeRepository.php
UTF-8
5,199
2.515625
3
[]
no_license
<?php namespace AppBundle\Entity\Repository; use AppBundle\Entity\Episode; use Okto\MediaBundle\Entity\Repository\EpisodeRepository as BaseEpisodeRepository; class EpisodeRepository extends BaseEpisodeRepository { public function findNewerEpisodes(Episode $episode, $numberEpisodes = 3) { return $this->getEntityManager() ->createQuery( 'SELECT e FROM AppBundle:Episode e WHERE e.series = :series_id AND e.onlineStart > :episode_date AND e.isActive = 1 ORDER BY e.onlineStart ASC' ) ->setParameter('series_id', $episode->getSeries()->getId()) ->setParameter('episode_date', $episode->getOnlineStart()) ->setMaxResults($numberEpisodes) ->getResult(); } public function findNewestEpisodes($numberEpisodes = 8, $query_only = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT e, p FROM AppBundle:Episode e LEFT JOIN e.posterframe p LEFT JOIN e.series s WHERE e.isActive = 1 AND s.isActive = 1 AND e.onlineStart < :now ORDER BY e.onlineStart DESC' ) ->setParameter('now', new \DateTime()); if ($query_only) { return $query; } return $query->setMaxResults($numberEpisodes)->getResult(); } public function findBestEpisodes($numberEpisodes= 8, $query_only = false) { $query= $this->createQueryBuilder('e') ->addSelect('COUNT(u) AS HIDDEN personCount') ->leftJoin('e.users', 'u') ->leftJoin('e.posterframe', 'p') ->leftJoin('e.series', 's') ->groupBy('e') ->orderBy('personCount', 'DESC') ->where('e.isActive = 1') ->andWhere('s.isActive = 1') ->andWhere('e.onlineStart < :now') ->setParameter('now', new \DateTime()) ->getQuery(); if ($query_only) { return $query; } return $query->setMaxResults($numberEpisodes)->getResult(); } /** * returns episodes with most clicks in the last x days days. */ public function findTrendingEpisodes($numberEpisodes = 8, $query_only = false) { $query = $this->getEntityManager()->createQuery( "SELECT e FROM AppBundle:Episode e JOIN e.series s WHERE e.isActive = 1 AND s.isActive = 1 AND e.onlineStart < :now ORDER BY e.trending_score DESC" )->setParameter('now', new \DateTime()); if ($query_only) { $query->setMaxResults(60); return $query; } return $query->setMaxResults($numberEpisodes)->getResult(); } public function findEpisodesForSeries($series, $query_only = false) { $query = $this->getEntityManager()->createQuery( "SELECT e, p FROM AppBundle:Episode e LEFT JOIN e.posterframe p WHERE e.series = :series ORDER BY e.firstranAt DESC" ) ->setParameter('series', $series->getId()); if ($query_only) { return $query; } return $query->getResult(); } public function findNextEpisode($episode, $query_only = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT e FROM AppBundle:Episode e WHERE e.firstranAt > :episode_ran AND e.series = :series AND e.isActive = true' ) ->setParameter('episode_ran', $episode->getFirstranAt()) ->setParameter('series', $episode->getSeries()) ->setMaxResults(1); if ($query_only) { return $query; } return $query->getOneOrNullResult(); } public function findPreviousEpisode($episode, $query_only = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT e FROM AppBundle:Episode e WHERE e.firstranAt < :episode_ran AND e.series = :series AND e.isActive = true' ) ->setParameter('episode_ran', $episode->getFirstranAt()) ->setParameter('series', $episode->getSeries()) ->setMaxResults(1); if ($query_only) { return $query; } return $query->getOneOrNullResult(); } public function findEpisodesByFirstRanAtYear($year = "2005", $query_only = false) { $query = $this->getEntityManager() ->createQuery( 'SELECT e FROM AppBundle:Episode e WHERE e.firstranAt >= :start AND e.firstranAt <= :end' ) ->setParameter('start', new \DateTime('01.01.'.$year)) ->setParameter('end', new \DateTime('31.12.'.$year)); if ($query_only) { return $query; } return $query->getResult(); } } ?>
true
44bd3555907661e2cd63b4388cf83b4b572da18b
PHP
dkonasov/minerva
/system/functions/dbconn.php
WINDOWS-1251
1,259
2.53125
3
[]
no_license
<?php /* : dbconn MySQL. : -$encoding - ( - cp1251). !!! , $HOST( , $USER( ), $PASS ( ). . */ function dbconn($encoding='cp1251') { //global DBHOST; //global DBUSER; //global DBPASS; //global DBNAME; if(!mysql_connect(DBHOST, DBUSER, DBPASS)) die(mysql_error()); mysql_select_db(DBNAME); mysql_set_charset($encoding); } ?>
true
0760d9bd813acd44dda3efc0353b2b293c9cb984
PHP
DR-Innovation/Harvester-Flickr
/src/CHAOS/Harvester/Flickr/Filters/FlickrTagFilter.php
UTF-8
1,309
2.84375
3
[]
no_license
<?php namespace CHAOS\Harvester\Flickr\Filters; class FlickrTagFilter extends \CHAOS\Harvester\Filters\Filter { const TAG_SEPERATOR = ' '; protected $_requiredTags; protected $_bannedTags; public function __construct($harvester, $name, $parameters = array()) { parent::__construct($harvester, $name, $parameters); if(array_key_exists('requiredTags', $parameters)) { $this->_requiredTags = explode(self::TAG_SEPERATOR, $parameters['requiredTags']); } else { $this->_requiredTags = array(); } if(array_key_exists('bannedTags', $parameters)) { $this->_bannedTags = explode(self::TAG_SEPERATOR, $parameters['bannedTags']); } else { $this->_bannedTags = array(); } } public function passes($externalObject, $objectShadow) { if(!array_key_exists('tags', $externalObject)) { throw new \RuntimeException("Expected a tags parameter on the photo returned from the Flickr service."); } $tags = explode(self::TAG_SEPERATOR, $externalObject['tags']); foreach($this->_requiredTags as $tag) { if(!in_array($tag, $tags)) { return "Required tag '$tag' was not found in the photo's tags."; } } foreach($this->_bannedTags as $tag) { if(in_array($tag, $tags)) { return "Banned tag '$tag' was found in the photo's tags."; } } return true; } }
true
7650d0c3fbd4ccf33f548c2d2e547b217c5e73fd
PHP
quintabcn/php.training
/PDO Marcadores en Consultas Preparadas/pag_busqueda_pdo.php
UTF-8
1,045
3.03125
3
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <?php // Conexión a la base de datos $search1=$_GET['nota1']; $search2=$_GET['nota2']; try{ $base= new PDO('mysql:host=localhost; dbname=perfulist', 'root', ''); $base-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $base->exec("SET CHARACTER SET utf8"); $sql="SELECT perfume FROM TOP_NOTES WHERE top_note= :n_1 and top_note= :n_2"; $resultado=$base->prepare($sql); $resultado->execute(array(":n_1"=>$search1, ":n_2"=>$search2)); echo "Here you are: <br>"; while($registro=$resultado->fetch(PDO::FETCH_ASSOC)){ echo "".$registro['perfume'].", "; } $resultado->closeCursor(); }catch(Exception $e){ die('Error: ' . $e->GetMessage()); }finally{ $base=null; } ?> </body> </html>
true
08d7d7fb615909be0aa66b5b3a1324fe7bce7de8
PHP
ay-coder/nanny-app
/app/Models/Messages/Messages.php
UTF-8
767
2.71875
3
[ "MIT" ]
permissive
<?php namespace App\Models\Messages; /** * Class Messages * * @author Anuj Jaha ( er.anujjaha@gmail.com) */ use App\Models\BaseModel; use App\Models\Messages\Traits\Attribute\Attribute; use App\Models\Messages\Traits\Relationship\Relationship; class Messages extends BaseModel { use Attribute, Relationship; /** * Database Table * */ protected $table = "data_messags"; /** * Fillable Database Fields * */ protected $fillable = [ "id", "booking_id", "from_user_id", "to_user_id", "image", "message", "is_image", "is_read", "created_at", "updated_at", ]; /** * Timestamp flag * */ public $timestamps = true; /** * Guarded ID Column * */ protected $guarded = ["id"]; }
true
3b87253718f9fd133a68b1d5be909e8b49c6c1e9
PHP
omarchouman/php-oop
/src/Models/Blog.php
UTF-8
2,172
2.96875
3
[]
no_license
<?php namespace App\Models; use App\Database\Database as DB; class Blog { private $db; public function __construct() { $this->db = new DB(); } public function addBlog($data, $user) { $this->db->query('INSERT INTO blog (title, overview, content, user_id) VALUES(:title, :overview, :content, :user_id)'); $this->db->bind(':title', $data['title']); $this->db->bind(':overview', $data['overview']); $this->db->bind(':content', $data['content']); $this->db->bind(':user_id', $user); if ($this->db->execute()) { return true; } else { return false; } } public function updateBlog($data, $id) { $this->db->query('UPDATE blog SET title=:title, overview=:overview, content=:content WHERE id=:blog_id'); $this->db->bind(':title', $data['title']); $this->db->bind(':overview', $data['overview']); $this->db->bind(':content', $data['content']); $this->db->bind(':blog_id', $id); if ($this->db->execute()) { return true; } else { return false; } } public function deleteBlog($id) { $this->db->query('DELETE FROM blog WHERE id=:blog_id'); $this->db->bind(':blog_id', $id); if ($this->db->execute()) { return true; } else { return false; } } public function getBlogsWithoutContent($start, $limit, $id) { $this->db->query('SELECT id, title, overview, created_at FROM blog WHERE user_id = :id LIMIT :start, :limit'); $this->db->bind(':id', $id); $this->db->bind(':start', $start); $this->db->bind(':limit', $limit); $row = $this->db->resultSet(); return $row; } public function getBlogWithContent($id) { $this->db->query('SELECT id, title, overview, content FROM blog WHERE id = :id'); $this->db->bind(':id', $id); $row = $this->db->single(); return $row; } public function getAllBlogs() { $this->db->query('SELECT id, title, overview, content FROM blog'); $row = $this->db->resultSet(); return $row; } public function countBlogs() { $this->db->query('SELECT COUNT(id) AS total FROM blog'); $row = $this->db->single(); return $row; } }
true
aa6062ece1acb59948c0aeac4c6f4abf3ab3590c
PHP
netcommons/NC2ExtensionModules
/faq/action/main/post/Post.class.php
UTF-8
2,620
2.59375
3
[]
no_license
<?php /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * 質問登録アクションクラス * * @package NetCommons * @author Noriko Arai,Ryuji Masukawa * @copyright 2006-2007 NetCommons Project * @license http://www.netcommons.org/license.txt NetCommons License * @project NetCommons Project, supported by National Institute of Informatics * @access public */ class Faq_Action_Main_Post extends Action { // リクエストパラメータを受け取るため var $block_id = null; var $faq_id = null; var $question_name = null; var $category_id = null; var $question_answer = null; var $question_id = null; // バリデートによりセット var $faq_obj = null; // 使用コンポーネントを受け取るため var $faqView = null; var $db = null; var $request = null; var $session = null; /** * 質問登録アクション * * @access public */ function execute() { $auth_id = $this->session->getParameter("_auth_id"); if($auth_id < $this->faq_obj['faq_authority']) { return 'error'; } if (!empty($this->question_id)) { $params = array( "category_id" => $this->category_id, "question_name" => $this->question_name, "question_answer" => $this->question_answer ); $whereParams = array("question_id"=>$this->question_id); $result = $this->db->updateExecute("faq_question", $params, $whereParams, true); if ($result === false) { return 'error'; } } else { $params = array('faq_id'=>$this->faq_id); $sql = "SELECT MAX(display_sequence) ". "FROM {faq_question} ". "WHERE faq_id = ?"; $sequences = $this->db->execute($sql, $params, null, null, false); if ($sequences === false) { $this->_db->addError(); return false; } $params = array( "faq_id" => $this->faq_id, "display_sequence" => $sequences[0][0] + 1, "category_id" => $this->category_id, "question_name" => $this->question_name, "question_answer" => $this->question_answer ); $question_id = $this->db->insertExecute("faq_question", $params, true, "question_id"); if($question_id === false) { return "error"; } $this->request->setParameter('question_id', $question_id); $this->question_id = $question_id; } $this->request->setParameter('category_id', null); return 'success'; } } ?>
true
f3e3f13636b6a459bdfef8c233b8bc463b605def
PHP
kai815/php-blog
/application/core/DbRepository.php
UTF-8
1,458
3.3125
3
[]
no_license
<?php /** * データベースへのアクセスを行うクラス * * テーブルごとに子クラスを作成する * SQLの実行時に頻繁に出てくるような処理を抽象化しておく */ abstract class DbRepository { protected $con; public function __construct($con) { $this->setConnection($con); } /** * DbManagerClassからPDOクラスのインスタンスを受け取り内部に保持する * * @param instance $con */ public function setConnection($con) { $this->con = $con; } /** * プリペアードステートメントを実際に実行する * * @param string $sql * @param array $params * @return instance */ public function execute($sql, $params = array()) { $stmt = $this->con->prepare($sql); $stmt->execute($params); return $stmt; } /** * レコードを1行取得 * * @param string $sql * @param array $params * @return array */ public function fetch($sql, $params = array()) { return $this->execute($sql, $params)->fetch(PDO::FETCH_ASSOC); } /** * レコードをすべて取得 * * @param string $sql * @param array $params * @return array */ public function fetchAll($sql, $params = array()) { return $this->execute($sql, $params)->fetchAll(PDO::FETCH_ASSOC); } }
true
cf4bdb493718236567d08701bd56f52beb3dd7be
PHP
theirfanirfi/PrivacyApp-Laravel
/app/Http/Controllers/CompaniesController.php
UTF-8
3,584
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use App\Models\Companies as COMP; use App\User; class CompaniesController extends Controller { // public function index(){ $user = Auth::user(); //$companies = COMP::where(['user_id' => $user->id])->get(); $companies = User::find($user->id)->companies; return view('companies.companies',['user' => $user,'companies' => $companies]); } public function addCompany(){ $user = Auth::user(); return view('companies.add',['user' => $user]); } public function addCompanyPost(Request $req){ $country = $req->input('country'); $score = $req->input('score'); $main_activity = $req->input('main_activity'); $company_name = $req->input('company_name'); $user = Auth::user(); if($country == null || $score == null || $main_activity == null || $company_name == null){ return redirect()->back()->with('error','All Fields are required. None can be empty.'); }else{ $comp = new COMP(); $comp->country = $country; $comp->score = $score; $comp->main_activity = $main_activity; $comp->user_id = $user->id; $comp->company_name = $company_name; if($comp->save()){ return redirect('companies')->with('success','Company Added.'); }else { return redirect()->back()->with('error','Error occurred in Adding the Company. Try again.'); } } } public function editCompany($id){ $user = Auth::user(); $company = COMP::find($id); return view('companies.edit',['user' => $user,'company' => $company]); } public function editCompanyPost(Request $req){ $country = $req->input('country'); $score = $req->input('score'); $main_activity = $req->input('main_activity'); $company_name = $req->input('company_name'); $id = $req->input('id'); $user = Auth::user(); if($country == null || $score == null || $main_activity == null || $id == null|| $company_name == null){ return redirect()->back()->with('error','All Fields are required. None can be empty.'); }else{ $comp = COMP::find($id); $comp->country = $country; $comp->score = $score; $comp->main_activity = $main_activity; $comp->company_name = $company_name; $comp->user_id = $user->id; if($comp->save()){ return redirect('companies')->with('success','Company Updated.'); }else { return redirect()->back()->with('error','Error occurred in Updating the Company. Try again.'); } } } public function deleteCompany($id){ $user = Auth::user(); $comp = COMP::where(['id' => $id]); if($comp->count() > 0){ if($comp->first()->user_id == $user->id){ if($comp->first()->delete()){ return redirect()->back()->with('success','Company Deleted.'); }else { return redirect()->back()->with('error','Error occurred in deleting the Company. Try again.'); } }else { return redirect()->back()->with('error','The Company does not belong to you.'); } }else { return redirect()->back()->with('error','No such Company exists in the system.'); } } }
true
eba6515a3834b6cbdb399b4ac26c26de12b95e42
PHP
hiroki0325/geechscamp
/todo/models/category.php
UTF-8
2,185
3.234375
3
[]
no_license
<?php class Category { // privateなプロパティを定義 private $plural_resorce = ''; public function __construct($db,$plural_resorce) { $this->db = $db; $this->plural_resorce = $plural_resorce; } // カテゴリを新規作成するSQL文を返すメソッド public function create(){ $sql = sprintf('INSERT INTO %s SET user_id=%d, name="%s", created=NOW()', $this->plural_resorce, mysqli_real_escape_string($this->db, $_SESSION['id']), mysqli_real_escape_string($this->db, $_POST['category_name']) ); return $sql; } // カテゴリ名の編集用SQL文を返すメソッド public function update(){ $sql = sprintf('UPDATE %s SET name="%s" WHERE id=%d', $this->plural_resorce, mysqli_real_escape_string($this->db, $_POST['edited_categoryname']), mysqli_real_escape_string($this->db, $_POST['category_id']) ); return $sql; } // カテゴリ削除時にそのカテゴリが本当にユーザー自身のカテゴリかどうかを確認するSQL文を返すメソッド public function check($id){ $sql = sprintf('SELECT * FROM %s WHERE id=%d', $this->plural_resorce, mysqli_real_escape_string($this->db, $id) ); return $sql; } // カテゴリを削除するSQL文を返すメソッド public function delete($id){ $sql = sprintf('DELETE FROM %s WHERE id=%d', $this->plural_resorce, mysqli_real_escape_string($this->db, $id) ); return $sql; } // 削除したカテゴリに紐付いていたタスクのカテゴリ設定を初期化するSQL文を返すメソッド public function clear($id){ $sql = sprintf('UPDATE tasks SET category_id=0 WHERE category_id=%d', mysqli_real_escape_string($this->db, $id) ); return $sql; } } ?>
true
5c0c93e50001fdb1a65184e9eff122fdda3589ae
PHP
wp-plugins/okv-oauth
/MyConnect/Google.php
UTF-8
21,140
2.578125
3
[ "MIT" ]
permissive
<?php /** * connect adapter. for call to those social with api and generate link or authenticate with out write it directly in HookLoginPage class. * * @package okv-oauth */ namespace OKVOAuth\MyConnect; if (!class_exists('\\OKVOAuth\\MyConnect\\Google')) { class Google extends \OKVOAuth\Library\HookLoginPage { public $okvoauth_login_method = 0; public $use_google_login = false; public function __construct() { require_once dirname(__DIR__).'/Google/autoload.php'; // get settings of google api. $plugin_options = $this->getOptions(['okvoauth_google_client_id', 'okvoauth_google_client_secret']); if (is_array($plugin_options)) { foreach ($plugin_options as $option_name => $option_val) { $$option_name = $option_val; } } unset($option_name, $option_val, $plugin_options); // check if admin was set google api then use this login. if ( (isset($okvoauth_google_client_id) && $okvoauth_google_client_id != null) && (isset($okvoauth_google_client_secret) && $okvoauth_google_client_secret != null) ) { $this->use_google_login = true; } $this->okvoauth_login_method = intval(get_option('okvoauth_login_method')); }// __construct /** * display this connect's css. * * @param boolean $force_echo set to true if use echo, set to false if use wp_enqueue_style. */ public function displayGoogleLoginCss($force_echo = false) { if ($this->use_google_login === true) { if ($force_echo === true) { echo '<link rel="stylesheet" href="' . plugins_url('css/okv-oauth-google-login.css', __DIR__) . '" type="text/css" />'."\n"; return true; } else { wp_enqueue_style('google-login-btn', plugins_url('css/okv-oauth-google-login.css', __DIR__)); return true; } } return false; }// displayGoogleLoginCss /** * display login link. * any content will be echo immediately here. * * @return boolean */ public function displayGoogleLoginLink() { if ($this->use_google_login === true) { $client = $this->newGoogleClient($this->getGoogleOptions()); $auth_url = $client->createAuthUrl(); if (isset($auth_url)) { echo '<p class="google-login oauth-login"><a href="'.$auth_url.'">'.__('Log in with Google', 'okv-oauth').'</a></p>'; } unset($auth_url, $client); return true; } else { return false; } }// displayGoogleLoginLink /** * display register link * * @return boolean */ public function displayGoogleRegisterLink() { if ($this->use_google_login === true) { $client = $this->newGoogleClient($this->getGoogleOptions()); $auth_url = $client->createAuthUrl(); if (isset($auth_url)) { echo '<p class="google-register oauth-login"><a href="'.$auth_url.'">'.__('Register with Google', 'okv-oauth').'</a></p>'; } if (isset($_REQUEST['error'])) { $this->googleRegisterError($_REQUEST['error'], true); return false; } if (isset($_COOKIE['google_access_token']) && !empty($_COOKIE['google_access_token'])) { $check_user_result = $this->googleRegisterCheckUser(); if ($check_user_result === false) { return false; } elseif (is_array($check_user_result)) { // check user passed. now it is ready to prepare register form. echo '<script>'."\n"; echo 'var okvoauth_google_register_got_code = true;'."\n"; echo 'var okvoauth_google_wp_user_login = \''.(isset($check_user_result['wp_user_login']) ? $check_user_result['wp_user_login'] : '').'\';'."\n"; echo 'var okvoauth_google_wp_user_email = \''.(isset($check_user_result['wp_user_email']) ? $check_user_result['wp_user_email'] : '').'\';'."\n"; echo 'var okvoauth_google_wp_user_avatar = \''.(isset($check_user_result['wp_user_avatar']) ? $check_user_result['wp_user_avatar'] : '').'\';'."\n"; echo '</script>'."\n"; } unset($check_user_result); } unset($auth_url, $client); return true; } else { return false; } }// displayGoogleRegisterLink /** * get wp-login url. * * @param string $action set ?action query string. if use auto leave false. * @param array $params additional querystrings. (key1 => val1, key2 => val2) * @return string */ public function getGoogleLoginUrl($action = false, array $params = []) { $login_url = wp_login_url(); if ($action === false) { $action = (isset($_GET['action']) ? $_GET['action'] : ''); } if ($this->isSecureLogin()) { $login_url = 'https://'.substr($login_url,7); } if ($action !== false && $action !== null && $action !== '') { $login_url .= '?action='.$action; } if (!empty($params)) { if (strpos($login_url, '?') === false) { $login_url .= '?'; } else { $login_url .= '&'; } $params_arr = []; foreach ($params as $key => $val) { $params_arr[] = $key.'='.$val; } $login_url .= implode('&', $params_arr); unset($key, $params_arr, $val); } return $login_url; }// getGoogleLoginUrl /** * get google required options. * * @return array */ public function getGoogleOptions() { // get settings of google api. $plugin_options = $this->getOptions(['okvoauth_google_client_id', 'okvoauth_google_client_secret']); if (is_array($plugin_options)) { foreach ($plugin_options as $option_name => $option_val) { $$option_name = $option_val; } } unset($option_name, $option_val, $plugin_options); $options = []; $options['client_id'] = $okvoauth_google_client_id; $options['client_secret'] = $okvoauth_google_client_secret; unset($okvoauth_google_client_id, $okvoauth_google_client_secret); return $options; }// getGoogleOptions /** * authenticate wordpress login by email. * * @param mixed $user null or WP_User or WP_Error * @param string $username * @param string $password * @return mixed return false if not use google login, return \WP_Error if found error, redirect if login success. */ public function googleLoginByEmail($user, $username=null, $password=null) { if ($this->use_google_login !== true) { return false; } if (isset($_REQUEST['error'])) { return $this->googleRegisterError($_REQUEST['error']); } if (isset($_GET['code'])) { $client = $this->newGoogleClient($this->getGoogleOptions()); try { if ($client->getAccessToken() == null) { $client->authenticate($_GET['code']); } else { $client->refreshToken($client); } // get token data. $token_data = $client->verifyIdToken()->getAttributes(); if ( is_array($token_data) && array_key_exists('payload', $token_data) && array_key_exists('email', $token_data['payload']) && array_key_exists('email_verified', $token_data['payload']) ) { if (!$token_data['payload']['email_verified']) { $user = new \WP_Error('okvoauth_google_login_error', __('You have to verify your email on Google account.', 'okv-oauth')); } else { $user = get_user_by('email', $token_data['payload']['email']); if ($user === false) { $user = new \WP_Error('okvoauth_google_login_error', __('Not found this email on the system.', 'okv-oauth')); } if ($user !== false && !is_wp_error($user)) { wp_clear_auth_cookie(); wp_set_auth_cookie($user->ID, true); setcookie('google_access_token', $client->getAccessToken(), time()+(2 * DAY_IN_SECONDS), '/', defined(COOKIE_DOMAIN) ? COOKIE_DOMAIN : '' ); // do hook action as login success. do_action('wp_login', $token_data['payload']['email'], $user); $this->loggedinRedirect($user); } } } else { $user = new \WP_Error('okvoauth_google_login_error', __('Unable to fetch user detail from Google.', 'okv-oauth')); } } catch (\Google_Exception $e) { $error_msg = $e->getMessage(); if (is_string($error_msg) && strpos($error_msg, 'invalid_client') !== false) { $user = new \WP_Error('okvoauth_google_login_error', __('Incorrect Client secret. Administrator needs to settings Google login.', 'okv-oauth')); } elseif (is_string($error_msg) && strpos($error_msg, 'invalid_grant') !== false) { $user = new \WP_Error('okvoauth_google_login_error', __('Unable to reload. Please click Log In button and try again.', 'okv-oauth')); } else { $user = new \WP_Error('okvoauth_google_login_error', $error_msg); } unset($err_msg); } unset($client, $token_data); } else { // none authenticate from google. return false to lets other oauth working. $user = false; } return $user; }// googleLoginByEmail /** * remove cookie. * * @param boolean $clear_cookie_var set to true to clear $_COOKIE variable. set to false to not clear that. */ public function googleLogout($clear_cookie_var = true) { if ($this->use_google_login === true) { setcookie('google_access_token', '', (time()-((2 * DAY_IN_SECONDS)*2)), '/', defined(COOKIE_DOMAIN) ? COOKIE_DOMAIN : '' ); if ($clear_cookie_var === true) { unset($_COOKIE['google_access_token']); } } }// googleLogout /** * auth google code secret after init wp.<br> * never send output here. headers are ok. */ public function googleRegisterAuthCode() { if (isset($_GET['code']) && !empty($_GET['code'])) { $client = $this->newGoogleClient($this->getGoogleOptions()); try { $client->authenticate($_GET['code']); setcookie('google_access_token', $client->getAccessToken(), time()+(2 * DAY_IN_SECONDS), '/', defined(COOKIE_DOMAIN) ? COOKIE_DOMAIN : '' ); wp_redirect($this->getGoogleLoginUrl()); exit; } catch (\Google_Exception $e) { $error_msg = $e->getMessage(); if (is_string($error_msg) && strpos($error_msg, 'invalid_client') !== false) { $error_msg = 'invalid_client'; } wp_redirect($this->getGoogleLoginUrl(false, ['error' => $error_msg])); exit; } unset($client); } elseif (isset($_COOKIE['google_access_token']) && !empty($_COOKIE['google_access_token'])) { $client = $this->newGoogleClient($this->getGoogleOptions()); try { $client->setAccessToken(stripslashes($_COOKIE['google_access_token'])); // get token data. $token_data = $client->verifyIdToken()->getAttributes(); if ( is_array($token_data) && array_key_exists('payload', $token_data) && array_key_exists('email', $token_data['payload']) && array_key_exists('email_verified', $token_data['payload']) ) { if (!$token_data['payload']['email_verified']) { // not verified email. $this->googleLogout(false); } else { $user = get_user_by('email', $token_data['payload']['email']); if ($user !== false) { // email exists. $this->googleLogout(false); } } } else { // unable to fetch user data from google. $this->googleLogout(false); } } catch (\Google_Exception $e) { // incorrect secret. $this->googleLogout(false); } unset($client, $token_data); } }// googleRegisterAuthCode /** * check google token and user's info and the wp user's info. * * @return mixed return false if failed to validate user or token. return array value of google user info */ public function googleRegisterCheckUser() { $client = $this->newGoogleClient($this->getGoogleOptions()); try { $client->setAccessToken(stripslashes($_COOKIE['google_access_token'])); // get token data. $token_data = $client->verifyIdToken()->getAttributes(); $g_oauth = new \Google_Service_Oauth2($client); if (property_exists($g_oauth, 'userinfo') && method_exists($g_oauth->userinfo, 'get')) { $g_userinfo = $g_oauth->userinfo->get(); } if ( is_array($token_data) && array_key_exists('payload', $token_data) && array_key_exists('email', $token_data['payload']) && array_key_exists('email_verified', $token_data['payload']) && isset($g_userinfo) ) { if (!$token_data['payload']['email_verified']) { $this->displayError(__('You have to verify your email on Google account.', 'okv-oauth')); return false; } else { $user = get_user_by('email', $token_data['payload']['email']); if ($user !== false) { $this->displayError(__('This email is already in use. Please try to register with Google use another email.', 'okv-oauth')); return false; } if (!is_wp_error($user)) { $output = []; $output['wp_user_login'] = $g_userinfo->givenName; $output['wp_user_email'] = $g_userinfo->email; $output['wp_user_avatar'] = $g_userinfo->picture; unset($client, $g_oauth, $g_userinfo, $token_data, $user); return $output; } } } else { $this->displayError(__('Unable to fetch user detail from Google.', 'okv-oauth')); return false; } unset($g_oauth, $g_userinfo, $token_data, $user); } catch (\Google_Exception $e) { $error_msg = $e->getMessage(); if (is_string($error_msg) && strpos($error_msg, 'invalid_client') !== false) { $this->displayError(__('Incorrect Client secret. Administrator needs to settings Google login.', 'okv-oauth')); } else { $this->displayError($error_msg); } unset($error_msg); return false; }// end try unset($client); }// googleRegisterCheckUser /** * check and display google login/register error. * * @param string $error * @param boolean $force_echo * @return \WP_Error|string */ public function googleRegisterError($error = '', $force_echo = false) { switch ($error) { case 'access_denied': $err_msg = __('You did not grant access.', 'okv-oauth'); break; case 'ga_needs_configuring': $err_msg = __('Administrator needs to settings Google login.', 'okv-oauth'); break; case 'invalid_client': $err_msg = __('Incorrect Client secret. Administrator needs to settings Google login.', 'okv-oauth'); break; default: $err_msg = htmlentities2($error); break; } if ($err_msg != null) { $err = new \WP_Error('okvoauth_google_login_error', $err_msg); if (is_wp_error($err) && $force_echo === true) { $error_string = $err->get_error_message(); $this->displayError($error_string); unset($error_string); } return $err; } unset($err, $err_msg); return $error; }// googleRegisterError /** * Fires after WordPress has finished loading but before any headers are sent. */ public function googleWpInit() { if (isset($_GET['action']) && $_GET['action'] == 'register') { // on register page $this->googleRegisterAuthCode(); } }// googleWpInit /** * create new google client object.<br> * for the scope. use https://www.googleapis.com/auth/userinfo.profile instead of https://www.googleapis.com/auth/plus.login will prevent require user to signup google plus. * * @param array $options * @return \Google_Client */ protected function newGoogleClient(array $options = []) { $client = new \Google_Client(); $client->setClientId((isset($options['client_id']) ? $options['client_id'] : '')); $client->setClientSecret((isset($options['client_secret']) ? $options['client_secret'] : '')); $client->setRedirectUri($this->getGoogleLoginUrl()); $client->setScopes('https://www.googleapis.com/auth/userinfo.profile'); $client->addScope('email'); $client->setApprovalPrompt('force');// always allow user to switch user or accept everytime. // done. $options = []; return $client; }// newGoogleClient }// end class ------------------------------------------------------------------ }
true
b72ecc5c72c82213fbf177158e1fe53a5024ab2c
PHP
muskanmahajan37/open-event
/custom/action/resposta-edital_export.php
UTF-8
2,609
2.515625
3
[]
no_license
<?php $user = Structure::verifyAdminSession(); Structure::header('nude'); $idEdital = false; if (array_key_exists("id", $_GET) && $_GET['id'] != "" && !is_null($_GET['id'])) { $idEdital = $_GET['id']; } else { echo "error"; exit(1); } $genericDAO = new GenericDAO; if (!$genericDAO->selectAll("Edital", "id = $idEdital")) { echo "error"; exit(1); } $firstLine = ""; $lines = array(); $perguntas = $genericDAO->selectAll("Pergunta", "id_edital = $idEdital"); if ($perguntas) { if (!is_array($perguntas)) $perguntas = array($perguntas); } $respostasEdital = $genericDAO->selectAll("RespostaEdital", "status = 1 AND id_edital = $idEdital"); if ($respostasEdital) { if (!is_array($respostasEdital)) $respostasEdital = array($respostasEdital); foreach ($respostasEdital as $respostaEdital) { $line = ""; $user = $genericDAO->selectAll("User", "id = ".$respostaEdital->get('id_user')); $line .= "{$user->get('id')},"; $line .= "\"{$user->get('nome')}\","; $line .= "\"{$user->get('email')}\","; if (sizeof($lines) === 0) { $firstLine .= "\"ID Usuário\","; $firstLine .= "\"Nome Usuário\","; $firstLine .= "\"Email\","; } foreach ($perguntas as $pergunta) { if (sizeof($lines) === 0) { $firstLine .= "\"{$pergunta->get('titulo')}\","; } $answer = ""; $respostasPergunta = $genericDAO->selectAll("RespostaPergunta", "id_pergunta = {$pergunta->get('id')} AND id_resposta_edital = {$respostaEdital->get('id')}"); if ($respostasPergunta) { if (!is_array($respostasPergunta)) $respostasPergunta = array($respostasPergunta); foreach ($respostasPergunta as $respostaPergunta) { if (strlen($answer) > 0) $answer .= ","; $valoresPossiveis = $genericDAO->selectAll("ValorPossivel", "id_pergunta = ".$respostaPergunta->get('id_pergunta')." AND valor = '".$respostaPergunta->get('vl_resposta')."'"); if ($valoresPossiveis) { if (is_array($valoresPossiveis)) echo "error"; // error else $answer .= "{$valoresPossiveis->get('label')}"; } else { $answer .= "{$respostaPergunta->get('vl_resposta')}"; } } } $line .= "\"$answer\","; $answer = ""; } if (sizeof($lines) === 0) $lines[] = $firstLine; $lines[] = $line; $line = ""; } } foreach ($lines as $line) { echo strtr($line, array("<br>" => "", "," => ","))."<br>"; } ?>
true
caf194f33ff75078897b7a15568015cc393c466c
PHP
armincms/core
/src/Plugin/PluginRepository.php
UTF-8
1,864
2.546875
3
[]
no_license
<?php namespace Core\Plugin; use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Collection; class PluginRepository { protected $files; protected $plugins; public function __construct(Filesystem $files) { $this->files = $files; } public function all() { if(! isset($this->plugins)) { $this->plugins = $this->getPluginInstances(); } return $this->plugins; } public function plugin(string $plugin) { return $this->all()->get($plugin); } /** * Get all of the migration files in a given path. * * @param string|array $paths * @return array */ public function getPluginInstances() { return Collection::make($this->pluginDirectories())->map(function ($path) { $name = $this->files->basename($path); $class = $this->qualifyNamespace($name); if(! class_exists($class)) { return null; } $plugin = new $class(app()); if($plugin instanceof Plugin) { return $plugin; } return null; })->filter(); } protected function pluginDirectories() { if(! $this->files->exists(plugin_path())) return []; return tap($this->files->directories(plugin_path()), function($directories) { $vendors = Collection::make($directories)->mapWithKeys(function($directory) { $namespace = studly_case($this->files->name($directory)); $vendor = "Plugin\\{$namespace}\\"; return [$vendor => $directory]; }); \Helper::resolvePsr4($vendors->toArray()); }); } public function qualifyNamespace(string $name) { $class = studly_case($name); return "Plugin\\{$class}\\{$class}"; } }
true
2263b0a60794497d4b3239f3c087baa3dd15e5bc
PHP
KrijnvdBurg/Laravel
/app/Article.php
UTF-8
1,676
2.71875
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; use Carbon\Carbon; class Article extends Model { protected $fillable = [ 'title', 'body', 'excerpt', 'published_at' ]; public static function date_locker($published_at){ if($published_at >= Carbon::now()){ return 'locked'; } else{ return 'open'; } } public static function ahref_locker($article){ if($article->published_at >= Carbon::now()){ return '<h2 class="post_h2">' . $article->title . '</h2>'; } else{ return '<h2 class="post_h2"> <a href="Articles/'. $article->id . '">'.$article->title.'</a></h2>'; } } public static function warning_locker($article){ if($article->published_at >= Carbon::now()){ return '<p class="article_lockedSpan">Full article publishes: ' . $article->published_at->format('Y-m-d') . '</p>'; } else{ return '<p class="article_openSpan">Click to read the full article!</p>'; } } public function scopeLatestArticles($query){ $query->where('published_at', '<=', Carbon::now()); } public function scopePublished($query){ $query->where('published_at', '<=', Carbon::now()); } public function scopeUnPublished($query){ $query->where('published_at', '>=', Carbon::now()); } public function setPublishedAtAttribute($date){ $this->attributes['published_at'] = Carbon::parse($date); } public function getPublishedAtAttribute($date){ return new Carbon($date); } public function user(){ return $this->belongsTo('App\User'); } public function tags(){ return $this->belongsToMany('App\Tag')->withTimestamps(); } public function getTagListAttribute(){ return $this->tags->lists('id'); } }
true
cdc8c1ffbff9e6867ce2d638a768e560cc549de3
PHP
t-ichi324/sesame
/lib/Validator.php
UTF-8
7,186
2.96875
3
[]
no_license
<?php class Validator { private static $errorCnt = 0; private static $msgLvl = 1; /** <p>パスワードのガイド文字列</p> */ public static function PASSWORD_GUIDE($min = Conf::USER_PW_MIN, $level = Conf::USER_PW_LEVEL){ switch ($level){ case 1: if($min < 2){ $min = 2; } $msg = __("valid.pw-guide-2", $min); break; case 2: if($min < 3){ $min = 3; } $msg = __("valid.pw-guide-3", $min); break; case 3: if($min < 4){ $min = 4; } $msg = __("valid.pw-guide-4", $min); break; default : if($min < 1){ $min = 1; } $msg = __("valid.pw-guide-1", $min); break; } return $msg; } /** * エラーメッセージのレベルを指定 * @param int $level */ public static function setMessageLevel($level){ self::$msgLvl = $level; } /** * エラーメッセージの追加 * @param string $msg エラーメッセージ */ public static function addError($msg){ self::$errorCnt += 1; switch (self::$msgLvl){ case 1: Message::addWarning($msg); break; case 2: Message::addError($msg); break; } } /** * エラーが存在するか * @return bool */ public static function hasError() { return self::$errorCnt > 0; } /** * 必須チェック */ public static function isAllNotEmpty(... $fields) { $b = TRUE; foreach($fields as $f){ if(empty($f)){ $b = FALSE; } } return $b; } /** * 必須チェック */ public static function required($field, $name){ if(empty($field)){ self::addError( __("valid.required", $name) ); return false; } return TRUE; } /** * パスワードの形式チェック<br> * <b>level:0</b> 長さ以外のチェックを行わない * <b>level:1</b> アルファベット・数字が含まれている * <b>level:2</b> アルファベット・数字・記号が含まれている * <b>level:3</b> 大文字と小文字アルファベット・数字・記号が含まれている */ public static function password($field, $name, $min = Conf::USER_PW_MIN, $level = Conf::USER_PW_LEVEL){ $msg = $name."は、".self::PASSWORD_GUIDE($min, $level); switch ($level){ case 1: if($min < 2){ $min = 2; } break; case 2: if($min < 3){ $min = 3; } break; case 3: if($min < 4){ $min = 4; } break; default : if($min < 1){ $min = 1; } break; } if(empty($field)){ self::addError($msg); return false; } $len = mb_strlen($field); if($len < $min){ self::addError($msg); return false; } if($level > 0){ $iLo = preg_match("/[a-z]+/", $field); $iUp = preg_match("/[A-Z]+/", $field); $iNm = preg_match("/[0-9]+/", $field); $iSy = preg_match("/[\!\#\$\%\(\)\*\+\-\.\/\:;\=\?\@\[\]\^_`\{\|\}]+/", $field); switch ($level){ case 1: if(!( ($iLo || $iUp) && $iNm) ){ self::addError($msg); return false; } break; case 2: if(!( ($iLo || $iUp) && $iNm & $iSy) ){ self::addError($msg); return false; } break; case 3 : if(!( $iLo && $iUp && $iNm & $iSy) ){ self::addError($msg); return false; } break; } } return true; } /** * 桁数チェック */ public static function lenMax($field, $name, $max){ $len = mb_strlen($field); if($len > $max){ self::addError( __("valid.lenMax", $name, $max) ); return false; } } public static function lenMin($field, $name, $min){ $len = mb_strlen($field); if($len < $min){ self::addError( __("valid.lenMin", $name, $min) ); return false; } return true; } public static function lenRange($field, $name, $min, $max){ $len = mb_strlen($field); if($len > $max || $len < $min){ self::addError( __("valid.lenRange",$name, $min, $max) ); return false; } return true; } public static function compare( $field1, $field2, $name){ if($field1 !== $field2){ self::addError( __("valid.compare",$name) ); return false; } return true; } /** 数字のみ */ public static function numOnly($field, $name){ if(!preg_match("/^[0-9]+$/", $field)){ self::addError( __("valid.numOnly",$name) ); return false; } return true; } /** アルファベットのみ */ public static function alphaOnly($field, $name){ if(!preg_match("/^[a-zA-Z]+$/", $field)){ self::addError( __("valid.alphaOnly",$name) ); return false; } return true; } /** アルファベット + 数字のみ */ public static function alphaNumOnly($field, $name){ if(!preg_match("/^[a-zA-Z0-9]+$/", $field)){ self::addError( __("valid.alphaNumOnly",$name) ); return false; } return true; } /** * メールアドレスのフォーマットチェック */ public static function format_email($field, $name){ if(!preg_match('/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/iD', $field)){ self::addError( __("valid.format_email",$name) ); return false; } return true; } /** * 郵便番号(ハイフン有)のフォーマットチェック */ public static function format_zipcode_hyphen($field, $name){ if(!preg_match('/^\d{3}\-\d{4}$/', $field)){ self::addError( __("valid.format_zipcode_hyphen",$name) ); return false; } return true; } /** * TEL・FAX(ハイフン有)のフォーマットチェック */ public static function format_tel_hyphen($field, $name){ if(!preg_match('/^([0-9]{2,})\-([0-9]{2,})\-([0-9]{4,})$/', $field)){ self::addError( __("valid.format_tel_hyphen",$name) ); return false; } return true; } }
true
5c839e6e98e8324b0871917874b6c47f5fe6893b
PHP
itemvirtual/vat-validate
/src/Services/EuropeanVatService.php
UTF-8
3,298
2.640625
3
[ "MIT" ]
permissive
<?php namespace Itemvirtual\VatValidate\Services; use Itemvirtual\VatValidate\Traits\VatTrait; use Illuminate\Support\Facades\Log; class EuropeanVatService { use VatTrait; public function check(string $vat, string $countryCode = 'ES') { $vat = $this->cleanVat($vat, $countryCode); $countryCode = strtoupper($countryCode); if (!\array_key_exists($countryCode, $this->patterns)) { throw new \Exception('Invalid country code'); } return preg_match($this->patterns[$countryCode], $vat); } private $patterns = [ 'AT' => '/^(U\d{8}$)/i', // Austria 'BE' => '/^(\d{10}$)/i', // Belgium 'BG' => '/^(\d{9,10}$)/i', // Bulgaria 'CY' => '/^([0-5|9]\d{7}[A-Z]$)/i', // Cyprus 'CZ' => '/^(\d{8,10})?$/i', // Czech Republic 'DE' => '/^([1-9]\d{8}$)/i', // Germany 'DK' => '/^(\d{8}$)/i', // Denmark 'EE' => '/^(10\d{7}$)/i', // Estonia 'EL' => '/^(\d{9}$)/i', // Greece 'ES' => '/^([0-9A-Z][0-9]{7}[0-9A-Z]$)/i', // Spain 'EU' => '/^(\d{9}$)/i', // EU-type 'FI' => '/^(\d{8}$)/i', // Finland 'FR' => '/^([0-9A-Z]{2}[0-9]{9}$)/i', // France 'GB' => '/^((?:[0-9]{12}|[0-9]{9}|(?:GD|HA)[0-9]{3})$)/i', // UK (Standard = 9 digits), (Branches = 12 digits), (Government = GD + 3 digits), (Health authority = HA + 3 digits) 'GR' => '/^(\d{8,9}$)/i', // Greece 'HR' => '/^(\d{11}$)/i', // Croatia 'HU' => '/^(\d{8}$)/i', // Hungary 'IE' => '/^([0-9A-Z\*\+]{7}[A-Z]{1,2}$)/i', // Ireland 'IT' => '/^(\d{11}$)/i', // Italy 'LV' => '/^(\d{11}$)/i', // Latvia 'LT' => '/^(\d{9}$|\d{12}$)/i', // Lithuania 'LU' => '/^(\d{8}$)/i', // Luxembourg 'MT' => '/^([1-9]\d{7}$)/i', // Malta 'NL' => '/^(\d{9}B\d{2}$)/i', // Netherlands 'NO' => '/^(\d{9}$)/i', // Norway (not EU) 'PL' => '/^(\d{10}$)/i', // Poland 'PT' => '/^(\d{9}$)/i', // Portugal 'RO' => '/^([1-9]\d{1,9}$)/i', // Romania 'RU' => '/^(\d{10}$|\d{12}$)/i', // Russia 'RS' => '/^(\d{9}$)/i', // Serbia 'SI' => '/^([1-9]\d{7}$)/i', // Slovenia 'SK' => '/^([1-9]\d[(2-4)|(6-9)]\d{7}$)/i', // Slovakia Republic 'SE' => '/^(\d{10}01$)/i', // Sweden ]; }
true
248fade47f28bce92fc1a6bd6990258750677e4e
PHP
iammati/centauri_core
/Classes/CentauriCore.php
UTF-8
2,265
2.9375
3
[ "MIT" ]
permissive
<?php namespace Centauri\Core; use TYPO3\CMS\Core\Utility\GeneralUtility; class CentauriCore { /** * Core version of the system. * * @var string */ protected $version = "1.0"; /** * Absolute path from webserver to the extension itself - defined inside of the constructor. * * @var string */ protected $path = ""; /** * Constructor for registering main functionality of this extension. * * @return void */ public function __construct() { $version = $this->version; // $this->checkUpdates($version); $this->path = \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath("centauri_core"); $this->loadAll(); } /** * Loader for everything. * * @return void */ public function loadAll() { $path = $this->path; include $path . "Classes/Utility/DumpDieUtility.php"; } /** * Returns the config file its content. * * @return void */ public function getConfig() { $configFile = GeneralUtility::getFileAbsFileName("EXT:centauri_core/Configuration/core.php"); return (include $configFile); } private function checkUpdates($version) { $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_RETURNTRANSFER => 1, CURLOPT_URL => "TODO API URL FOR VERSION CHECK", CURLOPT_POST => 1 ]); $latestversion = curl_exec($curl); curl_close($curl); $flashUtility = new \Centauri\Core\Utility\FlashUtility; if($version !== $latestversion) { return $flashUtility->message("Centauri Core (EXT:centauri_core) - Version", "Please update your current version ($version) up to the latest version ($latestversion)!", 1); } else { // return $flashUtility->message("Centauri Core", "Running latest version of Centauri Core.", 0); } return; } /** * Returns version of CentauriCore. * * @return string */ public function getVersion() { return $this->version; } }
true
5430a04398f5ee106a0d53e55faf6f4859137c8d
PHP
sahabuddin123/Inventory-management-system-Laravel-v2
/app/Http/Controllers/Admin/GroupsController.php
UTF-8
3,111
2.578125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\BaseController; use Illuminate\Http\Request; use App\Contracts\GroupsContract; class GroupsController extends BaseController { protected $groupsRepository; public function __construct(GroupsContract $groupsRepository) { $this->groupsRepository = $groupsRepository; } /* * It redirects to the manage group page * As well as the group data is also been passed to display on the view page */ public function index() { $groups = $this->groupsRepository->listGroups(); $this->setPageTitle('Groups', 'List of all groups'); return view('admin.groups.index', compact('groups')); } /** * create */ public function create() { $groups = $this->groupsRepository->listGroups('id', 'asc'); $this->setPageTitle('groups', 'Create groups'); return view('admin.groups.create', compact('groups')); } /** * store */ public function store(Request $request) { $this->validate($request, [ 'name' => 'required|max:191', 'slug' => 'required|max:191', 'permissions' => 'required' ]); $params = $request->except('_token'); $groups = $this->groupsRepository->createGroups($params); if (!$groups) { return $this->responseRedirectBack('Error occurred while creating groups.', 'error', true, true); } return $this->responseRedirect('admin.groups.index', 'groups added successfully' ,'success',false, false); } /** * edit */ public function edit($id) { $targetgroup = $this->groupsRepository->findGroupsById($id); //$permissions = unserialize($this->targetgroup['permissions']); $groups = $this->groupsRepository->listGroups(); $this->setPageTitle('Groups', 'Edit Groups : '.$targetgroup->name); return view('admin.groups.edit', compact('groups', 'targetgroup')); } /** * update */ public function update(Request $request) { $this->validate($request, [ 'name' => 'required|max:191', 'slug' => 'required|max:191', 'permissions' => 'required' ]); $params = $request->except('_token'); $groups = $this->groupsRepository->updateGroups($params); if (!$groups) { return $this->responseRedirectBack('Error occurred while updating groups.', 'error', true, true); } return $this->responseRedirect('admin.groups.index' ,'groups updated successfully' ,'success',false, false); } public function delete($id) { $groups = $this->groupsRepository->deleteGroups($id); if (!$groups) { return $this->responseRedirectBack('Error occurred while deleting groups.', 'error', true, true); } return $this->responseRedirect('groups deleted successfully' ,'success',false, false); } }
true
9b1fc17304d2b0ff7ce1209fec33ac39c4e5b0fc
PHP
adrielsales/alura
/php/php_e_mysql/banco-categoria.php
UTF-8
616
2.9375
3
[]
no_license
<?php function listaCategorias($conexao) { $categorias = array(); $resultado = mysqli_query($conexao, "select * from categorias"); while ($categoria = mysqli_fetch_object($resultado)) { array_push($categorias, $categoria); } return $categorias; } // function insereProduto($conexao, $nome, $preco, $descricao){ // $query = "insert into produtos (nome, preco, descricao) values ('{$nome}',{$preco},'{$descricao}')"; // return mysqli_query($conexao, $query); // } // function removeProduto($conexao, $id){ // $query = "delete from produtos where id = {$id}"; // return mysqli_query($conexao, $query); // }
true
6c8f817f347382ba87141ea33ff5e4cd0a17ed23
PHP
heidkaemper/statamic-toolbar
/src/Breakpoints/Breakpoints.php
UTF-8
2,591
2.6875
3
[]
no_license
<?php namespace Heidkaemper\Toolbar\Breakpoints; use Heidkaemper\Toolbar\Breakpoints\Parser\BootstrapParser; use Heidkaemper\Toolbar\Breakpoints\Parser\PicoParser; use Heidkaemper\Toolbar\Breakpoints\Parser\TailwindParser; use Illuminate\Support\Collection; class Breakpoints { protected Collection $breakpoints; public function __construct() { $this->breakpoints = collect(); $this ->getFromConfig() ->getFromTailwind() ->getFromPico() ->getFromBootstrap() ->format(); } public function toArray(): array { return $this->breakpoints->toArray(); } private function getFromConfig(): self { if (! $this->breakpoints->isEmpty()) { return $this; } $this->breakpoints = collect(config('statamic.toolbar.breakpoints', [])); return $this; } private function getFromTailwind(): self { if (! $this->breakpoints->isEmpty()) { return $this; } $files = [ 'tailwind.config.js', 'tailwind.config.theme.js', 'tailwind.config.site.js', ]; $this->breakpoints = Cache::remember('tailwind', $files, function () use ($files) { return collect((new TailwindParser($files))->parse() ?? []); }); return $this; } private function getFromPico(): self { if (! $this->breakpoints->isEmpty()) { return $this; } $this->breakpoints = collect((new PicoParser())->parse() ?? []); return $this; } private function getFromBootstrap(): self { if (! $this->breakpoints->isEmpty()) { return $this; } $files = [ 'scss/_variables.scss', 'sass/_variables.scss', ]; $this->breakpoints = Cache::remember('bootstrap', $files, function () use ($files) { return collect((new BootstrapParser($files))->parse() ?? []); }); return $this; } private function format(): self { $this->breakpoints = $this->breakpoints ->map(function ($breakpoint) { if (is_numeric($breakpoint)) { return "min-width: {$breakpoint}px"; } if (preg_match('/^[0-9]*.{2,3}$/', $breakpoint)) { return "min-width: {$breakpoint}"; } return (string) $breakpoint; }) ->filter(); return $this; } }
true
b3db7f2b0b32e4d6aa4341cbdd6f4a3e39973233
PHP
logoscreative/pods-code-library
/example/classes/PodsAPI/load_pod/examples/post-type-bread-crumb.php
UTF-8
1,141
2.671875
3
[]
no_license
<?php /** * Basic breadcrumbs for custom post type Pod, using load_pod to get Pod labels. * * Someone should add handling for posts and pages as well as ACTs to this. Possibly make a plugin. */ function slug_post_type_breadcrumb( $divider = '&gt;&gt;' ) { $front = slug_link( site_url(), 'Home' ); if ( is_home() || is_front_page() ) { return $front; } if( is_post_type_archive() || ( is_singular() && get_post_type() !== false ) ) { $post_type = get_post_type(); $pod = pods_api()->load_pod( $post_type ); if ( !is_string( $pod ) ) { $single = $pod->options[ 'single_label' ]; $plural = slug_link( get_post_type_archive( $post_type ), $pod->label, 'All ' . $single ); if ( is_post_type_archive() ) { return $front . $divider . $plural; } global $post; $single = slug_link( get_permalink( $post->ID ), get_the__title( $post->ID ), 'View '.$single ); return $front . $divider . $single; } else { return; } } } function slug_link( $link, $text, $title = null ) { if ( is_null( $title ) ) { $title = $text; } return '<a href="'.$link.'" title="'.$title.'">'.$text.'</a>'; }
true
41d7089f69079ea1c0d49e1f6c8968d0088c267f
PHP
ravinderwave/prepmymeal
/app/Http/Controllers/Backend/ComponentController.php
UTF-8
4,014
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Component; /** * Class ComponentController * @package App\Http\Controllers */ class ComponentController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $components = Component::all(); return view('backend.components.index')->withComponents($components); } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { return view('backend.components.create'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $this->validate($request,[ 'title' => 'required', 'weight' => 'required|numeric|gt:0', 'price' => 'required|numeric|gt:0', 'image' => 'required|image|mimes:jpeg,png,jpg|max:2048', ]); if ($request->hasFile('image')) { $image = 'components_'.uniqid().'.'.$request->image->getClientOriginalExtension(); $request->image->move(public_path('uploads'), $image); }else{ $image = null; } $component = new Component; $component->title = $request->title; $component->weight = $request->weight; $component->type = $request->type; $component->price = $request->price; $component->ntr_options = json_encode($request->ntr); $component->image = $image; $component->save(); return redirect()->route('components.index'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show(Component $component) { if ($component->status=='1'){ $component->status='0'; }else{ $component->status='1'; } $component->save(); return redirect()->route('components.index'); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $component = Component::find($id); return view('backend.components.edit')->withComponent($component); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, Component $component) { $this->validate($request,[ 'title' => 'required', 'weight' => 'required|numeric|gt:0', 'price' => 'required|numeric|gt:0', 'image' => 'sometimes|required|image|mimes:jpeg,png,jpg|max:2048', ]); if ($request->hasFile('image')) { $image = 'components_'.uniqid().'.'.$request->image->getClientOriginalExtension(); $request->image->move(public_path('uploads'), $image); }else{ $image = $request->image; } $component->title = $request->title; $component->weight = $request->weight; $component->type = $request->type; $component->price = $request->price; $component->ntr_options = json_encode($request->ntr); $component->image = $image; $component->save(); return redirect()->route('components.index'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Component $component) { $component->delete(); return redirect()->route('components.index'); } }
true
76040a6ca6d76900945f3aaa8c50a7a129be6b10
PHP
scott7rj/contratos-antigo
/classes/tipo_contrato.php
UTF-8
1,698
2.8125
3
[]
no_license
<?php class tipo_contrato { private $idTipoContrato; private $tipoContrato; private $ativo; public function getIdTipoContrato(){ return $this->idTipoContrato; } public function setIdTipoContrato($idTipoContrato){ $this->idTipoContrato = $idTipoContrato; } public function getTipoContrato(){ return $this->tipoContrato; } public function setTipoContrato($tipoContrato){ $this->tipoContrato = $tipoContrato; } public function getAtivo(){ return $this->ativo; } public function setAtivo($ativo){ $this->ativo = $ativo; } public function selecionarTiposContrato() { $sql = "SELECT * FROM [contratos].[fn_tipo_contrato_selecionar](1)"; $rst = conexao::execute($sql); $lst = array(); while($array = odbc_fetch_array($rst)) { $tipo_contrato = new tipo_contrato(); $tipo_contrato->setIdTipoContrato(utf8_encode($array["id_tipo_contrato"])); $tipo_contrato->setTipoContrato(utf8_encode($array["tipo_contrato"])); array_push($lst, $tipo_contrato); } return $lst; } public function inserir($tipo_contrato, $usuario_alteracao) { $sql = "EXEC [contratos].[tipo_contrato_inserir] @tipo_contrato = '$tipo_contrato', @usuario_alteracao = '$usuario_alteracao'"; $rst = conexao::execute($sql); return odbc_result($rst, 1); } public function remover($id_tipo_contrato) { $sql = "EXEC [contratos].[tipo_contrato_remover] @id_tipo_contrato = $id_tipo_contrato"; $rst = conexao::execute($sql); return odbc_result($rst, 1); } }
true
9f54998627df1d3644b6ab3befbd7f25f9df8533
PHP
datosgcba/plan-de-gobierno
/source/bt-admin/Logica/cPlantillasMacrosZonas.class.php
UTF-8
4,450
2.828125
3
[]
no_license
<?php include(DIR_CLASES_DB."cPlantillasMacrosZonas.db.php"); class cPlantillasMacrosZonas extends cPlantillasMacrosZonasdb { protected $conexion; protected $formato; // Constructor de la clase function __construct($conexion,$formato=FMT_TEXTO){ $this->conexion = &$conexion; $this->formato = $formato; parent::__construct(); } // Destructor de la clase function __destruct() { parent::__destruct(); } //----------------------------------------------------------------------------------------- // PUBLICAS //----------------------------------------------------------------------------------------- // Trae los macros pertenecientes a una platnilla // Parámetros de Entrada: // datos: arreglo de datos // plantcod = codigo de la Plantilla // zonanombre = nombre de la zona // Retorna: // numfilas,resultado: cantidad de filas y query de resultado // la función retorna true o false si se pudo ejecutar con éxito o no public function BuscarZonasxPlantMacrocod($datos,&$resultado,&$numfilas) { if (!parent::BuscarZonasxPlantMacrocod ($datos,$resultado,$numfilas)) return false; return true; } //----------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------- // Trae los datos del macro por codigo // Parámetros de Entrada: // datos: arreglo de datos // macrozonacod = codigo del macro zona // Retorna: // numfilas,resultado: cantidad de filas y query de resultado // la función retorna true o false si se pudo ejecutar con éxito o no public function BuscarxCodigo($datos,&$resultado,&$numfilas) { if (!parent::BuscarxCodigo ($datos,$resultado,$numfilas)) return false; return true; } //----------------------------------------------------------------------------------------- // Inserta nuevo formato // Parámetros de Entrada: // formatodesc: descripción del formato // formatoancho: ancho del formato // formatoalto: alto del formato // formatocarpeta: formato de la carpeta // formatocropea: si se cropea el formato vale 1 si no vale 0 // Retorna: // la función retorna true o false si se pudo ejecutar con éxito o no public function Insertar($datos,&$codigoinsertado) { if (!$this->_ValidarDatosAlta($datos)) return false; if(!parent::Insertar($datos,$codigoinsertado)) return false; return true; } //----------------------------------------------------------------------------------------- // Eliminar un macro // Parámetros de Entrada: // plantmacrocod: codigo del plantmacrocod // Retorna: // la función retorna true o false si se pudo ejecutar con éxito o no public function Eliminar($datos) { if (!$this->_ValidarEliminarDatos($datos)) return false; if(!parent::Eliminar($datos)) return false; return true; } //----------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------- // Retorna true o false si algunos de los campos esta vacio // Parámetros de Entrada: // Retorna: // la función retorna true o false si se pudo ejecutar con éxito o no public function _ValidarDatosVacios($datos) { return true; } //----------------------------------------------------------------------------------------- // Retorna true o false al dar de alta si algunos de los campos esta vacio o si exite otro album con ese nombre // Parámetros de Entrada: // formatodesc: descripción del formato // formatoancho: ancho del formato // formatoalto: alto del formato // formatocarpeta: formato de la carpeta // formatocropea: si se cropea el formato vale 1 si no vale 0 // Retorna: // la función retorna true o false si se pudo ejecutar con éxito o no function _ValidarDatosAlta($datos) { if (!$this->_ValidarDatosVacios($datos)) return false; return true; } //----------------------------------------------------------------------------------------- // Retorna true o false al validar si puede o no eliminar una zona del macro // Parámetros de Entrada: // formatocod: código del formato // Retorna: // la función retorna true o false si se pudo ejecutar con éxito o no private function _ValidarEliminarDatos($datos) { //validar que no tenga columnas return true; } } ?>
true
6b3a7c509988213fbb4c67653739f8362e681127
PHP
geomagilles/flowgraph
/src/Geomagilles/FlowGraph/PetriNet/Dumper/DumperInterface.php
UTF-8
575
2.5625
3
[]
no_license
<?php /** * This file is part of the Flow framework. * * (c) Gilles Barbier <geomagilles@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Geomagilles\FlowGraph\PetriNet\Dumper; use Geomagilles\FlowGraph\PetriNet\PetriNetInterface; /** * Interface for Petrinet dumpers. */ interface DumperInterface { /** * Dump a box. * @param PetriNetInterface $petrinet * @return string The string representation */ public function dump(PetriNetInterface $petrinet); }
true
9cceb350d23c6b6cd17cdcdd8648080cbc2fda11
PHP
kikmedia/metamodels_full
/modules/generalDriver/InterfaceGeneralCallback.php
UTF-8
3,898
2.640625
3
[]
no_license
<?php /** * PHP version 5 * @package generalDriver * @author Stefan Heimes <cms@men-at-work.de> * @copyright The MetaModels team. * @license LGPL. * @filesource */ interface InterfaceGeneralCallback { /** * Set the DC * * @param DC_General $objDC */ public function setDC($objDC); /** * Get the DC * * @return DC_General */ public function getDC(); /** * Exectue a callback * * @param array $varCallbacks * @return array */ public function executeCallbacks($varCallbacks); /** * Call the customer label callback * * @param InterfaceGeneralModel $objModelRow * @param string $mixedLabel * @param array $args * @return string */ public function labelCallback(InterfaceGeneralModel $objModelRow, $mixedLabel, $args); /** * Call the button callback for the regular operations * * @param InterfaceGeneralModel $objModelRow * @param string $strLabel * @param string $strTitle * @param array $arrAttributes * @param string $strTable * @param array $arrRootIds * @param array $arrChildRecordIds * @param boolean $blnCircularReference * @param string $strPrevious * @param string $strNext * * @return string|null */ public function buttonCallback($objModelRow, $arrOperation, $strLabel, $strTitle, $arrAttributes, $strTable, $arrRootIds, $arrChildRecordIds, $blnCircularReference, $strPrevious, $strNext); /** * Call the button callback for the global operations * * @param str $strLabel * @param str $strTitle * @param array $arrAttributes * @param string $strTable * @param array $arrRootIds * * @return string|null */ public function globalButtonCallback($strLabel, $strTitle, $arrAttributes, $strTable, $arrRootIds); /** * Call the header callback * * @param array $arrAdd * @return array|null */ public function headerCallback($arrAdd); /** * Call the child record callback * * @param InterfaceGeneralModel $objModel * @return string|null */ public function childRecordCallback(InterfaceGeneralModel $objModel); /** * Call the options callback for given the fields * * @param string $strField * @return array|null */ public function optionsCallback($strField); /** * Call the onrestore callback * * @param int $intID ID of current dataset * @param string $strTable Name of current Table * @param array $arrData Array with all Data * @param int $intVersion Version which was restored */ public function onrestoreCallback($intID, $strTable, $arrData, $intVersion); /** * Call the load callback * * @param string $strField * @param mixed $varValue * @return mixed|null */ public function loadCallback($strField, $varValue); /** * Call onload_callback (e.g. to check permissions) * * @param string $strTable name of current table */ public function onloadCallback(); /** * Call the group callback * * @param type $group * @param type $mode * @param type $field * @param InterfaceGeneralModel $objModelRow * * @return type */ public function groupCallback($group, $mode, $field, $objModelRow); /** * Call the save callback for a widget * * @param array $arrConfig Configuration of the widget * @param mixed $varNew New Value * * @return mixed */ public function saveCallback($arrConfig, $varNew); /** * Call ondelete_callback * * @return void */ public function ondeleteCallback(); /** * Call the onsubmit_callback * * @return void */ public function onsubmitCallback(); /** * Call the oncreate_callback * * @param mixed $insertID The id from the new record * @param array $arrRecord the new record * * @return void */ public function oncreateCallback($insertID, $arrRecord); /** * Get the current pallette * * @param DC_General $objDC * @param array $arrPalette */ public function parseRootPaletteCallback($arrPalette); }
true
79192f26a147c3da7333a48f16c1d5b27714644c
PHP
bulfaitelo/tests
/PHP/in_array/in_array.php
WINDOWS-1252
284
2.90625
3
[]
no_license
<?php echo " case Sensitive <br /><br />"; $os = array("Mac", "NT", "Irix", "Linux"); if (in_array("Irix", $os)) { echo "Tem Irix"; } if (in_array("mac", $os)) { echo "Tem mac"; } echo "<br />"; if (in_array("Mac", $os)) { echo "Tem Mac"; } ?>
true
f0b9c280e78fa0ef106f289d8a0ff84916711517
PHP
gam6itko/dpd-carrier
/src/Type/Geography/Address.php
UTF-8
2,629
2.90625
3
[]
no_license
<?php namespace Gam6itko\DpdCarrier\Type\Geography; use Gam6itko\DpdCarrier\Type\AbstractDeliveryPoint; class Address extends AbstractDeliveryPoint { /** @var string|null */ protected $regionName; /** @var string|null */ protected $street; /** @var string|null */ protected $streetAbbr; /** @var string|null */ protected $houseNo; /** @var string|null */ protected $building; /** @var string|null */ protected $structure; /** @var string|null */ protected $ownership; /** @var string|null */ protected $descript; /** @var string|null */ protected $index; public function getRegionName(): ?string { return $this->regionName; } public function setRegionName(?string $regionName): Address { $this->regionName = $regionName; return $this; } public function getStreet(): ?string { return $this->street; } public function setStreet(?string $street): Address { $this->street = $street; return $this; } public function getStreetAbbr(): ?string { return $this->streetAbbr; } public function setStreetAbbr(?string $streetAbbr): Address { $this->streetAbbr = $streetAbbr; return $this; } public function getHouseNo(): ?string { return $this->houseNo; } public function setHouseNo(?string $houseNo): Address { $this->houseNo = $houseNo; return $this; } public function getBuilding(): ?string { return $this->building; } public function setBuilding(?string $building): Address { $this->building = $building; return $this; } public function getStructure(): ?string { return $this->structure; } public function setStructure(?string $structure): Address { $this->structure = $structure; return $this; } public function getOwnership(): ?string { return $this->ownership; } public function setOwnership(?string $ownership): Address { $this->ownership = $ownership; return $this; } public function getDescript(): ?string { return $this->descript; } public function setDescript(?string $descript): Address { $this->descript = $descript; return $this; } public function getIndex(): ?string { return $this->index; } public function setIndex(?string $index): Address { $this->index = $index; return $this; } }
true
93b7e008195ef723b6cbb8ad5a94fcfde81e5ff5
PHP
barracudanetworks/php-ews
/EWSType/AvailabilityProxyRequestType.php
UTF-8
832
2.84375
3
[]
permissive
<?php /** * Contains EWSType_AvailabilityProxyRequestType. */ /** * Defines whether a proxy request is a cross-site or a cross-forest request. * * @package php-ews\Enumerations */ class EWSType_AvailabilityProxyRequestType extends EWSType { /** * Indicates that this request is cross-forest. * * @since Exchange 2010 * * @var string */ const CROSS_FOREST = 'CrossForest'; /** * Indicates that this request is cross-site. * * @since Exchange 2010 * * @var string */ const CROSS_SITE = 'CrossSite'; /** * Element value. * * @var string */ public $_; /** * Returns the value of this object as a string. * * @return string */ public function __toString() { return $this->_; } }
true
d88b1c4bc60279ca1bbcdd4af3b8743eeaf33b3a
PHP
ISSKJ/php-framework-benchmark
/minph/framework/test/RouteTest.php
UTF-8
1,050
2.53125
3
[ "Apache-2.0" ]
permissive
<?php use PHPUnit\Framework\TestCase; use Minph\Http\Route; use Minph\Exception\FileNotFoundException; class RouteTest extends TestCase { public function setup() { } public function testRoute() { $uri = '/'; try { $res = Route::run($uri); $this->assertEquals($res, 'index'); } catch (FileNotFoundException $e) { $ret = Route::run('/404'); $this->assertEquals($ret, 'error404'); } $uri = '/404'; try { $res = Route::run($uri); $this->assertEquals($res, 'error404'); } catch (FileNotFoundException $e) { $res = Route::run('/404'); $this->assertEquals($res, 'error404'); } $uri = '/04'; try { $res = Route::run($uri); // not reached. $this->assertTrue(false); } catch (FileNotFoundException $e) { $res = Route::run('/404'); $this->assertEquals($res, 'error404'); } } }
true
efa0aa9e0d604812a8d6540aff1c1a13de6fb2c4
PHP
limb-php-framework/limb-app-buildman
/lib/limb/toolkit/src/lmbMockToolsWrapper.class.php
UTF-8
919
2.625
3
[]
no_license
<?php /** * Limb Web Application Framework * * @link http://limb-project.com * * @copyright Copyright &copy; 2004-2007 BIT * @license LGPL http://www.gnu.org/copyleft/lesser.html * @version $Id: lmbMockToolsWrapper.class.php 5007 2007-02-08 15:37:18Z pachanga $ * @package toolkit */ class lmbMockToolsWrapper implements lmbToolkitTools { protected $toolkit; protected $mock; protected $use_only_methods; function __construct($mock, $use_only_methods = array()) { $this->mock = $mock; $this->use_only_methods = $use_only_methods; } function getToolsSignatures() { $signatures = array(); foreach(get_class_methods(get_class($this->mock)) as $method) { if($this->use_only_methods && !in_array($method, $this->use_only_methods)) continue; $signatures[$method] = $this->mock; } return $signatures; } } ?>
true
0eeb2e7f3ddca547dbffbe03003a3c689ba64482
PHP
cuvelierm/ws1-sws-course-materials
/assets/03/examples/formchecking_thanks.php
UTF-8
1,549
3.515625
4
[]
no_license
<?php /** * Guaranteed slashes (if magic_quotes is off, it adds the slashes) * * @param string $string The string to add the slashes to * @return string */ function addPostSlashes($string) { if ((get_magic_quotes_gpc()==1) || (get_magic_quotes_runtime()==1)) return $string; else return addslashes($string); } /** * Guaranteed no slashes (if magic_quotes is on, it strips the slashes) * * @param string $string The string to remove the slashes from * @return string */ function stripPostSlashes($string) { if ((get_magic_quotes_gpc()==1) || (get_magic_quotes_runtime()==1)) return stripslashes($string); else return $string; } ?><!DOCTYPE html> <html> <head> <title>Testform</title> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <?php // Name completed if (isset($_GET['name'])) { echo '<p>Hello ' . htmlentities(stripPostSlashes($_GET['name'])). '</p>'; } // Age completed else if (isset($_GET['age'])) { echo '<p>Hello, ' . htmlentities(stripPostSlashes($_GET['age'])). ' year old stranger</p>'; } // Name not completed else { echo '<p>Hello, stranger</p>'; } ?> <div id="debug"> <?php /** * Helper Functions * ======================== */ /** * Dumps a variable * @param mixed $var * @return */ function dump($var) { echo '<pre>'; var_dump($var); echo '</pre>'; } /** * Main Program Code * ======================== */ // dump $_GET dump($_GET); ?> </div> </body> </html>
true
bd4ab2bbd1e2c0db5a04afa0f68e9feab699299c
PHP
m-narayan/bbb-conf
/classes/DBAccess.php
UTF-8
13,613
2.578125
3
[]
no_license
<?php class DBAccess{ public function checkMaxMeeting($user_id){ $msg=""; $period=-1; $max_conference=-1; $sql="select * from user_settings where user_id=".$user_id; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $period=$row['period']; $max_conference=$row['max_conference']; } if($period==0){ $date=date("Ymd"); $date = date("Ymd",strtotime(date("Ymd", strtotime($date)) . "-6 day")); $sql="select count(*) as meeting_count from meetings where owner_id=".$user_id." and meeting_date >=".$date." and meeting_date<=".date("Ymd"); $result=mysql_query($sql); $row=mysql_fetch_array($result); if($max_conference != -1 && $row['meeting_count'] >= $max_conference ){ $msg="You can create only a maximum of $max_conference conference in a week"; } }else if($period==1){ $date=date("Ymd"); $date = date("Ymd",strtotime(date("Ymd", strtotime($date)) . "-1 month")); $sql="select count(*) as meeting_count from meetings where owner_id=".$user_id." and meeting_date >=".$date." and meeting_date<=".date("Ymd"); $result=mysql_query($sql); $row=mysql_fetch_array($result); if($max_conference != -1 && $row['meeting_count'] >= $max_conference ){ $msg="You can create only a maximum of $max_conference conference in a month"; } } echo $msg; } public function getSetting($id){ $sql="select a.full_name,b.* from users a,user_settings b where a.id=b.user_id and b.id=".$id; $result=mysql_query($sql); $row=mysql_fetch_array($result); return $row; } public function updateSetting($id,$period,$max_conference) { $sql="update user_settings set period=".$period.", max_conference=".$max_conference." where id=".$id; mysql_query($sql); } public function getAllSettings(){ $sql="select a.full_name,b.* from users a,user_settings b where a.id=b.user_id order by full_name"; return(mysql_query($sql)); } public function addUserSettings($user_id,$period,$max_conference) { $sql="select * from user_settings where user_id=".$user_id; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count==1){ $sql="update user_settings set period=".$period.", max_conference=".$max_conference." where user_id=".$user_id; mysql_query($sql); }else{ $sql="insert into user_settings (user_id,period,max_conference) values(".$user_id.",".$period.",".$max_conference.")"; mysql_query($sql); } } public function getAllUsersExceptAdmin(){ $sql="select * from users where login <>'admin' order by full_name"; return(mysql_query($sql)); } public function checkUser($login,$pass,$userType){ $sql="select * from users where login='".$login."' and password='".$pass."' and user_type='".$userType."'"; $result=mysql_query($sql); $count=mysql_num_rows($result); return $count; } public function getUser($login,$pass){ $sql="select * from users where login='".$login."' and password='".$pass."'"; $result=mysql_query($sql); $row=mysql_fetch_array($result); return $row; } public function createOrUpdateUser($login,$password,$email,$full_name,$user_type){ $sql="select * from users where login='".$login."'"; $result=mysql_query($sql); $count=mysql_num_rows($result); $row=mysql_fetch_array($result); $pos=strpos($full_name,'.'); $full_name=substr($full_name,$pos+2,strlen($full_name)); $full_name=str_replace(',', '', $full_name); $user_type=strtolower($user_type); if($count==1){ $sql="update users set email='".$email."',password='".$password."',full_name='".$full_name."',user_type='".$user_type."' where login='".$login."'"; }else{ $sql="insert into users (login,password,email,full_name,user_type) values ('".$login."','".$password."','".$email."','".$full_name."','".$user_type."')"; } mysql_query($sql); } public function addServer($name,$url,$salt,$status) { $sql="insert into servers (name,url,salt,status) values('".$name."','".$url."','".$salt."',".$status.")"; mysql_query($sql); } public function updateServer($id,$name,$url,$salt,$status) { $sql="update servers set name='".$name."',url='".$url."',salt='".$salt."',status=".$status." where id=".$id; mysql_query($sql); } public function deleteServer($id) { $sql="delete from servers where id=".$id; mysql_query($sql); } public function deleteSettings($id) { $sql="delete from user_settings where id=".$id; mysql_query($sql); } public function getServer($id){ $sql="select * from servers where id=".$id; $result=mysql_query($sql); $row=mysql_fetch_array($result); return($row); } public function getAllServers(){ $sql="select * from servers"; return(mysql_query($sql)); } public function getRandomServer(){ $sql="select * from servers where status=1 order by rand() limit 1"; $result=mysql_query($sql); $row=mysql_fetch_array($result); return($row); } public function checkServerInUse($id){ $flag=false; $sql="select * from meetings where server_id=".$id; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count>=1) $flag=true; return $flag; } public function fromDBDate($date){ $y=substr($date,0,4); $m=substr($date,4,2); $d=substr($date,6,2); return $m."/".$d."/".$y; } public function setMeetingId($id,$meetingid){ $sql="update meetings set meetingid='".$meetingid."' where id=".$id; mysql_query($sql) or die(mysql_error()); } public function setStarted($id){ $sql="update meetings set started='true' where id=".$id; mysql_query($sql) or die(mysql_error()); } public function addMeeting($server_id,$attendeePw,$moderatorPw,$owner_id,$name,$welcome_msg,$meeting_date,$duration,$speaker,$topic,$slide) { $temp=$meeting_date; $temp=explode(" ",$temp); $meeting_date=$temp[0]; $meeting_time=$temp[1]; $date=explode("/",$meeting_date); $meeting_date=$date[2].$date[0].$date[1]; $sql="insert into meetings (slide,server_id,owner_id,name,welcome_msg,record,meeting_date,meeting_time,duration,moderator_password,attendee_password,speaker,topic,status) "; $sql=$sql." values('".$slide."',".$server_id.",".$owner_id.",'".$name."','".$welcome_msg."','true','".$meeting_date."','".$meeting_time."',".$duration.",'".$moderatorPw."','".$attendeePw."','".$speaker."','".$topic."','reject')"; mysql_query($sql); $sql = "select max(id) as max from meetings"; $result=mysql_query($sql); $row = mysql_fetch_array($result); return($row['max']); } public function broadcast($meeting_id,$users){ $sql="delete from broadcast where meeting_id=".$meeting_id; mysql_query($sql); foreach($users as $user_id){ $sql="insert into broadcast (meeting_id,user_id) values(".$meeting_id.",".$user_id.")"; mysql_query($sql); } } public function addInvitations($meeting_id,$users){ $sql="delete from invitations where meeting_id=".$meeting_id; mysql_query($sql); foreach($users as $user_id){ $sql="insert into invitations (meeting_id,user_id) values(".$meeting_id.",".$user_id.")"; mysql_query($sql); } } public function getMeeting($id){ $sql="select * from meetings where id=".$id; $result=mysql_query($sql); $row=mysql_fetch_array($result); return($row); } public function getMeetingDetail($id){ $sql="select a.*,b.full_name from meetings a,users b where a.owner_id=b.id and a.id=".$id; $result=mysql_query($sql); $row=mysql_fetch_array($result); return($row); } public function getAllMeetings($owner_id){ $sql="select * from meetings where owner_id=".$owner_id." order by meeting_date desc"; return(mysql_query($sql)); } public function getTodayMeetings($owner_id){ $sql="select * from meetings where owner_id=".$owner_id." and meeting_date=".date("Ymd")." order by meeting_date desc"; return(mysql_query($sql)); } public function getPastMeetings($owner_id){ $sql="select * from meetings where owner_id=".$owner_id." and meeting_date<".date("Ymd")." order by meeting_date desc"; return(mysql_query($sql)); } public function getFutureMeetings($owner_id){ $sql="select * from meetings where owner_id=".$owner_id." and meeting_date>".date("Ymd")." order by meeting_date desc"; return(mysql_query($sql)); } public function getAllConferences(){ $sql="select a.*,b.full_name from meetings a,users b where a.owner_id=b.id"; $sql=$sql." and a.meeting_date>=".date("Ymd")." order by meeting_date"; return(mysql_query($sql)); } public function getInvitations($owner_id){ $sql="select a.*,b.full_name from meetings a,users b where a.status='accept' and a.owner_id=b.id and owner_id<>".$owner_id; $sql=$sql." and a.id in (select meeting_id from broadcast where user_id=".$owner_id." and meeting_id not in "; $sql=$sql." (select meeting_id from invitations where user_id=".$owner_id."))"; return(mysql_query($sql)); } public function getJoinRequests($owner_id){ $sql="select a.*,b.full_name from meetings a,users b where a.status='accept' and a.owner_id=b.id and owner_id<>".$owner_id; $sql=$sql." and a.id not in (select meeting_id from invitations where user_id=".$owner_id.")"; return(mysql_query($sql)); } public function getAllUsers($owner_id){ $sql="select * from users where id<>".$owner_id." and id<>1 order by full_name"; return(mysql_query($sql)); } public function accept($meeting_id){ $sql="update meetings set status='accept' where id =".$meeting_id; mysql_query($sql); } public function reject($meeting_id){ $sql="update meetings set status='reject' where id =".$meeting_id; mysql_query($sql); } public function enroll($meeting_id,$user_id){ $sql="delete from invitations where meeting_id=".$meeting_id." and user_id=".$user_id; mysql_query($sql); $sql="insert into invitations (meeting_id,user_id) values(".$meeting_id.",".$user_id.")"; mysql_query($sql); } public function deenroll($meeting_id,$user_id){ $sql="delete from invitations where meeting_id=".$meeting_id." and user_id=".$user_id; mysql_query($sql); } public function enrolledConferences($owner_id){ $sql="select a.*,b.full_name from meetings a,users b,invitations c where a.id=c.meeting_id and b.id=c.user_id and owner_id<>".$owner_id; return(mysql_query($sql)); } public function getBroadcast($meeting_id,$user_id){ $flag=false; $sql="select * from broadcast where meeting_id=".$meeting_id." and user_id=".$user_id; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count>=1) $flag=true; return($flag); } public function checkEnrollment($meeting_id,$user_id){ $flag=false; $sql="select * from invitations where meeting_id=".$meeting_id." and user_id=".$user_id; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count>=1) $flag=true; return($flag); } public function checkOldPassword($pass){ $flag=false; $sql="select * from users where password='".$pass."' and id=1"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count>=1) $flag=true; return($flag); } public function changePassword($pass){ $sql="update users set password='".$pass."' where id=1"; mysql_query($sql); } } ?>
true
7d72cb7d8c3b07f2343d6fc202cc6dea9e005ff8
PHP
corowne/lorekeeper
/app/Models/Feature/FeatureCategory.php
UTF-8
2,826
2.78125
3
[ "MIT" ]
permissive
<?php namespace App\Models\Feature; use Config; use App\Models\Model; class FeatureCategory extends Model { /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'sort', 'has_image', 'description', 'parsed_description' ]; /** * The table associated with the model. * * @var string */ protected $table = 'feature_categories'; /** * Validation rules for creation. * * @var array */ public static $createRules = [ 'name' => 'required|unique:feature_categories|between:3,100', 'description' => 'nullable', 'image' => 'mimes:png', ]; /** * Validation rules for updating. * * @var array */ public static $updateRules = [ 'name' => 'required|between:3,100', 'description' => 'nullable', 'image' => 'mimes:png', ]; /********************************************************************************************** ACCESSORS **********************************************************************************************/ /** * Displays the model's name, linked to its encyclopedia page. * * @return string */ public function getDisplayNameAttribute() { return '<a href="'.$this->url.'" class="display-category">'.$this->name.'</a>'; } /** * Gets the file directory containing the model's image. * * @return string */ public function getImageDirectoryAttribute() { return 'images/data/trait-categories'; } /** * Gets the file name of the model's image. * * @return string */ public function getCategoryImageFileNameAttribute() { return $this->id . '-image.png'; } /** * Gets the path to the file directory containing the model's image. * * @return string */ public function getCategoryImagePathAttribute() { return public_path($this->imageDirectory); } /** * Gets the URL of the model's image. * * @return string */ public function getCategoryImageUrlAttribute() { if (!$this->has_image) return null; return asset($this->imageDirectory . '/' . $this->categoryImageFileName); } /** * Gets the URL of the model's encyclopedia page. * * @return string */ public function getUrlAttribute() { return url('world/trait-categories?name='.$this->name); } /** * Gets the URL for a masterlist search of characters in this category. * * @return string */ public function getSearchUrlAttribute() { return url('world/traits?feature_category_id='.$this->id); } }
true
27843f4d2e75f3cf643a611043884e7645885b96
PHP
warvels/gms
/api/functionsGMS.php
UTF-8
7,986
2.984375
3
[]
no_license
<?php # ============================================================================================== # /gms/api/functionsGMS.php # ============================================================================================== # Revisions # Ver 0.3 2012/11/27 Initial GET/POST functions # Ver 0.4 2012/12/08 Database functions moved to here, Added DB function "findSubjectArea()" to find a SUBJAREA based on passed string # Ver 0.5 2012/12/30 try and catch for call to error_log # ============================================================================================== /* ---------------------------------------------------------------------- ERROR AND LOGGING FUNCTIONS ---------------------------------------------------------------------- */ # ============================================================================================== # GMS error handler function gmsError( $errorCode, $errorText, $av1, $av2 ) { # this is debugging only $displayFlag = 0; if ( $displayFlag ) { #echo '<br> GMSerror <br> '; printf( ' <b>GMS-Error: '. $errorCode. ' '. $errorText. '</b>'); } # Log errors $log_file = 'logs/gmserror.log'; $dlm = ';'; # create an entry with date.time, errorcode, error text. to get NEWLINE must put \r\n in double quotes. $logdata = gmdate('Y-m-d H:i:s'). ' UTC '. $dlm. $errorCode. $dlm. $errorText. $dlm. "\r\n"; error_log($logdata, 3, $log_file); return 1; } # GMS logging function gmsLog( $logData, $newFile, $av1, $av2 ) { # $log_file = 'logs/gmslog.log'; $dlm = ';'; # create an entry with date.time, errorcode, error text. to get NEWLINE must put \r\n in double quotes. try { $logdata = gmdate('Y-m-d H:i:s'). ' UTC '. $dlm. $logData. "\r\n"; error_log($logdata, 3, $log_file); } catch(GMSLOGException $e) { # returns error as json objects echo '{"error":{"text":'. $e->getMessage() .'}}'; } return 1; } # ============================================================================================== # GMS OS level file writer function gmsfwrite( $filename, $content ) { // Let's make sure the file exists and is writable first. if (is_writable($filename)) { // In our example we're opening $filename in append mode. // The file pointer is at the bottom of the file hence // that's where $somecontent will go when we fwrite() it. if (!$handle = fopen($filename, 'a')) { # set error stateecho $error ="Cannot open file ($filename)"; return 0; } // bindary : fwrite($fh,utf8_encode($content)); // fwrite($fp, pack('L',$content) ); // Write $somecontent to our opened file. if (fwrite($handle, $content) === FALSE) { # set error state $error = "Cannot write to file ($filename)"; return 0; } # Success, wrote $content) to file ($filename)"; fclose($handle); } else { $error = "The file $filename is not writable"; return 0; } } /* ---------------------------------------------------------------------- CORE DATABASE functions ---------------------------------------------------------------------- */ /** * Database OPEN based on gms config file * @param * @return $dbh PDO database handle * @throws */ function getConnection() { require("config.db.php"); $dbh = new PDO($pdo_connect, $db_user, $db_pass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $dbh; } /** * Database FIND SUBJAREA table from passed string to match 'AREA' column * @param : $subject_search = string to search for * @return : ID of subjarea row found if any * @throws */ function findSubjectArea($subject_search) { #---- Calling example : #$y='education'; #$x = 'search for sa = '.$y.' = '.findSubjectArea($y); #gmslog( $x, '', '', ''); #echo $x; $lower_subject = trim( strtolower( $subject_search) ); #printf('subjectarea = '.$lower_subject); #debug var_dump( $lower_subject ); $db_link = getConnection(); if ($db_link) { # query DB for ID of the selected subject area text $query = "select sa.idsubjarea, sa.* from subjarea sa where lower(area) = '". $lower_subject. "'" ; $qresult = dbqueryfetchallGMS( $db_link, $query, '', '' ); #var_dump( $qresult ); #print_r($qresult); if ($qresult) { # From the resutling rows of the query, extract the First row's [0] IDsubjarea (fieldname from db) $subject_id = $qresult[0]['idsubjarea']; if ($subject_id) { return $subject_id; } } } return null; } # ============================================================================================== # ============================================================================================== # ============================================================================================== # ============================================================================================== # ============================================================================================== # EARLY FUNCTIONS # ============================================================================================== # dbopenGMS - Open $pdo_connect definedin included db config. return channnel or exception function dbopenGMS( $db_link, $db_task ) { # if already open, just return the passed db_link if (isset($db_link) AND ($db_link != NULL) ) { #printf(' db link is already set and is Not NULL <br>' ); return $db_link; } include("config.db.php"); ##printf(' pre try pdo open '); try { $pdo_dblink = new PDO( "mysql:host=$db_host;dbname=$db_name", $db_user, $db_pass ); if (!$pdo_dblink) { throw new DBEx("Cannot connect to the database"); } } catch (PDOException $e) { gmsError( 'ECDBOPEN', $e->getMessage(), '', '', '' ); ##printf(' catch 1 '); return null; } catch (DBEx $e) { gmsError( 'ECDBOPENDBEX', $e->getMessage(), '', '', '' ); return null; } # setup Db attributes and return the $pdo_dblink->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo_dblink->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db_link = $pdo_dblink; return $pdo_dblink; } # ============================================================================================= # dbqueryGMS - Validates the query passed. return results from function. rowcnt return as param # does not get any rows. function dbqueryGMS( $db_link, $query_str, $row_count, $av1) { #$result = $stmt->setFetchMode(PDO::FETCH_NUM); # will return results in array with integer index (not col name) try { $result = $db_link->query( $query_str ); $row_count = $result->rowCount(); } catch (PDOException $e) { print_r($db_link->errorInfo()); gmsError( 'ECDBQUERY', $e->getMessage(), '', '', '' ); $row_count = 0; return null; } return $result; } # ============================================================================================= # dbqueryfetchallGMS - Validates the query passed and returns all results from query function dbqueryfetchallGMS( $db_link, $query_str, $av2, $av1) { try { $stmt = $db_link->query( $query_str ); } catch (PDOException $e) { print_r($db_link->errorInfo()); gmsError( 'ECDBQUERY', $e->getMessage(), '', '', '' ); $row_count = 0; return null; } try { $result = $stmt->fetchAll(PDO::FETCH_ASSOC); $row_count = $stmt->rowCount(); return $result; } catch (PDOException $e) { print_r($db_link->errorInfo()); gmsError( 'ECDBFETCHALL', $e->getMessage(), '', '', '' ); $row_count = 0; return null; } } # ============================================================================================== # dbupdateGMS - Execute the query passed and insert into the table function dbupdateGMS( $db_link, $insert_query, $insertId, $av1) { # exec for INSERT, UPDATE, DELETE statements. # try { $result = $db_link->exec( $insert_query ); #$insertId = $db_link->lastInsertId(); } catch (PDOException $e) { gmsError( 'ECDBUPDATE', $e->getMessage(), '', '', '' ); return null; } return $result; #return $insertId; } ?>
true
c068c73c24f91d8ff9281dada64cd8bdb4744e77
PHP
kanata-php/kanata-core
/src/Kanata/Models/Interfaces/SimpleCrudInterface.php
UTF-8
220
2.53125
3
[]
no_license
<?php namespace Kanata\Models\Interfaces; interface SimpleCrudInterface { public function create(array $data); public function update(array $data); public function get($id); public function delete(); }
true
4373709d60a9319c9ef618e1673ddb62bb7bb141
PHP
AndrewLivancov/php.study
/book-217.1.php
UTF-8
548
3.546875
4
[]
no_license
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <?php ## Использование ... function toomanyargs($fst, $snd, $thd, $fth) { echo "Первый параметр: $fst<br />"; echo "Второй параметр: $snd<br />"; echo "Третий параметр: $thd<br />"; echo "Четвертый параметр: $fth<br />"; } // Отображаем строки одну под другой $planets = ["Меркурий", "Венера", "Земля", "Марс"]; toomanyargs(...$planets); ?> </body> </html>
true
aad764903763fde19620781c92b70200e42f1923
PHP
cx-kyle/c2c
/common/models/member/MemberBindbank.php
UTF-8
2,713
2.734375
3
[ "Apache-2.0" ]
permissive
<?php namespace common\models\member; use Yii; use yii\web\NotFoundHttpException; use yii\db\ActiveRecord; /** * This is the model class for table "{{%member_bindbank}}". * * @property int $id * @property int $member_id 用户id * @property int $type 收款方式:1:支付宝,2:微信,3:银行卡 * @property string $name 姓名 * @property string $account 收款账号 * @property string $money_photo 付款码 * @property string $bank 开户行 * @property string $branch 开户支行 * @property int $status 状态 */ class MemberBindbank extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return '{{%member_bindbank}}'; } /** * {@inheritdoc} */ public function rules() { return [ [['type', 'name', 'account'], 'required'], [['member_id', 'type', 'status'], 'integer'], [['name', 'bank'], 'string', 'max' => 20], [['account','branch'], 'string', 'max' => 50], [['money_photo'], 'string', 'max' => 255], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'member_id' => '用户id', 'type' => '收款方式:0:支付宝,1:微信,2:银行卡', 'name' => '姓名', 'account' => '收款账号', 'money_photo' => '付款码', 'bank' => '开户行', 'branch' => '开户支行', 'status' => '状态', ]; } /** * 绑定银行信息,支付宝,微信 * */ public function bind() { if (!$this->validate()) { return null; } $prinfo = new MemberBindbank(); $prinfo->member_id = Yii::$app->user->identity->member_id; $prinfo->type = $this->type; $prinfo->name = $this->name; $prinfo->account = $this->account; if($prinfo->type == 0 || $prinfo->type == 1 ){ /** * 支付宝,微信信息绑定; */ if (!$this->money_photo) { throw new NotFoundHttpException('付款码不能为空.'); } $prinfo->money_photo = $this->money_photo; }else{ /** * 银行卡信息; */ if (!$this->bank) { throw new NotFoundHttpException('开户行不能为空.'); } $prinfo->bank = $this->bank; // 开户行 $prinfo->branch = $this->branch; // 开户支行 } return $prinfo->save() ? $prinfo : null; } }
true
79cacc057d27764377dd649916e0fb9e2842e485
PHP
nskun/desiginpattern
/PHP/Visitor/ListVisitor.php
UTF-8
982
3.25
3
[]
no_license
<?php require_once '/Visitor.php'; /** * Description of ListVisitor * * @author shain */ class ListVisitor extends Visitor{ private $currentDir; public function __construct() { $this->currentDir = ""; } public function visit($visitName) { $method = 'visit' . get_class($visitName); $this->$method($visitName); } private function visitFile(File $file) { print htmlentities($this->currentDir . "/" . $file->toString()) . "<BR>"; } private function visitMyDirectory(MyDirectory $directory) { print htmlentities($this->currentDir . "/" . $directory->toString()) . "<BR>"; $savedir = $this->currentDir; $this->currentDir = $this->currentDir . "/" . $directory->getName(); $it = $directory->iterator(); while($it->valid()) { $entry = $it->current(); $entry->accept($this); $it->Next(); } $this->currentDir = $savedir; } }
true
9bb4c8ec97f37b40edc650c61b4e959e1b2e0de8
PHP
aysegulYalcinkaya/Sam
/ConvertUTCtoEST/plotData.php
UTF-8
2,731
3.109375
3
[]
no_license
<?php include_once 'phplot/phplot.php'; class plotData { var $fileName; var $spikeFileName; var $imageFileName; function __construct($fileName, $spikeFileName) { $this->fileName = $fileName; $this->spikeFileName = $spikeFileName; $filepart2=substr($fileName,strrpos($fileName, "/")+1); $fname = substr($fileName, 0, strrpos($fileName, "/")+1) . substr($filepart2, strpos($filepart2, "_") +1, strrpos($filepart2, ".") - strpos($filepart2, "_") - 1); echo $fname; $this->imageFileName = $fname; } function createGraph($xIndex=0,$y1Index=1,$y2Index=1) { $file = fopen($this->fileName, "r"); $file2 = fopen($this->spikeFileName, "r"); // Define some data $read=false; if ($line = fgetcsv($file) and $line2 = fgetcsv($file2)){ $read=true; } $i = 0; $start=1; while ($read) { $data = Array(); while ($i < 1000 and $read) { if ($line = fgetcsv($file) and $line2 = fgetcsv($file2)){ $read=true; $data[] = array( $line[$xIndex], $line[$y1Index], $line2[$y2Index] ); $i++; } else { $read=false; } } $graphFile= $this->imageFileName."_".$start."-".($start+$i-1).".png"; $title="Data from row ". $start." to ".($start+$i-1); $start=$start+$i; $i=0; $plot = new PHPlot(10000, 400, $graphFile); $plot->SetIsInline(True); $min = min(array_column($data, 1)); $max = max(array_column($data, 1)); if ($max=="nan"){ $max=$min+5; } $legendText = array( 'Original Data', 'Spike Removed' ); $plot->SetTitle($title); $plot->SetImageBorderType('plain'); $plot->SetPlotType('lines'); $plot->SetDataType('text-data'); $plot->SetDataColors(array( 'red', 'blue' )); $plot->SetDataValues($data); $plot->SetPlotAreaWorld(NULL, $min - 1, NULL, $max + 1); $plot->SetLegend($legendText); $plot->SetXDataLabelAngle(90); $plot->SetLineStyles('solid'); $plot->SetXTickLabelPos('none'); $plot->SetXTickPos('none'); // Draw it $plot->DrawGraph(); } } } ?>
true
0190dde9df80457e5d7a843f7800f225cf54425e
PHP
uomer/frtmall
/mydb_class.php
GB18030
1,708
2.96875
3
[]
no_license
<?php /** ࣺݿIJࡣ **/ class mydb { //ֻڲõӷ static private function connect(){ return new mysqli("localhost","root","111111","frtm"); } public function select($sql){ $db = self::connect(); $db->query('set names gbk'); $re = $db->query($sql); $array = array(); while($row = $re->fetch_assoc()){ $array[]=$row; } $db->close(); if (count($array) > 0){ return $array; }else{ return false; } } public function insert($tab,$col,$val){ $db = self::connect(); $db->query('set names gbk'); $sql = 'insert into '.$tab.' ('.$col.') values ('.$val.')'; //echo $sql; $bool = $db->query($sql); $db->error; $db->close(); if ($bool == true){ return $bool; }else{ echo 'ûгɹ...<br />'; return false; } } public function query($sql) { $db = self::connect(); $db->query('set names gbk'); $bool = $db->query($sql); $db->close(); if ($bool == true){ return $bool; }else{ echo 'ûгɹ...<br />'; } } public function del($tab,$whe){ $db = self::connect(); $db->query('set names gbk'); $sql = "delete from {$tab} {$whe}"; $bool = $db->query($sql); if ($bool == true){ return $bool; }else{ echo 'ûгɹ...<br />'; } } public function update($tab,$cols,$vals,$whe) { $db = self::connect(); $db->query('set names gbk'); $set = ''; for ($i=0; $i < count($cols); $i++) { $set .="{$cols[$i]}={$vals[$i]}"; if ($i < count($cols) - 1){ $set .= ','; } } $sql = "update {$tab} set {$set} {$whe}"; //echo $sql; $bool = $db->query($sql); $db->close(); return $bool; } } $db = new mydb();
true
754ae71934635961c738b8445f29791b5790f58c
PHP
Danzabar/phalcon-starter
/app/controllers/BaseController.php
UTF-8
1,005
2.84375
3
[]
no_license
<?php use Phalcon\Mvc\Controller; /** * The Base controller defines basic behaivour for all other controllers * */ class BaseController extends Controller { /** * Renders and outputs a view * * @return String * @author Dan Cox */ public function renderView( $view, Array $params = Array(), $code = 200) { $content = $this->view->render($view, $params); $this->response->setStatusCode($code, NULL); $this->response->setContent($content); } /** * Return a json response * * @return void * @author Dan Cox */ public function json($content = Array(), $code = 200, $type = NULL) { $this->response->setStatusCode($code, $type); $this->response->setJsonContent($content); } /** * Returns a basic response * * @return void * @author Dan Cox */ public function response($content = '', $code = 200, $type = NULL) { $this->response->setStatusCode($code, $type); $this->response->setContent($content); } } // END class BaseController extends Controller
true
bba9e1f3a55f4a6e4f27648b4dd47d605f5f08f4
PHP
icepoke/swooleyaf
/libs_frame/SyMessagePush/JPush/Report/MessageStatus.php
UTF-8
3,069
2.6875
3
[ "BSD-3-Clause" ]
permissive
<?php /** * 送达状态查询 * User: 姜伟 * Date: 2019/6/26 0026 * Time: 11:27 */ namespace SyMessagePush\JPush\Report; use SyConstant\ErrorCode; use SyException\MessagePush\JPushException; use SyMessagePush\JPush\ReportBase; use SyMessagePush\PushUtilJPush; use SyTool\Tool; class MessageStatus extends ReportBase { /** * 消息ID * @var string */ private $msg_id = ''; /** * 设备ID列表 * @var array */ private $registration_ids = []; /** * 日期 * @var string */ private $date = ''; public function __construct(string $key) { parent::__construct($key); $this->reqHeader['Authorization'] = PushUtilJPush::getReqAuth($key, 'app'); $this->serviceUri = '/v3/status/message'; $this->reqData['date'] = date('Y-m-d'); } private function __clone() { } /** * @param string $msgId * @throws \SyException\MessagePush\JPushException */ public function setMsgId(string $msgId) { if (ctype_digit($msgId)) { $this->reqData['msg_id'] = $msgId; } else { throw new JPushException('消息ID不合法', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } } /** * @param array $registrationIds * @throws \SyException\MessagePush\JPushException */ public function setRegistrationIds(array $registrationIds) { $needNum = count($registrationIds); if ($needNum == 0) { throw new JPushException('设备ID列表不能为空', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } elseif ($needNum > 1000) { throw new JPushException('设备ID列表不能超过1000个', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } foreach ($registrationIds as $eRegistrationId) { if (ctype_alnum($eRegistrationId)) { $this->registration_ids[$eRegistrationId] = 1; } } } /** * @param int $dayTime * @throws \SyException\MessagePush\JPushException */ public function setDate(int $dayTime) { if ($dayTime > 0) { $this->reqData['date'] = date('Y-m-d', $dayTime); } else { throw new JPushException('日期时间戳不合法', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } } public function getDetail() : array { if (!isset($this->reqData['msg_id'])) { throw new JPushException('消息ID不能为空', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } if (empty($this->registration_ids)) { throw new JPushException('设备ID列表不能为空', ErrorCode::MESSAGE_PUSH_PARAM_ERROR); } $this->reqData['registration_ids'] = array_keys($this->registration_ids); $this->curlConfigs[CURLOPT_URL] = $this->serviceDomain . $this->serviceUri; $this->curlConfigs[CURLOPT_POST] = true; $this->curlConfigs[CURLOPT_POSTFIELDS] = Tool::jsonEncode($this->reqData, JSON_UNESCAPED_UNICODE); return $this->getContent(); } }
true
c32bc0faee294e72599da545abd7c0a93261e819
PHP
jaaic/invoice-payments
/app/Console/Commands/GeneratePaymentReminders.php
UTF-8
2,999
2.734375
3
[]
no_license
<?php namespace App\Console\Commands; use App\Core\Constants; use App\Models\Invoice; use App\Models\Reminder; use App\Modules\Invoicing\Factory\ReminderFactory; use App\Modules\Invoicing\Services\ReminderGenerationService; use Illuminate\Console\Command; use Illuminate\Support\Facades\Log; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class GeneratePaymentReminders extends Command { const BATCH_SIZE = 50; /** @var string */ protected $signature = 'generate-paymentReminders'; /** @var string */ protected $description = 'generate payment reminders such as emails, sms, notifications'; /** * @param InputInterface $input * @param OutputInterface $output */ public function execute(InputInterface $input, OutputInterface $output): void { $invoice = new Invoice(); $totalInvoices = $invoice->getUnpaidInvoices(true)[0] ?? 0; if ($totalInvoices == 0){ Log::info('No more unpaid invoices to generate EMAILS, SMS & NOTIFICATIONS '); exit(0); } $upper = 0; // process in batches while ($upper < $totalInvoices) { $invoices = $invoice->getUnpaidInvoices(false, $upper, static::BATCH_SIZE); if (empty($invoices)) { Log::info('No more unpaid invoices to generate EMAILS, SMS & NOTIFICATIONS '); exit(0); } $reminders = $this->generateReminders($invoices); $this->saveToDatabase($reminders); $upper += static::BATCH_SIZE; } } /** * @param array $reminders */ protected function saveToDatabase(array $reminders): void { $emails = $reminders[Constants::CHANNEL_EMAIL] ?? []; $sms = $reminders[Constants::CHANNEL_SMS] ?? []; $notifications = $reminders[Constants::CHANNEL_NOTIFICATION] ?? []; $reminderFactory = new ReminderFactory(); $this->saveRemindersByType($reminderFactory, $emails, Constants::CHANNEL_EMAIL); $this->saveRemindersByType($reminderFactory, $sms, Constants::CHANNEL_SMS); $this->saveRemindersByType($reminderFactory, $notifications, Constants::CHANNEL_NOTIFICATION); } /** * @param ReminderFactory $reminderFactory * @param array $reminders * @param string $type */ protected function saveRemindersByType(ReminderFactory $reminderFactory, array $reminders, string $type): void { if (!empty($reminders)) { /** @var Reminder $reminder */ $reminder = $reminderFactory->getReminderByChannel($type); $reminder::insert($reminders); } } /** * @param array $invoices * @return array */ public function generateReminders(array $invoices): array { $reminderGenerator = new ReminderGenerationService($invoices); return $reminderGenerator->populateReminders(); } }
true
8220b295818b76042cb48febdb26d87d53ee8816
PHP
drager/pophub
/app/view/Users.php
UTF-8
4,566
2.765625
3
[]
no_license
<?php namespace PopHub\View; class Users extends BaseView { private $errorView; private $cookie; private $errorMsg = "Message::Failure"; private $successMsg = "Message::Success"; private $searchFieldName = "q"; private $users = "users"; private $repos = "repos"; private $followers = "followers"; private $user = "user"; private $auth = "authenticated"; private $pages = "pages"; private $sort = "sort"; private $message = "message"; private $search_q = "search_q"; private $search_value = "search_value"; public function __construct() { $this->errorView = new Error(); $this->cookie = new CookieJar(); } public function getErrorMessage() { return $this->errorMsg; } public function getSuccessMessage() { return $this->successMsg; } /** * View for showing all the users * @param Array $context * @return void */ public function showAllUsers(array $context) { $page = $this->getPage(); $sort = $this->getSortBy(); $pages = $context["pages"]; $message = array( "success" => $this->cookie->get($this->successMsg), "failure" => $this->cookie->get($this->errorMsg), ); // Check for see if we tried to get a page that does not exist. if ($page > $pages->getNumPages()) { return $this->errorView->showPageNotFound("/users/?page=" . $page); } // var_dump(count($context["users"])); // die; echo $this->render('users.html', array( $this->users => $context[$this->users], $this->auth => $context[$this->auth], $this->pages => $pages, $this->sort => $sort, $this->message => $message, $this->search_q => $this->searchFieldName )); } /** * View for showing a single user * @param Array $context * @return void */ public function showSingleUser(array $context) { echo $this->render('show_user.html', array( $this->user => $context[$this->user], $this->repos => $context[$this->repos], $this->followers => $context[$this->followers], $this->auth => $context[$this->auth], $this->search_q => $this->searchFieldName )); } /** * View for showing the search results * @param Array $context * @return void */ public function showSearch(array $context) { echo $this->render('search.html', array( $this->users => $context[$this->users], $this->auth => $context[$this->auth], $this->search_q => $this->searchFieldName, $this->search_value => $this->getSearchBy() )); } /** * View for creating/removing a follower * @param Array $context * @return void */ public function createFollower(array $context) { if (isset($context[$this->successMsg])) { $this->cookie->set($this->successMsg, $context[$this->successMsg]); } else if (isset($context[$this->errorMsg])) { $this->cookie->set($this->errorMsg, $context[$this->errorMsg]); } header('Location: ' . "/users/", true, 303); die; } public function getSearchFieldName() { return $this->searchFieldName; } /** * @return String * DRY? */ public function getSearchBy() { if (isset($_GET[$this->searchFieldName])) { return $this->sanitize($_GET[$this->searchFieldName]); } } /** * @return String * DRY? */ public function getLanguage() { if (isset($_GET["language"])) { return $_GET["language"]; } } /** * @return String * DRY? */ public function getSortBy() { if (isset($_GET["sort_by"])) { return $_GET["sort_by"]; } } /** * @return String * DRY? */ public function getPage() { if (isset($_GET["page"])) { return $_GET["page"]; } } public function getUsersField() { return $this->users; } public function getReposField() { return $this->repos; } public function getFollowersField() { return $this->followers; } public function getUserField() { return $this->user; } public function getAuthField() { return $this->auth; } public function getPagesField() { return $this->pages; } public function getSortField() { return $this->sort; } public function getMessageField() { return $this->message; } public function getSearchField() { return $this->search_q; } public function getSearchValueField() { return $this->search_value; } private function sanitize($input) { $temp = trim($input); return filter_var($temp, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW); } }
true
be28f82533622a609419908f71bbcb86ca3d81ee
PHP
amilkhael/redlasalle
/modelo/OEduBO.php
UTF-8
1,423
2.609375
3
[]
no_license
<?php class OEduBO { //Constructor public function __construct() { } //Metodos public function despliega($tipo) { $bd = new ConectaBD; $bd->conectar(); $query = 'SELECT PK_O_Edu, nombre FROM o_edu WHERE FK_Tipo = '.$tipo.' ORDER BY nombre ASC'; $nombreCarrera = $bd->escribir($query); $query = 'SELECT PK_Plantel FROM plantel ORDER BY Nombre_Corto ASC'; $plantel = $bd->escribir($query); while ($filaCarrera = mysqli_fetch_row($nombreCarrera)){ echo "<tr>\n"; echo '<td>'.$filaCarrera[1]."</td>\n"; $query = 'SELECT plantel.PK_Plantel FROM plantel, plantel_o_edu WHERE plantel.PK_Plantel = plantel_o_edu.FK_Plantel AND plantel_o_edu.FK_O_Edu = '.$filaCarrera[0].' ORDER BY plantel.Nombre_Corto ASC'; $carreras = $bd->escribir($query); $filaCarreraPlantel = mysqli_fetch_row($carreras); mysqli_data_seek ( $plantel , 0 ); while ($filaPlantel = mysqli_fetch_row($plantel)) { if ($filaCarreraPlantel){ if ($filaCarreraPlantel[0] == $filaPlantel[0]){ echo "\t<td><span class='glyphicon glyphicon-ok-sign'></span></td>\n"; $filaCarreraPlantel = mysqli_fetch_row($carreras); } else { echo "\t<td></td>\n"; } } else { echo "\t<td></td>\n"; } } echo "</tr>\n"; } $bd->desconectar(); } } ?>
true
165a6ed2f7c21398a1f8b149714b629289fd76a4
PHP
centralnicgroup-opensource/rtldev-middleware-php-sdk
/tests/ClientFactoryTest.php
UTF-8
2,161
2.515625
3
[ "MIT" ]
permissive
<?php //declare(strict_types=1); namespace CNICTEST; use CNIC\ClientFactory as CF; use CNIC\HEXONET\Client as CL; final class ClientFactoryTest extends \PHPUnit\Framework\TestCase { /** * @var \CNIC\HEXONET\SessionClient|null $cl */ public static $cl; /** * @var string user name */ public static $user; /** * @var string password */ public static $pw; public static function setUpBeforeClass(): void { //session_start(); self::$user = getenv("TESTS_USER_CNR") ?: ""; self::$pw = getenv("TESTS_USERPASSWORD_CNR") ?: ""; } /** * Basic test for getClient with Registrar HEXONET * @return void */ public function testHexonetClient1() { $cl = CF::getClient([ "registrar" => "HEXONET" ]); $this->assertInstanceOf(CL::class, $cl); } /** * Extended Basic test for getClient with Registrar HEXONET * @return void */ public function testHexonetClient2() { $cl = CF::getClient([ "registrar" => "HEXONET", "username" => self::$user, "password" => self::$pw, "sandbox" => true, "referer" => "https://www.hexonet.net", "ua" => [ "name" => "WHMCS", "version" => "8.2.0", "modules" => [ "ispapi" => "7.0.4" ] ], "proxyserver" => "http://192.168.2.31", "logging" => true ]); $this->assertInstanceOf(CL::class, $cl); } /** * Basic test for getClient with Registrar CNR * @return void */ public function testCNRClient() { $cl = CF::getClient([ "registrar" => "CNR" ]); $this->assertInstanceOf(CL::class, $cl); } /** * Basic test for getClient with invalid Registrar ID * @return void */ public function testInvalidClient() { $this->expectException(\Exception::class); $cl = CF::getClient([ "registrar" => "InvalidRegistrar" ]); } }
true
444f70f6a2a213c35d6cc506bbf7cf7cda1d104f
PHP
Raymoon2601/Peliculas_2
/database/seeds/RolesTableSeeder.php
UTF-8
767
2.671875
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use App\Models\Role; class RolesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $Roles = array( ['Role' => 'Gerente general'], ['Role' => 'Cajero'], ['Role' => 'Rentador'], ['Role' => 'Conserje'], ['Role' => 'Vigilante'], ['Role' => 'Administración'], ['Role' => 'Aprendiz'], ['Role' => 'Pasante'], ['Role' => 'CEO'], ['Role' => 'Supervisor'], ); foreach ($Roles as $value) { $role = new Role; $role->name = $value['Role']; $role->status_id = rand(1,3); $role->save(); } } }
true
ce19c1ff19d98a2365aeba8d75c3ea5041118237
PHP
Ridji/EDBlogBundle
/Handler/ObjectGenerator.php
UTF-8
4,498
2.671875
3
[ "MIT" ]
permissive
<?php /** * Created by Eton Digital. * User: Vladimir Mladenovic (vladimir.mladenovic@etondigital.com) * Date: 25.5.15. * Time: 15.39 */ namespace ED\BlogBundle\Handler; use ED\BlogBundle\Interfaces\Model\ArticleInterface; use ED\BlogBundle\Model\Entity\Article; class ObjectGenerator { protected $object; protected $class; protected $constants; protected $metaDataClass; function __construct($class, $metaDataClass) { $this->class = new \ReflectionClass($class); $this->object = new $class(); $this->constants = $this->class->getConstants(); $this->metaDataClass = $metaDataClass; } public function getObject() { return $this->object; } public function setProperty(&$object, $property, $value) { $setter = 'set' . ucfirst($property); if($this->class->hasProperty($property)) { $object->$setter($value); } return $object; } public function getConstant($property) { return $this->constants[ $property ]; } public function generateDraftFromArticle(ArticleInterface $article) { $class = $this->class->name; $draft = new $class(); $this->loadArticle($draft, $article); $draft ->setStatus( Article::STATUS_DRAFTED ) ->setParent($article); return $draft; } /** * Will synchronize changes made on Draft to the master article and set it 'As Published' * * @param ArticleInterface $article * @param ArticleInterface $draft * @return ArticleInterface */ public function generateArticleFromDraft(ArticleInterface &$article, ArticleInterface $draft) { $this->loadArticle($article, $draft); $article ->setStatus( Article::STATUS_PUBLISHED ) ->setParent(null); return $article; } public function generateNewArticleFromDraft(ArticleInterface $draft) { $articleClass = get_class($draft); $article = new $articleClass(); $this->generateArticleFromDraft($article, $draft); return $article; } public function generateNewDraftFromLatestRevision(&$latestDraft, $article) { // last edited version of the document will be shown to user on edit page if(!$latestDraft) { $draft = $this->generateDraftFromArticle($article); $latestDraft = $draft; } else { $draft = $this->generateDraftFromArticle($latestDraft); $draft->setParent($article); } //to enable slug edit $draft ->setSlug( $article->getSlug() ); return $draft; } public function loadArticle(ArticleInterface &$destination, ArticleInterface $src, $skipSlug = false, $skipMetaData = false) { $destination ->setContent( $src->getContent() ) ->setTitle( $src->getTitle() ) ->setExcerpt( $src->getExcerpt() ) ->setExcerptPhoto( $src->getExcerptPhoto()) ->setAuthor( $src->getAuthor()) ->setCategories( $src->getCategories()) ->setTags( $src->getTags()) ; if(!$skipMetaData) { //remove old metaData foreach($destination->getMetaData() as $destMeta) { if($src->getMetaByKey($destMeta->getKey()) === false) { $destination->removeMetaData($destMeta); } } //add new metaData foreach($src->getMetaData() as $srcMeta) { if($destination->hasMetaData($srcMeta) === false && $srcMeta->getKey()!= 'writing_locked') { $destMeta = $destination->getMetaByKey($srcMeta->getKey() ); if ( $destMeta === false) { $metaDataClass = $this->metaDataClass; $destMeta = new $metaDataClass(); } $destMeta ->setKey($srcMeta->getKey()) ->setValue($srcMeta->getValue()) ->setArticle($destination); $destination ->addMetaData($destMeta); } } } if(!$skipSlug) { $destination ->setSlug($src->getSlug()); } } }
true
e79738750ac738f6f6a02b93b53293a2d736d274
PHP
citysites/ymlparser
/src/Offer/MedicineOffer.php
UTF-8
2,295
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace LireinCore\YMLParser\Offer; class MedicineOffer extends AOffer { /** * @var string */ protected $name; /** * @var string */ protected $vendor; /** * @var string */ protected $vendorCode; /** * @return array */ public function getAttributesList() { return array_merge(parent::getAttributesList(), [ //subNodes 'name', 'vendor', 'vendorCode' ]); } /** * @return bool */ public function isValid() { $isValid = parent::isValid(); if ($this->name === null) { $this->addError("Offer: missing required attribute 'name'"); } if ($this->delivery === null) { $this->addError("Offer: missing required attribute 'delivery'"); } elseif ($this->delivery !== 'false') { $this->addError("Offer: incorrect value in attribute 'delivery'"); } if ($this->pickup === null) { $this->addError("Offer: missing required attribute 'pickup'"); } elseif ($this->pickup !== 'true') { $this->addError("Offer: incorrect value in attribute 'pickup'"); } if ($this->cpa !== null && $this->cpa !== '0') { $this->addError("Offer: incorrect value in attribute 'cpa'"); } return $isValid && empty($this->errors); } /** * @return string|null */ public function getName() { return $this->name; } /** * @param string $value * @return $this */ public function setName($value) { $this->name = $value; return $this; } /** * @return string|null */ public function getVendor() { return $this->vendor; } /** * @param string $value * @return $this */ public function setVendor($value) { $this->vendor = $value; return $this; } /** * @return string|null */ public function getVendorCode() { return $this->vendorCode; } /** * @param string $value * @return $this */ public function setVendorCode($value) { $this->vendorCode = $value; return $this; } }
true
6dd5cfee4e753839bd7854bbb719c7777862a48a
PHP
Leopandro/catalogmaterial
/models/AccessUserGroupMaterial.php
UTF-8
1,303
2.5625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; /** * This is the model class for table "access_user_group_material". * * @property integer $id * @property integer $id_user * @property integer $id_group_material * @property integer $is_allow * * @property Catalog $idGroupMaterial * @property User $idUser */ class AccessUserGroupMaterial extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'access_user_group_material'; } /** * @inheritdoc */ public function rules() { return [ [['id_user', 'id_group_material', 'is_allow'], 'integer'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'id_user' => 'Id User', 'id_group_material' => 'Id Group Material', 'is_allow' => 'Is Allow', ]; } /** * @return \yii\db\ActiveQuery */ public function getIdGroupMaterial() { return $this->hasOne(Catalog::className(), ['id' => 'id_group_material']); } /** * @return \yii\db\ActiveQuery */ public function getIdUser() { return $this->hasOne(User::className(), ['id' => 'id_user']); } }
true
ddbe1437c533da7bca066b0bb46bdc9ee446a844
PHP
git4min3/gitamine
/app/Deprecated/Core/Command/RunPluginCommand.php
UTF-8
1,003
2.78125
3
[]
no_license
<?php declare(strict_types=1); namespace Gitamine\Deprecated\Core\Command; /** * Class RunPluginCommand. */ class RunPluginCommand { /** * @var string */ private $plugin; /** * @var string */ private $event; /** * @var string */ private $params; /** * RunPluginCommand constructor. * * @param string $plugin * @param string $event * @param string $params */ public function __construct(string $plugin, string $event, ?string $params = '') { $this->plugin = $plugin; $this->event = $event; $this->params = $params; } /** * @return string */ public function plugin(): string { return $this->plugin; } /** * @return string */ public function event(): string { return $this->event; } /** * @return string */ public function params(): string { return $this->params; } }
true
3f88e600b896394e150eb595b474b5bc1a9da99e
PHP
aniket0135/api
/api/tabelCreator.php
UTF-8
474
2.5625
3
[]
no_license
<?php require_once('Config/database.php'); $sql = "CREATE TABLE IF NOT EXISTS `users`( id INT(11) AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(256) NOT NULL, lastname VARCHAR(256) NOT NULL, email VARCHAR(256) NOT NULL, password VARCHAR(2048) NOT NULL, created datetime NOT NULL, modified timestamp NOT NULL )"; if (mysqli_query(Database::$conn, $sql)) { echo "Table users created successfully"; } else { //echo "Error creating table: " . mysqli_error($conn); } ?>
true
083a05966fb91944d828a5fac142b9a005b7b908
PHP
ssondaii/chat-app
/app/Http/helpers.php
UTF-8
453
2.8125
3
[]
no_license
<?php use App\Models\Permission; if (!function_exists('checkExistPermissionArray')) { /** * check permission array is exist in database. * * @param array $permissionArray * @return boolean */ function checkExistPermissionArray(Array $permissionArray) { if(count($permissionArray) === Permission::whereIn('id', $permissionArray)->count()){ return true; } return false; } }
true
a3636a6db55ef9fd92819d1bb22b704b58ecc824
PHP
tuanhud/quanlytaisan-cntt-dhcantho
/Admin/data_quyennguoidung.php
UTF-8
2,497
2.515625
3
[]
no_license
<?php #Include the connect.php file include('connect.php'); #Connect to the database //connection String $connect = mysql_connect($hostname, $username, $password) or die('Could not connect: ' . mysql_error()); //Select The database $bool = mysql_select_db($database, $connect); if ($bool === False){ print "can't find $database"; } /*if (isset($_GET['update'])) { // UPDATE COMMAND $update_query = "UPDATE `taisanthuocdonvi` SET `SoLuongCuaDonVi`='".$_GET['SoLuongCuaDonVi']."', `DonGiaTS`='".$_GET['DonGiaTS']."' WHERE `MaTaiSan`='".$_GET['MaTaiSan']."' and `MSDV`='".$_GET['MSDV']."'"; $result = mysql_query($update_query) or die("SQL Error 1: " . mysql_error()); echo $result; }*/ /*else if (isset($_GET['insert'])) { // INSERT COMMAND $insert_query = "insert into `taisanthuocdonvi`(MSDV,MaTaiSan) values('".$_GET['MSDV']."','".$_GET['MaTaiSan']."')"; $result = mysql_query($insert_query) or die("SQL Error 1: " . mysql_error()); echo $result; } else if (isset($_GET['delete'])) { // DELETE COMMAND $delete_query = "DELETE FROM `taisanthuocdonvi` WHERE `MaTaiSan`='".$_GET['MaTaiSan']."' AND `MSDV`='".$_GET['MSDV']."'"; $result = mysql_query($delete_query) or die("SQL Error 1: " . mysql_error()); echo $result; } else */ /*if (isset($_GET['check'])) { // SELECT COMMAND $select_query = "SELECT * FROM nguoidung a, coquyen b, quyen c where a.MSCB=b.MSCB and b.MaQuyen=c.MaQuyen and a.MSCB='".$_GET['MSCB']."'"; $result = mysql_query($select_query) or die("SQL Error 1: " . mysql_error()); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $employees[] = array( 'MQ' => $row['MaQuyen'], ); } echo json_encode($employees); } else*/ { $pagenum = $_GET['pagenum']; $pagesize = $_GET['pagesize']; $start = $pagenum * $pagesize; $query = "SELECT SQL_CALC_FOUND_ROWS * FROM nguoidung LIMIT $start, $pagesize"; $result = mysql_query($query) or die("SQL Error 1: " . mysql_error()); $sql = "SELECT FOUND_ROWS() AS `found_rows`;"; $rows = mysql_query($sql); $rows = mysql_fetch_assoc($rows); $total_rows = $rows['found_rows']; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $employees[] = array( 'MSCB' => $row['MSCB'], 'TenCB' => $row['TenCB'], ); } $data[] = array( 'TotalRows' => $total_rows, 'Rows' => $employees ); echo json_encode($data); } ?>
true
7afa5986ef90e06ff191932ca4fb43cfbf9c2dcb
PHP
zhoupenghui/zph
/application/controller/front/PlatformController.class.php
UTF-8
1,452
2.625
3
[]
no_license
<?php class PlatformController extends Controller { //构造方法,当子类被实例化时,此方法应当被触发 public function __construct() { $this->checkLogin(); } //检查用户是否已经登录 private function checkLogin() { //判断用户是否登录,如果登录了,什么都不干,如果没有登录,跳转到登录页面 $ignore = array( 'action' => array('login', 'signin'), 'controller' => array('captcha'), ); //判断是否是过滤掉的操作,如果是,不检测是否登录 if (!in_array(ACTION_NAME, $ignore['action']) && !in_array(CONTROLLER_NAME, $ignore['controller'])) { //过滤掉某些操作,不使用此验证 SessionDbTool::getInstance(); //如果已经登录过,就直接跳转到首页 if (!isset($_SESSION['is_login']) || $_SESSION['is_login'] != 'yes') { if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) { $model = new UserModel; if ($model->checkBySafePassword($_COOKIE['username'], $_COOKIE['password'])) { $_SESSION['is_login'] = 'yes'; } } else { $url = 'index.php?p=front&c=User&a=login'; $this->jump($url, '请先登录'); } } } } }
true
2617a3a9e309829696f5357defe36b263d16c87b
PHP
Phayvanh/resto_full_exemple
/application/models/BookingModel.class.php
UTF-8
501
2.84375
3
[]
no_license
<?php class BookingModel { public function createBooking($userId,$bookingDate,$bookingTime,$tableSize) { $database = new Database(); $sql = 'INSERT INTO Booking(User_Id,BookingDate,BookingTime,TableSize,CreationTimestamp) VALUES (?,?,?,?,now())'; $values= [ $userId, $bookingDate, $bookingTime, $tableSize ]; $database->executeSql($sql,$values); } }
true
18702398729343947a3e7fc34c3ba1968c8d2e6e
PHP
Sanika96/TEproject
/index.php
UTF-8
4,096
2.8125
3
[]
no_license
<?php # Script 3.4 - index.php session_start(); $page_title = 'Welcome to this Site!'; include ('header.html'); ?> <div id="navigation"> <ul> <li><h4><a href="register.php">Register</a></h4></li> </ul> </div> <div id="content"> <br> <?php require_once ('mysqli_connect.php'); // Connect to the db. $errors = array(); // Initialize an error array. if (isset($_POST['submitted1'])) { // Check for an email address: $e = mysqli_real_escape_string($dbc, trim($_POST['email'])); $_SESSION['varname1'] = $e; // Check for the password: $p = mysqli_real_escape_string($dbc, trim($_POST['pass'])); $_SESSION['varname2'] = $p; // Check that they've entered the right email address/password combination: $q1 = "select email from user_info where email='$e' and pass='$p';"; $r1 = @mysqli_query($dbc, $q1); $num1 = @mysqli_num_rows($r1); if ($num1 == 1) { // Match was made. ?><script type="text/javascript">window.alert("You've logged in successfully!");</script><?php ; //==================================================== //Redirection to user_information.php ?><script type="text/javascript">location.href = 'user_information.php';</script><?php //==================================================== } else { // Invalid email address/password combination. $errors[0] = 'Invalid email address and password combination'; } } //===================================================================================================================== if (isset($_POST['submitted2'])) { // Check for an admin's email address: $e_a = mysqli_real_escape_string($dbc, trim($_POST['email_admin'])); $_SESSION['email_admin'] = $e_a; // Check for the admin's password: $p_a = mysqli_real_escape_string($dbc, trim($_POST['pass_admin'])); $_SESSION['pass_admin'] = $p_a; // Check that they've entered the right email address/password combination: $q2 = "select email_admin from admin_login where email_admin='$e_a' and pass_admin='$p_a';"; $r2 = @mysqli_query($dbc, $q2); $num2 = @mysqli_num_rows($r2); if ($num2 == 1) { // Match was made. ?><script type="text/javascript">window.alert("Welcome Admin");</script><?php ; //==================================================== //Redirection to view_users.php ?>$<script type="text/javascript">location.href = 'view_users.php';</script><?php //===================================================== } else { // Invalid email address/password combination. $errors[1] = 'Clearance Level Omega required. You are not Authorized.'; } } // End of the main Submit conditional. mysqli_close($dbc); // Close the database connection. ?> <h1 id="mainhead"><font color='white'>Login</h1> <form action="index.php" method="post"> <p><font color='white'>Email Address: <input type="text" name="email" size="20" maxlength="80" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" /></p><br> <p>Password: <input type="password" name="pass" size="10" maxlength="20" value="<?php if (isset($_POST['pass'])) echo $_POST['pass']; ?>" /><?php echo "<p class=error>$errors[0]</p>"?></p> <p><a href="change_password.php" name="link2"><font color='white'>Change Password</a></p> <p><input type="submit" name="submit1" value="SUBMIT" style="height:18px; width:80px"/></p> <input type="hidden" name="submitted1" value="TRUE" /> </form> <br> <br> <br> <br> <br> <br> <br> <h4>Admin Login</h4> <form action="index.php" method="post"> <p>Email Address: <input type="text" name="email_admin" size="20" maxlength="80" value="<?php if (isset($_POST['email_admin'])) echo $_POST['email_admin']; ?>" /> </p><br> <p>Password: <input type="password" name="pass_admin" size="10" maxlength="20" value="<?php if (isset($_POST['pass_admin'])) echo $_POST['pass_admin']; ?>" /><?php echo "<p class=error>$errors[1]</p>"?></p> <p><input type="submit" name="submit2" value="SUBMIT" style="height:15px; width:80px"/></p> <input type="hidden" name="submitted2" value="TRUE" /> </form> <?php include ('footer.html'); ?>
true
a801fa19493ba0a42b6e654c7b14949d724b7e8a
PHP
pukku/tlpgstheme
/functions.php
UTF-8
4,985
2.671875
3
[ "MIT" ]
permissive
<?php if(!defined('IN_GS')){ die('you cannot load this page directly.'); } /** * Helper functions for the TLP theme */ function tlp_show_process_noop ($text) { return $text; } function tlp_show_process_credits ($text) { $lines = explode("\n", $text); $ret = ''; foreach ($lines as $line) { if (!empty($line)) { $ret .= '<p class="internal">' . $line . '</p>'; } } return $ret; } // create the show gallery function tlp_show_process_gallery () { $ret = ''; $images = return_special_field('images'); $images_arr = array(); if (!empty($images)) { $images_arr = explode('||', $images); } $gallerylink = return_special_field('gallery'); $gallerycredit = return_special_field('gallerycredit'); if (!empty($images_arr) || !empty($gallerylink)) { if (!empty($images_arr)) { $count = count($images_arr); $width = floor(100 / $count); foreach ($images_arr as $image) { list($link, $img) = preg_split('/(?:\s+\.\.\.\s+)|(?:\|)/', $image); $ret .= '<a href="' . $link . '"><img src="' . $img . '" width="' . $width . '%"></a>'; } } if (!empty($gallerycredit) || !empty($gallerylink)) { $ret .= '<p class="show-gallery-link">'; if (!empty($gallerycredit)) { $ret .= '<span class="show-gallery-credit">Photos by ' . $gallerycredit . '.</span> '; } if (!empty($gallerylink)) { $ret .= '<a href="' . $gallerylink . '">Explore the entire gallery.</a>'; } $ret .= '</p>'; } } return $ret; } // take a "person list" and return a table function tlp_show_process_personlist ($text) { $ret = ''; if (!empty($text)) { $ret .= '<table class="show-person-list"><tbody>'; $lines = explode("\n", $text); foreach ($lines as $line) { list($left, $right) = preg_split('/(?:\s*\.\.\.\s*)|(?:\|)/', $line); if (!empty($left) || !empty($right)) { $first_left_char = substr($left, 0, 1); if ($first_left_char === ':' || $first_left_char === '!') { $ret .= '<tr><th colspan="3">' . substr($left, 1) . '</th></tr>'; } else { $ret .= '<tr><td class="left">' . $left . '</td><td class="center"></td><td class="right">' . $right . '</td></tr>'; } } } $ret .= '</tbody></table>'; } return $ret; } // return the slugs of shows, sorted by sequence order, matching the provided tag function tlp_showlisting_filter ($tag) { $shows = array(); // retrieve the shows, filtering on the provided tag foreach (getChildrenMulti('productions', array('slug', 'meta', 'special', 'sequence')) as $page) { if (array_key_exists('special', $page) && $page['special'] === 'show') { if (in_array($tag, explode(', ', $page['meta']))) { $shows[$page['slug']] = $page['sequence']; } } } // sort by the sequence number asort($shows, SORT_NUMERIC); // return just the slugs return array_keys($shows); } function tlp_showlisting_process_show ($slug, $added_fields, $class) { $ret = ''; $title = returnPageField($slug, 'title'); $poster = returnPageField($slug, 'poster'); $ret .= '<figure class="row show-list-item show-list-item-' . $class . '" id="' . $slug . '">' . '<div class="col show-list-poster">' . '<a href="' . $slug . '"><img src="' . $poster . '" alt="Poster for ' . $title . '"></a>' . '</div>' . '<figcaption class="col show-list-caption">' . '<h2><a href="' . $slug . '">' . $title . '</a></h2>'; foreach ($added_fields as $added_field => $processor) { $data = returnPageField($slug, $added_field); if (!empty($data)) { $ret .= '<div class="show-list-' . $added_field . '">' . call_user_func($processor, $data) . '</div>'; } } $ret .= '</figcaption></figure>'; return $ret; } // return the front page items up to num function tlp_frontpage_newsitems_slugs ($num = 3, $minforpinned = 2) { // get all news items, and sort them by slug descending $items = getChildrenMulti('news', array('slug', 'pin')); usort($items, function ($a, $b) { return strcmp($b['slug'], $a['slug']); }); // grab the first two. Then, look for any that have been pinned and add them. // if the number of items is less than 3, add one more $good = array(); $hold = array(); while ((count($good) < $minforpinned) && (!empty($items))) { $good[] = array_shift($items); } while(!empty($items)) { $temp = array_shift($items); if ($temp['pin'] == 'on') { $good[] = $temp; } else { $hold[] = $temp; } } if ((count($good) < $num) && (!empty($hold))) { $rest = array_splice($hold, 0, ($num - count($good))); $good = array_merge($good, $rest); } $ret = array(); foreach ($good as $item) { $ret[] = $item['slug']; } return $ret; } $tlp_num_to_ordinal_ends = array('th','st','nd','rd','th','th','th','th','th','th'); function tlp_num_to_ordinal ($num) { global $tlp_num_to_ordinal_ends; if (($num >= 11) && ($num <= 19)) { return $num . 'th'; } else if ($num === 1) { return 'First'; } else { return $num . $tlp_num_to_ordinal_ends[$num % 10]; } }
true
b5b7ec4fdc89c6a936d9e02db5e8da0d1ced50ab
PHP
feliciogs/yourLifeSocial
/chat.php
UTF-8
2,463
2.578125
3
[]
no_license
<?php include("header.php"); $id = $_GET["from"]; $tudo = mysqli_query($connect,"SELECT * FROM users WHERE id='$id' "); $saber = mysqli_fetch_assoc($tudo); $email = $saber["email"]; $sql = mysqli_query($connect,"SELECT * FROM mensagens WHERE para='$login_cookie' AND de='$email' OR de='$login_cookie' AND para='$email' ORDER BY id "); if(isset($_POST["send"])){ $msg= $_POST['text']; $data = date("Y/m/d"); if($msg==""){ echo "<h3>Não é possivel enviar uma mensagem sem escrever nada!</h3>"; }else{ $query = "INSERT INTO mensagens (de,para,texto,status,data) VALUES ('$login_cookie','$email','".mysqli_real_escape_string($connect,$msg)."',0,'$data')"; $data = mysqli_query($connect,$query); if($data){ //echo "<script>location.reload(false);</script>"; }else{ echo "<h3>Erro ao enviar sua mensagem...Tente Novamente!</h3>"; echo mysqli_error($connect); } } } ?> <html> <head> <style type="text/css"> h2{text-align: center;font-size: 32px;color: #007fff;} a{color: #007fff;text-decoration: none;} div#box{display: block;margin: auto;width: 650px;height: 600px;border: 1px solid #42f4e2;border-radius: 5px;} div#send{display: block;margin: auto;width: 650px;height:100px;padding-top:30px;text-align: center;font-size: 20px;border: 1px solid #42f4e2;border-radius: 5px;} div#send input[name="image"]{width: 100px;height: 35px;border: none;border-radius: 3px;font-size: 16px;background: #007fff;color:#FFF;cursor: pointer;} div#send input[name="text"]{width: 300px;height: 35px;border: none;border-radius: 3px;font-size: 16px;padding-left: 10px;} div#send input[name="send"]{width: 100px;height: 35px;border: none;border-radius: 3px;font-size: 16px;padding-left: 10px; background: #007fff;color:#FFF;cursor: pointer;} </style> </head> <body> <h2><a href="profile.php?id=<?php echo $id; ?>"><?php echo $saber["nome"];?></a></h2><br/><br/> <form method="POST"> <div id="box"> <object type="text/html" data="bubble.php?from=<?php echo $id;?>#bottom" width="635px" height="600px" style="overflow:auto;"></object> </div> <br/> <div id="send"> <a href="image.php?id=<?php echo $id; ?>"><input value="Imagem" type="button" name="image"></a>&nbsp;&nbsp;&nbsp;<input type="text" name="text" placeholder="Escreva aqui uma mensagem...." autocomplete="off">&nbsp;&nbsp;&nbsp;<input type="submit" name="send" value="Enviar"> </div> </form> </body> </html>
true
869cdc99f9d1631c576a21796d85814b9bc7ccd5
PHP
plansson/chicslazer
/application/mktplace/ns/DAO/productsDAO.php
WINDOWS-1250
1,956
2.84375
3
[]
no_license
<?php require_once '../application/mktplace/conexao.php'; class productsDAO{ public static $instance; public static function getInstance() { if (!isset(self::$instance)) self::$instance = new productsDAO(); return self::$instance; } public function selectProductSKU(productsBD $product) { try { $sql = "select * from products"; $sql .= " where sku_sf = ?"; $stmt = Conexao::getInstanceNS()->prepare($sql); $stmt->bindValue(1, $product->getSkuSF(), PDO::PARAM_STR); $stmt->execute(); $ret = array(); $ret['body'] = $stmt->fetchAll(); $ret['total'] = $stmt->rowCount(); return $ret; } catch (Exception $e) { echo "Cdigo: " . $e->getCode() . " Mensagem: " . $e->getMessage(); var_dump($stmt); exit; } } public function insertProductID(productsBD $product) { try { $sql = "insert into products (id_ns, sku_sf)"; $sql .= " values (?, ?)"; $stmt = Conexao::getInstanceNS()->prepare($sql); $stmt->bindValue(1, $product->getIdNS(), PDO::PARAM_INT); $stmt->bindValue(2, $product->getSkuSF(), PDO::PARAM_STR); $stmt->execute(); return Conexao::getInstanceNS()->lastInsertId(); } catch (Exception $e) { echo $product->getSkuSF() . "</br>"; echo "Cdigo: " . $e->getCode() . " Mensagem: " . $e->getMessage(); var_dump($stmt); exit; } } public function updateProductID(productsBD $product) { try { $sql = "UPDATE `products` set updated_at = CURRENT_TIMESTAMP where id_ns = ? and sku_sf = ?"; $stmt = Conexao::getInstanceNS()->prepare($sql); $stmt->bindValue(1, $product->getIdNS(), PDO::PARAM_INT); $stmt->bindValue(2, $product->getSkuSF(), PDO::PARAM_STR); $stmt->execute(); return $stmt->rowCount(); } catch (Exception $e) { echo $product->getSkuSF() . "</br>"; echo "Cdigo: " . $e->getCode() . " Mensagem: " . $e->getMessage(); var_dump($stmt); exit; } } }
true
a5c87154a8d16a87f0cc88153db4156995596a5a
PHP
binbinly/laravel-admin-base
/src/Controllers/WebStack/SiteController.php
UTF-8
1,775
2.515625
3
[]
no_license
<?php namespace AdminBase\Controllers\WebStack; use AdminBase\Controllers\AdminBaseController; use AdminBase\Models\Admin\Site; use AdminBase\Models\Admin\SiteCategory; use AdminBase\Traits\FormTrait; use AdminBase\Traits\GridTrait; use Encore\Admin\Form; use Encore\Admin\Grid; /** * 站点导航 * Class SiteController * @package AdminBase\Controllers\WebStack */ class SiteController extends AdminBaseController { use GridTrait; use FormTrait; /** * Title for current resource. * * @var string */ protected $title = '网站管理'; /** * Make a grid builder. * * @return Grid */ protected function grid() { $grid = new Grid(new Site()); $grid->id('ID'); $grid->category()->title('分类'); $grid->title('标题'); $grid->thumb('图标')->gallery(['width' => 50, 'height' => 50]); $grid->describe('描述')->limit(40); $grid->url('地址'); $grid->disableFilter(); $grid->disableExport(); return $grid; } /** * Make a form builder. * * @return Form */ protected function form() { $form = new Form(new Site); $form->select('category_id', '分类')->options(SiteCategory::selectOptions(null, ''))->rules('required'); $form->text('title', '标题')->attribute('autocomplete', 'off')->rules('required|max:50'); $form->image('thumb', '图标')->resize(120, 120)->uniqueName(); $form->text('describe', '描述')->attribute('autocomplete', 'off')->rules('required|max:300'); $form->url('url', '地址')->attribute('autocomplete', 'off')->rules('required|max:250'); $this->disableFormFooter($form); return $form; } }
true
69a61a968404f24e3e2908a01f23542d7d02762e
PHP
Warbi2601/Astro-Events
/cms/process/editevent.php
UTF-8
1,159
2.640625
3
[]
no_license
<?php //includes include("../../includes/sessions.inc.php"); include("../../includes/conn.inc.php"); include("../../includes/functions.inc.php"); //variable declarations $sEventID = safeString($_POST['eventID']); $sEventName = safeString($_POST['name']); $sEventDetails = safeString($_POST['details']); $sGenre = safeString($_POST['genre']); $sArtist = safeString($_POST['artist']); $sPicture = safeString($_POST['picture']); $GenreID = (int)$sGenre; $ArtistID = (int)$sArtist; $EventID = (int)$sEventID; //edit event code $sql = "UPDATE EVENTS SET Name = :Name, Details = :Details, Picture = :Picture, ArtistID = :ArtistID, GenreID = :GenreID WHERE ID = :EventID"; $stmt = $pdo->prepare($sql); $stmt->bindParam(':Name', $sEventName, PDO::PARAM_STR); $stmt->bindParam(':Details', $sEventDetails, PDO::PARAM_STR); $stmt->bindParam(':Picture', $sPicture, PDO::PARAM_STR); $stmt->bindParam(':ArtistID', $ArtistID, PDO::PARAM_INT); $stmt->bindParam(':GenreID', $GenreID, PDO::PARAM_INT); $stmt->bindParam(':EventID', $EventID, PDO::PARAM_INT); $stmt->execute(); header("Location: ../../event.php?id=" . $sEventID); //ensure no more code is ran exit(); ?>
true
d015346beb04ed2f8fa26ca0600e2fccb06e3b47
PHP
vincent4vx/ByxxR-cms
/core/helpers/Url.php
UTF-8
2,153
2.734375
3
[]
no_license
<?php class Url { public static function genUrl($controller='', $method='', $vars=array()) { $url = Core::conf('root'); if(!Core::conf('rewrite')) { $url .= 'index.php/'; } $url .= $controller; if($method !== '') { $url .= '/'.$method; } if(!empty($vars)) { if(is_array($vars)) $url.='/'.implode('/', $vars); else $url.='/'.$vars; } return $url; } public static function link($title, $controller = '', $method = '', $vars=array(), $class = '') { $url=self::genUrl($controller, $method, $vars); return self::linkByUrl($title, $url, $class); } public static function linkByUrl($title, $url, $class='') { $link = '<a href="'.$url.'"'; if($class !== '') { $link .= ' class="'.$class.'"'; } $link .= '>'.$title.'</a>'; return $link; } public static function redirect($route = '', $time = 0, $external = false){ if($external) $url = $route; else $url = self::genUrl($route); if(!headers_sent() && $time===0){ Core::get_instance()->loader->get('Output')->addHeader('location: '.$url); Core::get_instance()->loader->get('Output')->addHeader('HTTP/1.1 303'); return; } echo '<meta http-equiv="refresh" content="'.$time.';url= '.$url.'"/>'; } public static function forum($route = '', $encode = true){ if(is_array($route)){ if($encode) $route = array_map('urlencode', $route); $route = implode('/', $route); } if(($url = Core::conf('forum.forum_url'))) return $url.$route; return self::genUrl('forum/'.$route); } public static function forumList(array $path, $encode = true){ array_unshift($path, 'list'); return self::forum($path, $encode); } public static function forumThread(array $path, $encode = true){ array_unshift($path, 'thread'); return self::forum($path, $encode); } }
true
81fa980dc86cb776aa1087791b6b5071a5ca6939
PHP
muhdaniboyrendi/Lat-UKK-pengaduan-masyarakat
/index.php
UTF-8
2,338
2.78125
3
[]
no_license
<?php session_start(); require 'function.php'; if(isset($_SESSION["masyarakat"])){ header("location: masyarakat/"); exit; } if(isset($_SESSION["admin"])){ header("location: admin/"); exit; } if(isset($_SESSION["petugas"])){ header("location: petugas/"); exit; } if(isset($_POST["login"])){ global $conn; $username = $_POST["username"]; $password = $_POST["password"]; $result = mysqli_query($conn, "SELECT * FROM masyarakat WHERE username = '$username'"); $cek = mysqli_num_rows($result); $row = mysqli_fetch_assoc($result); $result2 = mysqli_query($conn, "SELECT * FROM petugas WHERE username = '$username'"); $cek2 = mysqli_num_rows($result2); $row2 = mysqli_fetch_assoc($result2); if($cek > 0){ if(password_verify($password, $row["password"])){ $_SESSION["masyarakat"] = true; $_SESSION["data"] = $row; header("location: masyarakat/"); exit; } } if($cek2 > 0){ if(password_verify($password, $row2["password"])){ if($row2["level"] == "admin"){ $_SESSION["admin"] = true; $_SESSION["data"] = $row2; header("location: admin/"); exit; } if($row2["level"] == "petugas"){ $_SESSION["petugas"] = true; $_SESSION["data"] = $row2; header("location: petugas/"); exit; } } } echo "<script> alert('Username atau password yang anda masukan salah') </script"; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <form action="" method="POST"> <label>Username</label> <input type="text" name="username" required> <br> <label>Password</label> <input type="password" name="password" required> <br> <button type="submit" name="login">Login</button> <br> <a href="register.php">Belun punya akun? Daftar</a> </form> </body> </html>
true
9902fa834ea23797500843e2d77c5b5932d0c464
PHP
Scoindy/webcms
/v0.1/email_view.php
UTF-8
2,879
2.734375
3
[]
no_license
<?php /******************************************************************************* * Indigo ******************************************************************************** * Name : email_view.php * Description : manages emails in the database * Author : Scott Walkinshaw * Date : 24th November 2011 * Parameters : * Comments : ******************************************************************************** * ******************************************************************************** * File Modification History * ******************************************************************************** * Inits | Vers | Date | Description * * SW | 1.0 | 24 Dec 11 | Initial issue * *******************************************************************************/ /**** * Includes ****/ require_once 'indigo_config.php'; // require_once 'indigo_library.php'; /**** * Connect to DB ****/ $db = mysqli_connect($db_hostname, $db_username, $db_password, $db_database); if (!$db) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } $ce_id = $_POST['ce_id']; $contact_id = $_POST['contact_id']; /**** * Start building query ****/ $query = "SELECT email_body FROM campaign_emails WHERE campaign_email_id = ".$ce_id." AND contact_id = ".$contact_id; file_put_contents( "/tmp/email_view.txt", $query); /**** * Run query ****/ if ($result = mysqli_query($db, $query)) { // printf("Select returned %d rows.\n", mysqli_num_rows($result)); /**** * Check only 1 record is returned ****/ if (mysqli_num_rows($result) != 1) { echo "error"; } /**** * Populate variables from record ****/ $row = mysqli_fetch_row($result); $html = $row[0]; /**** * Free result set ****/ mysqli_free_result($result); } /**** * Write the html to a temporary * file so it can be view ****/ $tmpfile = tempnam("/indigo/views", "email_view."); $handle = fopen($tmpfile, "w"); fwrite($handle, $html); fclose($handle); $status = 1; $string = basename($tmpfile); echo $_REQUEST['response'].$string; /**** * Package into a JSON string and * call the AJAX function callback with * number of rows and string echo $_REQUEST['response'].'({success:'.$status. ',string:"'.$string. '",error:"'.$error. '",error_code:"'.$error_code. '",new_id:"'.$new_id. '",count:"'.$count. '"})'; ****/ ?>
true
f1674958c5a03d80f83ad49cfb9be681a43a99ff
PHP
marcelaimar/GeradorCodigos
/Arquivo/PessoaTelefoneDAO.php
UTF-8
1,461
2.59375
3
[]
no_license
<?php /** * Marcel Aimar Estácio * Desenvolvedor Web * * Humberto de Campos, 161 - Sumaré * Presidente Venceslau, CEP 19400-000, Brasil * Telefone: +55(18)997467617 * * Classe PessoaTelefoneDAO * Representa objeto de acesso a dados para entidade PessoaTelefone * * @name PessoaTelefoneDAO * @access public * @license https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode CC BY-NC-ND * @copyright (c) 2020 * @author Marcel Aimar <marcel_aimar@hotmail.com> * */ abstract class PessoaTelefoneDAO extends \BancoDados { //<editor-fold defaultstate="collapsed" desc="CRUD"> /** * Método para incluir PessoaTelefone * * @access public * @param PessoaTelefone $pessoaTelefone */ /*public function incluir($pessoaTelefone) { $sql = "INSERT INTO PessoaTelefone ( CodigoPessoa, CodigoTelefone, Principal ) VALUES ( :CodigoPessoa, :CodigoTelefone, :Principal )"; $this->setSQL($sql); $this->setEntidade($pessoaTelefone); return $this->executar(); }*/ /** * Método para obter PessoaTelefone * * @access public * @param PessoaTelefone $pessoaTelefone */ /*public function obter($pessoaTelefone) { $sql = "SELECT CodigoPessoa, CodigoTelefone, Principal FROM PessoaTelefone WHERE CodigoPessoa =:CodigoPessoa AND CodigoTelefone =:CodigoTelefone"; $this->setSQL($sql); $this->setEntidade($pessoaTelefone); return $this->getDados(); }*/ //</editor-fold> } ?>
true
cda0d49911231b23696d23ea04026bf5dac68e9e
PHP
qlimix/serializable
/src/SerializableInterface.php
UTF-8
531
2.890625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Qlimix\Serializable; interface SerializableInterface { /** * A unique message name with application naming space. * This is used to deserialize the message back into * the message scheme object on the processing side. */ public function getName(): string; /** * @return mixed[] */ public function serialize(): array; /** * @param mixed[] $data */ public static function deserialize(array $data): SerializableInterface; }
true
7155b581345247bae0f89437a4878227740c1ee9
PHP
TheosDen/Laravel
/app/Repositories/Posts.php
UTF-8
410
2.734375
3
[]
no_license
<?php namespace App\Repositories; class Posts { private $_data = [ 'post 1', 'post 2', 'post 3', 'post 4', ]; public function all() : array { return $this->_data; } public function get() { Post::select()->get(); } public function find(int $index) : string { return $this->_data[$index] ?? 'not found'; } }
true
95f901fce676e04230d5166a8f97bd60bb8e022d
PHP
dfquintero/EDProyecto
/BackEnd/Mostrar_habitaciones_sin_filtro.php
UTF-8
1,877
3.25
3
[ "MIT" ]
permissive
<?php include('cn.php'); class Stack { protected $stack; public function __construct() { $this->stack = array(); } public function push($item) { array_push($this->stack, $item); } public function pop() { if ($this->isEmpty()) { return; } else { return array_pop($this->stack); } } public function top() { return current($this->stack); } public function isEmpty() { return empty($this->stack); } } $pila = new Stack(); $consulta = "SELECT ID_HABITACION, AMOBLADO ,PRECIO FROM HABITACION WHERE ID_HABITACION NOT IN (SELECT ID_HABITACION FROM OCUPA WHERE FECHA_FIN IS NULL)"; if ($resultado = mysqli_query($conn, $consulta)) { while ($fila = mysqli_fetch_array($resultado)) { $pila->push($fila); } mysqli_free_result($resultado); } echo "<h1>Habitaciones <br></h1>"; while (!($pila->isEmpty())){ $current = $pila->pop(); echo "<b>Habitación # </b>".$current['ID_HABITACION']."<b> Amoblado: </b>".$current['AMOBLADO']."<b> Precio: </b>".$current['PRECIO']."<br><br>"; } mysqli_close($conn); /* $tiempo_inicial = microtime(true); for ($i = 0; $i <=10000000; $i++){ $vivienda = rand( 1 , 1000); $area = rand(10, 500); $precio = rand(100000, 5000000); $otro = 'otro'; $vip = 1; $query = array($vivienda, $area, $precio, $otro, $vip); $pila->push($query) ; } $tiempo_final = microtime(true); $tiempo_total = $tiempo_final - $tiempo_inicial; echo $tiempo_total."<br>"; $tiempo_inicial = microtime(true); $pila->pop() ; $tiempo_final = microtime(true); $tiempo_total = $tiempo_final - $tiempo_inicial; echo $tiempo_total."<br>"; $tiempo_inicial = microtime(true); $pila->push($query) ; $tiempo_final = microtime(true); $tiempo_total = $tiempo_final - $tiempo_inicial; echo $tiempo_total."<br>"; */ ?>
true
a37c7ce7a0872c20b53758f25df3cd825f587193
PHP
atjoshi/chegg-love.com
/Business/Database.php
UTF-8
791
2.90625
3
[]
no_license
<?php /** * * Description of Database * * @author atjoshi * */ namespace Lovecom\Business; class Database { protected static $db = array(); public static function getInstance( $dbKey ) { if( !isset(self::$db[ $dbKey ] ) ) { self::$db[ $dbKey ] = self::instantiate( $dbKey ); self::$db[ $dbKey ]; } return self::$db[ $dbKey ]; } public static function instantiate( $dbKey ) { $dbConfig = Config::$db[ $dbKey ]; return new PDO( "mysql:host=". $dbConfig[ 'host_name' ]. ";port=". $dbConfig[ 'connection_port' ] ."dbname=". $dbConfig[ 'db_name' ], $dbConfig[ 'user_name' ], $dbConfig[ 'password' ] ); } }
true
cdc1514db7d25a37120256bf68ce99f45bd49b8d
PHP
domstor-project/kww-domstorlib
/vendor/Ds/Detail/Block/House/SizesBlock.php
UTF-8
2,185
2.78125
3
[]
no_license
<?php /** * Description of SaleSizesBlock * * @author pahhan */ class Ds_Detail_Block_House_SizesBlock extends Ds_Detail_Block_AbstractBlock { public function render(array $params = array()) { $vars = array('block' => $this); if( $this->fullHeight() or $this->height() or $this->width() or $this->long() or $this->groundWidth() or $this->groundLong() or $this->squareHouse() or $this->squareGround() or $this->squareKitchen() or $this->squareLiving() or $this->squareUtility() ) { return $this->getTemplating()->render($this->getTemplate(), $vars); } return ''; } // Высота потолков public function fullHeight() { if( $val = $this->getData()->get('size_house_z_full') ) return $val.' м'; } // Высота потолков public function height() { if( $val = $this->getData()->get('size_house_z') ) return $val.' м'; } public function width() { return (float) $this->getData()->get('size_house_x'); } public function long() { return (float) $this->getData()->get('size_house_y'); } public function groundWidth() { return (float) $this->getData()->get('size_ground_x'); } public function groundLong() { return (float) $this->getData()->get('size_ground_y'); } // Общая площадь public function squareHouse() { return (float) $this->getData()->get('square_house'); } // Общая площадь public function squareGround() { if( $val = $this->getData()->get('square_ground') ) return $val.' '.$this->getData()->get('square_ground_unit'); } // Жилая площадь public function squareLiving() { return (float) $this->getData()->get('square_living'); } // Площадь кухни public function squareKitchen() { return (float) $this->getData()->get('square_kitchen'); } // Площадь кармана public function squareUtility() { return (float) $this->getData()->get('square_utility'); } }
true
9f7553f8393116bea1f291e0143e5857b0980f4a
PHP
thangttttv/xs_tt
/protected/modules/thantaicp/models/AMobat.php
UTF-8
2,305
2.625
3
[]
no_license
<?php class AMobat extends CActiveRecord{ public static function model($className = __CLASS__) { return parent::model ( $className ); } public function getDataByOpenDate($open_date){ $data = array(); $sql = "SELECT * FROM xs_mobat WHERE open_date ='".$open_date."'"; $connect = Yii::app()->db; $command = $connect->createCommand($sql); $rows = $command->queryAll(); foreach($rows as $key =>$value){ $data[$value['province']] = $value; } return $data; } public function getDataSearch($open_date,$page,$row_per_page){ $str_sql = ""; $str_order = " ORDER BY id DESC "; $str_groupby = " GROUP BY open_date "; if(!empty($open_date)){ $str_sql .= " AND open_date = '" . $open_date. "'"; } $connect = Yii::app()->db; $sql = "SELECT open_date as count FROM xs_mobat WHERE 1 ".$str_sql.$str_groupby; $command = $connect->createCommand($sql); $data_count = $command->queryAll(); $max_page = ceil(intval(count($data_count))/$row_per_page); $first = ($page - 1)*$row_per_page; $sql = "SELECT * FROM xs_mobat WHERE 1 ".$str_sql.$str_groupby.$str_order." LIMIT ".$first.",".$row_per_page; $command = $connect->createCommand($sql); $data = $command->queryAll(); return array($max_page,intval(count($data_count)),$data); } public function getDataByOpenDateAndProvince($open_date,$province){ $data = array(); $sql = "SELECT * FROM xs_mobat WHERE open_date ='".$open_date."' AND province = ".$province; $connect = Yii::app()->db; $command = $connect->createCommand($sql); $rows = $command->queryAll(); foreach($rows as $key =>$value){ $data[$value['province']] = $value; } return $data; } public function getDataByWday($wday){ $data = array(); $sql = "SELECT * FROM province WHERE id<>1 AND thu".$wday."=1"; $connect = Yii::app()->db; $command = $connect->createCommand($sql); $rows = $command->queryAll(); foreach($rows as $value){ $data[$value["region"]][$value["id"]] = $value; } return $data; } }
true
2dcedc300c9b22387253f10a1820045bc16dd167
PHP
seansWebelevate/webprogramming
/workshop7/Main.class.php
UTF-8
99
2.71875
3
[]
no_license
<?php include "Sphere.class.php"; $sphere= new Sphere(1); echo $sphere->getVolume(); ?>
true
2ba6b1ed1061ac676eaa9798138a97cdae1b20b5
PHP
luisbryan/backend_api
/app/Repositories/SuperadminRepository.php
UTF-8
207
2.59375
3
[]
no_license
<?php namespace Testu\Repositories; use Testu\Repositories\Eloquent\Repository; class SuperadminRepository extends Repository { public function model() { return 'Testu\User'; } }
true
7a6b68a1ef85404e14d19f21b379d1bab3b38521
PHP
neowutran/CheapTeraDpsDatabase
/store.php
UTF-8
1,852
2.515625
3
[]
no_license
<?php //error_reporting(E_ALL); //ini_set("display_errors", 1); $directory = "/home/http/tmp/"; $time = time(); $date = date("Y-m-d", $time); $uniqid = uniqid(); $raw = file_get_contents('php://input'); $json = json_decode($raw, true); if($json === null){ die(); } $areaId = $json["areaId"]; $bossId = $json["bossId"]; $partyDps = $json["partyDps"]; $region = getRegion($json); if($region === NULL) die(); $fightDuration = $json["fightDuration"]; if( $areaId != "886" && $areaId != "467" && $areaId != "767" && $areaId != "768" && $areaId != "470" && $areaId != "468" && $areaId != "770" && $areaId != "769" && $areaId != "916" && $areaId != "969" && $areaId != "970" && $areaId != "950" ) { die(); } if(!preg_match("#^\d+$#", $areaId) || !preg_match("#^\d+$#", $bossId) || !preg_match("#^\d+$#", $partyDps) || !preg_match("#^\d+$#", $fightDuration)){ die(); } $json["timestamp"] = $time; $filename = $partyDps.".".$fightDuration.".".$time.".".$uniqid; $container = $region.".".$areaId.".".$bossId; mkdir($directory.$container."/", 0777, true); file_put_contents($directory.$container."/".$filename.".json",json_encode($json)); function getRegion($json){ $server = $json["members"][0]["playerServer"]; $handle = fopen("./TeraDpsMeterData/servers.txt", "r"); if ($handle) { while (($line = fgets($handle)) !== false) { $server_details = explode(" ", $line, 4); if(count($server_details) < 4){ continue; } $server_details[3] = str_replace(PHP_EOL, '', $server_details[3]); if($server_details[3] == $server){ fclose($handle); return $server_details[1]; } } fclose($handle); } return NULL; }
true
75d1efda58759dd5f9b78482959b717fd9ad3cfa
PHP
Tagarela76/voc
/vwm/modules/classes/VWM/Apps/UnitType/Entity/Type.class.php
UTF-8
1,195
2.90625
3
[]
no_license
<?php namespace VWM\Apps\UnitType\Entity; use VWM\Framework\Model; class Type extends Model { protected $type_id; protected $type_desc; const TABLE_NAME = '`type`'; public function __construct(\db $db) { $this->db = $db; } /** * TODO: implement this method * * @return array property => value */ public function getAttributes() { return array(); } public function getTypeId() { return $this->type_id; } public function setTypeId($type_id) { $this->type_id = $type_id; } public function getTypeDesc() { return $this->type_desc; } public function setTypeDesc($type_desc) { $this->type_desc = $type_desc; } public function save() { throw new \Exception('You cannot add/edit this entity'); } public function load() { if(!$this->getTypeId()) { throw new \Exception("You cannot get type without type id"); } $sql = "SELECT * " . "FROM ".self::TABLE_NAME. " t " . "WHERE t.type_id = {$this->db->sqltext($this->getTypeId())}"; $this->db->query($sql); if($this->db->num_rows() == 0) { return false; } $row = $this->db->fetch_array(0); $this->initByArray($row); return true; } } ?>
true
0ade127a41b64c30d4f6ee4a21b9a81c168c9ad5
PHP
Daniil-Trukhan/php-design-patterns
/Creational/AbstractFactory/BookFactory/Williams.php
UTF-8
462
2.625
3
[]
no_license
<?php namespace Creational\AbstractFactory\BookFactory; use Creational\AbstractFactory\BookFactory; use Creational\AbstractFactory\Book\PHP\Williams as WilliamsPHPBook; use Creational\AbstractFactory\Book\MySQL\Williams as WilliamsMySQLBook; class Williams extends BookFactory { public function createPHPBook() { return new WilliamsPHPBook(); } public function createMySQLBook() { return new WilliamsMySQLBook(); } }
true
3e3b04cb99acbf69129fba87164ecaf4b120555e
PHP
Evafan1337/Auction
/application/core/model.php
UTF-8
1,002
2.703125
3
[]
no_license
<?php class Model { /* Модель обычно включает методы выборки данных, это могут быть: > методы нативных библиотек pgsql или mysql; > методы библиотек, реализующих абстракицю данных. Например, методы библиотеки PEAR MDB2; > методы ORM; > методы для работы с NoSQL; > и др. */ // метод выборки данных public function get_data() { // todo } public function model_get_express_tour_data(){ var_dump('MODEL-get_express_tour_stages'); // // var_dump($data); // $opt = [ // PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, // PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // PDO::ATTR_EMULATE_PREPARES => false, // ]; // $pdo = new PDO("mysql:host=localhost;dbname=auction",'root','2k91abin1420pirzy',$opt); } }
true
52370e0748a4478d37493aced9e0e67d171eb7fa
PHP
elgervb/compact
/classes/compact/auth/ILoginProvider.php
UTF-8
682
3.015625
3
[]
no_license
<?php namespace compact\auth; interface ILoginProvider { /** * Returns the logged in user * * @param int $id The ID of the user * * @return \compact\auth\user\UserModel the user model, or null when not logged in */ public function getUser($id); /** * Signs in the user with supplied credentials * * @param string $username * The username * @param string $password * The plain text password * * @return UserModel|false The usermodel when successfully logged in or false when the user could nog be found */ public function login($username, $password); }
true
a6c3bbbf3ecfe78a6da99ea02b818ddd7c7e05d5
PHP
adamyousef/PHP-course
/tag17_datenformate_3/uebung_bundesliga.php
UTF-8
2,366
2.765625
3
[]
no_license
<!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Tolle Webseite</title> <style> td img {width:30px;} </style> </head> <body> <h2>Bundesliga</h2> <?php $options = [ 'http'=> [ 'method' => "GET", 'header' => "Accept-language: de\r\n". "Accept:application/xml" ] ]; $context = stream_context_create($options); $text = file_get_contents("http://www.openligadb.de/api/getmatchdata/bl1/2016/8", false, $context); $xml = simplexml_load_string($text); echo '<h3>'.$xml->Match[0]->Goals->Goal[0]->GoalGetterName.'</h3>'; //$xml->Match[0]->Team1.... //$xml->Match[0]->MatchResults[].... $html = '<table border="1">'; $html .= '<tr>'; $html .= '<td>'.$xml->Match[0]->Team1->TeamName.'</td>'; $html .= '<td><img src="'.$xml->Match[0]->Team1->TeamIconUrl.'" /></td>'; $html .= '<td>:</td>'; $html .= '<td><img src="'.$xml->Match[0]->Team2->TeamIconUrl.'" /></td>'; $html .= '<td>'.$xml->Match[0]->Team2->TeamName.'</td>'; $html .= '<td>'.$xml->Match[0]->MatchResults->MatchResult[1]->PointsTeam1.' : '.$xml->Match[0]->MatchResults->MatchResult[1]->PointsTeam2.'</td>'; $html .= '</tr>'; $html .= '<tr>'; $html .= '<td>'.$xml->Match[1]->Team1->TeamName.'</td>'; $html .= '<td><img src="'.$xml->Match[1]->Team1->TeamIconUrl.'" /></td>'; $html .= '<td>:</td>'; $html .= '<td><img src="'.$xml->Match[1]->Team2->TeamIconUrl.'" /></td>'; $html .= '<td>'.$xml->Match[1]->Team2->TeamName.'</td>'; $html .= '<td>'.$xml->Match[1]->MatchResults->MatchResult[1]->PointsTeam1.' : '.$xml->Match[0]->MatchResults->MatchResult[1]->PointsTeam2.'</td>'; $html .= '</tr>'; $html .= '</table>'; echo $html; echo '<hr/>'; $html = '<table border="1"'; foreach($xml->Match as $value){ $html .= '<tr>'; $html .= '<td>'.$value->Team1->TeamName.'</td>'; $html .= '<td><img src="'.$value->Team1->TeamIconUrl.'" /></td>'; $html .= '<td>:</td>'; $html .= '<td><img src="'.$value->Team2->TeamIconUrl.'" /></td>'; $html .= '<td>'.$value->Team2->TeamName.'</td>'; $html .= '<td>'.$value->MatchResults->MatchResult[1]->PointsTeam1.' : '.$value->MatchResults->MatchResult[1]->PointsTeam2.'</td>'; $html .= '</tr>'; } $html .= '</table>'; echo $html; ?> </body> </html>
true
8bf96214d4603d45752b64cc08148eee187ea5b1
PHP
stadline/linkdata-bundle
/Mock/Resolver/LinkdataMockResolver.php
UTF-8
2,140
2.640625
3
[]
no_license
<?php namespace Geonaute\LinkdataBundle\Mock\Resolver; use Geonaute\LinkdataBundle\Mock\Exception\BadMockModelException; use Geonaute\LinkdataBundle\Mock\Exception\MockNotLoadedException; use Geonaute\LinkdataBundle\Mock\LinkdataMockInterface; use Guzzle\Service\Command\OperationCommand; use JMS\Serializer\SerializerInterface; /** * Class LinkdataMockResolver * * Return a LinkdataMockInterface from OperationCommand. */ class LinkdataMockResolver { /** @var SerializerInterface */ private $serializer; /** * An array of models loaded. * * @var array */ private $loadedModels = array(); /** * LinkdataMockResolver constructor. * @param SerializerInterface $serializer */ public function __construct(SerializerInterface $serializer) { $this->serializer = $serializer; } /** * Load a list a models. * Models have to implements LinkdataMockInterface * * @param $models * @throws BadMockModelException */ public function loadModels($models) { foreach ($models as $model) { if (!$model instanceof LinkdataMockInterface) { throw new BadMockModelException( 'Mock models loaded must be instances of LinkdataMockInterface, %s is not an instance of LinkdataMockInterface', get_class($model) ); } $this->loadedModels[] = $model; } } /** * Resolve mocks. * * @param $command * @return array * @throws MockNotLoadedException if command is not loaded. */ public function resolve(OperationCommand $command) { foreach ($this->loadedModels as $model) { if ($model->getCommandName() === $command->getName()) { return $model->getResponse($this->serializer, $command->getAll()); } } throw new MockNotLoadedException(sprintf( 'Command %s must be loaded before executing test using method loadModels of class LinkdataMockResolver', $command->getName() )); } }
true
0d4542b74316a115e8380bcfe116ac44f1ad75e9
PHP
rehanurrashid/wazuapp
/app/Http/Controllers/API/RecipeController.php
UTF-8
4,268
2.546875
3
[]
no_license
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Recipe; use App\Product; class RecipeController extends Controller { public function show_all(){ $recipe = Recipe::all(); if(!empty($recipe)){ return response(['recipes' => $recipe], 200); } else{ return response(['recipes' => 'No Recipes Found!'], 401); } } // public function show($id){ // $recipe = Recipe::find($id); // if(!empty($recipe)){ // $ingredients_word = explode(",",$recipe->ingredients); // $recipe['recipe_products'] = Recipe::where(function ($q) use ($ingredients_word) { // foreach ($ingredients_word as $value) { // $q->orWhere('tags', 'like', '%'.$value.'%') // ->orWhere('title', 'like', '%'.$value.'%'); // } // })->with(['rating'])->limit(5)->get(); // if(!empty($recipe['recipe_products'][0])){ // return response(['recipes' => $recipe], 200); // } // else{ // $recipe['recipe_products'] = 'No Related Recipes Found!'; // return response(['recipes' => $recipe], 200); // } // } // else{ // return response(['recipes' => 'No Recipes Found!'], 401); // } // } public function show(Request $request){ if($request->keyword == '' && $request->slug == ''){ return response(['error' => 'Atleast one word(keyword/slug) is required for searching...!'], 200); } if(!empty($request->slug)){ $recipe = Recipe::where('slug', $request->slug)->first(); if(!empty($recipe)){ $ingredients_word = explode(",",$recipe->ingredients); $recipe['recipe_products'] = Product::where(function ($q) use ($ingredients_word) { foreach ($ingredients_word as $value) { $q->orWhere('tags', 'like', '%'.$value.'%') ->orWhere('title', 'like', '%'.$value.'%'); } })->limit(5)->get(); if(!empty($recipe['recipe_products'][0])){ return response(['recipes' => $recipe], 200); } else{ $recipe['recipe_products'] = 'No Related Recipes Found!'; return response(['recipes' => $recipe], 200); } } else{ $recipe['recipe'] = 'No Recipe Found!'; return response(['error' => $recipe], 200); } } else if(!empty($request->keyword)){ $searchValues = preg_split('/\s /', $request->keyword, -1, PREG_SPLIT_NO_EMPTY); $search_terms = explode(" ", $searchValues[0]); // $recipes = Searchy::recipes('title')->query($searchValues[0])->get(); $recipes = Recipe::where(function ($q) use ($search_terms) { foreach ($search_terms as $value) { $q->orWhere('title', 'like', '%'.$value.'%') ->orWhere('ingredients', 'like', '%'.$value.'%'); } })->get(); $props = ['title']; $recipes = $recipes->sortByDesc(function($i, $k) use ($search_terms, $props) { // The bigger the weight, the higher the record $weight = 0; // Iterate through search terms foreach($search_terms as $searchTerm) { // Iterate through recipes (address1, address2...) foreach($props as $prop) { // Use strpos instead of %value% (cause php) if(strpos($i->{$prop}, $searchTerm) !== false) $weight += 1; // Increase weight if the search term is found } } return $weight; }); $recipes = $recipes->values()->all(); if(!empty($recipes[0])){ return response(['recipes' => $recipes], 200); } else{ return response(['recipes' =>[]], 200); } } } }
true
a9f113e3c627c7fe91387ba24c6c5474df38ce3c
PHP
smarcet/openstackid
/app/services/openid/ServerExtensionsService.php
UTF-8
1,383
2.71875
3
[]
no_license
<?php namespace services\openid; use openid\services\IServerExtensionsService; use utils\services\ServiceLocator; use ServerExtension; use ReflectionClass; /** * Class ServerExtensionsService * @package services\openid */ class ServerExtensionsService implements IServerExtensionsService { /** * @return array */ public function getAllActiveExtensions() { $extensions = ServerExtension::where('active', '=', true)->get(); $res = array(); foreach ($extensions as $extension) { $class_name = $extension->extension_class; if (empty($class_name)) continue; $class = new ReflectionClass($class_name); $constructor = $class->getConstructor(); $constructor_params = $constructor->getParameters(); $deps = array(); foreach($constructor_params as $constructor_param){ $param_class = $constructor_param->getClass(); $name = $constructor_param->getName(); if(is_null($param_class)){ array_push($deps,$extension->$name); } else{ $service = ServiceLocator::getInstance()->getService($param_class->getName()); array_push($deps,$service); } } $implementation = $class->newInstanceArgs($deps); array_push($res, $implementation); } return $res; } }
true