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
c55d356017d02978226845edd2d0ee6abf4e7cb8
PHP
data-quest/histat-web
/application/views/en/admin/stats/option_5.php
UTF-8
720
2.53125
3
[]
no_license
<?php if (count($result) > 0): ?> <h3><b><?= count($result) ?></b> Ergebnisse wurden gefunden</h3> <table> <thead> <tr> <th>ZA Nr.</th> <th>Studientitel</th> </tr> </thead> <tbody> <?php foreach ($result as $res): ?> <tr> <td> <?= $res->za ?></td> <td class="even"> <?= $res->title ?></td> </tr> <?php endforeach; ?> </tbody> </table> <?php else: ?> Leider keine Ergebnisse , bitte Zeitraum ändern. <?php endif; ?>
true
339b8db8f024e9d2cd41b002e8643bdd305dbe44
PHP
Thoronir42/paf
/extensions/SeStep/NetteAuditTrail/src/Components/FeedControl/AuditTrailFeedControlFactory.php
UTF-8
2,100
2.703125
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace SeStep\NetteAuditTrail\Components\FeedControl; use SeStep\NetteAuditTrail\Entity\Entry; use PAF\Modules\CommonModule\Latte\UserFilter; use SeStep\NetteFeed\Components\FeedControl\FeedEntryControl; use SeStep\NetteFeed\Components\FeedControl\FeedEntryControlFactory; use SeStep\NetteFeed\FeedEvents; use SeStep\NetteFeed\Model\FeedEntry; class AuditTrailFeedControlFactory implements FeedEntryControlFactory { private array $typeToTemplateFileMap = []; private array $matcherToTemplateFileMap = []; private UserFilter $userFilter; public function __construct(UserFilter $userFilter, array $templateByType = []) { foreach ($templateByType as $type => $templateFile) { $this->registerTemplate($type, $templateFile); } $this->userFilter = $userFilter; } public function registerTemplate($feedType, string $templateFile) { if (strpos($feedType, '*')) { $this->matcherToTemplateFileMap[] = [ 'mask' => str_replace('*', '\w', $feedType), 'file' => $templateFile, ]; } else { $this->typeToTemplateFileMap[$feedType] = $templateFile; } } public function create(FeedEvents $events, FeedEntry $entry): FeedEntryControl { /** @var Entry $auditEntry */ $auditEntry = $entry->getSource(); $control = new AuditTrailFeedControl($events, $auditEntry, $this->userFilter); if ($template = $this->getTemplateByType($auditEntry->type)) { $control->setTemplateFile($template); } return $control; } private function getTemplateByType(string $type): ?string { if (isset($this->typeToTemplateFileMap[$type])) { return $this->typeToTemplateFileMap[$type]; } foreach ($this->matcherToTemplateFileMap as $matcher) { $mask = "/$matcher[mask]/"; if (preg_match($mask, $type)) { return $matcher['file']; } } return null; } }
true
de000d6d412e8bb3a90148fe31a768b2abe9255c
PHP
casthetrack/proyecto
/enviarEmail.php
UTF-8
1,499
2.625
3
[]
no_license
<?php use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exeption; require 'vendor/autoload.php'; // Instantiation and passing `true` enables exceptions $mail = new PHPMailer(true); try { //Server settings $mail->SMTPDebug = 0; // Enable verbose debug output $mail->isSMTP(); // Send using SMTP $mail->Host = 'smtp.gmail.com'; // Set the SMTP server to send through $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'juagno19@gmail.com'; // SMTP username $mail->Password = '3135888212'; // SMTP password $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged $mail->Port = 587; // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above //Recipients $mail->setFrom('juagno19@gmail.com', 'Junior'); $mail->addAddress('juagno15@gmail.com', 'JDAN'); // Add a recipient // Content $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'SASPA'; $mail->Body = 'Recuperación de contraseña <b>lista</b>'; $mail->AltBody = 'bery good'; $mail->send(); echo 'Mensaje enviado'; } catch (Exception $e) { echo "Mensaje no enviado. Mailer Error: {$mail->ErrorInfo}"; }
true
fe4ab464f8c1d07f82d8a9ec6408b9d7fdee3e20
PHP
necatikartal/ojs
/src/Ojs/AnalyticsBundle/Document/ObjectDownload.php
UTF-8
2,116
2.625
3
[ "MIT" ]
permissive
<?php namespace Ojs\AnalyticsBundle\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; /** * This collection keeps page information and download action details *without total count* * There will be one record for each paths * @MongoDb\Document(collection="analytics_download_object_sum") */ class ObjectDownload { /** * @MongoDb\Id */ public $id; /** * @MongoDb\String */ protected $filePath; /** @MongoDB\Int */ protected $objectId; /** @MongoDB\string */ protected $entity; /** @MongoDB\String */ protected $rawData; /** @MongoDB\Int */ protected $total; /** * Get id * * @return int $id */ public function getId() { return $this->id; } /** * Get total * * @return string $total */ public function getTotal() { return $this->total; } /** * Page full url with domain * Set total * * @param string $total * @return self */ public function setTotal($total) { $this->total = $total; return $this; } /** * Get filePath * * @return string $filePath */ public function getFilePath() { return $this->filePath; } /** * Page full url with domain * Set filePath * * @param string $filePath * @return self */ public function setFilePath($filePath) { $this->filePath = $filePath; return $this; } public function getObjectId() { return $this->objectId; } public function setObjectId($id) { $this->objectId = $id; return $this; } public function getEntity() { return $this->entity; } public function setEntity($entity) { $this->entity = $entity; return $this; } /** Jungle Boogie */ public function getRawData() { return $this->rawData; } public function setRawData($data) { $this->rawData = $data; return $this; } }
true
554a1890600344fb0856becf6bde8b2566e53c80
PHP
klapuch/Access
/Core/ThrowawayRemindedPassword.php
UTF-8
1,101
3.03125
3
[]
no_license
<?php declare(strict_types = 1); namespace Klapuch\Access; use Klapuch\Output; use Klapuch\Storage; /** * Reminded password just for one use */ final class ThrowawayRemindedPassword implements Password { private $reminder; private $database; private $origin; public function __construct( string $reminder, \PDO $database, Password $origin ) { $this->reminder = $reminder; $this->database = $database; $this->origin = $origin; } public function change(string $password): void { if ($this->used($this->reminder)) throw new \UnexpectedValueException('The reminder is already used'); $this->origin->change($password); } /** * Is the reminder already used? * @param string $reminder * @return bool */ private function used(string $reminder): bool { return (bool) (new Storage\ParameterizedQuery( $this->database, 'SELECT 1 FROM forgotten_passwords WHERE reminder IS NOT DISTINCT FROM ? AND used = TRUE', [$reminder] ))->field(); } public function print(Output\Format $format): Output\Format { return $this->origin->print($format); } }
true
48e8f5d5ae4f0d09e68d2ab5f6da944da84c3282
PHP
nikic/Ardent
/src/SortedMap.php
UTF-8
4,237
3.1875
3
[ "MIT" ]
permissive
<?php namespace Collections; class SortedMap implements Map { use IteratorCollection; /** * @var BinarySearchTree */ private $avl; /** * @var callable */ private $comparator; function __construct($comparator = null) { $this->comparator = $comparator ?: '\Collections\compare'; $this->avl = new AvlTree([$this, 'compareKeys']); } function compareKeys(Pair $a, Pair $b) { return call_user_func($this->comparator, $a->first, $b->first); } /** * @return void */ function clear() { $this->avl->clear(); } /** * @param mixed $item * @param callable $callback * * @return bool * @throws TypeException when $item is not the correct type. */ function contains($item, callable $callback = null) { if ($callback === null) { $callback = '\Collections\compare'; } foreach ($this->avl as $pair) { /** * @var Pair $pair */ if (call_user_func($callback, $pair->second, $item) === 0) { return true; } } return false; } /** * @return bool */ function isEmpty() { return $this->avl->isEmpty(); } /** * @return mixed * @throws EmptyException when the tree is empty */ function first() { return $this->avl->first(); } /** * @return mixed * @throws EmptyException when the tree is empty */ function last() { return $this->avl->last(); } /** * @link http://php.net/manual/en/arrayaccess.offsetexists.php * * @param mixed $offset * * @return bool */ function offsetExists($offset) { return $this->avl->contains(new Pair($offset, null)); } /** * @param mixed $offset * @link http://php.net/manual/en/arrayaccess.offsetget.php * @return mixed * @throws KeyException */ function offsetGet($offset) { if (!$this->offsetExists($offset)) { throw new KeyException; } return $this->get($offset); } /** * @link http://php.net/manual/en/arrayaccess.offsetset.php * * @param mixed $offset * @param mixed $value * * @return void */ function offsetSet($offset, $value) { $this->set($offset, $value); } /** * @link http://php.net/manual/en/arrayaccess.offsetunset.php * * @param mixed $offset * * @return void */ function offsetUnset($offset) { $this->remove($offset); } /** * @param $key * * @return mixed * @throws TypeException when the $key is not the correct type. * @throws KeyException when the $key is not the correct type. */ function get($key) { if (!$this->offsetExists($key)) { throw new KeyException; } /** * @var Pair $pair */ $pair = $this->avl->get(new Pair($key, null)); return $pair->second; } /** * Note that if the key is considered equal to an already existing key in * the map that it's value will be replaced with the new one. * * @param $key * @param mixed $value * * @return void * @throws TypeException when the $key or value is not the correct type. */ function set($key, $value) { $this->avl->add(new Pair($key, $value)); } /** * @param $key * * @return mixed * @throws TypeException when the $key is not the correct type. */ function remove($key) { $this->avl->remove(new Pair($key, null)); } /** * @link http://php.net/manual/en/countable.count.php * @return int */ function count() { return $this->avl->count(); } /** * @link http://php.net/manual/en/iteratoraggregate.getiterator.php * @return SortedMapIterator */ function getIterator() { return new SortedMapIterator( new InOrderIterator($this->avl->toBinaryTree(), $this->avl->count()), $this->avl->count() ); } }
true
f08d084e79acb467888e1effbb4ced51d1963d69
PHP
smk87/videoLibraryAPI
/app/Http/Controllers/VideosController.php
UTF-8
5,304
2.640625
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Video; use Illuminate\Support\Facades\Validator; use App\Http\Resources\Video as VideoResource; use Vimeo\Laravel\Facades\Vimeo; class VideosController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // Check for sorting parameter if (isset($_GET['sortBy'])) { switch ($_GET['sortBy']) { case 'name': return VideoResource::collection(Video::orderBy('title')->get()); // Return all the videos in the library ordered by title break; case 'like count': return VideoResource::collection(Video::orderBy('totalLikes', 'DESC')->get()); // Return all the videos in the library ordered by total likes break; case 'updated time': return VideoResource::collection(Video::orderBy('updated_at', 'DESC')->get()); // Return all the videos in the library ordered by update time break; default: return VideoResource::collection(Video::all()); // Return all the videos in the library break; } } else { return VideoResource::collection(Video::all()); // Return all the videos in the library } } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // Validation with custom response $validator = Validator::make($request->all(), [ 'url' => 'required' ]); if ($validator->fails()) { return response()->json(['errors' => $validator->messages()->all()], 400); // Returns validation error as JSON } else { // Check for vimeo video $vimeoID = substr($request->url, 18); $vimeo = Vimeo::request('/videos/' . $vimeoID, ['per_page' => 10], 'GET'); if (isset($vimeo['body']['error'])) { // Assign and save video to DB normally $video = Video::create([ 'title' => ($request->title ? $request->title : "unnamed"), 'url' => $request->url, 'description' => $request->description, 'thumbnailUrl' => $request->thumbnailUrl, ]); return new VideoResource($video); // Returns new created video } else { // Assign and save vimeo video to DB $video = Video::create([ 'title' => $vimeo['body']['name'], 'url' => $request->url, 'description' => $vimeo['body']['description'], 'thumbnailUrl' => $vimeo['body']['pictures']['sizes'][2]['link'], ]); return new VideoResource($video); // Returns new created video from vimeo } } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { if (Video::find($id)) { return new VideoResource(Video::find($id)); // Returns a specific video by id from DB } else { return response()->json(['error' => 'Video does not exist.'], 404); // Returns error when video doesn't exist } } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // Validation with custom response $validator = Validator::make($request->all(), [ 'title' => 'required', 'url' => 'required' ]); if ($validator->fails()) { return response()->json(['errors' => $validator->messages()->all()], 400); // Returns validation error as JSON } else if (Video::find($id)) { // Update and save to DB Video::find($id)->update([ 'title' => $request->title, 'url' => $request->url, 'description' => $request->description, 'thumbnailUrl' => $request->thumbnailUrl ]); return new VideoResource(Video::find($id)); // Returns new updated video } else { return response()->json(['error' => 'Video does not exist.'], 404); // Returns error when video doesn't exist } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { if (Video::destroy($id)) { return response()->json(['success' => true, 'message' => 'Video deleted successfully.'], 200); // Returns success on video delete } else { return response()->json(['error' => 'Video does not exist.'], 404); // Returns error when video doesn't exist } } }
true
669ad7ad02159bbbf8975db848d69b334cface25
PHP
KimBonggyu/welfare
/fnc/common.php
UTF-8
13,593
2.71875
3
[]
no_license
<?php include 'function.php'; /*그누보드 참조*/ // mysqli_query 와 mysqli_error 를 한꺼번에 처리 // mysql connect resource 지정 - 명랑폐인님 제안 function sql_query($sql, $error=G5_DISPLAY_SQL_ERROR, $link=null) { global $Conn; if(!$link) $link = $Conn; // Blind SQL Injection 취약점 해결 $sql = trim($sql); // union의 사용을 허락하지 않습니다. //$sql = preg_replace("#^select.*from.*union.*#i", "select 1", $sql); $sql = preg_replace("#^select.*from.*[\s\(]+union[\s\)]+.*#i ", "select 1", $sql); // `information_schema` DB로의 접근을 허락하지 않습니다. $sql = preg_replace("#^select.*from.*where.*`?information_schema`?.*#i", "select 1", $sql); if(function_exists('mysqli_query') ) { if ($error) { $result = @mysqli_query($link, $sql) or die("<p>$sql<p>" . mysqli_errno($link) . " : " . mysqli_error($link) . "<p>error file : {$_SERVER['SCRIPT_NAME']}"); } else { $result = @mysqli_query($link, $sql); } } else { if ($error) { $result = @mysql_query($sql, $link) or die("<p>$sql<p>" . mysql_errno() . " : " . mysql_error() . "<p>error file : {$_SERVER['SCRIPT_NAME']}"); } else { $result = @mysql_query($sql, $link); } } return $result; } //////////실제 ip 찾아내기///////////// function getRealIpAddr(){ if(!empty($_SERVER['HTTP_CLIENT_IP']) && getenv('HTTP_CLIENT_IP')){ return $_SERVER['HTTP_CLIENT_IP']; } elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && getenv('HTTP_X_FORWARDED_FOR')){ return $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif(!empty($_SERVER['REMOTE_HOST']) && getenv('REMOTE_HOST')){ return $_SERVER['REMOTE_HOST']; } elseif(!empty($_SERVER['REMOTE_ADDR']) && getenv('REMOTE_ADDR')){ return $_SERVER['REMOTE_ADDR']; } return false; } $_SERVER['REMOTE_ADDR']=getRealIpAddr();//실제 아이피 변경 // 쿼리를 실행한 후 결과값에서 한행을 얻는다. function sql_fetch($sql, $error=G5_DISPLAY_SQL_ERROR, $link=null) { global $Conn; if(!$link) $link = $Conn; $result = sql_query($sql, $error, $link); //$row = @sql_fetch_array($result) or die("<p>$sql<p>" . mysqli_errno() . " : " . mysqli_error() . "<p>error file : $_SERVER['SCRIPT_NAME']"); $row = sql_fetch_array($result); return $row; } // 결과값에서 한행 연관배열(이름으로)로 얻는다. function sql_fetch_array($result) { if(function_exists('mysqli_fetch_assoc')) $row = @mysqli_fetch_assoc($result); else $row = @mysql_fetch_assoc($result); return $row; } // 결과값에서 한행 연관배열(이름으로)로 얻는다. function sql_fetch_assoc($result) { if(function_exists('mysqli_fetch_assoc')) $row = @mysqli_fetch_assoc($result); else $row = @mysql_fetch_assoc($result); return $row; } // $result에 대한 메모리(memory)에 있는 내용을 모두 제거한다. // sql_free_result()는 결과로부터 얻은 질의 값이 커서 많은 메모리를 사용할 염려가 있을 때 사용된다. // 단, 결과 값은 스크립트(script) 실행부가 종료되면서 메모리에서 자동적으로 지워진다. function sql_free_result($result) { if(function_exists('mysqli_free_result')) return mysqli_free_result($result); else return mysql_free_result($result); } function sql_password($value) { // mysql 4.0x 이하 버전에서는 password() 함수의 결과가 16bytes // mysql 4.1x 이상 버전에서는 password() 함수의 결과가 41bytes $row = sql_fetch(" select password('$value') as pass "); return $row['pass']; } function sql_insert_id($link=null) { global $Conn; if(!$link) $link = $Conn; if(function_exists('mysqli_insert_id') ) return mysqli_insert_id($link); else return mysql_insert_id($link); } function sql_num_rows($result) { if(function_exists('mysqli_num_rows')) return mysqli_num_rows($result); else return mysql_num_rows($result); } function sql_field_names($table, $link=null) { global $Conn; if(!$link) $link = $Conn; $columns = array(); $sql = " select * from `$table` limit 1 "; $result = sql_query($sql, $link); if(function_exists('mysqli_fetch_field')) { while($field = mysqli_fetch_field($result)) { $columns[] = $field->name; } } else { $i = 0; $cnt = mysql_num_fields($result); while($i < $cnt) { $field = mysql_fetch_field($result, $i); $columns[] = $field->name; $i++; } } return $columns; } function sql_error_info($link=null) { global $Conn; if(!$link) $link = $Conn; if(function_exists('mysqli_error')) { return mysqli_errno($link) . ' : ' . mysqli_error($link); } else { return mysql_errno($link) . ' : ' . mysql_error($link); } } // 한글 요일 function get_yoil($date, $full=0) { $arr_yoil = array ('일', '월', '화', '수', '목', '금', '토'); $yoil = date("w", strtotime($date)); $str = $arr_yoil[$yoil]; if ($full) { $str .= '요일'; } return $str; } //페이징함수 function getDefaultValue($Value, $DefaultValue) { if($Value == ""){ return $DefaultValue; } else{ return $Value; } } function alert($msg='', $url='') { if (!$msg) $msg = '올바른 방법으로 이용해 주십시오.'; $msg = str_replace("\n","\\n",$msg); echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"; echo "<script language='javascript'>alert('$msg');"; if (!$url) echo "history.go(-1);"; echo "</script>"; if ($url) // 4.06.00 : 불여우의 경우 아래의 코드를 제대로 인식하지 못함 //echo "<meta http-equiv='refresh' content='0;url=$url'>"; echo "<script language='JavaScript'> location.replace('$url'); </script>"; exit; } function alert_close($msg,$mode="") { if($mode=="reload"){ echo "<script> window.opener.document.location.reload();</script>"; } echo "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">"; echo "<script language='javascript'> alert('$msg'); </script>"; echo "<script language='javascript'> window.close(); </script>"; exit; } //날짜간 간격 구하기 function dateType($sdate,$edate){ $dateInfo; //return 값 $dateTimeBegion = strtotime($edate); //현재시간 $dateTimeEnd = strtotime($sdate); //넘어오는 시간 $dateNum = intval(($dateTimeBegion-$dateTimeEnd)/3600); //계산 $dateInfo = intval($dateNum/24).""; return $dateInfo; //결과값 } function monthType($sdate,$edate){ $dateInfo; //return 값 $sdate = preg_replace("/([0-9]{4})([0-9]{2})/", "\\1-\\2", $sdate); $edate = preg_replace("/([0-9]{4})([0-9]{2})/", "\\1-\\2", $edate); $dateTimeBegion = strtotime($edate."-02"); //현재시간 $dateTimeEnd = strtotime($sdate."-01"); //넘어오는 시간 $dateNum = intval(($dateTimeBegion-$dateTimeEnd)/3600); //계산 $dateInfo = intval($dateNum/(365*2)).""; return $dateInfo; //결과값 } //게시글 날짜 타임 간격 function dateintval($sdate,$edate){ $dateInfo; //return 값 $dateTimeBegion = strtotime($edate); //현재시간 $dateTimeEnd = strtotime($sdate); //넘어오는 시간 $dateNum = intval(($dateTimeBegion-$dateTimeEnd)/3600); //계산 if($dateNum < 24){ //$dateInfo = $dateNum."시간 전"; $dateInfo = $dateNum; }else{ $dateInfo = intval($dateNum/24)."일 전"; } return $dateInfo; //결과값 } function injection($str){ global $Conn; if(function_exists('mysqli_real_escape_string') ) { $str=mysqli_real_escape_string($Conn,$str); }else{ $str=mysql_real_escape_string($Conn,$str); } return $str; } function ex_rate($to,$end,$date){ $date = preg_replace("/([0-9]{4})([0-9]{2})([0-9]{2})/", "\\1-\\2-\\3", $date); $sql="select * from `EXCHANGE_RATE` where `CURRENCY_TO`='".$to."' and `CURRENCY_END`='".$end."' and substring(`DATE`,1,10)='".$date."'"; $res=sql_query($sql); $data=sql_fetch_assoc($res); $rate=$data['RATE']; if(!$rate){ $sql="select * from `EXCHANGE_RATE` where `CURRENCY_TO`='".$to."' and `CURRENCY_END`='".$end."' and (RATE <> '' or RATE<>0 ) order by `DATE` desc limit 1"; $res=sql_query($sql); $data=sql_fetch_assoc($res); $rate=$data['RATE']; } return $rate; } function objectToArray($d) { if (is_object($d)) { // Gets the properties of the given object // with get_object_vars function $d = get_object_vars($d); } if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return array_map(__FUNCTION__, $d); } else { // Return array return $d; } } function arrayToObject($d) { if (is_array($d)) { /* * Return array converted to object * Using __FUNCTION__ (Magic constant) * for recursive call */ return (object) array_map(__FUNCTION__, $d); } else { // Return object return $d; } } function Exl2phpTime( $tRes, $dFormat="1900" ) { if( $dFormat == "1904" ) $fixRes = 24107.375; else $fixRes = 25569.375; return intval( ( ( $tRes - $fixRes) * 86400 ) ); } function number2hangul($number){ $num = array('', '일', '이', '삼', '사', '오', '육', '칠', '팔', '구'); $unit4 = array('', '만', '억', '조', '경'); $unit1 = array('', '십', '백', '천'); $res = array(); $number = str_replace(',','',$number); $split4 = str_split(strrev((string)$number),4); for($i=0;$i<count($split4);$i++){ $temp = array(); $split1 = str_split((string)$split4[$i], 1); for($j=0;$j<count($split1);$j++){ $u = (int)$split1[$j]; if($u > 0) $temp[] = $num[$u].$unit1[$j]; } if(count($temp) > 0) $res[] = implode('', array_reverse($temp)).$unit4[$i]; } return implode('', array_reverse($res)); } function curl_soap($Url){ // is cURL installed yet? if (!function_exists('curl_init')){ die('Sorry cURL is not installed!'); } // OK cool - then let's create a new cURL resource handle $ch = curl_init(); // Now set some options (most are optional) // Set URL to download curl_setopt($ch, CURLOPT_URL, $Url); // Set a referer //curl_setopt($ch, CURLOPT_REFERER, "http://www.example.org/yay.htm"); // User agent //curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0"); // Include header in result? (0 = yes, 1 = no) curl_setopt($ch, CURLOPT_HEADER, 0); // Should cURL return or print out the data? (true = return, false = print) curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Timeout in seconds curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Download the given URL, and return output $output = curl_exec($ch); // Close the cURL resource, and free system resources curl_close($ch); return $output; } function isMobile(){ $arr_browser = array ("iphone", "android", "ipod", "iemobile", "mobile", "lgtelecom", "ppc", "symbianos", "blackberry", "ipad"); $httpUserAgent = strtolower($_SERVER['HTTP_USER_AGENT']); // 기본값으로 모바일 브라우저가 아닌것으로 간주함 $mobile_browser = false; // 모바일브라우저에 해당하는 문자열이 있는 경우 $mobile_browser 를 true로 설정 for($indexi = 0 ; $indexi < count($arr_browser) ; $indexi++){ if(strpos($httpUserAgent, $arr_browser[$indexi]) == true){ $mobile_browser = true; break; } } return $mobile_browser; } function statistics_res_price($price){ $tax=$price / 1.1; $res=floor($tax/10)*10; return $res; } // UTF-8 문자열 자르기 // 출처 : https://www.google.co.kr/search?q=utf8_strcut&aq=f&oq=utf8_strcut&aqs=chrome.0.57j0l3.826j0&sourceid=chrome&ie=UTF-8 function utf8_strcut( $str, $size, $suffix='...' ) { $substr = substr( $str, 0, $size * 2 ); $multi_size = preg_match_all( '/[\x80-\xff]/', $substr, $multi_chars ); if ( $multi_size > 0 ) $size = $size + intval( $multi_size / 3 ) - 1; if ( strlen( $str ) > $size ) { $str = substr( $str, 0, $size ); $str = preg_replace( '/(([\x80-\xff]{3})*?)([\x80-\xff]{0,2})$/', '$1', $str ); $str .= $suffix; } return $str; } function strcut_utf8($str, $len, $checkmb=false, $tail='...') { /** * UTF-8 Format * 0xxxxxxx = ASCII, 110xxxxx 10xxxxxx or 1110xxxx 10xxxxxx 10xxxxxx * latin, greek, cyrillic, coptic, armenian, hebrew, arab characters consist of 2bytes * BMP(Basic Mulitilingual Plane) including Hangul, Japanese consist of 3bytes **/ preg_match_all('/[\xE0-\xFF][\x80-\xFF]{2}|./', $str, $match); // target for BMP $m = $match[0]; $slen = strlen($str); // length of source string $tlen = strlen($tail); // length of tail string $mlen = count($m); // length of matched characters if ($slen <= $len) return $str; if (!$checkmb && $mlen <= $len) return $str; $ret = array(); $count = 0; for ($i=0; $i < $len; $i++) { $count += ($checkmb && strlen($m[$i]) > 1)?2:1; if ($count + $tlen > $len) break; $ret[] = $m[$i]; } return join('', $ret).$tail; } ?>
true
a61ef467f461522bbb59e359e0d1a91161a2dbbf
PHP
kataynoi/e_office
/application/views/calendar/index2.php
UTF-8
2,094
2.609375
3
[]
no_license
<div class="row"> <div class="col-lg-12"> <div class="row"> <?php $month_start = strtotime('first day of this month', time()); $month_end = strtotime('last day of this month', time()); $year_start = strtotime('first day of January', time()); $year_end = strtotime('last day of December', time()); /* echo "วันแรกของเดือน ".date('D', $month_start).'<br/>'; echo "วันแรกของเดือน ".date('N', $month_start).'<br/>';*/ echo date('D, M jS Y', $month_end).'<br/>'; $start_day = date('N', $month_start); $end_day = date('t', $month_start); echo " Number ".$end_day."<br>"; ?> </div> <table class="table table-bordered"> <thead > <th class="text-center"> อาทิตย์ </th> <th class="text-center"> จันทร์ </th> <th class="text-center"> อังคาร</th> <th class="text-center"> พุธ </th> <th class="text-center"> พฤหัสบดี </th> <th class="text-center"> ศุกร์ </th> <th class="text-center"> เสาร์ </th> </thead> <tbody> <?php echo "<tr>"; for ($i=1;$i<=35;$i++){ $date_now = $i-$start_day; if($i > $end_day+$start_day || $date_now <=0 ){ echo "<td></td>"; }else{ echo "<td> $date_now </td>"; } if($i%7 == 0 ){ if($i !=35 ){ echo "</tr><tr>"; }else{ echo "</tr>"; } }else{ echo "";} ; } ?> </tbody> </table> </div> <?php echo $calendar; ?> </div>
true
4f0619bc983b13fafbb3a41b9f4faa5b04ccde2b
PHP
pixelcollective/action-network-wordpress-powertools
/vendor/roots/acorn/src/Acorn/Bootloader.php
UTF-8
3,725
2.609375
3
[ "MIT" ]
permissive
<?php namespace Roots\Acorn; use function Roots\add_filters; use function Roots\env; use Illuminate\Contracts\Foundation\Application as ApplicationContract; use Roots\Acorn\Application; class Bootloader { /** @var string Application to be instantiated at boot time */ protected $application_class; /** @var string[] WordPress hooks that will boot application */ protected $boot_hooks; /** @var callable[] Callbacks to be run when application boots */ protected $queue = []; /** @var bool Signals that application is ready to boot */ protected $ready = false; /** * Create a new bootloader instance * * @param string|iterable $boot_hooks WordPress hooks to boot application * @param string $application_class Application class */ public function __construct( $boot_hooks = ['after_setup_theme', 'rest_api_init'], string $application_class = Application::class ) { $this->application_class = $application_class; $this->boot_hooks = (array) $boot_hooks; add_filters($this->boot_hooks, $this, 5); } /** * Enqueues callback to be loaded with application * * @param callable $callback * @return static; */ public function call(callable $callback) : Bootloader { if (! $this->ready()) { $this->queue[] = $callback; return $this; } $this->app()->call($callback); return $this; } /** * Determines whether the application is ready to boot * * @return bool */ public function ready() : bool { if ($this->ready) { return true; } foreach ($this->boot_hooks as $hook) { if (\did_action($hook) || \doing_action($hook)) { return $this->ready = true; } } return $this->ready = !! \apply_filters('acorn/ready', false); } /** * Boot the Application */ public function __invoke() { static $app; if (! $this->ready()) { return; } $app = $this->app(); foreach ($this->queue as $callback) { $app->call($callback); } $this->queue = []; $app->boot(); } /** * Get application instance * * @return \Illuminate\Contracts\Foundation\Application */ protected function app() : ApplicationContract { static $app; if ($app) { return $app; } $bootstrap = $this->bootstrap(); $basepath = $this->basePath(); $app = new $this->application_class($basepath); $app->bootstrapWith($bootstrap); return $app; } /** * Get the application basepath * * @return string */ protected function basePath() : string { $basepath = \dirname(\locate_template('config') ?: __DIR__ . '/../'); $basepath = \defined('ACORN_BASEPATH') ? \ACORN_BASEPATH : env('ACORN_BASEPATH', $basepath); return \apply_filters('acorn/basepath', $basepath); } /** * Get the list of application bootstraps * * @return string[] */ protected function bootstrap() : array { $bootstrap = [ \Roots\Acorn\Bootstrap\SageFeatures::class, \Roots\Acorn\Bootstrap\LoadConfiguration::class, \Roots\Acorn\Bootstrap\RegisterGlobals::class, \Roots\Acorn\Bootstrap\LoadBindings::class, \Roots\Acorn\Bootstrap\RegisterProviders::class, \Roots\Acorn\Bootstrap\Console::class, ]; return \apply_filters('acorn/bootstrap', $bootstrap); } }
true
6d0b95939377dfd728cefb894e230c2b7eaa42c7
PHP
icanhazstring/github-issue-aggregator
/src/App/Service/PackagistService.php
UTF-8
1,513
2.765625
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace App\Service; use App\Entity\Repository; use App\Provider\PackagistProvider; use Zend\Hydrator\HydratorInterface; /** * Class PackagistService * * @package App\Service * @author icanhazstring <blubb0r05+github@gmail.com> */ class PackagistService { private $provider; private $hydrator; public function __construct(PackagistProvider $provider, HydratorInterface $hydrator) { $this->provider = $provider; $this->hydrator = $hydrator; } /** * @param array $requirements * @return Repository[] */ public function resolveRepositories(array $requirements): array { $repositories = []; foreach ($requirements as $packageName => $version) { $data = [ 'package_name' => $packageName, 'name' => $this->resolvePackageName($packageName), 'url' => $this->resolvePackageRepository($packageName) ]; $repositories[] = $this->hydrator->hydrate($data, new Repository()); } return $repositories; } public function resolvePackageRepository(string $packageName): string { return $this->provider->loadPackage($packageName)->getRepository(); } public function resolvePackageName(string $packageName): string { $repository = $this->provider->loadPackage($packageName)->getRepository(); return str_replace('https://github.com/', '', $repository); } }
true
11d8718c9aa48550176b59bc00d33a721b691e1c
PHP
zeeshankhan8467/fansonly
/vendor/transbank/transbank-sdk/src/Webpay/Oneclick/MallInscription.php
UTF-8
5,320
2.625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace Transbank\Webpay\Oneclick; use Transbank\Webpay\Oneclick; use Transbank\Webpay\Oneclick\Exceptions\InscriptionDeleteException; use Transbank\Webpay\Oneclick\Exceptions\InscriptionFinishException; use Transbank\Webpay\Oneclick\Exceptions\InscriptionStartException; class MallInscription { const INSCRIPTION_START_ENDPOINT = 'rswebpaytransaction/api/oneclick/v1.0/inscriptions'; const INSCRIPTION_FINISH_ENDPOINT = 'rswebpaytransaction/api/oneclick/v1.0/inscriptions/$TOKEN$'; const INSCRIPTION_DELETE_ENDPOINT = 'rswebpaytransaction/api/oneclick/v1.0/inscriptions'; public static function getCommerceIdentifier($options) { if ($options == null) { $commerceCode = Oneclick::getCommerceCode(); $apiKey = Oneclick::getApiKey(); $baseUrl = Oneclick::getIntegrationTypeUrl(); } else { $commerceCode = $options->getCommerceCode(); $apiKey = $options->getApiKey(); $baseUrl = Oneclick::getIntegrationTypeUrl($options->getIntegrationType()); } return array( $commerceCode, $apiKey, $baseUrl, ); } public static function start($userName, $email, $responseUrl, $options = null) { list($commerceCode, $apiKey, $baseUrl) = MallInscription::getCommerceIdentifier($options); $http = Oneclick::getHttpClient(); $headers = [ "Tbk-Api-Key-Id" => $commerceCode, "Tbk-Api-Key-Secret" => $apiKey ]; $payload = json_encode(["username" => $userName, "email" => $email, "response_url" => $responseUrl]); $httpResponse = $http->post( $baseUrl, self::INSCRIPTION_START_ENDPOINT, $payload, ['headers' => $headers] ); $httpCode = $httpResponse->getStatusCode(); if ($httpCode != 200 && $httpCode != 204) { $reason = $httpResponse->getReasonPhrase(); $message = "Could not obtain a response from the service: $reason (HTTP code $httpCode)"; $body = json_decode($httpResponse->getBody(), true); if (isset($body["error_message"])) { $tbkErrorMessage = $body["error_message"]; $message = "$message. Details: $tbkErrorMessage"; } throw new InscriptionStartException($message, $httpCode); } $responseJson = json_decode($httpResponse->getBody(), true); $inscriptionStartResponse = new InscriptionStartResponse($responseJson); return $inscriptionStartResponse; } public static function finish($token, $options = null) { list($commerceCode, $apiKey, $baseUrl) = MallInscription::getCommerceIdentifier($options); $http = Oneclick::getHttpClient(); $headers = [ "Tbk-Api-Key-Id" => $commerceCode, "Tbk-Api-Key-Secret" => $apiKey ]; $url = str_replace('$TOKEN$', $token, self::INSCRIPTION_FINISH_ENDPOINT); $httpResponse = $http->put( $baseUrl, $url, null, ['headers' => $headers] ); $httpCode = $httpResponse->getStatusCode(); if ($httpCode != 200 && $httpCode != 204) { $reason = $httpResponse->getReasonPhrase(); $message = "Could not obtain a response from the service: $reason (HTTP code $httpCode)"; $body = json_decode($httpResponse->getBody(), true); if (isset($body["error_message"])) { $tbkErrorMessage = $body["error_message"]; $message = "$message. Details: $tbkErrorMessage"; } throw new InscriptionFinishException($message, $httpCode); } $responseJson = json_decode($httpResponse->getBody(), true); $inscriptionFinishResponse = new InscriptionFinishResponse($responseJson); return $inscriptionFinishResponse; } public static function delete($tbkUser, $userName, $options = null) { list($commerceCode, $apiKey, $baseUrl) = MallInscription::getCommerceIdentifier($options); $http = Oneclick::getHttpClient(); $headers = [ "Tbk-Api-Key-Id" => $commerceCode, "Tbk-Api-Key-Secret" => $apiKey ]; $payload = json_encode(["tbk_user" => $tbkUser, "username" => $userName]); $httpResponse = $http->delete( $baseUrl, self::INSCRIPTION_DELETE_ENDPOINT, $payload, ['headers' => $headers] ); $httpCode = $httpResponse->getStatusCode(); if ($httpCode != 200 && $httpCode != 204) { $reason = $httpResponse->getReasonPhrase(); $message = "Could not obtain a response from the service: $reason (HTTP code $httpCode)"; $body = json_decode($httpResponse->getBody(), true); if (isset($body["error_message"])) { $tbkErrorMessage = $body["error_message"]; $message = "$message. Details: $tbkErrorMessage"; } throw new InscriptionDeleteException($message, $httpCode); } $inscriptionFinishResponse = new InscriptionDeleteResponse($httpCode); return $inscriptionFinishResponse; } }
true
385265823fcaf0b510061590bd967a9ce177b9fd
PHP
Antaxio14/Clothes
/src/TungstenVn/Clothes/Clothes.php
UTF-8
5,669
2.65625
3
[ "Unlicense" ]
permissive
<?php namespace TungstenVn\Clothes; use jojoe77777\FormAPI\SimpleForm; use pocketmine\command\Command; use pocketmine\command\CommandSender; use pocketmine\event\Listener; use pocketmine\event\player\PlayerJoinEvent; use pocketmine\Player; use pocketmine\plugin\PluginBase; use TungstenVn\Clothes\copyResource\copyResource; use TungstenVn\Clothes\skinStuff\resetSkin; use TungstenVn\Clothes\skinStuff\saveSkin; use TungstenVn\Clothes\skinStuff\setSkin; use TungstenVn\Clothes\checkStuff\checkRequirement; use TungstenVn\Clothes\checkStuff\checkClothes; class Clothes extends PluginBase implements Listener { /** @var self $instance */ public static $instance; // sth like ["wing","lefthand"]: public $clothesTypes = []; //something like ["wing" =>["wing1","wing2"]]: public $clothesDetails = []; public function onEnable() { self::$instance = $this; $this->getServer()->getPluginManager()->registerEvents($this, $this); $a = new checkRequirement(); $a->checkRequirement(); $a = new checkClothes(); $a->checkClothes(); } public function onCommand(CommandSender $sender, Command $command, String $label, array $args) : bool { if($sender instanceof Player) { switch(strtolower($command->getName())) { case "clo": case "clothes": $this->mainform($sender, ""); break; } }else { $sender->sendMessage("§cOnly work in game"); } return true; } public function mainform(Player $player, string $txt) { $form = new SimpleForm(function(Player $player, int $data = null) { $result = $data; if($result === null) { return; } if($result == 0){ $this->resetSkin($player); }else{ if($result > count($this->clothesTypes)){ return; }else{ $this->deeperForm($player, "",$result -1); } } }); $form->setTitle("§0Clothes §aMenu"); $form->setContent($txt); $i = 0; $form->addButton("Reset Skin", 0, "textures/persona_thumbnails/skin_steve_thumbnail_0"); foreach ($this->clothesTypes as $value) { $form->addButton($value, 0, "textures/items/light_block_".$i); if($i < 15){ $i += 3; }else{ $i = 0; } } $form->addButton("Exit", 0, "textures/ui/redX1"); $player->sendForm($form); return $form; } public function deeperForm(Player $player, string $txt,int $type) { $form = new SimpleForm(function(Player $player, int $data = null) use ($type){ $result = $data; if($result === null) { return; } $clothesName = $this->clothesTypes[$type]; if(!array_key_exists($result, $this->clothesDetails[$clothesName])) { $this->mainform($player, ""); return; } $perms = $this->getConfig()->getNested('perms'); if(array_key_exists($this->clothesDetails[$clothesName][$result], $perms)) { if($player->hasPermission($perms[$this->clothesDetails[$clothesName][$result]])) { $setskin = new setSkin(); $setskin->setSkin($player, $this->clothesDetails[$clothesName][$result],$this->clothesTypes[$type]); }else { $this->deeperForm($player, "§cYou dont have that cloth!",$type); return; } }else { $setskin = new setSkin(); $setskin->setSkin($player, $this->clothesDetails[$clothesName][$result], $this->clothesTypes[$type]); $player->sendMessage("§aChange cloth successfull"); } }); $clothesName = $this->clothesTypes[$type]; $form->setTitle("§0".$clothesName." §aMenu"); if($this->clothesDetails[$clothesName] != []){ foreach ($this->clothesDetails[$clothesName] as $value) { $perms = $this->getConfig()->getNested('perms'); if(array_key_exists($value, $perms)) { if($player->hasPermission($perms[$value])) { $form->addButton($value, 0, "textures/ui/check"); }else { $form->addButton($value, 0, "textures/ui/icon_lock"); } }else { $form->addButton($value, 0, "textures/ui/check"); } } $form->setContent($txt); $form->addButton("Back", 0, "textures/gui/newgui/undo"); }else { $form->setContent("There is no ".$clothesName." in here currently"); #chinh lai image undo, va ktra lai nut back xuong duoi cac option $form->addButton("Back", 0, "textures/gui/newgui/undo"); } $player->sendForm($form); return $form; } public function resetSkin(Player $player) { $player->sendMessage("§aReset to original skin successfull"); $reset = new resetSkin(); $reset->setSkin($player); } public function onJoin(PlayerJoinEvent $e) { $name = $e->getPlayer()->getName(); $skin = $e->getPlayer()->getSkin(); $saveSkin = new saveSkin(); $saveSkin->saveSkin($skin, $name); } }
true
1ed2aa4bc211e171b173da2c37aa1a0ed59d4cf1
PHP
nickurt/laravel-postcodeapi
/tests/Providers/nl_NL/ApiPostcodeTest.php
UTF-8
5,092
2.578125
3
[ "MIT" ]
permissive
<?php namespace nickurt\PostcodeApi\tests\Providers\nl_NL; use GuzzleHttp\Client; use GuzzleHttp\Handler\MockHandler; use GuzzleHttp\Psr7\Response; use nickurt\PostcodeApi\Entity\Address; use nickurt\PostcodeApi\Providers\nl_NL\ApiPostcode; use nickurt\PostcodeApi\tests\Providers\BaseProviderTest; class ApiPostcodeTest extends BaseProviderTest { /** @var ApiPostcode */ protected $apiPostcode; public function setUp(): void { $this->apiPostcode = (new ApiPostcode) ->setRequestUrl('http://json.api-postcode.nl') ->setApiKey('c56a4180-65aa-42ec-a945-5fd21dec0538'); } /** @test */ public function it_can_get_the_default_config_values_for_this_provider() { $this->assertSame('c56a4180-65aa-42ec-a945-5fd21dec0538', $this->apiPostcode->getApiKey()); $this->assertSame('http://json.api-postcode.nl', $this->apiPostcode->getRequestUrl()); } /** @test */ public function it_can_get_the_correct_values_for_find_by_postcode_and_house_number_a_valid_postal_code() { $address = $this->apiPostcode->setHttpClient(new Client([ 'handler' => new MockHandler([ new Response(200, [], '{"street":"Evert van de Beekstraat","postcode":"1118CP","house_number":"202","city":"Schiphol","longitude":"4.7479072","latitude":"52.3038976","province":"Noord-Holland"}') ]), ]))->findByPostcodeAndHouseNumber('1118CP', '202'); $this->assertSame('c56a4180-65aa-42ec-a945-5fd21dec0538', $this->apiPostcode->getApiKey()); $this->assertSame('http://json.api-postcode.nl?postcode=1118CP&number=202', $this->apiPostcode->getRequestUrl()); $this->assertInstanceOf(Address::class, $address); $this->assertSame([ 'street' => 'Evert van de Beekstraat', 'house_no' => '202', 'town' => 'Schiphol', 'municipality' => null, 'province' => 'Noord-Holland', 'latitude' => 52.3038976, 'longitude' => 4.7479072 ], $address->toArray()); } /** @test */ public function it_can_get_the_correct_values_for_find_by_postcode_and_house_number_an_invalid_postal_code() { // GuzzleHttp\Exception\ClientException: Client error: `GET http://json.api-postcode.nl?postcode=1118CP&number=1` resulted in a `404 Not Found` response: // {"error":"Cannot resolve address for postcode: 1118CP"} $address = $this->apiPostcode->setHttpClient(new Client([ 'handler' => MockHandler::createWithMiddleware([ new Response(404, [], '{"error":"Cannot resolve address for postcode: 1118CP"}') ]), ]))->findByPostcodeAndHouseNumber('1118CP', '1'); $this->assertInstanceOf(Address::class, $address); $this->assertSame([ 'street' => null, 'house_no' => null, 'town' => null, 'municipality' => null, 'province' => null, 'latitude' => null, 'longitude' => null ], $address->toArray()); } /** @test */ public function it_can_get_the_correct_values_for_find_a_valid_postal_code() { $address = $this->apiPostcode->setHttpClient(new Client([ 'handler' => new MockHandler([ new Response(200, [], '{"street":"Evert van de Beekstraat","postcode":"1118CP","house_number":"178","city":"Schiphol","longitude":"4.7517046","latitude":"52.3052535","province":"Noord-Holland"}') ]), ]))->find('1118CP'); $this->assertSame('c56a4180-65aa-42ec-a945-5fd21dec0538', $this->apiPostcode->getApiKey()); $this->assertSame('http://json.api-postcode.nl?postcode=1118CP', $this->apiPostcode->getRequestUrl()); $this->assertInstanceOf(Address::class, $address); $this->assertSame([ 'street' => 'Evert van de Beekstraat', 'house_no' => null, 'town' => 'Schiphol', 'municipality' => null, 'province' => 'Noord-Holland', 'latitude' => 52.3052535, 'longitude' => 4.7517046 ], $address->toArray()); } /** @test */ public function it_can_get_the_correct_values_for_find_an_invalid_postal_code() { // GuzzleHttp\Exception\ClientException: Client error: `GET http://json.api-postcode.nl?postcode=XXXXAB` resulted in a `400 Bad Request` response: // {"error":"Given postcode incorrect"} $address = $this->apiPostcode->setHttpClient(new Client([ 'handler' => MockHandler::createWithMiddleware([ new Response(400, [], '{"error":"Given postcode incorrect"}') ]), ]))->find('XXXXAB'); $this->assertInstanceOf(Address::class, $address); $this->assertSame([ 'street' => null, 'house_no' => null, 'town' => null, 'municipality' => null, 'province' => null, 'latitude' => null, 'longitude' => null ], $address->toArray()); } }
true
dc477a6875d6649a9d97130b26aa4c45c60fe05d
PHP
wquadrillion/coupon-system
/app/Coupon.php
UTF-8
568
2.671875
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Coupon extends Model { public function coupon(){ return $this->morphTo(); } /** * @param $code * * @return mixed * * Find Coupon By Code */ public static function findByCode($code){ return self::where('code', $code)->first(); } /** * @param $order * * @return mixed * * Get The Discount in a Coupon */ public function discount($order){ return $this->coupon->discount($order); } }
true
4b01a40e7184029d383f124c9eacbe55d70b7e11
PHP
pbws/php-prototype001
/php/createXML.php
UTF-8
3,289
2.6875
3
[]
no_license
<?php $formData = $_GET; $partsNodes = array(); $rootNode = new SimpleXMLElement( "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><root></root>" ); foreach ($formData as $key => $data) { $row = intval(substr($key,5)); if ($row != 0 && !isset($partsNodes[$row])) { $partsNodes[$row] = $rootNode->addChild('parts'); $partsNodes[$row]->addAttribute('row', $row); } switch (substr($key,0,5)){ case 'title': if(isset($partsNodes[$row])){ $partsNodes[$row]->addChild('title', $data); } break; case 'selec': if(isset($partsNodes[$row])){ $partsNodes[$row]->addAttribute('type', $data); } break; case 'optio': if (isset($partsNodes[$row])) { switch ($partsNodes[$row]['type']) { case 'radio': case 'check': if (!empty($data)) { $options = explode(',', $data); $optionNode = $partsNodes[$row]->addChild('options'); foreach ($options as $option) { $optionNode->addChild('option', $option); } } break; default: } } break; default: } } //for($i = 0; $i < $rootNode->count(); $i++){ // var_dump($rootNode->parts[$i]->tittle); // if(empty($rootNode->parts[$i]->tittle)){ // unset($rootNode->parts[$i]); // } //// var_dump($rootNode->parts[$i]); //} foreach ($rootNode as $node) { echo $node->title; if(empty($node->title)){ var_dump($node); unset($node); } } $file_name = $formData['filen']; $file_path = '../xml/'.$file_name.'.xml'; $dom = new DOMDocument( '1.0' ); $dom->loadXML( $rootNode->asXML() ); $dom->formatOutput = true; $dom->save(mb_convert_encoding($file_path,'SJIS','auto')); //echo $dom->saveXML(); function a(){ $rootNode = new SimpleXMLElement( "<?xml version='1.0' encoding='UTF-8' standalone='yes'?><root></root>" ); //テキストフィールド $partsNode = $rootNode->addChild('parts'); $partsNode->addAttribute('type', 'textFeild'); $partsNode->addChild('title', $title); //テキストエリア $partsNode = $rootNode->addChild('parts'); $partsNode->addAttribute('type', 'textArea'); $partsNode->addChild('title', $title); //ラベル $partsNode = $rootNode->addChild('parts'); $partsNode->addAttribute('type', 'label'); $partsNode->addChild('title', $title); // ノードの追加 $itemNode = $rootNode->addChild('item'); $itemNode->addChild( 'itemCode', 'mk' ); $itemNode->addChild( 'itemName', 'orange' ); $itemNode = $rootNode->addChild('item'); $itemNode->addChild( 'itemCode', 'ap' ); $itemNode->addChild( 'itemName', 'apple' ); $itemNode = $rootNode->addChild('item'); $itemNode->addChild( 'itemCode', 'tof' ); $itemNode->addChild( 'itemName', '豆腐' ); // ノードに属性を追加 $itemNode->addAttribute('stock', 'none'); // 作ったxmlツリーを出力する $dom = new DOMDocument( '1.0' ); $dom->loadXML( $rootNode->asXML() ); $dom->formatOutput = true; //$dom->save('../xml/create_test.xml'); echo $dom->saveXML(); }
true
63d2371b08fa8da641eeee2125a437b08e573e54
PHP
whitedream31/dana3
/scripts/old.class.formbuilder.filewebsite.php
UTF-8
452
2.546875
3
[]
no_license
<?php require_once 'class.formbuilder.file.php'; // file upload for general (safe) files field - FLDTYPE_FILEWEBSITE class filewebsitefield extends filefield { function __construct($name, $value, $label, $targetname) { parent::__construct($name, $value, $label, $targetname); } protected function Init() { global $MIME_WEBSITE; $this->fieldtype = basetable::FLDTYPE_FILEWEBSITE; $this->acceptedfiletypes = $MIME_WEBSITE; } }
true
16b452dd911f257c7526c6edf9249f88686a3a17
PHP
kevinliposl/ProyectoGestion
/business/TagBusiness.php
UTF-8
628
2.671875
3
[]
no_license
<?php require_once '../domain/Tag.php'; class TagBusiness { //Attributes private $data; function __construct() { include_once '../data/TagData.php'; $this->data = new TagData(); //End construct } function insert($words) { return $this->data->insert($words); //End insert } function selectActivity($activityId) { return $this->data->selectActivity($activityId); //End selectAll } function selectActivitySize($idActivity){ return $this->data->selectActivitySize($idActivity); } //End class ActivityBusiness }
true
cb1dfeaeb80d24fe10dc34a56edb30de9730fc7f
PHP
kaiser-coder/language
/Language.php
UTF-8
2,401
3.375
3
[]
no_license
<?php namespace Kaiser; class Language { // Si le mot sasie existe dans le dictionnaire fr. > cette phrase est en fr. // Sinon le mot ou la phrase saisie a une origine inconnue // Ouvrir la liste des mots fr // Comparer la phrase sasie pour trouver une correspondance dans le dictionnaire // Compter le nombre de mots qui paraissent dans le dictionnaire pour définir la langue // Compter le nombre de mots que l'on ne connait pas private $lang = [ "fr." => [], "en." => [] ]; private $result = [ "francais" => [], "anglais" => [], "inconnu" => [], "defined_language" => null ]; public function __construct() { $this->setDictionary([ 'fr.' => 'ressources/french.json', 'en.' => 'ressources/english.json' ]); } /** * @param Array $words * @return Array */ public function defineLanguage($words) { $this->countWords($words); if( count($this->result['francais']) + count($this->result['anglais']) > count($this->result['inconnu']) ) { if(count($this->result['francais']) > count($this->result['anglais'])) { $this->result['defined_language'] = 'francais'; }; if(count($this->result['francais']) < count($this->result['anglais'])) { $this->result['defined_language'] = 'anglais'; } if(count($this->result['francais']) == count($this->result['anglais'])) { $this->result['defined_language'] = 'mixed'; } } else { $this->result['defined_language'] = 'inconnu'; } return $this->result; } /** * @param Array $path */ private function setDictionary($path) { foreach ($path as $key => $value) { $file = file_get_contents($path[$key]); $this->lang[$key]= json_decode($file, true); } } /** * @param Array $words */ private function countWords($words) { foreach ($words as $key => $value) { if (in_array($value, $this->lang['fr.'])) { array_push($this->result['francais'], $value); } else if(in_array($value, $this->lang['en.'])) { array_push($this->result['anglais'], $value); } else { array_push($this->result['inconnu'], $value); } } } }
true
f5bf13292118766ee14751e1b5e9cc18e4a35908
PHP
typoworx-de/php-snipplets
/xml/XmlParser.php
UTF-8
3,470
2.796875
3
[]
no_license
<?php namespace App\Database; use \stdClass; use \DOMXPath; use \XMLReader; use \DOMDocument; /** * Class XmlParser * @package App\Console\Tasks\Feed\Reader */ class XmlParser { /** * @var \XMLReader */ protected $xmlReader; /** * @var \stdClass */ protected $rootNode; /** * @var bool */ protected $ignoreCommentNodes = true; public function __construct($ignoreCommentNodes = true) { $this->xmlReader = new XMLReader(); $this->ignoreCommentNodes = $ignoreCommentNodes; } /** * @param string $file * @param null $encoding * @param int $options A bitmask of the LIBXML_* * @return bool */ public function loadFile(string $file, $encoding = null, $options = 0) : bool { if($this->xmlReader->open($file, $encoding, $options)) { // Fetch Root-Node $this->parseRootNode(); return true; } return false; } /** * @param string $xml * @param null $encoding * @param int $options A bitmask of the LIBXML_* * @return bool */ public function loadXML(string $xml, $encoding = null, $options = 0) : bool { if($this->xmlReader->XML($xml, $encoding, $options)) { // Fetch Root-Node $this->parseRootNode(); return true; } return false; } protected function parseRootNode() { $this->rootNode = $this->fetch(); } public function getRootNode() { return $this->rootNode; } /** * @return \stdClass */ public function fetch() : stdClass { $node = new \stdClass(); // Skip Comment-Nodes with ease if($this->ignoreCommentNodes) { while ($this->xmlReader->read() && in_array($this->xmlReader->name, ['#comment'])) {} } $this->xmlReader->moveToElement(); $node->{'attributes'} = $this->getNodeAttributes(); $node->{'domElement'} = $this->xmlReader->expand(); return $node; } /** * @return \DOMDocument */ public function fetchAsDomDocument() : DOMDocument { $doc = new DOMDocument(); $doc->importNode($this->xmlReader->expand()); return $doc; } /** * @return \stdClass */ protected function getNodeAttributes(string $matchName = '') : \stdClass { $this->xmlReader->moveToElement(); $attributes = new \stdClass(); $attributes->{'length'} = empty($matchName) ? $this->xmlReader->attributeCount : 0; $count = 0; if($this->xmlReader->hasAttributes) { $this->xmlReader->moveToFirstAttribute(); do { if(!empty($matchName)) { if (strpos($this->xmlReader->name, $matchName) !== false) { $count++; $attributes->{ $this->xmlReader->name } = $this->xmlReader->value; } continue; } $attributes->{ $this->xmlReader->name } = $this->xmlReader->value; } while ($this->xmlReader->moveToNextAttribute()); } if(!empty($matchName)) { $attributes->{'length'} = $count; } return $attributes; } }
true
61e9af6371ec1fc6bd01a63fbfbd3b5e36928cf5
PHP
undercloud/xpc
/consoler/function/out.xpc.php
UTF-8
1,845
2.859375
3
[]
no_license
<?php if (false === function_exists('xpc_outln')) { /** * @param string $msg * @param null $style * @return void */ function xpc_outln ($msg = '', $style = null) { xpc_out($msg . XPC_PHP_EOL, $style); } } if (false === function_exists('xpc_out')) { /** * @param $msg * @param null $style * @param false $return * @return array|string */ function xpc_out($msg, $style = null, $return = false) { if(!$style){ $style = 'f-default:b-default'; } if (is_array($msg)) { return array_map('xpc_outln', $msg); } if(XPC_COLORIZE_ENABLED){ static $map = array( 't-bold' => 1, 't-underlined' => 4, 'f-black' => 30, 'f-red' => 31, 'f-green' => 32, 'f-yellow' => 33, 'f-blue' => 34, 'f-purple' => 35, 'f-cyan' => 36, 'f-white' => 37, 'f-default' => 39, 'b-black' => 40, 'b-red' => 41, 'b-green' => 42, 'b-yellow' => 43, 'b-blue' => 44, 'b-purple' => 45, 'b-cyan' => 46, 'b-white' => 47, 'b-default' => 49, ); $keys = explode(':', (string) $style); $keys = array_map( static function ($key) use ($map) { return array_key_exists($key, $map) ? $map[$key] : null; }, $keys ); $keys = array_filter($keys); $style = implode(';', $keys ? $keys : array(0,39,49)); $msg = sprintf("\033[%sm%s\e[0;39;49m", $style, $msg); } if ($return) { return $msg; } fwrite(STDOUT, $msg); } }
true
a61e5408d0468e573320e4097eb2c14d544e5d38
PHP
wangjh1/newblog
/backend/models/WebContentPage.php
UTF-8
1,191
2.609375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace backend\models; use Yii; use backend\models\WebContent; /** * This is the model class for table "web_content_page". * * @property integer $id * @property integer $content_id * @property string $body */ class WebContentPage extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'web_content_page'; } /** * @inheritdoc */ public function rules() { return [ [['content_id',], 'required'], [['content_id'], 'integer'], [['body'], 'string'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => Yii::t('app', 'ID'), 'content_id' => Yii::t('app', 'Content ID'), 'body' => Yii::t('app', '内容'), ]; } public function getContent() { $content = new WebContent(); // 第一个参数为要关联的子表模型类名, // 第二个参数指定 通过子表的customer_id,关联主表的id字段 return $this->hasOne($content::className(), ['id' => 'content_id']); } }
true
b275f4d4648402938215c6f043d8b65efac9e929
PHP
dominio3/berexpress
/app/Repositories/ConsignementRepository.php
UTF-8
805
2.640625
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use App\Models\Consignement; use InfyOm\Generator\Common\BaseRepository; /** * Class ConsignementRepository * @package App\Repositories * @version June 6, 2019, 6:52 pm -03 * * @method Consignement findWithoutFail($id, $columns = ['*']) * @method Consignement find($id, $columns = ['*']) * @method Consignement first($columns = ['*']) */ class ConsignementRepository extends BaseRepository { /** * @var array */ protected $fieldSearchable = [ 'document', 'line01', 'line02', 'line03', 'line04', 'line05', 'total_price', 'status', 'users_id' ]; /** * Configure the Model **/ public function model() { return Consignement::class; } }
true
c3355bbf9a91c959776b1d7b76f4c0b8db138c23
PHP
mfinkels/miPrimerProyecto
/ALANAPI/vendor/knplabs/knp-menu/src/Knp/Menu/MenuFactory.php
UTF-8
3,778
2.9375
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace Knp\Menu; use Knp\Menu\Factory\CoreExtension; use Knp\Menu\Factory\ExtensionInterface; use Knp\Menu\Loader\ArrayLoader; use Knp\Menu\Loader\NodeLoader; /** * Factory to create a menu from a tree */ class MenuFactory implements FactoryInterface { /** * @var array[] */ private $extensions = array(); /** * @var ExtensionInterface[] */ private $sorted; public function __construct() { $this->addExtension(new CoreExtension(), -10); } public function createItem($name, array $options = array()) { // TODO remove this BC layer before releasing 2.0 $processedOptions = $this->buildOptions($options); if ($processedOptions !== $options) { trigger_error(sprintf('Overwriting Knp\Menu\MenuFactory::buildOptions is deprecated. Use a factory extension instead of %s.', get_class($this)), E_USER_DEPRECATED); $options = $processedOptions; } foreach ($this->getExtensions() as $extension) { $options = $extension->buildOptions($options); } $item = new MenuItem($name, $this); foreach ($this->getExtensions() as $extension) { $extension->buildItem($item, $options); } // TODO remove this BC layer before releasing 2.0 if (method_exists($this, 'configureItem')) { trigger_error(sprintf('Overwriting Knp\Menu\MenuFactory::configureItem is deprecated. Use a factory extension instead of %s.', get_class($this)), E_USER_DEPRECATED); $this->configureItem($item, $options); } return $item; } /** * Adds a factory extension * * @param ExtensionInterface $extension * @param integer $priority */ public function addExtension(ExtensionInterface $extension, $priority = 0) { $this->extensions[$priority][] = $extension; $this->sorted = null; } /** * Builds the full option array used to configure the item. * * @deprecated Use a Knp\Menu\Factory\ExtensionInterface instead * * @param array $options * * @return array */ protected function buildOptions(array $options) { return $options; } /** * Create a menu item from a NodeInterface * * @deprecated Use \Knp\Menu\Loader\NodeLoader * * @param NodeInterface $node * * @return ItemInterface */ public function createFromNode(NodeInterface $node) { trigger_error(__METHOD__ . ' is deprecated. Use Knp\Menu\Loader\NodeLoader instead', E_USER_DEPRECATED); $loader = new NodeLoader($this); return $loader->load($node); } /** * Creates a new menu item (and tree if $data['children'] is set). * * The source is an array of data that should match the output from MenuManipulator->toArray(). * * @deprecated Use \Knp\Menu\Loader\ArrayLoader * * @param array $data The array of data to use as a source for the menu tree * * @return ItemInterface */ public function createFromArray(array $data) { trigger_error(__METHOD__ . ' is deprecated. Use Knp\Menu\Loader\ArrayLoader instead', E_USER_DEPRECATED); $loader = new ArrayLoader($this); return $loader->load($data); } /** * Sorts the internal list of extensions by priority. * * @return ExtensionInterface[] */ private function getExtensions() { if (null === $this->sorted) { krsort($this->extensions); $this->sorted = !empty($this->extensions) ? call_user_func_array('array_merge', $this->extensions) : array(); } return $this->sorted; } }
true
92e34ee99a8c9ddc7451e3afdf49c0d8437d6381
PHP
v-radev/basic-router
/classes/BooksController.php
UTF-8
1,075
3.21875
3
[]
no_license
<?php require_once "BaseController.php"; class BooksController extends BaseController { /* GET /book - show all view - index() GET /book/create - show create view - create() POST /book - create new book - store() GET /book/{id} - show book id view - show($id) GET /book/{id}/edit - show update view - edit($id) PUT /book/{id} - update book id view - update($id) DELETE /book/{id} - delete book id view - delete($id) */ public static function index(){ return "Show all books view."; } public static function create(){ return "Show create new book view."; } public static function store(){ return "Write book to DB."; } public static function show($id){ return "Show book with id: {$id}"; } public static function edit($id){ return "Edit book with id: {$id}"; } public static function update($id){ return "Update book with id: {$id}"; } public static function delete($id){ return "Delete book with id: {$id}"; } }
true
20d7a69f7c8df312271372b41ef5d44e46191aa8
PHP
aaronmp13/MarketSimulator
/alpha.php
UTF-8
760
2.546875
3
[]
no_license
<?php $API_KEY = "2T11QGW4OZZG5891"; $FUNC = "TIME_SERIES_DAILY"; $SYMB = $_GET['stock']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,("https://www.alphavantage.co/query?function=" . $FUNC . "&symbol=" . $SYMB . "&apikey=" . $API_KEY)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec ($ch); curl_close ($ch); $result = json_decode($server_output); $dataForAllDays = $result->{'Time Series (Daily)'}; $date = date("Y-m-d"); $dataForSingleDate = $dataForAllDays->{"2021-04-27"}; echo "Open: " . $dataForSingleDate->{'1. open'} . '<br/>'; echo $dataForSingleDate->{'2. high'} . '<br/>'; echo $dataForSingleDate->{'3. low'} . '<br/>'; echo $dataForSingleDate->{'4. close'} . '<br/>'; echo $dataForSingleDate->{'5. volume'} . '<br/>'; ?>
true
03aa326a018d59d031510281cf6dc85dc00abaae
PHP
edwintenbrinke/mafia-api
/src/Service/CrimeService.php
UTF-8
3,790
2.6875
3
[]
no_license
<?php namespace App\Service; use App\Entity\User; use App\Helper\Message; use App\Helper\Random; use App\Helper\Time; use Symfony\Contracts\Translation\TranslatorInterface; /** * Class Crime * @author Edwin ten Brinke <edwin.ten.brinke@extendas.com> */ class CrimeService { public const CRIME_JACKPOT_CHANCE = 2.5; private $translator; private $rank; private $car; public function __construct(RankService $rank, CarService $car, TranslatorInterface $translator) { $this->translator = $translator; $this->rank = $rank; $this->car = $car; } /** * @param User $user * * @throws \Exception */ public function executeGta(User $user) { $rank = $this->rank->getUserRank($user); // check cooldown Time::isFuture($user->getCooldown()->getGrandTheftAuto()); $car = null; $amount = null; $chance = Random::chance(); switch(true) { case $chance < $rank->gta_chance: list($message, $car) = $this->car->getCar($user, $rank); $user->addExperience(50); $user->getCounter()->addGrandTheftAuto(); break; default: //failed $message = Message::failure(); } $user->getCooldown()->setGrandTheftAuto(Time::addSeconds(2)); return [$message, $car]; } /** * @param User $user * * @return int * @throws \Exception */ public function executeCrime(User $user) { $rank = $this->rank->getUserRank($user); // TODO Prison check // RANK: Empty suit // check cooldown Time::isFuture($user->getCooldown()->getCrime()); $amount = null; $chance = Random::chance(); switch(true) { case $chance < self::CRIME_JACKPOT_CHANCE: $amount = Random::between(1000, 2500); $message = Message::jackpot($amount); break; case $chance < $rank->crime_chance: $amount = Random::between(100, 250); $message = Message::success($amount); break; default: //failed $message = Message::failure(); } if ($amount) { $user->addCash($amount); $user->addExperience(10); $user->getCounter()->addCrime(); } // set cooldown $user->getCooldown()->setCrime(Time::addSeconds(2)); return $message; } /** * @param User $user * * @return int * @throws \Exception */ public function executeOrganizedCrime(User $user) { $rank = $this->rank->getUserRank($user); //TODO prison RankService::isAllowed($user, RankService::RANKS['Deliveryboy']); Time::isFuture($user->getCooldown()->getOrganizedCrime()); $amount = null; $chance = Random::chance(); switch(true) { case $chance < self::CRIME_JACKPOT_CHANCE: $amount = (Random::between(750, 1500) * 5); $message = Message::jackpot($amount); break; case $chance < $rank->crime_chance: $amount = Random::between(750, 1500); $message = Message::success($amount); break; default: //failed $message = Message::failure(); } if ($amount) { $user->addCash($amount); $user->addExperience(50); $user->getCounter()->addOrganizedCrime(); } // set cooldown $user->getCooldown()->setOrganizedCrime(Time::addMinutes(3)); return $message; } }
true
2061b1627e23d8ceb2f14763900c472d32a5844f
PHP
WaukeeApexWebDev2016/apex_webdev_1_001_programming-ChrisHougaard
/function.php
UTF-8
125
3.390625
3
[]
no_license
<?php function sub($first, $second) { return $first - $second; } echo sub(5, 1); $result = sub(10, 9); echo $result; ?>
true
3a9a4c250f83a158376db709c7e4f23f556ab487
PHP
viktorsh/ddos-guard
/DdosGuard/dist/lib/Row.php
UTF-8
1,117
2.703125
3
[ "MIT" ]
permissive
<?php namespace sb\DdosGuard; /** * Created by PhpStorm. * User: viktor * Date: 10.01.2017 * Time: 15:10 */ class Row { public $row; public $ip; public $unixtime; public $timezone; public $request; public $status; public $body_bytes_sent; public $http_referer; public $http_user_agent; public $http_x_forwarded_for; function __construct($row) { $this->row = $row; } function parse($handlerFunction) { if (!$this->row) throw new \Exception('Property "row" is not set'); $handlerFunction($this); if (!$this->ip) throw new \Exception('Property "ip" is not defined'); if (!ip2long($this->ip)) throw new \Exception('Property "ip" is incorrect'); if (!$this->status) throw new \Exception('Property "status" is not defined'); if (!is_numeric($this->status)) throw new \Exception('Property "status" is incorrect'); if (!$this->unixtime) throw new \Exception('Property "unixtime" is not defined'); } }
true
710f699156f76ea475b885485a6c8327fae84257
PHP
claerosystems/cl4auth
/classes/model/cl4/session.php
UTF-8
1,865
2.6875
3
[]
no_license
<?php defined('SYSPATH') or die ('No direct script access.'); /** * This model was created using cl4_ORM and should provide * standard Kohana ORM features in additon to cl4-specific features. */ class Model_cl4_Session extends ORM { protected $_table_names_plural = FALSE; protected $_table_name = 'session'; protected $_primary_key = 'session_id'; // default: id protected $_primary_val = 'session_id'; // default: name (column used as primary value) public $_table_name_display = 'Session'; // cl4-specific // column definitions protected $_table_columns = array( /** * see http://v3.kohanaphp.com/guide/api/Database_MySQL#list_columns for all possible column attributes * see the modules/cl4/config/cl4orm.php for a full list of cl4-specific options and documentation on what the options do */ 'session_id' => array( 'field_type' => 'select', 'is_nullable' => FALSE, 'field_options' => array( 'source' => array( 'source' => 'model', 'data' => 'session', ), ), ), 'last_active' => array( 'field_type' => 'text', 'is_nullable' => FALSE, 'field_attributes' => array( 'maxlength' => 10, 'size' => 10, ), ), 'contents' => array( 'field_type' => 'textarea', 'is_nullable' => FALSE, ), ); /** * @var array $_display_order The order to display columns in, if different from as listed in $_table_columns. * Columns not listed here will be added beneath these columns, in the order they are listed in $_table_columns. */ protected $_display_order = array( 10 => 'session_id', 20 => 'last_active', 30 => 'contents', ); /** * Labels for columns * * @return array */ public function labels() { return array( 'session_id' => 'Session', 'last_active' => 'Last Active', 'contents' => 'Contents', ); } // function labels } // class Model_Session
true
574e86b9bc595279a0eef979095cffe218c3bd53
PHP
hovenko/Madcow
/DF/Web/HTTP/Request/MagicQuotes.php
UTF-8
499
2.734375
3
[ "MIT" ]
permissive
<?php class DF_Web_HTTP_Request_MagicQuotes { static public function stripslash_request() { $gpc = array(&$_POST, &$_REQUEST, &$_GET, &$_COOKIE); foreach ($gpc as &$var) { $var = self::stripslashes_deep($var); } } static public function stripslashes_deep($value) { $value = is_array($value) ? array_map(array(__CLASS__, 'stripslashes_deep'), $value) : stripslashes($value); return $value; } }
true
ae48eadbcd355e53d4b2eaf6e6c987e721af9591
PHP
kaushikpatel11/laravel-demo
/app/Services/RealEstateService.php
UTF-8
16,992
2.59375
3
[]
no_license
<?php namespace App\Services; use App\Http\Requests\RealEstateRequest; use App\Repositories\RealEstateRepository; use Carbon\Carbon; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\DB; /** * Class RealEstateService * * @package App\Services * @author David Cigala * @version 0.0.1 * @since 2020-08-21 */ class RealEstateService { /** * @var \App\Repositories\RealEstateRepository $realEstate */ protected RealEstateRepository $realEstate; /** * Create a new controller instance. * It injects instances inside the controller. * * @param \App\Repositories\RealEstateRepository $realEstate * * @return void */ public function __construct(RealEstateRepository $realEstate) { $this->realEstate = $realEstate; } /** * Return a formated array with a REAL ESTATE. If it exists. * It also return its associated data (location and zones). * If it does not exist, return an exception. * * @param integer $id REAL ESTATE ID to search. * * @return array $data * @throws \Throwable */ public function find($id) { $data = []; $dataRealEstate = $this->realEstate->find($id); // Array to associate the model used in the polymorphic relation with its translation to spanish. $zoneable_types = [ 'App\Country' => 'Pa&iacute;s', 'App\State' => 'Autonom&iacute;a', 'App\County' => 'Provincia', 'App\City' => 'Ciudad', ]; if (0 < $dataRealEstate->id) { // Get the Real Estate $data['real_estate'] = $dataRealEstate->toArray(); // Get the related location and its associated texts/names $locations = $dataRealEstate->locations; if (!is_null($locations)) { $data['locations'] = []; foreach ($locations as $key => $location) { $data['locations'][$key] = $location->toArray(); $data['locations'][$key]['country_name'] = $location->country->name; $data['locations'][$key]['state_name'] = $location->state->name; $data['locations'][$key]['county_name'] = $location->county->name; $data['locations'][$key]['city_name'] = $location->city->name; } } // Get the related zones and its associated texts/names $zones = $dataRealEstate->zones; if (!is_null($zones)) { $data['zones'] = []; foreach ($zones as $zone) { $data['zones'][] = [ 'id' => $zone->id, 'realestate_id' => $zone->realestate_id, 'zoneable_id' => $zone->zoneable_id, 'zoneable_type' => substr($zone->zoneable_type, 4), // Remove 'App\' because when we update it is added and we can have 'App\App\City' 'text_type' => html_entity_decode($zoneable_types[$zone->zoneable_type]), // Spanish accents to HTML 'text_name' => $zone->zoneable->name, ]; } } // Get the related ratings $ratings = $dataRealEstate->ratings; if (!is_null($ratings)) { $data['ratings'] = []; foreach ($ratings as $rating) { $comment_keys = explode(';', $rating->comment_key); $translations = DB::table('rating_comments') ->whereIn('key', $comment_keys) ->get('es') ->pluck('es') ->toArray(); $translations = implode('. ', $translations); $data['ratings'][] = [ 'id' => $rating->id, 'card_id' => $rating->card_id, // @ TODO @DCA 2020-08-31 este campo aparentemente solo es necesario para ver los tipos fijos de valoraciones que tiene una inmobiliaria y no se usa en la vista // 'comment_key' => $rating->comment_key, 'rating' => $rating->rating, 'open_comment' => $rating->open_comment, 'comment_key_translated' => $translations, ]; } } } return $data; } /** * Set an array with all the combined data (real estate data, location, work zones) * of the record/model RealEstate which ID is $id. * * @param integer $id ID from the RealEstate. * @param \App\Http\Requests\RealEstateRequest $attributes Field list to update. * * @return array */ private function setRealEstateData($id, RealEstateRequest $attributes) { $data = []; // Set REAL ESTATE fiscal data $data['real_estate'] = [ 'user_id' => Auth::id(), 'web' => $attributes->input('web', null), 'business_name' => $attributes->input('business_name', null), 'commercial_name' => $attributes->input('commercial_name', null), 'vat_number' => $attributes->input('vat_number', null), 'session_title_id' => $attributes->input('session_title_id', null), 'name' => $attributes->input('name', null), 'surname' => $attributes->input('surname', null), 'phone_1' => $attributes->input('phone_1', null), 'phone_2' => $attributes->input('phone_2', null), 'punctuation' => $attributes->input('punctuation', null), 'status' => $attributes->input('status', null), 'origin' => $attributes->input('origin', null), 'language' => $attributes->input('language', null), ]; // Set REAL ESTATE, address, gps location $locations = $attributes->input('locations', null); $data['locations'] = []; foreach ($locations['country_id'] as $key => $location) { $data['locations'][] = [ 'realestate_id' => (0 < $id) ? $id : null, 'country_id' => $locations['country_id'][$key], 'state_id' => $locations['state_id'][$key], 'county_id' => $locations['county_id'][$key], 'city_id' => $locations['city_id'][$key], 'street' => $locations['street'][$key], 'postcode' => $locations['postcode'][$key], 'latitude' => $locations['latitude'][$key], 'longitude' => $locations['longitude'][$key], ]; } // Set REAL ESTATE, zones $zones = $attributes->input('zones', null); $data['zones'] = []; if ($zones != null) { foreach ($zones['id'] as $key => $zone) { $data['zones'][] = [ 'id' => $zones['pkey_id'][$key], 'realestate_id' => (0 < $id) ? $id : null, 'zoneable_id' => $zone, 'zoneable_type' => 'App\\' . $zones['model'][$key], ]; } } else { $data['zones'][] = [ //'id' => $zones['pkey_id'][$key], //'realestate_id' => (0 < $id) ? $id : null, 'zoneable_id' => 1, 'zoneable_type' => 'App\\Country', ]; } return $data; } /** * Update fields passed by array $attributes * of the record/model RealEstate which ID is $id. * * @param integer $id ID from the Real Estate. * @param \App\Http\Requests\RealEstateRequest $attributes Field list to update. * * @return \App\RealEstate * @return \Exception * @return \Illuminate\Database\Eloquent\ModelNotFoundException * @return \Illuminate\Database\QueryException * @throws \Throwable */ public function update($id, RealEstateRequest $attributes) { try { // Set an array with all the combined data (session, music, blocks and timelines) $data = $this->setRealEstateData($id, $attributes); if($data['real_estate']['status']==null) $data['real_estate']['status']='1'; return $this->realEstate->updateOrCreate($id, $data); } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $exception) { return $exception; } catch (\Illuminate\Database\QueryException $exception) { return $exception; } } public function countPropertiesByZones($realEstate) { //ultimo historico de todas las propiedades $last_historical = DB::table('historical_lines') ->select(DB::raw('MAX(historical_lines.id) as max_historical_id'), 'historical_lines.property_id as historical_property_id') ->groupBy('historical_lines.property_id'); //ultimo historico de todas las propiedades /* $last_historical = DB::table('historical_lines') ->select(DB::raw('MAX(historical_lines.id) as max_historical_id'), 'historical_lines.property_id') ->groupBy('historical_lines.property_id');*/ $zones = $realEstate->zones; $properties = []; foreach ($zones as $zone) { //quitamos la zona si es un pais porque sino coje todas las propiedades $queryField = substr(strtolower($zone->zoneable_type), 4) . '_id'; $locations = DB::table('locations') ->joinSub($last_historical, 'last_historical', function ($join) { $join->on('last_historical.historical_property_id', '=', 'locations.locationable_id'); }) ->join('historical_lines', 'historical_lines.id', '=', 'last_historical.max_historical_id') ->where('historical_lines.status_id', '=', 2) ->where('locationable_type', 'App\Properties') ->where($queryField, $zone->zoneable->id) ->where($queryField, $zone->zoneable->id)->pluck('locationable_id')->toArray(); $properties = array_merge($properties, $locations); } return (count(array_unique($properties))); } public function propertiesByZones($realEstate) { //ultimo historico de todas las propiedades $last_historical = DB::table('historical_lines') ->select(DB::raw('MAX(historical_lines.id) as max_historical_id'), 'historical_lines.property_id as historical_property_id') ->groupBy('historical_lines.property_id'); //ultimo historico de todas las propiedades /* $last_historical = DB::table('historical_lines') ->select(DB::raw('MAX(historical_lines.id) as max_historical_id'), 'historical_lines.property_id') ->groupBy('historical_lines.property_id');*/ $zones = $realEstate->zones; /*$properties = []; foreach ($zones as $zone) { //quitamos la zona si es un pais porque sino coje todas las propiedades $queryField = substr(strtolower($zone->zoneable_type), 4) . '_id'; $locations = DB::table('locations') ->join('properties', 'properties.id', '=', 'locations.locationable_id') ->joinSub($last_historical, 'last_historical', function ($join) { $join->on('last_historical.historical_property_id', '=', 'locations.locationable_id'); }) ->join('historical_lines', 'historical_lines.id', '=', 'last_historical.max_historical_id') ->where('historical_lines.status_id', '=', 2) ->where('locationable_type', 'App\Properties') //->where($queryField, $zone->zoneable->id) ->where($queryField, $zone->zoneable->id)->get()->toArray(); $properties = array_merge($properties, $locations); } //$unique = array_unique($properties);*/ $properties = collect(); foreach ($zones as $zone) { //quitamos la zona si es un pais porque sino coje todas las propiedades $queryField = substr(strtolower($zone->zoneable_type), 4) . '_id'; $locations = DB::table('locations') ->select('*', 'properties.id as id', 'counties.name as county_name', 'cities.name as city_name') ->join('counties', 'counties.id', '=', 'locations.county_id') ->join('cities', 'cities.id', '=', 'locations.city_id') ->join('properties', 'properties.id', '=', 'locations.locationable_id') ->joinSub($last_historical, 'last_historical', function ($join) { $join->on('last_historical.historical_property_id', '=', 'locations.locationable_id'); }) ->join('historical_lines', 'historical_lines.id', '=', 'last_historical.max_historical_id') ->where('historical_lines.status_id', '=', 2) ->whereNull('properties.deleted_at') ->where('locationable_type', 'App\Properties') ->where('locationable_type', 'App\Properties') //->where($queryField, $zone->zoneable->id) ->where('locations.'.$queryField, $zone->zoneable->id)->get(); $properties = $properties->merge($locations); } $properties = $properties->unique('property_id'); return ($properties); } /* private function countOpenCards(){ //numero de aperturas de ficha por mes $result = DB::table('cards') ->select( DB::raw('count(cards.real_estate_id) as re_number'), DB::raw('MONTH(cards.created_at) as mo' )) ->leftJoin('properties', 'properties.id', '=', 'cards.property_id') ->groupBy( DB::raw('MONTH(cards.created_at) ')) ->get() ->toArray(); //se formatea el aray para que lo entienda la grafica $result_formatted = [0,0,0,0,0,0,0,0,0,0]; $i=0; foreach($result as $res){ $result_formatted[$res->mo] = $res->re_number; } return $result_formatted; }*/ public function countPropertiesByZonesByMonth($realEstate) { //ultimo historico de todas las propiedades $last_historical = DB::table('historical_lines') ->select(DB::raw('MAX(historical_lines.id) as max_historical_id'), 'historical_lines.property_id as historical_property_id') ->groupBy('historical_lines.property_id'); $zones = $realEstate->zones; $properties = []; foreach ($zones as $zone) { //quitamos la zona si es un pais porque sino coje todas las propiedades $queryField = substr(strtolower($zone->zoneable_type), 4) . '_id'; $locations = DB::table('locations') ->joinSub($last_historical, 'last_historical', function ($join) { $join->on('last_historical.historical_property_id', '=', 'locations.locationable_id'); }) ->join('historical_lines', 'historical_lines.id', '=', 'last_historical.max_historical_id') ->where('historical_lines.status_id', '=', 2) ->where('locationable_type', 'App\Properties') ->where($queryField, $zone->zoneable->id) ->get([ 'locationable_id', DB::raw('MONTH(locations.created_at) as mo'), DB::raw('YEAR(locations.created_at) as year')]) ->where('year', Carbon::now()->year) ->toArray(); $properties = array_merge($properties, $locations); } //dd($properties); /* $unique_properties = array(); foreach($properties as $property){ $unique_properties[$property->locationable_id] = $property->created_at; } */ $unique_properties = collect($properties) ->unique('locationable_id') ->groupBy('mo') ->toArray(); /* for($i=0; i<$unique_properties) */ //se formatea el aray para que lo entienda la grafica $result_formatted = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; $i = 0; //se obtiene el numero de propiedades por mes foreach ($unique_properties as $key => $res) { $result_formatted[$key-1] = count($res); } return $result_formatted; } }
true
9b1d90867d400614d766e9eeda6ec05eea57a999
PHP
nenad591/Novine
/classes/Users.php
UTF-8
784
2.90625
3
[]
no_license
<?php class Users{ public function selectAll(){ global $conn; $q = $conn->prepare('SELECT user_id,name, lastName, email, date, status, level FROM users'); $q->execute(); $res = $q->fetchAll(PDO::FETCH_ASSOC); return $res; } public function updateUser($level, $id){ global $conn; $q = $conn->prepare('UPDATE users SET level = :level WHERE user_id = :id'); $user_level = $q->bindParam('level', $level); $user_id = $q->bindParam('id', $id); $q->execute(); return true; } public function showUpdate($id){ global $conn; $q = $conn->prepare('SELECT name, lastName FROM users WHERE user_id = :id'); $user_id = $q->bindParam('id', $id); $q->execute(); $res = $q->fetch(PDO::FETCH_ASSOC); return $res; } } ?>
true
235705faa6681e5520ea799a00ae8e4cd4dc060c
PHP
chapmanu/chap-press
/content/plugins/next-active-directory-integration/classes/Adi/Authentication/Persistence/FailedLoginRepository.php
UTF-8
5,636
2.8125
3
[ "GPL-3.0-only", "MIT" ]
permissive
<?php if (!defined('ABSPATH')) { die('Access denied.'); } if (class_exists('NextADInt_Adi_Authentication_Persistence_FailedLoginRepository')) { return; } /** * NextADInt_Adi_Authentication_Persistence_FailedLoginRepository stores the failed login attempts and the block time of an user. * * @author Tobias Hellmann <the@neos-it.de> * @access public */ class NextADInt_Adi_Authentication_Persistence_FailedLoginRepository { const PREFIX = 'fl_'; const PREFIX_LOGIN_ATTEMPTS = 'la_'; const PREFIX_BLOCKED_TIME = 'bt_'; /* @var Logger */ private $logger; /** */ public function __construct() { $this->logger = NextADInt_Core_Logger::getLogger(); } /** * Generate the WordPress option name from the type and the username. * * @param int $loginAttempts * @param string $username * * @return string */ protected function getOptionName($loginAttempts, $username) { $prefix = $loginAttempts ? self::PREFIX_LOGIN_ATTEMPTS : self::PREFIX_BLOCKED_TIME; return NEXT_AD_INT_PREFIX . self::PREFIX . $prefix . '_' . $this->encodeUsername($username); } /** * Block the user for a number of seconds. * * @param string $username * @param int $seconds * * @return bool */ public function blockUser($username, $seconds) { $blockTime = $this->getCurrentTime() + $seconds; return $this->persistBlockUntil($username, $blockTime); } /** * Is the user blocked? * * @param string $username * * @return bool */ public function isUserBlocked($username) { $blockTime = $this->findBlockUntil($username); $currentTime = $this->getCurrentTime(); return $blockTime >= $currentTime; } /** * Increase the number of failed login attempts for the user. * * @param string $username * * @return bool */ public function increaseLoginAttempts($username) { $loginAttempts = $this->findLoginAttempts($username); return $this->persistLoginAttempts($username, $loginAttempts + 1); } /** * Unblock the user and reset his login attempts counter. * * @param string $username * * @return bool */ public function resetUser($username) { $user = $this->deleteBlockUntil($username); $loginAttempts = $this->deleteLoginAttempts($username); return $user && $loginAttempts; } /** * Get the number of seconds until the user is unblocked * * @param string $username * * @return int|null|string */ public function getSecondsUntilUnblock($username) { $seconds = $this->findBlockUntil($username) - $this->getCurrentTime() + 1; if (0 > $seconds) { return 0; } return $seconds; } /** * This method should not be called by the outside. * Get the login attempts for the user. * * @param string $username * * @return int|null|string */ function findLoginAttempts($username) { $optionName = $this->getOptionName(true, $username); /* This function is almost identical to get_option(), except that in multisite, it returns the network-wide option. For non-multisite installs, it uses get_option. */ return get_site_option($optionName, 0); } /** * This method should not be called by the outside. * Set the number of login attempts for the user. * * @param string $username * @param int $loginAttempts * * @return bool */ function persistLoginAttempts($username, $loginAttempts) { $optionName = $this->getOptionName(true, $username); /* This function is essentially the same as update_option() but works network wide when using WP Multisite. */ return update_site_option($optionName, $loginAttempts); } /** * Delete the login attempts option for $username. * * @param string $username * * @return bool */ function deleteLoginAttempts($username) { $optionName = $this->getOptionName(true, $username); /* Essentially the same as delete_option() but works network wide when using WP Multisite. */ return delete_site_option($optionName); } /** * This method should not be called by the outside. * Get the unix time 'block_until' for the user. * * @param string $username * * @return int|null|string */ function findBlockUntil($username) { $optionName = $this->getOptionName(false, $username); /* This function is almost identical to get_option(), except that in multisite, it returns the network-wide option. For non-multisite installs, it uses get_option. */ return get_site_option($optionName, 0); } /** * This method should not be called by the outside. * Set the unix time 'block_until' for the user. * * @param string $username * @param int $blockUntil * * @return bool */ public function persistBlockUntil($username, $blockUntil) { $optionName = $this->getOptionName(false, $username); /* This function is essentially the same as update_option() but works network wide when using WP Multisite. */ return update_site_option($optionName, $blockUntil); } /** * Delete the 'block time until' value option for $username. * * @param string $username * * @return bool */ function deleteBlockUntil($username) { $optionName = $this->getOptionName(false, $username); /* Essentially the same as delete_option() but works network wide when using WP Multisite. */ return delete_site_option($optionName); } /** * This method should not be called by the outside. * Get the current time. This method is necessary for unit-testing. * * Get current time * * @return int */ public function getCurrentTime() { return time(); } /** * Encodes given Username to SHA1 * * @param $username * @return string */ function encodeUsername($username) { return sha1($username); } }
true
84274d558188af1c7f568c62ff448db94a647fe7
PHP
PauloVitorDB/pagpayment
/src/Model/BoletoModel.php
UTF-8
1,932
2.84375
3
[ "MIT" ]
permissive
<?php namespace PagseguroApi\Model; use JsonSerializable; class BoletoModel implements JsonSerializable { private $due_date; private $line_1 = ""; private $line_2 = ""; private \PagseguroApi\Model\BoletoHolder $holder; /** * Get the value of holder */ public function getHolder() { return $this->holder; } /** * Set the value of holder * * @return self */ public function setHolder($holder) { $this->holder = $holder; return $this; } public function jsonSerialize() { $json = [ "due_date" => $this->due_date, // "instruction_lines" => [ // "line_1" => $this->line_1, // "line_2" => $this->line_2, // ], "holder" => $this->holder ]; return $json; } /** * Get the value of due_date */ public function getDueDate() { return $this->due_date; } /** * Set the value of due_date * * @return self */ public function setDueDate($due_date) { $this->due_date = $due_date; return $this; } /** * Get the value of line_1 */ public function getline1() { return $this->line_1; } /** * Set the value of line_1 * * @return self */ public function setline1($line_1) { $this->line_1 = $line_1; return $this; } /** * Get the value of line_2 */ public function getline2() { return $this->line_2; } /** * Set the value of line_2 * * @return self */ public function setline2($line_2) { $this->line_2 = $line_2; return $this; } }
true
c589430a2606dfcf333328c175b550fc8fa7b3e0
PHP
NibelungQin/Yaf
/library/Log.php
UTF-8
447
2.71875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: marico * Date: 2017/4/20 * Time: 下午4:10 */ class Log { /** * 添加日志 * @param int $type * @param array $data */ public static function debug($type=1, $data=[]) { is_array($data) && $data = json_encode($data); // 存入数据库 DB::name('debug')->insert([ 'type' => $type, 'content' => $data, ]); } }
true
7935b77a817a8eb1d3073c1ed0496eef07221164
PHP
autepos/tax
/src/Exceptions/TaxRateNotFoundException.php
UTF-8
824
2.9375
3
[ "MIT" ]
permissive
<?php namespace Autepos\Tax\Exceptions; use Autepos\Tax\Contracts\TaxableDeviceLine; /** * Tax rate not found exception. */ class TaxRateNotFoundException extends \Exception implements ExceptionInterface { /** * Taxable device line. */ protected TaxableDeviceLine $taxableDeviceLine; /** * Constructor. * * @param \Throwable $previous */ public function __construct(TaxableDeviceLine $taxableDeviceLine, string $message = '', int $code = 0, \Throwable $previous = null) { $this->taxableDeviceLine = $taxableDeviceLine; parent::__construct($message, $code, $previous); } /** * Get the value of taxableDeviceLine */ public function getTaxableDeviceLine(): TaxableDeviceLine { return $this->taxableDeviceLine; } }
true
48befa7586f3de59257118e4b8a22c475efaba8d
PHP
kmchugh/YiiPlinth
/protected/cli/views/webapp/protected/controllers/SiteController.php
UTF-8
697
2.71875
3
[ "MIT" ]
permissive
<?php /** * Class SiteController Default controller for the site */ class SiteController extends Controller { /** * Declares class-based actions. */ public function actions() { return array( // page action renders "static" pages stored under 'protected/views/site/pages' // They can be accessed via: /site/page/view/FileName 'page'=>array( 'class'=>'CViewAction', ), ); } /** * This is the default 'index' action that is invoked * when an action is not explicitly requested by users. */ public function actionIndex() { $this->render('index'); } } ?>
true
63295282e65824fa6ff5423559c3e50cc405ec60
PHP
plfort/CogimixJamendoBundle
/ViewHooks/Playlist/PlaylistRenderer.php
UTF-8
1,864
2.515625
3
[]
no_license
<?php namespace Cogipix\CogimixJamendoBundle\ViewHooks\Playlist; use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Cogipix\CogimixCommonBundle\Utils\SecurityContextAwareInterface; use Cogipix\CogimixCommonBundle\ViewHooks\Playlist\PlaylistRendererInterface; /** * * @author plfort - Cogipix * */ class PlaylistRenderer implements PlaylistRendererInterface,SecurityContextAwareInterface{ private $accessTokenManager; private $jamendoApi; private $securityContext; public function __construct($accessTokenManager,$jamendoApi){ $this->accessTokenManager=$accessTokenManager; $this->jamendoApi= $jamendoApi; } public function getListTemplate(){ return 'CogimixJamendoBundle:Playlist:list.html.twig'; } public function getPlaylists(){ $user=$this->getCurrentUser(); if($user!==null){ $jamendoToken = $this->accessTokenManager->getUserAccessToken($user); if($jamendoToken!==null){ $playlists= $this->jamendoApi->getUserPlaylists($jamendoToken); //var_dump($playlists);die(); if($playlists !==false){ return $playlists; }else{ echo $this->jamendoApi->lastError; } } } return array(); } public function setSecurityContext( SecurityContextInterface $securityContext) { $this->securityContext=$securityContext; } protected function getCurrentUser() { $user = $this->securityContext->getToken()->getUser(); if ($user instanceof AdvancedUserInterface){ return $user; } return null; } public function getTag(){ return 'jamendo'; } }
true
0298c38b53319b6122831f4276857f42aabdf56e
PHP
jamet-julien/framework
/DEV/__APP__/lib/Core/Request/Method/Put.php
UTF-8
815
2.75
3
[]
no_license
<?php namespace Core\Request\Method; use Core\Request\Method\Method as Method, Core\Dispenser\Dispenser as Dispenser; class Put extends Method { /** * [$_sType description] * @var string */ protected $_sType = 'put'; /** * [$_sFile description] * @var [type] */ private $_sFile = null; /** * [$_bEmpty description] * @var boolean */ protected $_bCanBeEmpty = false; /** * [setFile description] * @param [type] $sFile [description] */ public function setFile(){ $this->_sFile = file_get_contents("php://input"); return $this; } /** * [getFile description] * @param [type] $sFile [description] */ public function getFile(){ return $this->_sFile; } }
true
e814066d5da82b97f9e88d24805722c6aa504a04
PHP
napra17/Falak
/reportes/gethoras.php
UTF-8
1,573
2.53125
3
[]
no_license
<?php $fdesde =$_POST["fdesde"]; $fhasta = $_POST["fhasta"]; require ("../conexion.php"); $sql= "SELECT Apellido, Nombre, fecha, f_pago, horas, estado from profesores inner join horas on horas.id_profesor = profesores.id_profesor where fecha between '".$fdesde."' and '".$fhasta."' "; $result = mysqli_query ($con, $sql); $count = mysqli_num_rows($result); if ($count > 0){ header("Pragma: public"); header("Expires: 0"); $filename = "reporte_horas.xls"; header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=$filename"); header("Pragma: no-cache"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); ?> <meta charset="UTF-8"> <table> <thead> <tr> <th>Apellido</th> <th>Nombre</th> <th>Fecha</th> <th>Fecha de Pago</th> <th>Horas</th> <th>Estado</th> </tr> </thead> <tbody> <?php while($row = mysqli_fetch_array($result)){ $apellido = $row["Apellido"]; $nombre = $row["Nombre"]; $fecha = $row["fecha"]; $f_pago = $row["f_pago"]; $horas = $row["horas"]; $estado = $row["estado"]; ?> <tr> <td><?php echo $apellido; ?></td> <td><?php echo $nombre; ?></td> <td><?php echo $fecha; ?></td> <td><?php echo $f_pago; ?></td> <td><?php echo $horas; ?></td> <td><?php echo $estado; ?></td> </tr> <?php } ?> </tbody> </table> <?php } else{ echo '<script language="javascript">alert("No hay horas para el periodo seleccionado");</script>'; echo '<script language="javascript">window.history.back(-1);</script>'; } ?>
true
841d41a37e47fc6a9a7fa8eb993a8f59de1856a4
PHP
xtrem-creative/panda-core
/lib/Panda/Core/Tool/Function/Dir.php
UTF-8
316
2.65625
3
[]
no_license
<?php if (!function_exists('rm_dir')) { function rm_dir($dir) { $files = array_diff(scandir($dir), array('.', '..')); foreach ($files as $file) { (is_dir($dir . '/' . $file)) ? rm_dir($dir . '/' . $file) : unlink($dir . '/' . $file); } return rmdir($dir); } }
true
5c5ff36de410c44370cbfbdcab6feabeef143b72
PHP
omarfawzi/MENA-TASK
/app/Http/Controllers/NewsController.php
UTF-8
1,471
2.640625
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Repositories\NewsRepository; use Illuminate\Http\Request; class NewsController extends Controller { public $news_repo; public function __construct(NewsRepository $news_repository) { $this->news_repo = $news_repository ; } /** * Display a listing of news. * * @return \Illuminate\Http\JsonResponse */ public function index() { // return $this->news_repo->all(); } /** * Store a newly created news in storage. * @return \Illuminate\Http\JsonResponse */ public function store(Request $request) { // return $this->news_repo->save($request); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\JsonResponse */ public function show($id) { // return $this->news_repo->show($id); } /** * Update the specified news in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\JsonResponse */ public function update(Request $request, $id) { // return $this->news_repo->update($request,$id); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\JsonResponse */ public function destroy($id) { // return $this->news_repo->delete($id); } }
true
e798b027c490ec14ab6f120ea3e9e3a7f18c3dff
PHP
superelebe/reposi_cne
/database/migrations/2017_03_28_194629_create_capacitacions_table.php
UTF-8
844
2.53125
3
[]
no_license
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCapacitacionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('capacitaciones', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->date('start'); $table->date('end'); $table->string('url'); $table->string('color')->default('#A1BA77'); $table->string('pdf'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('capacitaciones'); } }
true
4c71c7111ddbd7741c7bba876a3fcdb520af0105
PHP
phpenthusiast/object-oriented-php-tutorials
/chapters/chapter_0020/snippet_0005.php
UTF-8
355
2.9375
3
[]
no_license
<?php class View { private $controller; // Set the controller so we can use it public function __construct(Controller $controller) { $this->controller = $controller; } // Output the data after processing it by the controller public function output() { return $this->controller->expensiveOrNot(); } }
true
7e2b6f1beb464b8cf8b6d540592056705687e2f5
PHP
DamianSowinski/tauron-api
/src/Model/AllUsage.php
UTF-8
717
3.21875
3
[ "MIT" ]
permissive
<?php namespace App\Model; class AllUsage { private ZoneUsage $consume; private ZoneUsage $generate; /** * @var YearUsage[] */ private array $years; /** * @param YearUsage[] $years */ public function __construct(ZoneUsage $consume, ZoneUsage $generate, array $years) { $this->consume = $consume; $this->generate = $generate; $this->years = $years; } public function getConsume(): ZoneUsage { return $this->consume; } public function getGenerate(): ZoneUsage { return $this->generate; } /** * @return YearUsage[] */ public function getYears(): array { return $this->years; } }
true
aea3690341ea0f46f0ddddf7ad7e1be12f95212b
PHP
saiury92/osc
/2306/system/MY_Model.php
UTF-8
2,810
2.84375
3
[]
no_license
<?php /** * Class name * Author: * Date: */ class MY_Model extends Database { protected $_select = "*"; protected $_where; protected $_order; protected $_limit; public function __construct() { parent::__construct(); } /* public function setSelect($column = "*") { $this->_select = $column; } public function getSelect() { return $this->_select; } public function setWhere($where = "") { if($where == "") { return false; } $this->_where = "WHERE $where "; } public function getWhere() { return $this->_where; } public function setOrder($column = "",$type = "ASC") { if($column == "") { return false; } $this->_order = "ORDER BY $column $type"; } public function getOrder() { return $this->_order; } public function setLimit($limit="",$start="") { if($start == "" && $limit != "") { $this->_limit = "LIMIT $limit"; }else if($start != "" && $limit != ""){ $this->_limit = "LIMIT $start,$limit"; }else{ return false; } } public function getLimit() { return $this->_limit; } public function getAll($table = "") { if($table == "") { return false; } $sql = "SELECT {$this->getSelect()} FROM $table {$this->getWhere()} {$this->getOrder()} {$this->getLimit()} "; $this->query($sql); return $this->fetchAll(); } public function insert($data = array(),$table = "") { if($data == null || $table == "" ) { return false; } $columsArr = array_keys($data); $valuesArr = array_values($data); foreach($valuesArr as $key=>$val) { $valuesArr[$key] = "'".$val."'"; } $colums = implode(",",$columsArr); $values = implode(",",$valuesArr); $sql = "INSERT INTO $table($colums) VALUES($values)"; $this->query($sql); } public function update($data = array(),$table = "") { if($data == null || $table == "" ) { return false; } foreach($data as $key=>$val) { $dataUpdate[] = "$key='".$val."'"; } $stringSet = implode(',',$dataUpdate); $sql = "UPDATE $table SET $stringSet {$this->getWhere()}"; $this->query($sql); } public function delete($table = "") { if($table == "") { return false; } $sql = "DELETE FROM $table {$this->getWhere()}"; $this->query($sql); } */ }
true
4a585fed814a2f101fd3974a56a50e32ddac4d61
PHP
aaronnoblej/its-website
/admin/db/requestorinfo.php
UTF-8
3,991
3.203125
3
[]
no_license
<?php class requestorInfo { //------------------------------------------------------ // INSTANCE VARIABLES //------------------------------------------------------ private $workOrder = 0; private $email = NULL; private $requestor_type = NULL; private $phone_number = NULL; private $office_extension = NULL; private $preferred_contact = NULL; private $issue_location = NULL; private $computer_no = NULL; private $issue_duration = NULL; private $phone_software = NULL; private $computer_software = NULL; private $last_restart = NULL; private $ip_address = NULL; private $mac_address = NULL; private $uniprint_issue = NULL; //------------------------------------------------------ // CONSTRUCTOR //------------------------------------------------------ function __construct() { if(func_num_args() === 15) { call_user_func_array(array($this, 'create'), func_get_args()); } } //------------------------------------------------------ // METHODS //------------------------------------------------------ function create($wo, $email, $type, $phone, $office, $location, $comp_no, $duration, $phone_os, $comp_os, $last_restart, $ip, $mac, $preferred_contact, $uniprint_issue) { $this->workOrder = $wo; $this->email = $email; $this->requestor_type = $type; $this->phone_number = $phone; $this->office_extension = $office; $this->issue_location = $location; $this->computer_no = $comp_no; $this->issue_duration = $duration; $this->phone_software = $phone_os; $this->computer_software = $comp_os; $this->last_restart = $last_restart; $this->ip_address = $ip; $this->mac_address = $mac; $this->preferred_contact = $preferred_contact; $this->uniprint_issue = $uniprint_issue; } function save() { require_once('database.php'); $db = new database(); try { $db->connect(); $sql = 'INSERT INTO RequestorInfo (WorkOrder, Email, RequestorType, PhoneNumber, OfficeExtension, IssueLocation, ComputerNumber, IssueDuration, PhoneSoftware, ComputerSoftware, LastRestart, IpAddress, MacAddress, PreferredContact, PrintIssue) VALUES (:workOrder, :email, :requestor_type, :phone_number, :office_extension, :issue_location, :computer_no, :issue_duration, :phone_software, :computer_software, :last_restart, :ip_address, :mac_address, :preferred_contact, :uniprint_issue)'; $ps = $db->getConnection()->prepare($sql); $ps->bindParam(':workOrder', $this->workOrder); $ps->bindParam(':email', $this->email); $ps->bindParam(':requestor_type', $this->requestor_type); $ps->bindParam(':phone_number', $this->phone_number); $ps->bindParam(':office_extension', $this->office_extension); $ps->bindParam(':issue_location', $this->issue_location); $ps->bindParam(':computer_no', $this->computer_no); $ps->bindParam(':issue_duration', $this->issue_duration); $ps->bindParam(':phone_software', $this->phone_software); $ps->bindParam(':computer_software', $this->computer_software); $ps->bindParam(':last_restart', $this->last_restart); $ps->bindParam(':ip_address', $this->ip_address); $ps->bindParam(':mac_address', $this->mac_address); $ps->bindParam(':preferred_contact', $this->preferred_contact); $ps->bindParam(':uniprint_issue', $this->uniprint_issue); if($ps->execute()) { return true; } else { die('Connection Error --- ' . $ps->errorInfo()[2]); return false; } $db->disconnect(); } catch(PDOException $e) { die('Connection Error --- ' . $e->getMessage()); } } } ?>
true
13708e6b7350be10cc243d80ca231c6d85fb1c01
PHP
pazoler/PHP-rep
/lesson2 - циклы/cycle.php
UTF-8
2,385
3.390625
3
[]
no_license
<?php echo ' логические операторы', " && - and, || or, ! - not, xor - искл или"; $bool = false || true; var_dump($bool); $bool = false or true; var_dump($bool); //оператор xor $a = 45; $b = 45; var_dump($a==45 xor $b==45); var_dump($a==45 xor $b==79); //Тернарный оператор $a = 23; $b = 45; $c = 12; //проверить находится ли с в диапахоне между a b. Информацию $res = $c > $a && $c < $b ? "c in the diapazone $a $b" : "c not in diapazone $a $b"; $login; $login = isset($login) ? $login : 'Гость'; //начиная с php 7 эквивалентно работе объединения с null $login = $login ?? 'Гость'; var_dump($login); //сокращенная запись тернарного оператора $data = 0; $res = $data ?: "Значение data = $data"; var_dump($res); //if ifelse else $num = 2000; if ($num > 500 && $num < 800) { $sum = $num - $num*0.05; var_dump($sum); } else if ($num > 800 && $num < 1000) { $sum = $num - $num*0.10; var_dump($sum); } else if ($num > 1000 && $num < 1300) { $sum = $num - $num*0.10; var_dump("$sum + подарок"); } else if ($num > 1300) { $sum = $num - $num*0.15; var_dump($sum); } else { var_dump($num); }; // $num ='№29' // switch ($num) { // case '№29': // var_dump("протяженность маршрута $num - 12 "); // break; // case '№34': // var_dump("протяженность маршрута $num - 6 "); // break; // case '№2': // var_dump("протяженность маршрута трамвая $num - 18 "); // break; // case '№26': // var_dump("протяженность маршрута трамвая $num - 12 "); // break; // case '№31': // var_dump("протяженность маршрута троллейбус $num - 17 "); // break; // default: // var_dump("введите корректный номер маршрута"); // }; // for($i=0; $i<3; $i++) { // while (true) { // $res= rand(0, 99); // var_dump($res); // if ($res > 90) break; // }; // }; // while(условие): // тело цикла; // endwhile; // for (инициализация; условие; обноввление счетчика): // тело цикла; // endfor; echo "массивы"; ?>
true
c56baf54df55e943a3427f6005d964023c18761b
PHP
ehiaig/vesi-landing
/app/Http/Controllers/Auth/RegisterController.php
UTF-8
6,580
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Auth; use App\Models\User; use App\Models\Personal; use App\Models\Business; use Illuminate\Http\Request; use App\Models\VerifyUser; use App\Mail\verifyEmail; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Validator; use Illuminate\Foundation\Auth\RegistersUsers; use Illuminate\Support\Facades\Mail; class RegisterController extends Controller { /* |-------------------------------------------------------------------------- | Register Controller |-------------------------------------------------------------------------- | | This controller handles the registration of new users as well as their | validation and creation. By default this controller uses a trait to | provide this functionality without requiring any additional code. | */ use RegistersUsers; protected function registered(Request $request, $user) { $this->guard()->logout(); return redirect('/login')->with('status', 'You will get an activation code in few minutes. Check your email inbox or spam folder and click the button to activate your account.'); } /** * Where to redirect users after registration. * * @var string */ protected $redirectTo = '/dashboard'; /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest'); } //Call personal Registration Form public function showRegisterPersonal() { return view('auth.personal'); } //Create a new user instance of personal. public function registerPersonal(Request $request) { $validator = Validator::make($request->input(), [ 'firstname' => 'required|string|max:255', 'lastname' => 'required|string|max:255', 'phone'=>'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $userData = [ 'firstname' => $request->input('firstname'), 'lastname' => $request->input('lastname'), 'phone' => $request->input('phone'), 'email' => $request->input('email'), 'password' => $request->input('password'), 'user_type' => 'personal', 'account_balance' => 0.00, ]; $user = $this->create($userData); if($user){ $personal = new Personal(); $personal->user_id = $user->id; $personal->save(); } $verifyUser = VerifyUser::create([ 'user_id' => $user->id, 'token' => str_random(40) ]); \Mail::to($user->email)->send(new verifyEmail($user)); return view('auth/login'); } //Call the business registration form. public function showRegisterBusiness() { return view('auth.business'); } //Create a new user instance of business. public function registerBusiness(Request $request) { $validator = Validator::make($request->input(), [ 'firstname' => 'required|string|max:255', 'lastname' => 'required|string|max:255', 'phone'=>'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:6|confirmed', ]); if ($validator->fails()) { return redirect()->back()->withErrors($validator)->withInput(); } $userData = [ 'firstname' => $request->input('firstname'), 'lastname' => $request->input('lastname'), 'phone' => $request->input('phone'), 'email' => $request->input('email'), 'password' => $request->input('password'), 'user_type' => 'business', 'account_balance' => 0.00, ]; $user = $this->create($userData); if($user){ $business = new Business(); $business->business_name = $request->input('business_name'); $business->access_token = str_random(20); $business->user_id = $user->id; $business->save(); } $verifyUser = VerifyUser::create([ 'user_id' => $user->id, 'token' => sha1(time()) ]); \Mail::to($user->email)->send(new verifyEmail($user)); return view('auth/login')->with('success', 'Welcome to Vesicash!'); } public function verifyUser($token) { $verifyUser = VerifyUser::where('token', $token)->first(); if(isset($verifyUser) ){ $user = $verifyUser->user; if(!$user->verified) { $verifyUser->user->verified = 1; $verifyUser->user->save(); $status = "Your e-mail is verified. You can now login."; }else{ $status = "Your e-mail is already verified. You can now login."; } }else{ return redirect('/login')->with('warning', "Sorry your email cannot be identified. Click the link below to create an account"); } return redirect('/login')->with('status', $status); } /** * Get a validator for an incoming registration request. * * @param array $data * @return \Illuminate\Contracts\Validation\Validator */ // protected function validator(array $data) // { // return Validator::make($data, [ // 'firstname' => 'required|string|max:255', // 'lastname' => 'required|string|max:255', // 'phone'=>'required|string|max:255', // 'email' => 'required|string|email|max:255|unique:users', // 'password' => 'required|string|min:8|confirmed', // ]); // } /** * Create a new user instance after a valid registration. * * @param array $data * @return \App\User */ protected function create(array $data) { return User::create([ 'firstname' => $data['firstname'], 'lastname' => $data['lastname'], 'phone' => $data['phone'], 'email' => $data['email'], 'password' => Hash::make($data['password']), 'user_type' => $data['user_type'], 'account_balance' => $data['account_balance'], ]); } }
true
7c9b164d7e0206d0120af1b7a5d0af7099c4cf06
PHP
ampleeve/yii2.com
/basic/models/Test.php
UTF-8
944
2.75
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use yii\base\Model; class Test extends Model{ public $title; public $content; public $date; const EVENT_TEST = 'test'; public function attributeLabels(){ return [ 'title' => 'заголовок', 'content' => 'контент', 'description' => 'описание', ]; } //public function save(){ // набросок по сохранению файла из формы (пытались в конце 7 урока предпоследним кейсом после алиасов) // $this->content->save //} public function rules(){ return [ [['title', 'content', 'date'], 'required'], [['content'], 'file', 'extensions' => 'png, jpg'] ]; } public function getData(){ $this->trigger(self::EVENT_TEST); return "123"; } }
true
b30e7a21fce807df774e8457bb12c4550fdeb254
PHP
mikailmiko/ares-habbo-backend
/src/Rcon/Helper/RconHelper.php
UTF-8
3,096
2.90625
3
[ "MIT" ]
permissive
<?php /** * @copyright Copyright (c) Ares (https://www.ares.to) * * @see LICENSE (MIT) */ namespace Ares\Rcon\Helper; use Ares\Rcon\Exception\RconException; use Ares\Rcon\Interfaces\Response\RconResponseCodeInterface; use PHLAK\Config\Config; /** * Class RconHelper * * @package Ares\Rcon\Helper */ class RconHelper { /** * RconHelper constructor. * * @param Config $config */ public function __construct( private Config $config ) {} /** * @param resource $socket * @param string $command * @param array|null $parameter * * @return array|null * @throws RconException * @throws \JsonException */ public function sendCommand($socket, string $command, array $parameter = null): ?array { /** @var string $encodedData */ $encodedData = json_encode([ 'key' => $command, 'data' => $parameter ], JSON_THROW_ON_ERROR); $executor = @socket_write($socket, $encodedData, strlen($encodedData)); if (!$executor) { throw new RconException( __('Could not send the provided Command'), RconResponseCodeInterface::RESPONSE_RCON_COULD_NOT_SEND_COMMAND ); } return json_decode( @socket_read($socket, 2048), true, 512, JSON_THROW_ON_ERROR ); } /** * Builds the Socket connection * * @param resource $socket * * @return RconHelper * @throws RconException */ public function buildConnection($socket): self { /** @var string $host */ $host = $this->config->get('hotel_settings.client.rcon_host'); /** @var int $port */ $port = $this->config->get('hotel_settings.client.rcon_port'); $isConnectionEstablished = $this->connectToSocket($socket, $host, $port); if (!$isConnectionEstablished) { throw new RconException( __('Could not establish a connection to the rcon server'), RconResponseCodeInterface::RESPONSE_RCON_NO_CONNECTION ); } return $this; } /** * Connects to our Socket * * @param $socket * @param $host * @param $port * * @return bool */ public function connectToSocket($socket, $host, $port): bool { return @socket_connect($socket, $host, $port); } /** * Creates a Socket * * @return \Socket * @throws RconException */ public function createSocket(): \Socket { $socket = @socket_create( AF_INET, SOCK_STREAM, SOL_TCP ); if (!$socket) { throw new RconException( __('Could not create the socket'), RconResponseCodeInterface::RESPONSE_RCON_COULD_NOT_CREATE_SOCKET ); } return $socket; } }
true
d9f471929ac0dab72de4b38d77b2e6cc347df5d4
PHP
youweiqi/ymjs
/common/models/SpecificationDetail.php
UTF-8
1,154
2.53125
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use Yii; /** * This is the model class for table "specification_detail". * * @property integer $id * @property integer $specification_id * @property string $detail_name * @property integer $order_no */ class SpecificationDetail extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'yg_goods.specification_detail'; } /** * @return \yii\db\Connection the database connection used by this AR class. */ public static function getDb() { return Yii::$app->get('db_goods'); } /** * @inheritdoc */ public function rules() { return [ [['specification_id', 'order_no'], 'integer'], [['order_no'], 'required'], [['detail_name'], 'string', 'max' => 50], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'specification_id' => '规格id', 'detail_name' => '规格详情名称', 'order_no' => '排序', ]; } }
true
79d268d0ae1e57fff00902d4edca11b49472a9cf
PHP
zefredz/claroline-packages
/modules/COMPILAT/lib/compilatio.class.php
ISO-8859-1
12,768
2.921875
3
[]
no_license
<?php /** * Description : * tablit la communication avec le serveur SOAP de Compilatio.net * appelle diverses mthodes concernant la gestion d'un document dans Compilatio.net * * Date: 31/03/09 * @version:0.9 * */ class compilatio { /* Clef d'identification pour le compte Compilatio*/ var $key = null; /*Connexion au Webservice*/ var $soapcli; /*Constructeur -> cre la connexion avec le webservice*/ //MODIF 2009-03-19: passage des paramtres //MODIF 2009-04-08: si le client soap ne peut pas etre cr // alors l'erreur survenue est sauvegarde dans soapcli // les fonctions appellant call sur cet object testent s'il s'agit bien d'un object // renvoyent donc l'erreur sauvegarde dans soapcli sinon function compilatio($key,$urlsoap,$proxy_host,$proxy_port) { try { if(!empty($key)) { $this->key = $key; if(!empty($urlsoap)) { if(!empty($proxy_host)) { $param=array('trace'=>false, 'soap_version'=> SOAP_1_2, 'exceptions'=>true, 'proxy_host'=> '"' . $proxy_host . '"', 'proxy_port'=> $proxy_port); } else { $param=array('trace'=>false, 'soap_version'=>SOAP_1_2, 'exceptions'=>true); } $this->soapcli = new SoapClient($urlsoap,$param); } else { $this->soapcli = 'WS urlsoap not available' ; } } else { $this->soapcli ='API key not available'; } } catch (SoapFault $fault) { $this->soapcli = "Error constructor compilatio " . $fault->faultcode ." " .$fault->faultstring ; } catch (Exception $e) { $this->soapcli = "Error constructor compilatio with urlsoap" . $urlsoap; } } /*Mthode qui permet le chargement de fichiers sur le compte compilatio*/ function SendDoc($title,$description,$filename,$mimetype,$content) { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $idDocument = $this->soapcli->__call('addDocumentBase64',array($this->key ,utf8_encode(urlencode($title)) ,utf8_encode(urlencode($description)) ,utf8_encode(urlencode($filename)) ,utf8_encode($mimetype) ,base64_encode($content))); return $idDocument; } catch (SoapFault $fault) { return("Erreur SendDoc()" . $fault->faultcode ." " .$fault->faultstring); } } /*Mthode qui rcupre les informations d'un document donn*/ function GetDoc($compi_hash) { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $param=array($this->key,$compi_hash); $idDocument = $this->soapcli->__call('getDocument',$param); return $idDocument; } catch (SoapFault $fault) { return("Erreur GetDoc()" . $fault->faultcode ." " .$fault->faultstring); } } /*Mthode qui permet de rcupr l'url du rapport d'un document donn*/ function GetReportUrl($compi_hash) { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $param=array($this->key,$compi_hash); $idDocument = $this->soapcli->__call('getDocumentReportUrl',$param); return $idDocument; } catch (SoapFault $fault) { return("Erreur GetReportUrl()" . $fault->faultcode ." " .$fault->faultstring); } } /*Mthode qui permet de supprim sur le compte compilatio un document donn*/ function DelDoc($compi_hash) { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $param=array($this->key,$compi_hash); $this->soapcli->__call('deleteDocument',$param); } catch (SoapFault $fault) { return("Erreur DelDoc()" . $fault->faultcode ." " .$fault->faultstring); } } /*Mthode qui permet de lancer l'analyse d'un document donn*/ function StartAnalyse($compi_hash) { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $param=array($this->key,$compi_hash); $this->soapcli->__call('startDocumentAnalyse',$param); } catch (SoapFault $fault) { return("Erreur StartAnalyse()" . $fault->faultcode ." " .$fault->faultstring); } } /*Mthode qui permet de rcupr les quotas du compte compilatio*/ function GetQuotas() { try { if (!is_object($this->soapcli)) { return("Error in constructor compilatio() " . $this->soapcli); } $param=array($this->key); $resultat=$this->soapcli->__call('getAccountQuotas',$param); return $resultat; } catch (SoapFault $fault) { return("Erreur GetQuotas()" . $fault->faultcode ." " .$fault->faultstring); } } } /** * Fonction qui extrait l'extension d'un fichier et dit si elle est gre par Compilatio * return true si l'extension est supporte, false sinon * 2009-03-18*/ function veriffiletype($nomFichier) { $types = array("doc","docx","rtf","xls","xlsx","ppt","pptx","odt","pdf","txt","htm","html"); $extension=substr($nomFichier, strrpos($nomFichier, ".")+1); $extension=strtolower($extension); return in_array($extension, $types); } /** * Fonction affichage de la barre de progression d'analyse version 3.1 * * @param $statut du document * @param $pour * @param $chemin_images * @param $texte : array contenant les morceaux de texte ncessaires * @return unknown_type */ function getProgressionAnalyseDocv31($status,$pour=0,$chemin_images='',$texte='') { $refreshretour = "<a href=\"javascript:window.location.reload(false);\"><img src=\"".$chemin_images."refresh.gif\" title=\"" . $texte['refresh'] . "\" alt=\"" . $texte['refresh'] . "\"/></a>"; $debutretour="<table cellpadding=\"0\" cellspacing=\"0\" style=\"border:0px;margin:0px;padding:0px;\"><tr>"; $debutretour.="<td width=\"15\" style=\"border:0px;margin:0px;padding:0px;\">&nbsp;</td>"; $debutretour.="<td width=\"25\" valign=\"middle\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">$refreshretour</td>"; $debutretour.= "<td width=\"55\" style=\"border:0px;margin:0px;padding:0px;\">"; $debutretour2="<table cellpadding=\"0\" cellspacing=\"0\" style=\"border:0px;margin:0px;padding:0px;\"><tr>"; $debutretour2.="<td width=\"15\" valign=\"middle\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">$refreshretour </td>"; $finretour="</td></tr></table>"; if($status=="ANALYSE_IN_QUEUE" ) { return $debutretour . "<span style='font-size:11px'>".$texte['analysisinqueue']."</span>".$finretour; } if($status=="ANALYSE_PROCESSING" ) { if($pour==100) { return $debutretour."<span style='font-size:11px'>".$texte['analysisinfinalization']."</span>".$finretour; } else { return $debutretour2."<td width=\"25\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">$pour%</td><td width=\"55\" style=\"border:0px;margin:0px;padding:0px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_fond.png) no-repeat scroll 0;height:12px;padding:0 0 0 2px;width:55px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_gris.png) no-repeat scroll 0;height:12px;width:" . $pour/2 . "px;\"></div></div>".$finretour; } } } /** * Fonction d'affichage de la PomprankBar (% de plagiat) version 3.1 * @param $pourcentagePompage * @param $seuil_faible * @param $seuil_eleve * @param $chemin_images * @param $texte : array contenant les morceaux de texte ncessaires * @return unknown_type */ function getPomprankBarv31($pourcentagePompage, $seuil_faible, $seuil_eleve, $chemin_images='',$texte='') { $pourcentagePompage = round($pourcentagePompage); $pour = round((50*$pourcentagePompage)/100); $retour="<table cellpadding=\"0\" cellspacing=\"0\"><tr>"; if($pourcentagePompage<$seuil_faible) { $retour.="<td width=\"15\" style=\"border:0px;margin:0px;padding:0px;\"><img src=\"".$chemin_images."mini-drapeau_vert.png\" title=\"" . $texte['result'] . "\" alt=\"faible\" width=\"15\" height=\"15\" /></td>"; $retour.="<td width=\"25\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">" . $pourcentagePompage . "%</td>"; $retour.= "<td width=\"55\" style=\"border:0px;margin:0px;padding:0px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_fond.png) no-repeat scroll 0;height:12px;padding:0 0 0 2px;width:55px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_vert.png) no-repeat scroll 0;height:12px;width:" . $pour . "px\"></div></div></td>"; } else if($pourcentagePompage>=$seuil_faible && $pourcentagePompage<$seuil_eleve) { $retour.="<td width=\"15\" style=\"border:0px;margin:0px;padding:0px;\"><img src=\"".$chemin_images."mini-drapeau_orange.png\" title=\"" . $texte['result'] . "\" alt=\"faible\" width=\"15\" height=\"15\" /></td>"; $retour.="<td width=\"25\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">" . $pourcentagePompage . "%</td>"; $retour.= "<td width=\"55\" style=\"border:0px;margin:0px;padding:0px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_fond.png) no-repeat scroll 0;height:12px;padding:0 0 0 2px;width:55px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_orange.png) no-repeat scroll 0;height:12px;width:" . $pour . "px\"></div></div></td>"; } else { $retour.="<td width=\"15\" style=\"border:0px;margin:0px;padding:0px;\"><img src=\"".$chemin_images."mini-drapeau_rouge.png\" title=\"" . $texte['result'] . "\" alt=\"faible\" width=\"15\" height=\"15\" /></td>"; $retour.="<td width=\"25\" align=\"right\" style=\"border:0px;margin:0px;padding:0px;\">" . $pourcentagePompage . "%</td>"; $retour.= "<td width=\"55\" style=\"border:0px;margin:0px;padding:0px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_fond.png) no-repeat scroll 0;height:12px;padding:0 0 0 2px;width:55px;\"><div style=\"background:transparent url(".$chemin_images."mini-jauge_rouge.png) no-repeat scroll 0;height:12px;width:" . $pour . "px\"></div></div></td>"; } $retour.="</tr></table>"; return $retour; } function is_md5($hash) { return preg_match('`^[a-f0-9]{32}$`',$hash); } function typeMime($nomFichier) { if(preg_match("@Opera(/| )([0-9].[0-9]{1,2})@", $_SERVER['HTTP_USER_AGENT'], $resultats)) { $navigateur="Opera"; } elseif(preg_match("@MSIE ([0-9].[0-9]{1,2})@", $_SERVER['HTTP_USER_AGENT'], $resultats)) { $navigateur="Internet Explorer"; } else { $navigateur="Mozilla"; } $mime=parse_ini_file("mime.ini"); $extension=substr($nomFichier, strrpos($nomFichier, ".")+1); if(array_key_exists($extension, $mime)) { $type=$mime[$extension]; } else { $type=($navigateur!="Mozilla") ? 'application/octetstream' : 'application/octet-stream'; } return $type; }
true
a1a9c7b44180450cdcf683425f9f3e0a0bdd7ebe
PHP
dpopovska/api-currency-converter
/app/Repositories/User/UserRepository.php
UTF-8
1,462
2.84375
3
[]
no_license
<?php namespace App\Repositories\User; use App\Models\User; use Carbon\Carbon; class UserRepository implements UserRepositoryContract { /** * @var User */ private $user; /** * UserRepository constructor. * @param User $user */ public function __construct(User $user) { $this->user = $user; } /** * @param $user */ public function updateLastLoginAt($user): void { $user->last_login_at = Carbon::now()->toDateTimeString(); $user->save(); } /** * @param array $userData */ public function create(array $userData): void { /** @var User $user */ $user = new User($userData); $user->save(); } /** * @param $idUser * @param array $updatedData * @throws \Illuminate\Database\Eloquent\ModelNotFoundException * @throws \Illuminate\Database\Eloquent\MassAssignmentException */ public function update($idUser, array $updatedData): void { /** @var User $user */ $user = $this->user->newQuery()->findOrFail($idUser); $user->fill($updatedData); $user->save(); } /** * @param $idUser * @return int */ public function delete($idUser): int { return $this->user->where('id', $idUser)->delete(); } public function findOrFail($idUser) { return $this->user->newQuery()->findOrFail($idUser); } }
true
c27a67d4c7c118159f09da4655660c7f7e36ef7f
PHP
NeidraServices/GAO-Laravel-Vuejs
/database/seeders/AttributionSeeder.php
UTF-8
946
2.828125
3
[]
no_license
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class AttributionSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $array = []; $today = mktime(0, 0, 0, date("m"), date("d"), date("Y")); $tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y")); for ($i = 1; $i < 10; $i++) { $array[] = $this->attribution($i, $i, $today); $array[] = $this->attribution(9 + $i, $i, $tomorrow); } DB::table('attribution')->insert( $array ); } private function attribution($id, $i, $date) { return [ "id" => $id, "id_client" => ($id % 6) + 1, "id_ordinateur" => ($id % 5) + 1, "horaire" => 8 + $i, "date" => date('Y-m-d', $date) ]; } }
true
30cc06b3def371a4584b21192c489e877fd7e19a
PHP
DiegooNogueira/prjBiblioteca
/Livro.php
UTF-8
3,817
3.28125
3
[]
no_license
<?php class Livro{ private $titulo; private $categoria; private $quantidade; private $con; public function __construct(){ } public function conectar(){ $this->con=mysqli_connect("localhost","root","","biblioteca"); if(!$this->con){ //caso ocorra um erro, exiba uma mensagem com o erro die("Problemas com a conexão"); } } public function desconectar(){ $this->con->close(); } public function verificar($titulo, $categoria, $quantidade){ if (!empty($titulo) && !empty($categoria) && is_numeric($quantidade)) { return true; } else return false; } public function cadastrar($titulo, $categoria,$quantidade){ $resp=$this->verificar($titulo, $categoria, $quantidade); if ($resp==true) { $this->conectar(); $stm=$this->con->prepare("insert into livro values(null, ?, ?, ?)"); $stm->bind_param("ssi", $titulo, $categoria, $quantidade); $resp = $stm->execute(); $stm->close(); $this->desconectar(); } return $resp; } public function exibeDados(){ $retorno = "<h2>Não há livros cadastrados!</h2>"; $this->conectar(); $sql = "select * from livro"; $dados = $this->con->query($sql); if ($dados->num_rows > 0) { $tabela = '<table class="table"> <tr> <thead class="thead-dark"> <th scope="col">Título</th> <th scope="col">Categoria</th> <th scope="col">Quantidade</th> </thead> </tr>'; while ($livro = $dados->fetch_object()) { $tabela .="<tr> <td>$livro->titulo</td> <td>$livro->categoria</td> <td>$livro->quantidade</td> </tr>"; } $tabela .="</table>"; $dados->close(); $retorno = $tabela; } $this->desconectar(); return $retorno; } public function consulta($consulta){ $this->conectar(); $sql = "select * from livro where titulo like '%$consulta%' order by titulo;"; $dados = $this->con->query($sql); if ($dados->num_rows > 0) { $tabela = '<table class="table"> <tr> <thead class="thead-dark"> <th scope="col">Codigo</th> <th scope="col">Titulo</th> <th scope="col">Categria</th> <th scope="col">Quantidade</th> <th>Alterar</th> <th>Excluir</th> </thead> </tr>'; while ($livro = $dados->fetch_object()) { $tabela .="<tr> <td>$livro->idLivro</td> <td>$livro->titulo</td> <td>$livro->categoria</td> <td>$livro->quantidade</td> <td><a href='alterar.php?idLivro=$livro->idLivro'>Alterar</a></td> <td><a href='excluir.php?idLivro=$livro->idLivro'>Excluir</a></td> </tr>"; } $tabela .="</table>"; $dados->close(); $retorno = $tabela; }else{ $retorno = "Não há Livros com esse nome"; } $this->desconectar(); return $retorno; } function recuperaDados($codigo){ $this->conectar(); $resp=$this->con->query("select * from livro where idLivro = $codigo"); $dados = mysqli_fetch_assoc($resp); return $dados; } public function alterar($codigo, $titulo, $categoria, $quantidade){ $this->conectar(); $stm=$this->con->prepare("update livro set titulo = ?, categoria=?, quantidade=? where idLivro = $codigo"); $stm->bind_param("ssi", $titulo, $categoria, $quantidade); $resp = $stm->execute(); $stm->close(); $this->desconectar(); return $resp; } public function excluir($codigo, $titulo, $categoria, $quantidade){ $this->conectar(); $stm=$this->con->prepare("delete from livro where idLivro = $codigo"); $stm->bind_param("ssi", $titulo, $categoria, $quantidade); $resp = $stm->execute(); $stm->close(); $this->desconectar(); return $resp; } } ?>
true
d231883e6b0a0f9946a646456fc036100dae100e
PHP
OzorMox/Predikta
/addhofentry.php
UTF-8
1,201
2.765625
3
[]
no_license
<?php //create session session_start(); //connect to the database include("connect.php"); if (isset($_SESSION['username'])) { $entry = mysqli_real_escape_string($connection, $_POST["entry"]); $awardedto = $_POST['awardedto']; //TODO: this should come from a drop down list of players $awardedby = $_SESSION['username']; $datetime = date("Y/m/d H:i:s"); if ($entry != "" && $awardedto != "") { $playerexists = mysqli_query($connection, "SELECT * FROM players WHERE name = '" . $awardedto . "'"); if (mysqli_num_rows($playerexists) != 0) { mysqli_query($connection, "INSERT INTO halloffame (entry, awardedto, awardedby, datetime) VALUES ('" . strip_tags($entry) . "', '" . strip_tags($awardedto) . "', '" . $awardedby . "', '" . $datetime . "')"); include("log.php"); $action = "Added Hall Of Fame entry"; writelog($action); header('Location: halloffame.php'); } else { header('Location: error.php?error=Player+does+not+exist'); } } else { header('Location: halloffame.php'); } } else { header('Location: error.php?error=Session+expired'); } ?>
true
34face88262085a0e7d3a21278a1b184f554e386
PHP
rafaelMcosta/rafaelMcosta-curso_php7_avancado-2
/arrays/exemplo-01.php
UTF-8
122
3.203125
3
[]
no_license
<?php $frutas = array("laranja", "abacaxi", "melancia"); //array com uma só dimensão é um vetor print_r($frutas); ?>
true
5a38ad7bf5b199df6504a1e1353e68f65a8ce4b8
PHP
wangyv/web_git
/CI/application/controllers/Welcome.php
UTF-8
2,985
2.5625
3
[]
no_license
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Welcome extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->load->view('welcome_message'); } public function index1() { $this->load->view('index'); } public function register() { $this->load->view('register'); } public function login() { $this->load->view('login'); } public function success() { $this->load->view('success'); } public function save_user() { $username = $this -> input -> post('username'); $pwd = $this -> input -> post('pwd'); $realname = $this -> input -> post('realname'); $tel = $this -> input -> post('tel'); $this -> load -> model('user_model'); $row = $this -> user_model -> save($username,$pwd,$realname,$tel); // echo "用户名:$username ,真实姓名:$realname ,联系方式:$tel"; if($row > 0){ redirect('welcome/success'); }else{ echo 'insert failed'; } } public function check_login() { $username = $this -> input -> post('username'); $pwd = $this -> input -> post('pwd'); $this -> load -> model('user_model'); $user = $this -> user_model ->find_by_name($username,$pwd); if($user){ $this -> session -> set_userdata('login_name', $username); redirect('welcome/index1'); }else{ echo '不存在此用户'; } } public function query_all(){ $this -> load -> model('user_model'); $list = $this -> user_model -> find_all(); if($list){ $this -> load -> view('user_list',array( 'users' => $list )); }else{ echo '表不存在或表为空'; } } public function delete_user($id){ $this -> load -> model('user_model'); $result = $this -> user_model -> delete_item($id); if($result>0){ redirect('welcome/query_all'); }else{ echo '删除失败'; } } public function change_user($id){ $this -> load -> model('user_model'); $result = $this -> user_model -> change_item($id); $this->load->view('update', array( 'user' => $result )); } public function update_user($id) { $username = $this -> input -> post('username'); $pwd = $this -> input -> post('pwd'); $realname = $this -> input -> post('realname'); $tel = $this -> input -> post('tel'); $this -> load -> model('user_model'); $row = $this -> user_model -> update_item($id, $username, $pwd, $realname, $tel); // echo "用户名:$username ,真实姓名:$realname ,联系方式:$tel"; if($row > 0){ redirect('welcome/query_all'); }else{ echo 'update failed'; } } }
true
43de5a25beee0f027cbebd462e68f3fbe5b2bb1a
PHP
JuanJoya/note-component
/app/Domain/Author.php
UTF-8
1,513
3.21875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Note\Domain; use Note\Domain\Traits\Timestamps; class Author { use Timestamps; /** * @var User usuario creador del autor. */ private $user; /** * @var string seudónimo de un autor. */ private $username; /** * @var string slug formado por el seudónimo. */ private $slug; /** * @var int id identificador de un autor. */ private $id; /** * @param User $user * @param string $username * @param string $slug * @param string $created_at * @param string $updated_at * @param int $id */ public function __construct( User $user, string $username, string $slug, int $id, string $created_at = null, string $updated_at = null ) { $this->user = $user; $this->username = $username; $this->slug = $slug; $this->id = $id; $this->created_at = $created_at; $this->updated_at = $updated_at; } /** * @return User */ public function getUser(): User { return $this->user; } /** * @return string */ public function getUsername(): string { return $this->username; } /** * @return string */ public function getSlug(): string { return $this->slug; } /** * @return int */ public function getId(): int { return $this->id; } }
true
269c27b461bc1a28f9b70557afa258e9a786d7eb
PHP
OpenMageModuleFostering/nektria_recs
/app/code/community/Nektria/ReCS/Helper/Data.php
UTF-8
7,966
2.546875
3
[]
no_license
<?php class Nektria_ReCS_Helper_Data extends Mage_Core_Helper_Abstract { const CONFIG_KEY = 'carriers/nektria_recs'; const CARRIER = 'nektria_recs'; const ASSETS_VERSION = 1; const CONNECT_TIMEOUT = 1.5; const TIMEOUT = 2; const SHIPPINGLOGFILE = 'shipping_nektria.log'; /** * Return checkout config value by key and store * * @param string $key * @return variant|null */ public function getConfig($key='', $store = null) { if( !isset ( $this->_configs) ){ $this->_configs = Mage::getStoreConfig(self::CONFIG_KEY, $store); } return (isset($this->_configs[$key])?$this->_configs[$key] : NULL ); } public function getReCSMethods(){ return array( 'lastmile' => $this->__('Elige día y hora'), 'classic' => $this->__('RECS: Servicio Estándar') ); } /** * Get configured parameters of the service from backend * @param array $params of configuration * @return array Merged params with defaults */ public function getServiceParams($params){ $recs = new NektriaSdk(); $return = array_merge( array( 'APIKEY' => self::getConfig('apikey'), 'environment'=>'production', 'timeout' => self::TIMEOUT, 'connect_timeout' => self::CONNECT_TIMEOUT ), $params ); //if demo or sandbox then get SandboxKey if (self::getConfig('sandbox') || self::checkDemoFlag()){ $return['APIKEY'] = $recs->getSandboxApiKey(); $return['environment'] = 'sandbox'; } return $return; } /** * Get carrier name * @return string */ public function getCode(){ return self::CARRIER; } /** * Get the number of assets version * @return int the version */ public function getAssetsVersion(){ return self::ASSETS_VERSION; } /** * Get if the extension is active and get an apikey from config * @return bool */ public function getEnabled(){ return (Mage::helper('nektria')->getConfig('active') && ! is_null(Mage::helper('nektria')->getConfig('apikey')) ); } /** * Get if LightCheckout is installed and enabled * @return bool */ public function getGomageLightCheckoutEnabled(){ return Mage::getStoreConfig('gomage_checkout/general/enabled'); } /** * Get the last timeWindow selection for Last Mile used in template view * @return JSON Stringify */ public function getLastSelection(){ return Mage::getSingleton('checkout/session')->getNektriaUserSelection(FALSE); } /** * Get if nektria last mile shipping method is selected * @return bool */ public function getLastMileSelected(){ $shipping_method = self::getShippingMethod(); //Switch with method type if ($shipping_method == 'nektria_recs_lastmile'){ return TRUE; }else{ return FALSE; } } /** * Returns the last Mile selected Price * @return string price with currency code */ public function getLastMileSelectedPrice(){ if ( self::getLastMileSelected() ){ $selectedPrice = Mage::helper('core')->jsonDecode(self::getLastSelection()); return Mage::helper('core')->currency( $selectedPrice['total_price'] ); }else{ return ''; } } /** * Get the selected shipping method * @return bool */ public function getShippingMethod(){ $quote = $checkout = Mage::getSingleton('checkout/session')->getQuote(); $address = $quote->getShippingAddress(); return $address->getShippingMethod(); } /** * Get the selected payment method * @return string code of the method */ public function getPaymentMethod(){ $quote = $checkout = Mage::getSingleton('checkout/session')->getQuote(); return $quote->getPayment()->getMethodInstance()->getCode(); } /** * Get direct payment methods from magento usetting offline methods * @return array of payment methods */ public function getDirectPaymentMethods(){ $methods = Mage::helper('payment')->getPaymentMethodList(TRUE, TRUE, TRUE); unset($methods['offline']); return $methods; } /** * Returns the list of offline payment methods names * @return array of names */ public function getOfflinePaymentMethods(){ $methods = Mage::helper('payment')->getPaymentMethodList(TRUE, TRUE, TRUE); $methods = array_keys( $methods['offline']['value'] ); return $methods; } /** * Get backend disabled by the admin payment methods * @return array */ public function getDisabledPaymentMethods(){ $paymentsallow = self::getConfig('paymentsallow'); //convert variable to array $paymentsallow = ($paymentsallow)?explode( ',', $paymentsallow ) : array(); //returns selected direct payment methods and all offline payment methods return array_merge( $paymentsallow, self::getOfflinePaymentMethods() ); } /** * Check if the payment method selected allow Nektria Last Mile * @param string $method Payment method * @return bool if allow this method for last mile */ public function checkAllowPaymentMethod($method){ if ( in_array( $method, self::getDisabledPaymentMethods() ) ){ $this->log($method,'This Payment method is NOT allowed',self::SHIPPINGLOGFILE); return FALSE; }else{ return TRUE; } } /** * Write html template with the Last Mile Selection * @return string html */ public function htmlLastMileSelection(){ $template = Mage::app()->getLayout()->createBlock('core/template') ->setTemplate('recs/totals/lastmile.phtml'); return $template->toHtml(); } /** * Write html template with the Last Mile Selection * @return string html */ public function htmlAdminLastMileSelection($order){ $template = Mage::app()->getLayout()->createBlock('core/template') ->setData('order', $order) ->setTemplate('recs/sales/order/view/lastmile.phtml'); return $template->toHtml(); } /** * Returns if array1 is different to array2 * @param array $array1 * @param array $array2 * @return bool */ public function checkChanges($array1, $array2){ //Compare serialized arrays helps with multilevel arrays if (serialize($array1) !== serialize($array2)){ return TRUE; } else { return FALSE; } //OLD CODE DEPRECATED /*$original = count($array1); if ($original !== count($array2)){ return TRUE; } $result = count(array_intersect($array1, $array2)); if( $original == $result){ return FALSE; }else{ return TRUE; }*/ } /** * Check if the edition of magento and version if correct * @param string $edition 'Community|Enterprise' * @param string $version 'x.x.x.x' * @return bool */ public function checkMagentoVersion($edition, $version){ if ($edition == Mage::getEdition() && strpos(Mage::getVersion(), $version)===0){ return TRUE; }else{ return FALSE; } } /** * Helper function for translations * @param string $string Traslate to string * @return string translation */ public function _($string){ return self::__($string); } /** * Returns the session timeout in seconds * @param int store id * @return int seconds */ public function getSessionTimeout($store = NULL){ return Mage::getStoreConfig( 'web/cookie/cookie_lifetime' , $store); } public function checkDemoFlag(){ $sTestDefault = Mage::getStoreConfig('design/head/demonotice'); if ($sTestDefault){ return TRUE; }else{ return FALSE; } } /** * Log into file var exporting * @param var $object * @param string $title The title of the log section * @param string $file the name of the log file * @return void */ public function log($object, $title = NULL, $file = NULL){ if ($title){ Mage::log('----------------------'.$title.'--------------------------', null, $file); } Mage::log(var_export($object, TRUE), null, $file); } /** * Gets the currency symbol associated to a Currency Code * @return string currency symbol */ public function getCurrencySymbol(){ $currency_code = Mage::app()->getStore()->getBaseCurrencyCode(); return Mage::app()->getLocale()->currency( $currency_code )->getSymbol(); } }
true
111b805874ce022c4c9583406e75ebc112eb8c2d
PHP
bomkeen/abconnect
/models/Product.php
UTF-8
1,055
2.515625
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\models; use Yii; use app\models\ProductType; /** * This is the model class for table "product". * * @property int $product_id * @property string $product_name * @property int $product_type_id */ class Product extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'product'; } /** * {@inheritdoc} */ public function rules() { return [ [['product_name'], 'string'], [['product_type_id'], 'integer'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'product_id' => 'Product ID', 'product_name' => 'ชื่อสินค้า', 'product_type_id' => 'Product Type ID', 'producttype' => 'ประเภทสินค้า' ]; } public function getProducttype() { return $this->hasOne(ProductType::className(), ['product_type_id' => 'product_type_id']); } }
true
9953fdff65afdf7cda2dc71e1512ca11215b97dc
PHP
quang0212083/php-mvc-example
/controllers/posts_controller.php
UTF-8
2,342
2.796875
3
[]
no_license
<?php /** * Class PostsController */ class PostsController { /** * Show all post */ public function index() { // we store all the posts in a variable $posts = Post::all(); require_once('views/posts/index.php'); } /** * Show by id post */ public function show() { // we expect a url of form ?controller=posts&action=show&id=x // without an id we just redirect to the error page as we need the post id to find it in the database if (!isset($_GET['id'])) return call('pages', 'error'); // we use the given id to get the right post $post = Post::find($_GET['id']); require_once('views/posts/show.php'); } public function add() { require_once('views/posts/add.php'); } public function doAdd() { $firstname= $_POST['firstname']; $lastname = $_POST['lastname']; $author = $_POST['author']; $content = $_POST['content']; $post = array( 'first_name' => $firstname, 'last_name' => $lastname, 'author' => $author, 'content' => $content, ); require_once('models/post.php'); $posts =Post::addPost($post); $posts = Post::all(); require_once('views/posts/index.php'); // require_once('views/posts/index.php'); // $view = Post::view($status); } public function update() { if (!isset($_GET['id'])) return call('pages', 'error'); // we use the given id to get the right post $post = Post::find($_GET['id']); require_once('views/posts/update.php'); } public function postUpdate() { $firstname= $_POST['firstname']; $lastname = $_POST['lastname']; $author = $_POST['author']; $content = $_POST['content']; $post = array( 'first_name' => $firstname, 'last_name' => $lastname, 'author' => $author, 'content' => $content, ); $id = $_POST['id']; require_once('models/post.php'); $posts =Post::update($post,$id); $posts = Post::all(); require_once('views/posts/index.php'); } public function delete() { if (!isset($_GET['id'])) return call('pages', 'error'); // we use the given id to get the right post $post = Post::delete($_GET['id']); $posts = Post::all(); require_once('views/posts/index.php'); } } ?>
true
993c005112ee3699014d55dac85ce45599537c73
PHP
anedovba/MVC
/src/Controller/CartController.php
UTF-8
1,538
2.75
3
[]
no_license
<?php namespace Controller; use Library\Controller; use Library\Request; use Model\Cart; use Model\Repository\BookRepository; class CartController extends Controller { public function addAction(Request $request) { // TODO: repo - check if exists & active $id = $request->get('id'); $cart = new Cart(); $cart->addProduct($id); $this->container->get('router')->redirect("/book-{$id}.html"); } /** * @param Request $request * @return string */ public function showListAction(Request $request) { $cart = new Cart();//попытка достать из куков $repo = $this->container->get('repository_manager')->getRepository('Book'); //получаем книги из репозитория $books = $repo->findByIdArray($cart->getProducts()); return $this->render('show.phtml', ['books' => $books]); } public function removeItemAction(Request $request) { } public function clearAction(Request $request) { } // maybe OrderController public function orderAction(Request $request) { /** * TODO: доработать базу сделать таблицы с заказами * 1. Order table in DB (id, user-data(?), email, order_item_id, created, status) * 2. OrderItem table (id, product_id, price) * 3. Form, Model * * * **/ } }
true
643aaa12bdc0db9afba875ec254d521d08f99a6c
PHP
alexisbellido/simple-wordpress-theme
/inc/class-snake.php
UTF-8
432
3.3125
3
[]
no_license
<?php namespace Zoo\Reptiles; /** * Snake * */ class Snake extends \Zoo\Animal { public function hiss() { echo "<h2>Sssss, help yourself an apple, I'm {$this->name}</h2>"; } } // // the standard way again, using current namespace // $lil_snake = new Snake('little snaky'); // $lil_snake->hiss(); // // // using fully qualified name (the namespace prefix) // $lil_dog = new \Zoo\Mammals\Dog('puppy'); // $lil_dog->bark();
true
e8c4930ab9809446de3ad0d31ef202a024deffaa
PHP
jeffjr2060/contact-form-validation-in-php
/index.php
UTF-8
2,051
2.671875
3
[]
no_license
<?php if(filter_has_var(INPUT_POST, 'submit')){ $name = htmlentities($_POST['name']); $email = htmlentities($_POST['email']); $message = htmlentities($_POST['message']); if(!empty($name) && !empty($email) && !empty($message)){ }else{ echo'please fill the from '; } if(filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAIL===false)){ }else{ echo 'enter a valid email'; } //recepient email $TO ='jeffjr2060@gmail.com'; $subject = 'Contact Request Form'. $name; $body = ' <h2>Contact Request</h2> <h4>name</h4><p>'.$name.'</p> <h4>email</h4><p>'.$email.'</p> <h4>message</h4><p>'.$message.'</p> '; //emai headers $headers ="MIME-version:1.0"."\r\n"; $headers = "Content.Type: text/html; charset=UTF-8"."\r\n"; //additional headers $headers.="from:".$name."<".$email.">"."\r\n"; //mail function to send if(mail($TO, $subject,$body, $headers)){ //mail sent }else{ //alert } }else{ } ?> <!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>contact form</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="container" style=" background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url(background.jpg) center/cover no-repeat fixed; min-height: 100vh;"> <div class="box"> <span>Contact form</span> <hr id="indicator"> <form method="$_POST" action="<?php echo $_SERVER['PHP_SELF'] ?>"> <input type="text" name="name" placeholder="enter name"> <input type="email" name="email" placeholder="enter email"> <textarea name="message" cols="30" rows="10" placeholder="message"></textarea> <button type="submit" name="submit">Submit</button> </form> </div> </div> </body> </html>
true
e72b91fb7215fd64073c55f160a5ab7a86a9ec6a
PHP
qingsongsun/habagou
/web/bjphp/vendor/workflow/appmgr.php
UTF-8
1,647
2.578125
3
[]
no_license
<?php /** * http://www.baijienet.com * User: sint * Date: 2016/11/27 * Time: 8:06 */ class vendor_workflow_appmgr { //根据流程名称获得流程定义的源码 public function load_app($appname) { $app = meta('app.app')->Load(['name'=>$appname]); if( $app == null ) bjerror("流程{$appname}不存在"); $ver = bjcreate( 'vendor.db.dao', 'select t.[verid],t.[bsl] from {m1} t where t.{appid=} order by t.[verid] desc', [ 'm1' => meta('app.appver')->TableName(), 'appid' => $app->id ] )->first(); if( $ver == null ) bjerror("流程{$appname}不存在"); return $ver->bsl; } //根据流程名称获得流程id public function load_appid($appname) { $app = meta('app.app')->Load(['name'=>$appname]); if( $app == null ) bjerror("流程{$appname}不存在"); $ver = bjcreate( 'vendor.db.dao', 'select t.[verid] from {m1} t where t.{appid=} order by t.[verid] desc', [ 'm1' => meta('app.appver')->TableName(), 'appid' => $app->id ] )->first(); if( $ver == null ) bjerror("流程{$appname}不存在"); return $ver->verid; } //根据流程名称获得流程id public function load_verid($appid) { $ver = bjcreate( 'vendor.db.dao', 'select t.[verid] from {m1} t where t.{appid=} order by t.[verid] desc', [ 'm1' => meta('app.appver')->TableName(), 'appid' => $appid ] )->first(); if( $ver == null ) bjerror("流程{$appid}不存在"); return $ver->verid; } //根据流程ID(版本ID)获得流程定义的源码 public function load_app_byid($appid) { return meta('app.appver')->Load(['verid'=>$appid],['bsl'])->bsl; } }
true
8049a61a79777d939e5dc25d0aad8e9dfb4dd08a
PHP
phly/PhlyBlog
/src/Compiler/Listener/Tags.php
UTF-8
3,887
2.6875
3
[ "BSD-2-Clause" ]
permissive
<?php namespace PhlyBlog\Compiler\Listener; use DomainException; use InvalidArgumentException; use Laminas\Tag\Cloud as TagCloud; use PhlyBlog\Compiler\Event; use PhlyBlog\Compiler\SortedEntries; use function count; use function in_array; use function iterator_to_array; use function sprintf; use function str_replace; use function strtolower; class Tags extends AbstractList { protected $tagCloud; protected $tags = []; public function onCompile(Event $e) { $entry = $e->getEntry(); if (! $entry->isPublic()) { return; } foreach ($entry->getTags() as $tag) { if (! isset($this->tags[$tag])) { $this->tags[$tag] = new SortedEntries(); } $this->tags[$tag]->insert($entry, $entry->getCreated()); } } public function onCompileEnd(Event $e) { foreach ($this->tags as $tag => $heap) { $this->tags[$tag] = iterator_to_array($heap); } } public function compile() { $this->createTagPages(); $this->createTagFeeds('rss'); $this->createTagFeeds('atom'); } public function getTagCloud() { if ($this->tagCloud) { return $this->tagCloud; } $tagUrlTemplate = $this->options->getTagCloudUrlTemplate(); $cloudOptions = $this->options->getTagCloudOptions(); $tags = []; foreach ($this->tags as $tag => $list) { $tags[$tag] = [ 'title' => $tag, 'weight' => count($list), 'params' => [ 'url' => sprintf( $tagUrlTemplate, str_replace(' ', '+', $tag) ), ], ]; } $options['tags'] = $tags; $this->tagCloud = new TagCloud($options); return $this->tagCloud; } public function createTagPages($template = null) { if (null === $template) { $template = $this->options->getByTagTemplate(); if (empty($template)) { throw new DomainException('No template provided for listing entries by tag'); } } $filenameTemplate = $this->options->getByTagFilenameTemplate(); $urlTemplate = $this->options->getByTagUrlTemplate(); $titleTemplate = $this->options->getByTagTitle(); foreach ($this->tags as $tag => $list) { $this->iterateAndRenderList( $list, $filenameTemplate, [$tag], sprintf($titleTemplate, $tag), $urlTemplate, $tag, $template ); } } public function createTagFeeds($type) { $type = strtolower($type); if (! in_array($type, ['atom', 'rss'])) { throw new InvalidArgumentException( 'Feed type must be "atom" or "rss"' ); } $filenameTemplate = $this->options->getTagFeedFilenameTemplate(); $blogLinkTemplate = $this->options->getTagFeedBlogLinkTemplate(); $feedLinkTemplate = $this->options->getTagFeedFeedLinkTemplate(); $titleTemplate = $this->options->getTagFeedTitleTemplate(); foreach ($this->tags as $tag => $list) { $title = sprintf($titleTemplate, $tag); $filename = sprintf($filenameTemplate, $tag, $type); $blogLink = sprintf($blogLinkTemplate, str_replace(' ', '+', $tag)); $feedLink = sprintf($feedLinkTemplate, str_replace(' ', '+', $tag), $type); $this->iterateAndGenerateFeed( $type, $list, $title, $blogLink, $feedLink, $filename ); } } }
true
524d2bb25b21b656f14be05818de3914cbba4316
PHP
adriangalan/Tarea-Ejercicio-de-Mini-Foro
/app/funciones.php
UTF-8
1,482
3.25
3
[]
no_license
<?php function usuarioOk($usuario, $contraseña) :bool { $respuesta=false; if (strlen($contraseña)>=8 && $contraseña==strrev($usuario)) { $respuesta=true; } return $respuesta; } function contarPalabras($texto) { return str_word_count($texto,0); } function contarLetras($texto) { $respuesta=0; if ($texto!="") { $texto=str_replace(" ", "",$texto); for ($i = 0; $i < strlen($texto); $i++) { $letra=substr($texto,$i,1); if ($letra!="") { $numero=substr_count($texto, $letra); $texto=str_replace($letra, "",$texto); $contador[$letra]= $numero; if ($i==0) { $maximo=$numero; $respuesta=$letra; } } } foreach ($contador as $clave=> $value) { if ($value>$maximo) { $maximo=$value; $respuesta=$clave; } } } return $respuesta; } function contadorPalabrasMaxima($texto) { $resultado=0; if ($texto!="") { $palabras=str_word_count($texto,1); $contador=array_count_values($palabras); $maximo=0; foreach ($contador as $clave=> $value) { if ($value>$maximo) { $resultado=$clave; $maximo=$value; } } } return $resultado; }
true
21cfd10d88b89cc6c7cc39db50bc3599b5f915e2
PHP
Danack/TierJigDocs
/vendor/fluentdom/fluentdom/src/FluentDOM/Appendable.php
UTF-8
508
2.953125
3
[ "MIT" ]
permissive
<?php /** * Allow an object to be appendable to a FluentDOM\Element * * @license http://www.opensource.org/licenses/mit-license.php The MIT License * @copyright Copyright (c) 2009-2014 Bastian Feder, Thomas Weinert */ namespace FluentDOM { /** * Allow an object to be appendable to a FluentDOM\Element */ interface Appendable { /** * Append the object to a FluentDOM\Element * * @param Element $parentNode * @return Element */ function appendTo(Element $parentNode); } }
true
37ef7b803b8f834981453f055aed1fdda8361bf7
PHP
WPPlugins/dynamic-content-widget
/dcw-dynamic-content-widget.php
UTF-8
5,429
2.75
3
[]
no_license
<?php /** * Dynamic Content Widget class. * * @since 0.1 * * Copyright (C) 2011 Dikhoff Software * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ require_once("dcw-common.php"); class dcw_Dynamic_Content_Widget extends WP_Widget { /** * Widget constructor. */ function dcw_Dynamic_Content_Widget() { /* Widget settings. */ $widget_ops = array( 'classname' => 'Dynamic Content Widget', 'description' => __('A widget that renders content with a template.', 'dynamic content') ); /* Widget control settings. */ $control_ops = array( 'width' => 300, 'height' => 350, 'id_base' => 'dcw-dynamic-content-widget' ); /* Create the widget. */ $this->WP_Widget( 'dcw-dynamic-content-widget', __('Dynamic Content Widget', 'dynamic content'), $widget_ops, $control_ops ); } /** * Display widget in area. * @see WP_Widget::widget() */ function widget( $args, $instance ) { extract( $args ); $title = apply_filters('widget_title', $instance['title'] ); $dcw_slug = $instance['slug']; $dcw_template = $instance['subtemplate']; $dcw_id = $instance['id']; echo $before_widget; if ( $title ) { echo $before_title . $title . $after_title; } // if no id, try finding the content by the slug if (!$dcw_id) { if ($dcw_slug) { $rows = dcw_find_content_id($dcw_slug); $dcw_id = $rows[0]->ID; $instance['id'] = $dcw_id; } } if (!$dcw_id) { echo "No content found with id '$dcw_id' or identifier '$dcw_slug'."; } $content = new WP_Query(); $content->query('p=' . $dcw_id . '&post_type=any'); if (!$content->have_posts()) { echo "No content found with id '$dcw_id'."; } while ($content->have_posts()) { $content->the_post(); get_template_part($dcw_template); } echo $after_widget; } /** * Update fields. * @see WP_Widget::update() */ function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); $instance['slug'] = strip_tags( $new_instance['slug'] ); $instance['subtemplate'] = strip_tags( $new_instance['subtemplate'] ); $instance['id'] = strip_tags( $new_instance['id'] ); return $instance; } /** * Display form. * @see WP_Widget::form() */ function form( $instance ) { $defaults = array( 'title' => __('Dynamic content', 'dynamic content'), 'slug' => __('about', 'about'), 'subtemplate' => '', 'id' => '' ); $instance = wp_parse_args( (array) $instance, $defaults ); ?> <script type="text/javascript"> checkField('<?php echo $this->get_field_id( 'slug' ); ?>', '<?php echo $this->get_field_id( 'id' ); ?>'); </script> <input id="<?php echo $this->get_field_id( 'id' ); ?>" type="hidden" name="<?php echo $this->get_field_name( 'id' ); ?>" value="<?php echo $instance['id']; ?>" /> <p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'hybrid'); ?></label> <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" style="width: 100%;" /></p> <p><label for="<?php echo $this->get_field_id( 'slug' ); ?>"><?php _e('Slug or id:', 'slug'); ?></label> <input id="<?php echo $this->get_field_id( 'slug' ); ?>" name="<?php echo $this->get_field_name( 'slug' ); ?>" value="<?php echo $instance['slug']; ?>" style="width: 275px;" onblur="checkField('<?php echo $this->get_field_id( 'slug' ); ?>', '<?php echo $this->get_field_id( 'id' ); ?>');" /><span style="float:right;padding:4px 0 0 0;" id="<?php echo $this->get_field_id( 'slug' ); ?>-result">&nbsp;</span> </p> <?php dcw_write_subtemplates($this, $instance); ?> <?php } } // class /** * Register widgets. * @since 0.1 */ function dcw_load_widget() { register_widget( 'dcw_Dynamic_Content_Widget' ); } /** * Load CSS. */ function dcw_add_css() { global $pagenow; if (is_admin() && $pagenow == 'widgets.php') { $cssurl = plugins_url('/css/dynamic-content-widget.css', __FILE__ ); wp_register_style("dcw_css", $cssurl); wp_enqueue_style("dcw_css"); } } /** * Load scripts. */ function dcw_print_scripts() { global $pagenow; if (is_admin() && $pagenow == 'widgets.php') { $scripturl = plugins_url('/js/dynamic-content-widget.js', __FILE__ ); wp_enqueue_script("dcw_scripts", $scripturl, Array("suggest")); } } add_action( 'widgets_init', 'dcw_load_widget' ); add_action( 'admin_print_scripts', 'dcw_print_scripts'); add_action( 'admin_init', 'dcw_add_css'); ?>
true
40eaa5bf8a6867e48590204ebe582fa76fb78a72
PHP
websolutionsz/laravel-disk-monitor
/src/Commands/DiskMonitorCommand.php
UTF-8
903
2.546875
3
[ "MIT" ]
permissive
<?php namespace Websolutionsz\DiskMonitor\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\Storage; use Websolutionsz\DiskMonitor\Models\DiskMonitorEntry; class DiskMonitorCommand extends Command { public $signature = 'disk-monitor:record-metrics'; public $description = 'Record Metrics of disk'; public function handle() { $this->comment('Recording Metrics...'); collect(config('disk-monitor.disk_name'))->each(fn (string $diskName) => $this->recordMetrix($diskName)); $this->comment('All Done!'); } protected function recordMetrix(String $diskName) { $this->info("Recording metrics for disk `{$diskName}`..."); $filecount = count(Storage::disk($diskName)->allFiles()); DiskMonitorEntry::create([ 'disk_name' => $diskName, 'file_count' => $filecount, ]); } }
true
cbbf4f5748477d6acb7d9644192dd51b03d50f5c
PHP
Korbeil/quasarr
/project/src/Message/DownloadTvEpisodeMessage.php
UTF-8
652
2.828125
3
[ "MIT" ]
permissive
<?php namespace Quasarr\Message; final class DownloadTvEpisodeMessage { private $tvShowId; private $tvSeasonId; private $tvEpisodeNumber; public function __construct(int $tvShowId, int $tvSeasonId, int $tvEpisodeNumber) { $this->tvShowId = $tvShowId; $this->tvSeasonId = $tvSeasonId; $this->tvEpisodeNumber = $tvEpisodeNumber; } public function getTvShowId(): int { return $this->tvShowId; } public function getTvSeasonId(): int { return $this->tvSeasonId; } public function getTvEpisodeNumber(): int { return $this->tvEpisodeNumber; } }
true
bed6bce43fda5643800ff78c5272cc6a21800bf1
PHP
4slv/yaml-config
/CodeGenerator/structure/StructureInfoListInterface.php
UTF-8
1,048
2.796875
3
[]
no_license
<?php namespace YamlConfig\StructureCodeGenerator; use YamlConfig\YamlFileToTree; /** Список информации о структурах */ interface StructureInfoListInterface { /** * @return ConfigStructureInfoInterface[] список информации о структуре конфига */ public function getStructureInfoList(); /** * @param YamlFileToTree $yamlFileToTree преобразователь конфигурационного файла в конфигурацию */ public function setYamlFileToTree(YamlFileToTree $yamlFileToTree); /** * @param string $configNamespace пространство имён конфига */ public function setConfigNamespace($configNamespace); /** * @param array $tree дерево конфига * @param string[] $path текущий путь * @return ConfigStructureInfoInterface[] список информации о структуре */ public function initFromTree($tree, $path = []); }
true
0ceed303e63a27893225faacf795a22dd85607e5
PHP
tush59/interview-questions
/palindrom.php
UTF-8
395
3.015625
3
[]
no_license
<?php error_reporting(E_ALL^E_NOTICE); ini_set('display_errors','On'); $num=121; $copynum=$num; $digit; $reverse; while ($copynum>0){ $digit=$copynum%10; $reverse=($reverse*10+$digit); //echo $reverse; $copynum=$copynum/10; } echo "<br/>"; echo $reverse; echo "<br/>"; if($num==$reverse){ echo "palindrom"; }else{ echo "not"; } ?>
true
dc2867ee41e7a12a9466c48a913323cc221c7734
PHP
awesome-academy/ecommerce_03
/app/Repositories/ProductRepository.php
UTF-8
3,343
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Repositories; use App\Models\Product; use App\Repositories\EloquentRepository; use App\Repositories\CategoryRepository; class ProductRepository extends EloquentRepository { private $categoryRepository; public function __construct(CategoryRepository $categoryRepository) { parent::__construct(); $this->categoryRepository = $categoryRepository; } public function getModel() { return Product::class; } public function common($request, $products, $type) { if ($request){ $products->where(function($products) use ($request, $type) { foreach ($request as $each_request) { if ($each_request != trans('message.leftbar.all')) { $products->orWhere($type, 'LIKE', $each_request); } } }); } return true; } public function filter($categories, $strap, $skin, $energy, $price_min, $price_max, $search, $sort) { $products = $this->model->select('*'); if ($categories){ $products = $products->where(function($products) use ($categories) { foreach ($categories as $category) { $cat = $this->categoryRepository->categoryFirst($category); if ($category != config('custom.zero')) { if (count($cat->children) > config('custom.zero')) { foreach ($cat->children as $cat_child) { $products->orwhere('category_id', '=', $cat_child->id); } } else { $products->orwhere('category_id', '=', $category); } } } }); } $this->common($strap, $products, 'strap_type'); $this->common($skin, $products, 'skin_type'); $this->common($energy, $products, 'energy'); if ($price_min && $price_max){ $products->whereBetween('price', [$price_min * config('custom.million'), $price_max * config('custom.million')]); } $search = explode(' ',$search); $products->where(function($products) use ($search) { for($i = config('custom.zero'); $i < count($search); $i++) { $products->orWhere('name','LIKE','%'.$search[$i].'%'); } }); if ($sort == 'popularity'){ $products = $products->orderBy('best_seller', 'DESC'); } elseif ($sort == 'price_asc') { $products = $products->orderBy('price', 'asc'); } elseif ($sort == 'price_desc') { $products = $products->orderBy('price', 'desc'); } else { $products = $products->orderBy('id', 'DESC'); } $products = $products->paginate(config('custom.nine')); return $products; } public function descFirst() { return $this->model->orderBy('id', "DESC")->first(); } public function getProductBestSeller($category) { return $this->model->where('category_id', $category)->sum('best_seller'); } public function checkProductExist($name) { return $this->model->where('name', $name)->exists(); } }
true
b794a9e01510868c2806e18f96f5b00375c8824e
PHP
gogromat/yodatalk
/translators/bing/class/MicrosoftTranslator.class.php
UTF-8
7,957
2.640625
3
[ "MIT" ]
permissive
<?php /** * MicrosoftTranslator - A PHP Wrapper for Microsoft JSON Translator API * * @category Translation * @author Renjith Pillai * @link http://www.renjith.co.in * @copyright 2012 Renjith Pillai * @version 1.0.0 */ class MicrosoftTranslator { /** * Some Constants * */ const SUCCESS = 'SUCCESS'; const ERROR = 'ERROR'; const UNEXPECTED_ERROR = UNEXPECTED_ERROR; const MISSING_ERROR = MISSING_ERROR; const TRANSLATE = 'Translate'; const GET_LANG = 'GetLanguagesForTranslation'; const ENABLE_CACHE = ENABLE_CACHE; const CACHE_DIRECTORY = CACHE_DIRECTORY; const LANG_CACHE_FILE = LANG_CACHE_FILE; /** * Service root URL for translattion. You can get it from Nicrosoft Azure Dataset PAge * * @var unknown_type */ private $serviceRootURL = 'https://api.datamarket.azure.com/Data.ashx/Bing/MicrosoftTranslator/v1/'; /** * This is the unique key you have to obtain from Microsoft * * @var string $accountKey */ private $accountKey = ''; /** * Context from account key * * @var string $context */ private $context = ''; /** * Request Invoked * * @var string $requestInvoked */ private $requestInvoked = ''; /** * From which language * * @var strng $from */ private $from = ''; /** * To which language * * @var string $to */ private $to = ''; /** * Format Raw/Atom * * @var string $to */ private $format = ''; /** * $top * * @var string $top */ private $top = '100'; /** * Translated text output * * @var string $translatedText */ private $translatedText = ''; /** * Text to Translate * * @var string $textToTranslate */ private $textToTranslate = ''; /** * Text to translate. * * @var Object $response */ public $response = ''; /** * Constructor * * @param unknown_type $accountKey */ public function __construct($accountKey) { $this->accountKey = $accountKey; $this->context = $this->getContext(); } /** * Translator Method which wraps all other operations * @param string $from * @param to $to * @param to $text */ public function translate($from, $to, $text, $format = 'Raw' ) { if(empty($to) || empty($text)) { $this->getErrorResponse($response, self::MISSING_ERROR, $missing); return; } $this->from = (!empty($this->from )) ? $this->sanitize($from) : ''; $this->to = $this->sanitize($to); $this->textToTranslate = $this->sanitize($text); $this->format = $format; $request = $this->getRequest(self::TRANSLATE ); $response = file_get_contents( $request, 0, $this->context ); if(!empty($response) && isset($response)){ $this->getSuccessResponse($response); } else { $this->getErrorResponse($response, self::UNEXPECTED_ERROR, $missing ); } } /** * Get Languages for translation * */ public function getLanguagesSelectBox($selectBox){ //some how Raw format gives a single string of all countries and user changing format doesnt make sense here as output is html $this->format = 'json'; $request = $this->getRequest( self::GET_LANG); if( ! $response = $this->getCache( self::LANG_CACHE_FILE )) { $response = file_get_contents( $request, 0, $this->context ); $this->putToCache( self::LANG_CACHE_FILE, $response ); } $objResponse = json_decode($response); if(!empty($objResponse) && isset($objResponse)){ $this->getSuccessResponse($objResponse, $selectBox); } else { $this->getErrorResponse($objResponse, self::UNEXPECTED_ERROR, $missing ); } } /** * Encodes request in desirable format for Microsoft translator * @todo do more sanitization * @param string $text * @return unknown */ private function sanitize($text){ $text = urlencode("'".$text."'"); return $text; } /** * Success Response Object * * @param unknown_type $response */ private function getSuccessResponse($response, $selectBox = ''){ $this->response = new stdClass(); $this->response->status = self::SUCCESS; if($this->requestInvoked == self::TRANSLATE ) { $this->response->translation = strip_tags($response); // Fot instance if you need both Raw and Json format if($this->format == 'Raw') { $this->response->jsonResponse = !function_exists('json_decode') ? $this->response : json_encode($this->response); } } elseif($this->requestInvoked == self::GET_LANG ) { //currently it directly give selctbox $this->response->languageSelectBox = $this->getSelectBox($response,$selectBox); } } private function getSelectBox($response,$selectBox) { $options = ''; foreach($response->d->results as $values ) { if(isset( $values->Code )) { $options.= "<option value='".$values->Code."'>".$values->Code."</option>"; } } $select = "<select id ='".$selectBox['id']."' name='".$selectBox['name']. "'class='".$selectBox['class']."'>"; $select.= $options; $select.= "</select>"; return $select; } /** * Default error response, Currenlty i am not able to catch error for some reason, so giving custom errors * * @param unknown_type $response * @param unknown_type $reason * @param unknown_type $param */ private function getErrorResponse($response, $reason , $param){ $this->response = new stdClass(); $this->response->status = self::ERROR ; $this->response->errorReason = str_replace("%s", $param, $reason); $this->response->jsonResponse = !function_exists('json_decode') ? $this->response : json_encode($this->response); } /** * Ger Request in Desirable format for Microsoft Translator * * @return unknown */ private function getRequest($type) { $this->requestInvoked = $type; $text = (!empty($this->textToTranslate)) ? 'Text='.$this->textToTranslate : ''; $to = (!empty($this->to)) ? $to = '&To='. $this->to : ''; $from = (!empty($this->from)) ? '&From='. $this->from : ''; $format = '$format='.$this->format; $top = '$top='.$this->top; $params = $text . $from . $to .'&'. $format .'&'. $top ; if($type == self::TRANSLATE ) { $request = $this->serviceRootURL. $type.'?'. $params; } elseif ($type == self::GET_LANG ){ $request = $this->serviceRootURL. $type.'?'. $top.'&'. $format; } return $request ; } /** * Authentication of Application key * * @return unknown */ private function getContext() { $context = stream_context_create(array( 'http' => array( 'request_fulluri' => true, 'header' => "Authorization: Basic " . base64_encode($this->accountKey . ":" . $this->accountKey) ) )); return $context; } private function putToCache($file, $toCache) { if(self::ENABLE_CACHE == true) { try { if(is_dir(self::CACHE_DIRECTORY)) { $handle = fopen(self::CACHE_DIRECTORY . $file, "w"); fwrite($handle, $toCache); fclose($handle); } } catch (Exception $e) { die ('put to cache failed ' . $e->getMessage()); } } } private function getCache($file) { if(self::ENABLE_CACHE == true) { if(is_dir(self::CACHE_DIRECTORY) && file_exists(self::CACHE_DIRECTORY . $file)) { $handle = fopen(self::CACHE_DIRECTORY . $file, "r"); $contents = ''; while (!feof($handle)) { $contents .= fread($handle, 8192); } fclose($handle); return $contents; } else { return false; } } } }
true
e8cc714f290600d855219b67fc32a1df93288d72
PHP
Arhangel31337/wings
/Wings/File.php
UTF-8
4,936
2.71875
3
[]
no_license
<?php namespace Wings; final class File { public static $uploadDir; public function __construct() {} public static function confirmTempFile($filePath) { $fileMime = \preg_replace('/[\s\.]/', '_', \mime_content_type($filePath)); $type = \explode('/', $fileMime); $filePathNew = \explode('/', $filePath); $filePathNew = $filePathNew[(\count($filePathNew) - 1)]; $fileName = \str_replace(\session_id() . '_', '', $filePathNew); $dirPath = self::$uploadDir . $type[0] . '/'; $filePathNew = $dirPath . $fileName; Directory::create($dirPath); if (\rename($filePath, $filePathNew)) return ['name' => $fileName, 'mime' => \mime_content_type($filePathNew)]; else return false; } public static function copy($pathFrom, $pathTo) { if (\file_exists($pathTo)) \unlink($pathTo); \copy($pathFrom, $pathTo); } public static function initialize() { self::$uploadDir = $_SERVER['DOCUMENT_ROOT'] . \Wings::$settings['uploadDir']; } public static function issetTempFile($tempPath) { $tempPath = \explode('/', $tempPath); if (\stristr($_SERVER['SERVER_SOFTWARE'], 'win')) $tempPath[(count($tempPath) - 1)] = \iconv('utf-8', 'cp1251', $tempPath[(count($tempPath) - 1)]); $realPath = self::$uploadDir . 'temp/' . \session_id() . '_' . $tempPath[(count($tempPath) - 1)]; if (\file_exists($realPath)) return $realPath; else return false; } public static function getFileName($fileName) { if (\stristr($_SERVER['SERVER_SOFTWARE'], 'win')) $fileName = \iconv('cp1251', 'utf-8', $fileName); return $fileName; } public static function getUserTempFiles() { $fileDir = self::$uploadDir . 'temp/'; $mktime = \time(); $userTempFiles = []; $prefix = \session_id() . '_'; $fileList = Directory::getChildren($fileDir); foreach ($fileList as $value) { $filePath = $fileDir . $value; $fileTime = \filemtime($filePath); if (($mktime - $fileTime) < \Wings::$settings['sessionTime']) { $fileName = self::getFileName($value); if(\strstr($fileName, $prefix)) { $fileName = \str_replace($prefix, '', $fileName); $fileMime = \preg_replace('/[\s\.]/', '_', \mime_content_type($filePath)); $type = \explode('/', $fileMime); $userTempFiles[] = [ 'level' => 0, 'pageName' => 'Новые', 'id' => 0, 'pageID' => 'new', 'mime' => $fileMime, 'name' => $fileName, 'type' => $type[0], 'fullPath' => '/files/' . $type[0] . '/' . $fileName, 'size' => \filesize($filePath), 'time' => \date('Y-m-d H:i:s', $fileTime) ]; } } else { if (!\is_dir($filePath)) unlink($filePath); } } return $userTempFiles; } public static function transfer($pathFrom, $pathTo) { if (\stristr($_SERVER['SERVER_SOFTWARE'], 'win')) $pathTo = \iconv('utf-8', 'cp1251', $pathTo); if (\file_exists($pathTo)) \unlink($pathTo); $pathToDir = \explode('/', $pathTo); unset($pathToDir[(\count($pathToDir) - 1)]); $pathToDir = \implode('/', $pathToDir); Directory::create($pathToDir); \copy($pathFrom, $pathTo); \unlink($pathFrom); } public static function upload($file,$catalog = null, $name = null) { if (!\is_uploaded_file($file['tmp_name'])) return ['status' => 1, 'message' => 'Файл не был загружен на сервер.']; if ($name !== null && !empty($name)) $file['name'] = \urldecode($name); else $file['name'] = \urldecode($file['name']); $type = \explode('/', \mime_content_type($file['tmp_name'])); if ($catalog !== null && !empty($catalog)) { $path = $_SERVER['DOCUMENT_ROOT'] . $catalog; $fullPath = $fullPathToJS = $path . $file['name']; } else { $path = self::$uploadDir . $type[0] . '/'; $fullPath = $path . $file['name']; $fullPathToJS = '/files/' . $type[0] . '/' . $file['name']; } if (\stristr($_SERVER['SERVER_SOFTWARE'], 'win')) $fullPath = \iconv('utf-8', 'cp1251', $fullPath); if (\file_exists($fullPath)) return ['status' => 2, 'message' => 'Файл с таким именем существует.']; if ($catalog === false || empty($catalog)) { $path = self::$uploadDir . 'temp/'; $fullPath = $path . \session_id() . '_' . $file['name']; } if (\stristr($_SERVER['SERVER_SOFTWARE'], 'win')) $fullPath = \iconv('utf-8', 'cp1251', $fullPath); if (\file_exists($fullPath)) return ['status' => 2, 'message' => 'Файл с таким именем существует.']; Directory::create($path); if (!\move_uploaded_file($file['tmp_name'], $fullPath)) return ['status' => 3, 'message' => 'Файл нельзя переместить.']; return [ 'status' => 200, 'data' => [ 'name' => $file['name'], 'mime' => implode('/', $type), 'fullPath' => $fullPathToJS, 'date' => \date('Y-m-d H:i:s', \filemtime($fullPath)), 'size' => \filesize($fullPath) ] ]; } }
true
e5fa9d34000b26ab3999e7cc7373c651aee57192
PHP
phalcon/ide-stubs
/src/Messages/Message.php
UTF-8
2,750
2.875
3
[ "BSD-3-Clause" ]
permissive
<?php /* This file is part of the Phalcon Framework. * * (c) Phalcon Team <team@phalcon.io> * * For the full copyright and license information, please view the LICENSE.txt * file that was distributed with this source code. */ namespace Phalcon\Messages; use JsonSerializable; /** * Phalcon\Messages\Message * * Stores a message from various components */ class Message implements \Phalcon\Messages\MessageInterface, \JsonSerializable { /** * @var int */ protected $code; /** * @var string */ protected $field; /** * @var string */ protected $message; /** * @var string */ protected $type; /** * @var array */ protected $metaData = []; /** * Phalcon\Messages\Message constructor * * @param string $message * @param mixed $field * @param string $type * @param int $code * @param array $metaData */ public function __construct(string $message, $field = '', string $type = '', int $code = 0, array $metaData = []) { } /** * Magic __toString method returns verbose message * * @return string */ public function __toString(): string { } /** * @return int */ public function getCode(): int { } /** * @return string */ public function getField(): string { } /** * @return string */ public function getMessage(): string { } /** * @return string */ public function getType(): string { } /** * @return array */ public function getMetaData(): array { } /** * Serializes the object for json_encode * * @return array */ public function jsonSerialize(): array { } /** * Sets code for the message * * @param int $code * @return MessageInterface */ public function setCode(int $code): MessageInterface { } /** * Sets field name related to message * * @param mixed $field * @return MessageInterface */ public function setField($field): MessageInterface { } /** * Sets verbose message * * @param string $message * @return MessageInterface */ public function setMessage(string $message): MessageInterface { } /** * Sets message metadata * * @param array $metaData * @return MessageInterface */ public function setMetaData(array $metaData): MessageInterface { } /** * Sets message type * * @param string $type * @return MessageInterface */ public function setType(string $type): MessageInterface { } }
true
3a687d243d0da888128bf5122abf433f0f4bfab5
PHP
JanStanleyWatt/commonmark-furigana-extension
/tests/FuriganaTest.php
UTF-8
8,098
2.53125
3
[ "Apache-2.0" ]
permissive
<?php /** * Copyright 2023 Jan Stanley Watt * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ declare(strict_types=1); namespace JSW\Tests; use JSW\Furigana\FuriganaExtension; use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use PHPUnit\Framework\TestCase; /** * @coversDefaultClass \JSW\Furigana\Delimiter\FuriganaDelimiterProcesser * * @group furigana */ final class FuriganaTest extends TestCase { private const DEFAULT_RULE = [ 'furigana' => [ 'use_sutegana' => false, 'use_rp_tag' => false, ], ]; private function makeExpect(string $expect) { return '<p>'.$expect.'</p>'."\n"; } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateDelimited(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能は<ruby>素晴らしい<rt>Wonderful</rt></ruby>'); $actual = $converter->convert('この拡張機能は|素晴らしい《Wonderful》')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateKanji(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この<ruby>拡張機能<rt>かくちょうきのう</rt></ruby>は素晴らしい'); $actual = $converter->convert('この拡張機能《かくちょうきのう》は素晴らしい')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateZenkakuAlphabet(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能は<ruby>Excellent<rt>すばらしい</rt></ruby>'); $actual = $converter->convert('この拡張機能はExcellent《すばらしい》')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateHankakuAlphabet(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能は<ruby>Excellent<rt>すばらしい</rt></ruby>'); $actual = $converter->convert('この拡張機能はExcellent《すばらしい》')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateZenkakuKatakana(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能は<ruby>グレート<rt>Great</rt></ruby>だ'); $actual = $converter->convert('この拡張機能はグレート《Great》だ')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateHankakuKatakana(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能は<ruby>グレート<rt>Great</rt></ruby>だ'); $actual = $converter->convert('この拡張機能はグレート《Great》だ')->getContent(); $this->assertSame($expect, $actual); } /** * @covers \JSW\Furigana\Util\FuriganaKugiri::getKugiri * @covers \JSW\Furigana\Parser\FuriganaOpenParser::parse * @covers \JSW\Furigana\Parser\FuriganaOpenParser::getMatchDefinition * @covers \JSW\Furigana\Parser\FuriganaOpenParser::__construct */ public function testRubySeparateHiragana(): void { $environment = new Environment($this::DEFAULT_RULE); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この拡張機能、<ruby>いいかんじ<rt>some good</rt></ruby>だ'); $actual = $converter->convert('この拡張機能、いいかんじ《some good》だ')->getContent(); $this->assertSame($expect, $actual); } /** * @covers ::process */ public function testRubyParentheses(): void { $environment = new Environment([ 'furigana' => [ 'use_rp_tag' => true, ], ]); $environment->addExtension(new CommonMarkCoreExtension()) ->addExtension(new FuriganaExtension()); $converter = new MarkdownConverter($environment); $expect = $this->makeExpect('この<ruby>拡張機能<rp>(</rp><rt>かくちょうきのう</rt><rp>)</rp></ruby>は素晴らしい'); $actual = $converter->convert('この拡張機能《かくちょうきのう》は素晴らしい')->getContent(); $this->assertSame($expect, $actual); } }
true
2c926532db37ee8574b80342e3a1eb4da49906d7
PHP
paultxr/upload_quest
/upload.php
UTF-8
2,531
3.0625
3
[]
no_license
<?php if(!empty($_FILES['photos']['name'][0])) { $photos = $_FILES['photos']; $uploaded = array(); $failed =array(); $allowed = array('jpg', 'png', 'gif'); foreach($photos['name'] as $position => $photo_name) { $photo_tmp = $photos['tmp_name'][$position]; $photo_size = $photos['size'][$position]; $photo_error = $photos['error'][$position]; $photo_ext = explode('.', $photo_name); $photo_ext = strtolower(end($photo_ext)); if(in_array($photo_ext, $allowed)) { if($photo_error === 0) { if($photo_size <= 1048576) { $photo_name_new = uniqid("", true) . '.' .$photo_ext; $photo_destination = 'upload/' . $photo_name_new; if(move_uploaded_file($photo_tmp, $photo_destination)) { $uploaded[$position] = $photo_destination; } else { $failed[$position] = "[$photo_name] failed to upload"; } } else { $failed[$position] = "[$photo_name] is too large."; } } else { $failed[$position] = "[$photo_name] errored with code {$photo_error}"; } } else { $failed[$position] = "[{$photo_name}] file extension '{[$photo_ext}]' is not allowed !"; } }; // if (!empty($uploaded)) { // print_r($uploaded); // } // if(!empty($failed)) { // print_r($failed); // } } $photos = new FilesystemIterator(__DIR__.'/upload', FilesystemIterator::SKIP_DOTS); // var_dump($photos); die; ?> <!DOCTYPE html> <html lang="fr"> <head> <meta charset="UTF-8"> <title>Formulaire d'upload de fichiers</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <h2>Upload File</h2> <label for="fileUpload">Fichier:</label> <input type="file" name="photos[]" multiple> <input type="submit" name="submit" value="Upload"> <p></p><strong>Note:</strong> Only .jpg, .jpeg, .jpeg, .gif, .png are authorized until 1 Mo.</p> </form> <div> <?php foreach($photos as $photo) { // var_dump($photo); die; ?> <img src='upload/<?= $photo->getFileName();?>' alt=""> <figcaption><?= $photo->getFilename()?></figcaption> <?php } ?> </div> </body> </html>
true
e9e9a03aa2b56289f756cd9285f8e7a784369f2e
PHP
luigif/WsdlToPhp
/samples/directsmile/Authenticate/DirectSmileServiceAuthenticate.php
UTF-8
2,626
2.796875
3
[]
no_license
<?php /** * Class file for DirectSmileServiceAuthenticate * @date 02/08/2012 */ /** * Class DirectSmileServiceAuthenticate * @date 02/08/2012 */ class DirectSmileServiceAuthenticate extends DirectSmileWsdlClass { /** * Method to call Authenticate * Meta informations : * - documentation : Standard Authentication. Initiates a session. All mathod names that don't end with -Auth or -DSM demand a valid session. * @uses DirectSmileWsdlClass::getSoapClient() * @uses DirectSmileWsdlClass::setResult() * @uses DirectSmileWsdlClass::getResult() * @uses DirectSmileWsdlClass::saveLastError() * @uses DirectSmileTypeAuthenticate::getUserName() * @uses DirectSmileTypeAuthenticate::getPassword() * @uses DirectSmileTypeAuthenticate::getLanguage() * @param DirectSmileTypeAuthenticate Authenticate * @return DirectSmileTypeAuthenticateResponse */ public function Authenticate(DirectSmileTypeAuthenticate $_DirectSmileTypeAuthenticate) { try { $this->setResult(self::getSoapClient()->Authenticate(array('UserName'=>$_DirectSmileTypeAuthenticate->getUserName(),'Password'=>$_DirectSmileTypeAuthenticate->getPassword(),'Language'=>$_DirectSmileTypeAuthenticate->getLanguage()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method to call AuthenticateDSM * Meta informations : * - documentation : DSM internal Authentication. * @uses DirectSmileWsdlClass::getSoapClient() * @uses DirectSmileWsdlClass::setResult() * @uses DirectSmileWsdlClass::getResult() * @uses DirectSmileWsdlClass::saveLastError() * @uses DirectSmileTypeAuthenticateDSM::getUserName() * @uses DirectSmileTypeAuthenticateDSM::getPassword() * @param DirectSmileTypeAuthenticateDSM AuthenticateDSM * @return DirectSmileTypeAuthenticateDSMResponse */ public function AuthenticateDSM(DirectSmileTypeAuthenticateDSM $_DirectSmileTypeAuthenticateDSM) { try { $this->setResult(self::getSoapClient()->AuthenticateDSM(array('UserName'=>$_DirectSmileTypeAuthenticateDSM->getUserName(),'Password'=>$_DirectSmileTypeAuthenticateDSM->getPassword()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method returning the result content * * @return DirectSmileTypeAuthenticateResponse|DirectSmileTypeAuthenticateDSMResponse */ public function getResult() { return parent::getResult(); } /** * Method returning the class name * * @return string __CLASS__ */ public function __toString() { return __CLASS__; } } ?>
true
0dee15f60e91b3ba52870d981d987b9308e753d2
PHP
vnatco/posts
/php/mysql.class.php
UTF-8
23,645
2.671875
3
[ "Apache-2.0" ]
permissive
<?php class MySQL{ private $db; private $user; public function __construct(&$db,&$user){ $this->db=$db; $this->user=$user; } ///////////////////////////////////////////////////////////////////// // Get public function GetSharedId(){ $id=Functions::GenerateRandomString(8); while($this->db->query("SELECT `SHARED_ID` from `post` WHERE `SHARED_ID`='".preg_replace("/[^a-zA-Z0-9\_\-]/","",$id)."'")->fetch()!==false) $id=Functions::GenerateRandomString(8); return $id; } public function GetColors(){ $sth=$this->db->prepare("SELECT * FROM `color`"); $sth->execute(array()); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetProjects(){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `ID`, `pro`.`NAME` AS `NAME` FROM `project` `pro` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` WHERE (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `cli`.`NAME` ASC,`pro`.`NAME` ASC "); $sth->execute(array($this->user['ID'])); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetPersonalProject(){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `ID`, `pro`.`NAME` AS `NAME` FROM `project` `pro` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` WHERE `pro`.`OWNER_ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 LIMIT 0,1 "); $sth->execute(array($this->user['ID'],$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } public function GetProjectById($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `ID`, `pro`.`NAME` AS `NAME` FROM `project` `pro` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` WHERE `pro`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 LIMIT 0,1 "); $sth->execute(array($id,$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } public function GetCategoryById($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `cat`.`ID` AS `ID`, `cat`.`ORDER` AS `ORDER`, `cat`.`NAME` AS `NAME`, `cat`.`CREATED_AT` AS `CREATED_AT`, `cat`.`UPDATED_AT` AS `UPDATED_AT` FROM `category` `cat` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `cat`.`IS_VISIBLE`=1 AND `cat`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `cat`.`ORDER`,`cat`.`NAME` "); $sth->execute(array($id,$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } public function GetCategoriesByProjectId($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `cat`.`ID` AS `ID`, `cat`.`ORDER` AS `ORDER`, `cat`.`NAME` AS `NAME`, `cat`.`CREATED_AT` AS `CREATED_AT`, `cat`.`UPDATED_AT` AS `UPDATED_AT` FROM `category` `cat` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `cat`.`IS_VISIBLE`=1 AND `pro`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `cat`.`ORDER`,`cat`.`NAME` "); $sth->execute(array($id,$this->user['ID'])); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetGroupsByCategoryId($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `ID`, `grp`.`ORDER` AS `ORDER`, `grp`.`NAME` AS `NAME`, `grp`.`CREATED_AT` AS `CREATED_AT`, `grp`.`UPDATED_AT` AS `UPDATED_AT` FROM `group` `grp` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `cat`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `grp`.`ORDER`,`grp`.`NAME` "); $sth->execute(array($id,$this->user['ID'])); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetGroupById($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `ID`, `grp`.`NAME` AS `NAME`, `grp`.`CREATED_AT` AS `CREATED_AT`, `grp`.`UPDATED_AT` AS `UPDATED_AT` FROM `group` `grp` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `grp`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `grp`.`ORDER`,`grp`.`NAME` "); $sth->execute(array($id,$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } public function GetPostsByGroupId($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `ID`, `post`.`ORDER` AS `ORDER`, `post`.`NAME` AS `NAME`, `post`.`CREATED_AT` AS `CREATED_AT`, `post`.`UPDATED_AT` AS `UPDATED_AT` FROM `post` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `grp`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `post`.`ORDER`,`post`.`NAME` "); $sth->execute(array($id,$this->user['ID'])); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetPostById($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `ID`, `post`.`SHARED_ID` AS `SHARED_ID`, `post`.`ORDER` AS `ORDER`, `post`.`NAME` AS `NAME`, `post`.`CREATED_AT` AS `CREATED_AT`, `post`.`UPDATED_AT` AS `UPDATED_AT` FROM `post` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `post`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 LIMIT 0,1 "); $sth->execute(array($id,$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } public function GetSharedPostById($id){ $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `ID`, `post`.`SHARED_ID` AS `SHARED_ID`, `post`.`ORDER` AS `ORDER`, `post`.`NAME` AS `NAME`, `post`.`CREATED_AT` AS `CREATED_AT`, `post`.`UPDATED_AT` AS `UPDATED_AT` FROM `post` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `post`.`SHARED_ID`=? LIMIT 0,1 "); $sth->execute(array($id)); if($row=$sth->fetch()) return $row; else return false; } public function GetFieldsByPostId($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `POST_ID`, `post`.`NAME` AS `POST_NAME`, `type`.`ID` AS `TYPE_ID`, `type`.`NAME` AS `TYPE_NAME`, `field`.`ID` AS `ID`, `field`.`ORDER` AS `ORDER`, `field`.`CONTENT` AS `CONTENT`, `field`.`META` AS `META`, `field`.`CREATED_AT` AS `CREATED_AT`, `field`.`UPDATED_AT` AS `UPDATED_AT` FROM `post_field` `field` LEFT JOIN `post_field_type` `type` ON `type`.`ID`=`field`.`TYPE_ID` LEFT JOIN `post` ON `post`.`ID`=`field`.`POST_ID` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `field`.`IS_VISIBLE`=1 AND `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `post`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 ORDER BY `field`.`ORDER` "); $sth->execute(array($id,$this->user['ID'])); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetFieldsBySharedPostId($id){ $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `POST_ID`, `post`.`NAME` AS `POST_NAME`, `type`.`ID` AS `TYPE_ID`, `type`.`NAME` AS `TYPE_NAME`, `field`.`ID` AS `ID`, `field`.`ORDER` AS `ORDER`, `field`.`CONTENT` AS `CONTENT`, `field`.`META` AS `META`, `field`.`CREATED_AT` AS `CREATED_AT`, `field`.`UPDATED_AT` AS `UPDATED_AT` FROM `post_field` `field` LEFT JOIN `post_field_type` `type` ON `type`.`ID`=`field`.`TYPE_ID` LEFT JOIN `post` ON `post`.`ID`=`field`.`POST_ID` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `field`.`IS_VISIBLE`=1 AND `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `post`.`SHARED_ID`=? ORDER BY `field`.`ORDER` "); $sth->execute(array($id)); $rows=$sth->fetchAll(); if(!is_array($rows)||count($rows)>0) return $rows; else return false; } public function GetFieldById($id){ if($this->user===false) return false; $sth=$this->db->prepare(" SELECT `cli`.`ID` AS `CLIENT_ID`, `cli`.`NAME` AS `CLIENT_NAME`, `pro`.`ID` AS `PROJECT_ID`, `pro`.`NAME` AS `PROJECT_NAME`, `cat`.`ID` AS `CATEGORY_ID`, `cat`.`NAME` AS `CATEGORY_NAME`, `col`.`ID` AS `COLOR_ID`, `col`.`NAME` AS `COLOR_NAME`, `col`.`CLASS` AS `COLOR_CLASS`, `grp`.`ID` AS `GROUP_ID`, `grp`.`NAME` AS `GROUP_NAME`, `post`.`ID` AS `POST_ID`, `post`.`NAME` AS `POST_NAME`, `type`.`ID` AS `TYPE_ID`, `type`.`NAME` AS `TYPE_NAME`, `field`.`ID` AS `ID`, `field`.`ORDER` AS `ORDER`, `field`.`CONTENT` AS `CONTENT`, `field`.`META` AS `META`, `field`.`CREATED_AT` AS `CREATED_AT`, `field`.`UPDATED_AT` AS `UPDATED_AT` FROM `post_field` `field` LEFT JOIN `post_field_type` `type` ON `type`.`ID`=`field`.`TYPE_ID` LEFT JOIN `post` ON `post`.`ID`=`field`.`POST_ID` LEFT JOIN `group` `grp` ON `grp`.`ID`=`post`.`GROUP_ID` LEFT JOIN `category` `cat` ON `cat`.`ID`=`grp`.`CATEGORY_ID` LEFT JOIN `project` `pro` ON `pro`.`ID`=`cat`.`PROJECT_ID` LEFT JOIN `client` `cli` ON `cli`.`ID`=`pro`.`CLIENT_ID` LEFT JOIN `color` `col` ON `col`.`ID`=`cat`.`COLOR_ID` WHERE `field`.`IS_VISIBLE`=1 AND `post`.`IS_VISIBLE`=1 AND `grp`.`IS_VISIBLE`=1 AND `cat`.`IS_VISIBLE`=1 AND `field`.`ID`=? AND (SELECT COUNT(*) from `user_project_access` `upa` WHERE `upa`.`PROJECT_ID`=`pro`.`ID` AND `upa`.`USER_ID`=?)!=0 LIMIT 0,1 "); $sth->execute(array($id,$this->user['ID'])); if($row=$sth->fetch()) return $row; else return false; } ///////////////////////////////////////////////////////////////////// // Insert public function InsertCategory($project_id,$title,$color_id){ if($this->user===false) return false; $project=$this->GetProjectById($project_id); if(!$project) return false; $sth=$this->db->prepare("INSERT into `category` (`ORDER`,`PROJECT_ID`,`COLOR_ID`,`NAME`,`IS_VISIBLE`,`CREATED_AT`) VALUES ((SELECT IFNULL(MAX(`ORDER`),1) FROM `category` `c2` WHERE `c2`.`PROJECT_ID`=?)+1,?,?,?,1,NOW())"); $sth->execute(array($project['ID'],$project['ID'],$color_id,$title)); return $this->db->lastInsertId(); } public function InsertGroup($category_id,$title){ if($this->user===false) return false; $category=$this->GetCategoryById($category_id); if(!$category) return false; $sth=$this->db->prepare("INSERT into `group` (`ORDER`,`CATEGORY_ID`,`NAME`,`IS_VISIBLE`,`CREATED_AT`) VALUES ((SELECT IFNULL(MAX(`ORDER`),1) FROM `group` `g2` WHERE `g2`.`CATEGORY_ID`=?)+1,?,?,1,NOW())"); $sth->execute(array($category['ID'],$category['ID'],$title)); return $this->db->lastInsertId(); } public function InsertPost($group_id,$title){ if($this->user===false) return false; $group=$this->GetGroupById($group_id); if(!$group) return false; $sharedId=$this->GetSharedId(); $sth=$this->db->prepare("INSERT into `post` (`SHARED_ID`,`ORDER`,`GROUP_ID`,`NAME`,`IS_VISIBLE`,`CREATED_AT`) VALUES (?,(SELECT IFNULL(MAX(`ORDER`),1) FROM `post` `p2` WHERE `p2`.`GROUP_ID`=?)+1,?,?,1,NOW())"); $sth->execute(array($sharedId,$group['ID'],$group['ID'],$title)); return $this->db->lastInsertId(); } public function InsertField($post_id,$type_id,$content,$meta){ if($this->user===false) return false; $post=$this->GetPostById($post_id); if(!$post) return false; $sth=$this->db->prepare("INSERT into `post_field` (`ORDER`,`POST_ID`,`TYPE_ID`,`CONTENT`,`META`,`IS_VISIBLE`,`CREATED_AT`) VALUES ((SELECT IFNULL(MAX(`ORDER`),1) FROM `post_field` `pf2` WHERE `pf2`.`POST_ID`=?)+1,?,?,?,?,1,NOW())"); $sth->execute(array($post['ID'],$post['ID'],$type_id,$content,$meta)); return $this->db->lastInsertId(); } ///////////////////////////////////////////////////////////////////// // Update public function UpdateCategory($id,$title,$color_id){ if($this->user===false) return false; $category=$this->GetCategoryById($id); if(!$category) return false; $sth=$this->db->prepare("UPDATE `category` SET `COLOR_ID`=?,`NAME`=? WHERE `ID`=?"); $sth->execute(array($color_id,$title,$category['ID'])); return true; } public function UpdateGroup($id,$title){ if($this->user===false) return false; $group=$this->GetGroupById($id); if(!$group) return false; $sth=$this->db->prepare("UPDATE `group` SET `NAME`=? WHERE `ID`=?"); $sth->execute(array($title,$group['ID'])); return true; } public function UpdatePost($id,$title){ if($this->user===false) return false; $post=$this->GetPostById($id); if(!$post) return false; $sth=$this->db->prepare("UPDATE `post` SET `NAME`=? WHERE `ID`=?"); $sth->execute(array($title,$post['ID'])); return true; } public function UpdateField($id,$content,$meta){ if($this->user===false) return false; $field=$this->GetFieldById($id); if(!$field) return false; $sth=$this->db->prepare("UPDATE `post_field` SET `CONTENT`=?,`META`=? WHERE `ID`=?"); $sth->execute(array($content,$meta,$field['ID'])); return true; } ///////////////////////////////////////////////////////////////////// // Delete public function DeleteCategory($id){ if($this->user===false) return false; $category=$this->GetCategoryById($id); if(!$category) return false; $sth=$this->db->prepare("DELETE FROM `category` WHERE `ID`=?"); $sth->execute(array($category['ID'])); return true; } public function DeleteGroup($id){ if($this->user===false) return false; $group=$this->GetGroupById($id); if(!$group) return false; $sth=$this->db->prepare("DELETE FROM `group` WHERE `ID`=?"); $sth->execute(array($group['ID'])); return true; } public function DeletePost($id){ if($this->user===false) return false; $post=$this->GetPostById($id); if(!$post) return false; $sth=$this->db->prepare("DELETE FROM `post` WHERE `ID`=?"); $sth->execute(array($post['ID'])); return true; } public function DeleteField($id){ if($this->user===false) return false; $field=$this->GetFieldById($id); if(!$field) return false; $sth=$this->db->prepare("DELETE FROM `post_field` WHERE `ID`=?"); $sth->execute(array($field['ID'])); return true; } ///////////////////////////////////////////////////////////////////// // Delete public function ReOrderCategory($project_id,$ids){ if($this->user===false) return false; if(!is_array($ids)) return false; $categories=$this->GetCategoriesByProjectId($project_id); if(!$categories) return false; foreach($categories as $category){ if(($order=array_search($category['ID'],$ids))!==false&&($order+1)!=$category['ORDER']){ $this->db->prepare("UPDATE `category` SET `ORDER`=? WHERE `ID`=?")->execute(array(($order+1),$category['ID'])); } } } public function ReOrderGroup($category_id,$ids){ if($this->user===false) return false; if(!is_array($ids)) return false; $groups=$this->GetGroupsByCategoryId($category_id); if(!$groups) return false; foreach($groups as $group){ if(($order=array_search($group['ID'],$ids))!==false&&($order+1)!=$group['ORDER']){ $this->db->prepare("UPDATE `group` SET `ORDER`=? WHERE `ID`=?")->execute(array(($order+1),$group['ID'])); } } } public function ReOrderPost($group_id,$ids){ if($this->user===false) return false; if(!is_array($ids)) return false; $posts=$this->GetPostsByGroupId($group_id); if(!$posts) return false; foreach($posts as $post){ if(($order=array_search($post['ID'],$ids))!==false&&($order+1)!=$post['ORDER']){ $this->db->prepare("UPDATE `post` SET `ORDER`=? WHERE `ID`=?")->execute(array(($order+1),$post['ID'])); } } } public function ReOrderField($post_id,$ids){ if($this->user===false) return false; if(!is_array($ids)) return false; $fields=$this->GetFieldsByPostId($post_id); if(!$fields) return false; foreach($fields as $field){ if(($order=array_search($field['ID'],$ids))!==false&&($order+1)!=$field['ORDER']){ $this->db->prepare("UPDATE `post_field` SET `ORDER`=? WHERE `ID`=?")->execute(array(($order+1),$field['ID'])); } } } } ?>
true
37d1ba2ff6b225e9390a7ca60af84f2bca944473
PHP
codingXllama/iParkIt
/admin/includes/edit_parking.php
UTF-8
2,674
2.671875
3
[]
no_license
<?php if (isset($_GET['p_id'])) { } // finding all the posts -> Parkings $query = "SELECT * FROM posts"; $select_posts_by_id = mysqli_query($connection, $query); // Displaying the content in the db while ($row = mysqli_fetch_assoc($select_posts_by_id)) { $parking_id = $row['post_id']; $parking_title = $row['post_title']; $parking_image = $row['post_image']; $parking_status = $row['post_status']; $parking_region = $row['post_location']; $parking_price = $row['post_price']; $parking_admin = $row['post_author']; $parking_request_count = $row['post_comment_count']; $parking_start = $row['post_start']; $parking_end = $row['post_end']; $parking_date = $row['post_date']; } ?> <form action="" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="title">Parking Title</label> <input value="<?php echo $parking_title; ?>" type="text" class="form-control" name="parking_title"> </div> <div class="form-group"> <label for="title">Parking Region ID</label> <input type="text" class="form-control" name="parking_region_id"> </div> <div class="form-group"> <label for="parking_region">Parking Region</label> <input value="<?php echo $parking_region; ?>" type="text" class="form-control" name="parking_region"> </div> <div class="form-group"> <label for="parking_admin">Parking Admin</label> <input value="<?php echo $parking_admin; ?>" type=" text" class="form-control" name="parking_admin"> </div> <div class=" form-group"> <label for="parking_status">Parking Status</label> <input type="text" class="form-control" name="parking_status"> </div> <div class="form-group"> <label for="parking_image">Parking Image</label> <input value="<?php echo $parking_image; ?>" type="file" class="form-control" name="image"> </div> <!-- Start and End Time for the parking slot --> <div class=" form-group"> <label for="startTime">Start Time: </label> <input id=" startTime" type="time" name="startTime" value="<?php echo $startTime; ?>"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span> <label for="endTime">End Time: </label> <input id=" endTime" type="time" name="endTime"> </span> </div> <div class="form-group"> <label for="title">Parking Tags</label> <input type="text" class="form-control" name="parking_tags"> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" name="create_parking"> </div> </form>
true
54afc6f961cf74f725b0f4ca9ae86fc3800e9ba5
PHP
charlinedns/videotheque
/templates/filmsDetails.html.php
UTF-8
496
2.53125
3
[]
no_license
<?php $filmDetails = Film::displayFilm($id); foreach ($filmDetails as $value) { ?> <div class='card border-primary mb-3' style='max-width: 20rem;'> <div class='card-header'><?= $value['genres'] ?> </div> <div class='card-body'> <h4 class='card-title'><?= $value["title"] ?><br /><small class='text-muted'><?= $value['year'] ?></small> </h4> <p class='card-text'><?= $value['plot'] ?></p> </div> </div> <?php } ?>
true
68a3275cd6d5b4dc9533d1cdbeb09af2efa9df1f
PHP
AaronSchulz/WikiDataQueryOrient
/lib/WdqQueryEngine.php
UTF-8
2,767
2.9375
3
[ "MIT" ]
permissive
<?php class WdqQueryEngine { /** @var MultiHttpClient */ protected $http; /** @var string */ protected $url; /** @var string */ protected $user; /** @var string */ protected $password; /** @var string */ protected $sessionId; /** * @param MultiHttpClient $http * @param string $url * @param string $user * @param string $password */ public function __construct( MultiHttpClient $http, $url, $user, $password ) { $this->http = $http; $this->url = $url; $this->user = $user; $this->password = $password; } /** * Issue a WDQ query and return the results * * @param string $query * @param integer $timeout Seconds * @param integer $limit Maximum record * @return array */ public function query( $query, $timeout = 5000, $limit = 1e9 ) { $sql = WdqQueryParser::parse( $query, $timeout, $limit ); $req = array( 'method' => 'GET', 'url' => "{$this->url}/query/WikiData/sql/" . rawurlencode( $sql ) . "/$limit", 'headers' => array( 'Cookie' => "OSESSIONID={$this->getSessionId()}" ) ); list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( $req ); if ( $rcode == 401 ) { // Session probably expired; renew $this->sessionId = null; $req['headers']['Cookie'] = "OSESSIONID={$this->getSessionId()}"; list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( $req ); } $results = array(); $response = json_decode( $rbody, true ); if ( $response === null ) { throw new Exception( "HTTP error ($rcode): could not decode response ($rerr).\n\n" ); } else { $count = 0; foreach ( $response['result'] as $record ) { ++$count; $obj = array(); foreach ( $record as $key => $value ) { if ( $key === '*depth' ) { $obj[$key] = $value / 2; // only count vertex steps } elseif ( $key === '*timevalue' ) { $obj['*value'] = WdqUtils::getISO8601FromUnixTime( $value ); } elseif ( $key[0] !== '@' ) { $obj[$key] = $value; } } $results[] = $obj; } } return $results; } /** * @return string * @throws Exception */ protected function getSessionId() { if ( $this->sessionId !== null ) { return $this->sessionId; } $hash = base64_encode( "{$this->user}:{$this->password}" ); list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array( 'method' => 'GET', 'url' => "{$this->url}/connect/WikiData", 'headers' => array( 'Authorization' => "Basic " . $hash ) ) ); $m = array(); $ok = isset( $rhdrs['set-cookie'] ); if ( $ok && preg_match( '/(?:^|;)OSESSIONID=([^;]+);/', $rhdrs['set-cookie'], $m ) ) { $this->sessionId = $m[1]; } else { throw new Exception( "Invalid authorization credentials ($rcode).\n" ); } return $this->sessionId; } }
true
3bf2551eb65c2438a2875f6cf62b0d3d05ab498c
PHP
Jorge-William/PHP-Orientado-a-Objetos
/class_constants.php
UTF-8
257
3.59375
4
[]
no_license
<?php class Clock { public const DAY_IN_SECOUNDS = 60 * 60 * 24; public function tomorrow(){ return time() + self::DAY_IN_SECOUNDS; } } echo Clock::DAY_IN_SECOUNDS . "<br />"; echo Clock::tomorrow();
true
5f8ac40286cdc9e6c7f21db4e7851a4ebefa253d
PHP
kaleseverin/UW-courses
/comment/comment.php
UTF-8
1,740
2.5625
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>Comment function</title> <!-- <script src="https://ajax.googleapis.com/ajax/libs/prototype/1.7.0.0/prototype.js" type="text/javascript"></script> --> <script src="comment.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="comment.css" /> </head> <body> <h2>User Comments and Ratings</h2> <div id="quote"> <?php $users = file("professor2.txt", FILE_IGNORE_NEW_LINES); foreach ($users as $user) { $userinfo = explode(",", $user); $name = $userinfo[0]; $comment = $userinfo[1]; $star = $userinfo[2]; ?> <div class="comments"> <div class="comment"><p><?= $comment ?></p></div> <div class="star"><p><?= $star ?> stars</p></div> <div class="reviewer"><p>--<?= $name ?></p></div> </div> <?php } ?> </div> <form action="comment-submit.php" method="post"> <fieldset> <legend>Add Your Comment!</legend> <div> Your Name<input type="text" name="name" id="name" /> </div> <div>Your Comment: <textarea name="comment" rows="10" cols="50" id="comment"></textarea> </div> <div> Rate Your Professor: <select name="star" id="star"> <option value="no rating" checked="checked"></option> <option value="5">5</option> <option value="4">4</option> <option value="3">3</option> <option value="2">2</option> <option value="1">1</option> </select> stars </div> <input type="hidden" name="professor" value="professor" /> <div> <input type="submit" name="submit" id="submit" value="Submit Comment" /> </div> </fieldset> </form> </body> </html>
true
049ca12b664d0fbb142139b98576e3fef3f7daef
PHP
insomynwa/scoreboard
/controller/live-game-controller-class.php
UTF-8
12,974
2.71875
3
[]
no_license
<?php namespace scoreboard\controller; use scoreboard\config\Database; use scoreboard\includes\Tools; use scoreboard\model\Gameset_Model_Class; use scoreboard\model\Live_Game_Model_Class; use scoreboard\model\Player_Model_Class; use scoreboard\model\Score_Model_Class; use scoreboard\model\Team_Model_Class; class Live_Game_Controller_Class extends Controller_Class { private $connection; private $model = null; private $live_template_name = ''; private $live_template_loc = ''; private $root_key; private $scoreboard_key; /** * Class Constructor * * @param obj $connection * @return void */ public function __construct($connection = null) { $this->connection = $connection; $this->model = new Live_Game_Model_Class($connection); $this->root_key = 'livegame'; $this->scoreboard_key = 'scoreboard'; $this->init_templates(); } /** * Get Game Set ID * * Can be used to check if there is a live game * * @param boolean $live_check For live check * @return integer|boolean If $live_check is TRUE, return boolean */ public function get_gameset_id($live_check = false) { return $this->model->gameset_id($live_check); } /** * Has Live Game * * @return boolean */ public function has_live_game(){ return $this->model->gameset_id(true); } private function init_templates() { $template_loc = TEMPLATE_DIR . 'scoreboard/'; $this->live_template_name = 'live'; $this->live_template_loc = $template_loc . $this->live_template_name . '.php'; } /** * Get Live Game Bowstyle ID * * @return integer bowstyle ID */ public function get_game_bowstyle_id() { return $this->model->game_bowstyle_id(); } /** * Get Game Data (Bowstyle ID & Gamemode ID) * * @return array */ public function get_game_data_bm_id(){ return $this->model->game_data_bm_id(); } /** * Get Live Style Bowstyle ID * * @return integer bowstyle ID */ public function style_bowstyle_id(){ $action_m = $this->model->get_style_bowstyle_id(); $this->has_live_style = $action_m > 0; return $action_m; } /** * Get Live Style Bowstyle ID * * @return integer bowstyle ID */ public function get_style_bowstyle_id(){ $action_m = $this->model->get_style_bowstyle_id(); $this->has_live_style = $action_m > 0; return $action_m; } /** * Get Live Style ID * * @return integer */ public function style_id(){ $action_m = $this->model->get_style_id(); $this->has_live_style = $action_m > 0; return $action_m; } /** * Remove Live Style * * @return void */ public function remove_live_style(){ $this->model->clean_style(); } /** * Set Live Game * * @return void */ public function set_live_game($gameset_id=0){ return $this->model->set_live_game($gameset_id); } /** * Set Live Style * * @param integer $style_id * @return array */ public function set_live_style($style_id=0){ $result = [ 'status' => false]; if( $style_id==0 ) { $result['message'] = 'ERROR: Style ID : 0'; return $result; } $live_game_bowstyle_id = $this->get_game_bowstyle_id(); $scoreboard_style_oc = new Scoreboard_Style_Controller_Class($this->connection); if( ($live_game_bowstyle_id != 0) && ($live_game_bowstyle_id != $scoreboard_style_oc->get_bowstyle_id($style_id))){ $result['message'] = 'Wrong Style for the Game!'; return $result; } return [ 'status' => $this->model->set_style($style_id) ]; } /** * Set Live Style * * @param integer $style_id Style ID * @return boolean */ public function set_style($style_id=0){ return $this->model->set_style($style_id); } /** * Create Default Live Game * * @return boolean */ public function create_default() { if (!$this->model->has_default()) { $default_data = [ 'id' => 1, 'gameset_id' => 0, 'style_id' => 0, ]; $this->model->create_default($default_data); } return true; } /** * Check if Gameset is live * * @param array|integer Gameset ID * @return boolean */ public function is_gameset_live($gameset_id){ if(is_array($gameset_id)){ if(empty($gameset_id)) return false; return in_array($this->get_gameset_id(),$gameset_id); } else if( is_numeric($gameset_id) || is_int($gameset_id) ){ if( $gameset_id == 0 ) return false; return ($gameset_id == $this->get_gameset_id()); } return false; } /** * Start Game * * @param integer $gameset_id Gameset ID * @return array result */ public function start_game($gameset_id=0){ $result = [ 'status' => false ]; if( $gameset_id==0) return $result; // var_dump($gameset_id);die; $prev_live_gameset_id = $this->get_gameset_id(); $gameset_oc = new Gameset_Controller_Class($this->connection); if($prev_live_gameset_id != 0){ if( ! $gameset_oc->set_update_status($prev_live_gameset_id, 1)) { $result['message'] = 'ERROR: start_game set_update_status'; return $result; } } if( ! $gameset_oc->set_update_status($gameset_id, 2)) { $result['message'] = 'ERROR: start_game set_update_status'; return $result; } if( !$this->set_live_game($gameset_id)){ $result['message'] = 'ERROR: start_game set_live_game'; return $result; } $new_game_bowstyle_id = $gameset_oc->get_bowstyle_id($gameset_id); if( !$new_game_bowstyle_id ){ $result['message'] = 'ERROR: start_game get_bowstyle_id'; return $result; } $prev_style_bowstyle_id = $this->get_style_bowstyle_id(); if( $new_game_bowstyle_id != $prev_style_bowstyle_id){ if (!$this->set_style(0)) { $result['message'] = 'ERROR: start_game set_style'; return $result; } } $result['status'] = true; return $result; } /** * Stop live Game * * @param integer $gameset_id Gameset ID * @return array result */ public function stop_game($gameset_id = 0){ $result = [ 'status' => false ]; if( $gameset_id==0) return $result; $gameset_oc = new Gameset_Controller_Class($this->connection); if( ! $gameset_oc->set_update_status($gameset_id, 1)) { $result['message'] = 'ERROR: start_game set_update_status'; return $result; } if( !$this->set_live_game(0)){ $result['message'] = 'ERROR: start_game set_live_game'; return $result; } $result['status'] = true; return $result; } /** * Get Scoreboard * * @return array */ public function get_scoreboard_deprecated(){ $result = [ 'status' => false ]; $gameset_id = $this->get_gameset_id(); if( $gameset_id == 0){ $result['message'] = 'No Live Game'; return $result; } if($this->style_id() == 0) { $result['message'] = 'No live Style'; return $result; } $score_oc = new Score_Controller_Class($this->connection); $scoreboard_data = $score_oc->get_scoreboard_data(); if( ! empty($scoreboard_data )) { $scores = $scoreboard_data['scores']; $gamemode_id = $scores['gamemode_id']; $contestant_oc = null; if( $gamemode_id == 1){ $contestant_oc = new Team_Controller_Class($this->connection); } else if( $gamemode_id == 2) { $contestant_oc = new Player_Controller_Class($this->connection); } for ($i=0; $i < sizeof($scores['contestants']); $i++){ $scores['contestants'][$i]['logo'] = 'uploads/no-image.png'; $scores['contestants'][$i]['team'] = '-'; $scores['contestants'][$i]['player'] = '-'; $scoreboard_form_data = $contestant_oc->get_scoreboard_form_data($scores['contestants'][$i]['id']); if( $scoreboard_form_data ){ $scores['contestants'][$i]['logo'] = 'uploads/' . $scoreboard_form_data['team_logo']; $scores['contestants'][$i]['team'] = $scoreboard_form_data['team_name']; if( $scores['gamemode_id'] == 1 ){ $scores['contestants'][$i]['player'] = '-'; }else if( $scores['gamemode_id'] == 2){ $scores['contestants'][$i]['player'] = $scoreboard_form_data['player_name']; } } } $data_scores['gamemode_id'] = $gamemode_id; $data_scores['bowstyle_id'] = $scores['bowstyle_id']; $data_scores['sets'] = $scores['sets']; $data_scores['contestants'] = $scores['contestants']; $data_scores['style_config'] = json_decode($scores['style_config'], true); $style_config = ''; $style_config .= Tools::template($this->live_template_loc, $data_scores); $result['style_config'] = $style_config; } $result['status'] = true; return $result; } /** * Get Scoreboard * * @return mixed */ private function get_scoreboard(){ $res = array(); if( $this->model->is_ready() ) { $score_oc = new Score_Controller_Class($this->connection); $scoreboard_data = $score_oc->get_scoreboard_data(); $style_config = json_decode( $scoreboard_data['style_config'], true); $formatted_style_config = array(); foreach ($style_config as $key => $value) { foreach($value as $vkey => $vval ){ if($vkey == 'visibility_class' ){ $formatted_style_config[$key . '_vc' ] = $vval; } } } $scoreboard_data['style_config'] = $formatted_style_config; $res = $scoreboard_data; } return $res; } /** * Get Data * * @param array $req_data * @return array */ public function get_data($req_data = array( 'scoreboard' )){ $result = array(); $result[$this->root_key] = array(); $root_res = $result[$this->root_key]; $data = null; if(in_array($this->scoreboard_key,$req_data)){ $data = $this->get_scoreboard(); $root_res[$this->scoreboard_key] = $data; } $result[$this->root_key] = $root_res; return $result; } } if (isset($_POST['livegame_action'])) { $result = [ 'status' => true, ]; $request_name = 'livegame_action'; $request_value = $_POST[$request_name]; if (Tools::is_valid_string_request($request_value)) { $database = new Database(); $connection = $database->getConnection(); $live_game_oc = new Live_Game_Controller_Class($connection); $gameset_id = 0; $timer = 120; if( isset($_POST['gamesetid']) ){ $gameset_id = is_numeric($_POST['gamesetid']) ? $_POST['gamesetid'] : 0; } if ($request_value == 'stop-live-game') { $result = $live_game_oc->stop_game($gameset_id); } else if ($request_value == 'set-live-game') { $result = $live_game_oc->start_game($gameset_id); } $database->conn->close(); } echo json_encode($result); } if (isset($_GET['livegame_get'])) { $result = [ 'status' => true, ]; $request_name = 'livegame_get'; $request_value = $_GET[$request_name]; if (Tools::is_valid_string_request($request_value)) { $database = new Database(); $connection = $database->getConnection(); $live_game_oc = new Live_Game_Controller_Class($connection); if($request_value == 'scoreboard'){ // $result = $live_game_oc->get_scoreboard(); $live_game_data = $live_game_oc->get_data(['scoreboard']); $result = array_merge( $result, $live_game_data ); } $database->conn->close(); } echo json_encode($result); } ?>
true
500dbeea4f0b672dd918a21ca5e0096b430869cf
PHP
tomaj/prepositioner
/src/Prepositioner/Language/SlovakLanguage.php
UTF-8
792
2.640625
3
[]
no_license
<?php declare(strict_types=1); namespace Tomaj\Prepositioner\Language; class SlovakLanguage implements LanguageInterface { public function prepositions(): array { return [ /* 1 letter */ 'a', 'i', 'k', 'o', 'v', 'u', 'z', 's', /* 2 letter */ 'do', 'od', 'zo', 'ku', 'na', 'po', 'so', 'za', 'vo', 'či', /* 3 letter */ 'cez', 'pre', 'nad', 'pod', 'pri', /* 4 letter */ 'spod', 'pred', 'skrz', ]; } }
true
e8cf0f5611194d77ff0642660f73ddd727f64c30
PHP
gaetano1984/laravel-quake
/app/Console/Commands/updateEarthQuake.php
UTF-8
2,941
2.75
3
[ "MIT" ]
permissive
<?php namespace App\Console\Commands; use App\Services\quakeService; use Illuminate\Console\Command; use App\Services\locationService; use Symfony\Component\Console\Helper\ProgressBar; class updateEarthQuake extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'earthquake:update'; /** * The console command description. * * @var string */ protected $description = 'This command read list of earthquake and update list'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle(quakeService $quakeService, locationService $locationService) { // $header = ['Data', 'Luogo', 'magnitudo', 'latitudine', 'longitudine']; $header_location = ['Nome luogo']; $this->info('inizio a recuperare la lista dei terremoti'); $list = $quakeService->retrieveQuakeList(); $this->info('lista recuperata'); $to_save = $quakeService->getQuakeToSave($list); if(count($to_save)==0){ $this->error("non ci sono nuovi eventi da salvare"); return; } $this->info('controllo se devo salvare qualche location'); $location_to_save = $locationService->checkLocation($to_save); $table = []; if(count($location_to_save)>0){ $this->info("devo creare i seguenti ".count($location_to_save)." luoghi"); $bar = $this->output->createProgressBar(count($location_to_save)); $bar->start(); $bar->setRedrawFrequency(50); foreach ($location_to_save as $key => $location) { array_push($table, [$location]); $locationService->create($location); $bar->advance(); } $bar->finish(); $this->info("\nluoghi salvati"); } $this->info("\n"); if(count($table)>0){ $this->table($header_location, $table); } $this->info("devo salvare ".count($to_save)." eventi"); $table = []; if(count($to_save)>0){ $this->info('salvo i terremoti trovati'); $bar = $this->output->createProgressBar(count($to_save)); $bar->start(); $bar->setRedrawFrequency(50); foreach ($to_save as $key => $quake) { array_push($table, $quakeService->saveQuake($quake)); $bar->advance(); } $bar->finish(); } $this->info("\n"); if(count($table)>0){ $this->table($header, $table); } $this->info("\nprocedura terminata"); } }
true
e222662ad2e799edcd05ebc4b0d01cf4f8fbc72a
PHP
c4software/bts-sio
/.vuepress/public/demo/php/greta-tv/refactor-structure-mvc/utils/Gravatar.php
UTF-8
281
2.765625
3
[ "MIT" ]
permissive
<?php namespace utils; class Gravatar { static function get_gravatar($email, $s = 80, $d = 'mp', $r = 'g') { $url = 'https://www.gravatar.com/avatar/'; $url .= md5(strtolower(trim($email))); $url .= "?s=$s&d=$d&r=$r"; return $url; } }
true
93d3ff08627b1886199c6300b74e3fc1507d8ca7
PHP
anam5233/backend-projects
/work_shop/class_constant.php
UTF-8
262
3.078125
3
[]
no_license
<?php class WebcoachbdProduct { public $title = "default value"; const PI = "3.1416"; public function getTutorial($name) { echo "Webcoachbd provide massive tutorial on" . $name; } } $productObject = new WebcoachbdProduct(); echo $productObject::PI; ?>
true
fa3a6afd41bb682da38645a0bcf70df1834b216b
PHP
jbernie2/csc210final
/php/index.php
UTF-8
1,228
2.625
3
[]
no_license
<?php //display php errors on page ini_set('display_errors', 1); error_reporting(E_ALL); //allow for session variables to be used if(!isset($_SESSION)) { session_start(); } //functions that will allow the progams that the user has applied to to be displayed include_once "userProgramTable.php"; //check if user is logged in $loggedIn = isset($_SESSION['user_id']); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Grad to Go</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <script src="../js/login.js" type="text/javascript"></script> <script src="../js/updatePrograms.js" type="text/javascript"></script> <link rel="stylesheet" href="../css/ourStyle.css" type="text/css" /> </head> <body> <?php include_once('banner/banner.php'); ?> <?php if($loggedIn){ echo "<div id='response'> </div>"; getPrograms(); }else{ echo "<div id='homepage'>"; echo "<h2>Welcome to Grad to Go</h2>"; echo "</div>"; } ?> </body> </html>
true
efee101be0e10383b1aa58e330c69b0fce93640d
PHP
h-siegfried/efi-kzo-phpkurs
/17_db-insert/pages/insert.php
UTF-8
1,729
3.078125
3
[]
no_license
<?php $feedback = "Sie haben noch keine Daten gesendet."; // Das db_handler-Objekt erzeugen (ist bereits erledigt) try { $db_handler = new PDO('mysql:host=localhost;dbname=uebungsdb;charset=utf8', 'schuelerWeb', 'E2F0I1_k4zo'); } catch (PDOException $ex) { error_log($ex->getMessage()); print("<h3>Fehler bei der DB-Verbindung!</h3>"); print("<p>(Siehe php-error-log!)</p>"); exit(0); } /* * Kontrollieren Sie hier, ob schon Formulardaten gesendet worden sind. * * Wenn ja, kontrollieren Sie, ob alle Felder ausgefüllt worden sind. * * Wenn ja: * 0. Die DB-Verbindung mit dem PDO-Objekt ist bereits aufgebaut * und über die Variable $db_handler zugänglich. * 1. Formulieren Sie ein SQL-Statement mit Platzhaltern. * 2. Erzeugen Sie mit Ihrem SQL-Statement ein PDO-Statement-Objekt. * 3. «Binden» Sie mit bind_param die gesendeten Daten * an die Platzhalter des Statements * 4. Führen Sie das Statement aus. * 5. Kontrollieren Sie, ob MySQL dem neuen Datensatz * eine neue ID zugeteilt hat. Das ist das Zeichen dafür, * dass die Insert-Operation erfolgreich war. * 6. Weisen Sie der Variable $feedback einen Erfolgs-String zu. */ ?> <!DOCTYPE html> <html lang="de"> <head> <meta charset="utf-8"> <title>Personen eintragen</title> <link rel="stylesheet" href="../styles/styles.css"> </head> <body> <h1>Neue Personen in die Tabelle `person` eintragen</h1> <h2>Die Rückmeldung, ob der Eintrag funktioniert hat</h2> <?php // Hier geben wir nur noch den Inhalt der Variable $feedback aus: print($feedback); ?> <h2>Das Formular zum Eintragen</h2> <!-- Bauen Sie hier das Formular, in das wir eine neue Person eintragen können. --> </body> </html>
true
6139f40098019891ce8844138d9bfa4403aace3e
PHP
samanthayee18/349Midterm
/exam2.php
UTF-8
679
2.59375
3
[]
no_license
<!DOCTYPE html> <html> <body> <h1>MidTerm php connect&display</h1> <?php $conid = mysqli_connect("localhost", "root", "", "books") or die ("Cannot connect. " . mysqli_connect_errno() . " ". mysqli_connect_error()); echo "Connected. ". mysqli_get_host_info($conid). "<br />". "<br />"; $result = mysqli_query($conid, $query); if(!$result){ echo "Connection Failed. " . mysqli_error($conid); } else { echo "Query successful."; } mysqli_free_result($result); mysqli_close($conid); ?>
true
65f0392297a865643148480873e749750eebd475
PHP
bigjay517/Robot-Competition-Score-Keeper-Server
/update_team.php
UTF-8
1,616
2.859375
3
[]
no_license
<?php /* * Following code will update a team information * A product is identified by team id (id) */ // array for JSON response $response = array(); // check for required fields if (isset($_POST['id']) && isset($_POST['score']) && isset($_POST['touches'])) { $id = $_POST['id']; $score = $_POST['score']; $touches = $_POST['touches']; $track = $_POST['track']; $time = $_POST['time']; // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db = new DB_CONNECT(); $updated_at = date('Y-m-d H:i:s'); if($track == 0) { // mysql update row with matched id $result = mysql_query("UPDATE robocomp SET yellow_track_time = '$time', yellow_track_touches = '$touches', yellow_track_score = '$score', updated_at = '$updated_at' WHERE id = '$id'"); } else if ($track == 1) { $result = mysql_query("UPDATE robocomp SET blue_track_time = '$time', blue_track_touches = '$touches', blue_track_score = '$score', updated_at = '$updated_at' WHERE id = '$id'"); } else { // default to failure $result = 0; } // check if row inserted or not if ($result) { // successfully updated $response["success"] = 1; $response["message"] = "Team successfully updated."; // echoing JSON response echo json_encode($response); } else { } } else { // required field is missing $response["success"] = 0; $response["message"] = "Required field(s) is missing"; // echoing JSON response echo json_encode($response); } ?>
true
a8fec73260e74aa21805f9f78cd84f33dc12e339
PHP
kowal2499/sobczak-orders
/tests/Utilities/Factory/Definition/ProductFactory.php
UTF-8
626
2.5625
3
[]
no_license
<?php /** @author: Roman Kowalski */ namespace App\Tests\Utilities\Factory\Definition; use App\Entity\Product; use App\Tests\Utilities\Factory\FactoryDefinitionInterface; use Faker\Generator; class ProductFactory implements FactoryDefinitionInterface { public static function supports(): string { return Product::class; } public function defaultProperties(Generator $faker): array { return [ 'name' => $faker->word, 'description' => $faker->sentence(5), 'createDate' => new \DateTime(), 'factor' => $faker->randomFloat(2, 0, 1) ]; } }
true
6736700d4ef6d419ffd316c5b8c04709f81e768e
PHP
oxygen-cms/mod-pages
/src/Repository/PageRepositoryInterface.php
UTF-8
442
2.640625
3
[]
no_license
<?php namespace OxygenModule\Pages\Repository; use Oxygen\Core\Templating\TemplatableRepositoryInterface; use Oxygen\Data\Repository\RepositoryInterface; use OxygenModule\Pages\Entity\Page; interface PageRepositoryInterface extends RepositoryInterface, TemplatableRepositoryInterface { /** * Finds a Page based upon the slug. * * @param string $slug * @return Page */ public function findBySlug($slug); }
true