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
7e2a176acfe0e73608fc86f40a8986336bccd900
PHP
manwolf/test
/sicai/PHP/trunk/srvapi/framework/controller/JS_classStatistics.php
UTF-8
11,309
2.515625
3
[]
no_license
<?php include_once 'base/crudCtr.php'; /** * 功能:教师请假及课程安排 * 作者: 黄东 * 日期:2015年8月31日 */ class JS_classStatistics extends crudCtr { public function __construct() { $this->tablename = 'teacher_info'; } // 教师上课统计 ---教师端现在主页 function teacherIndex() { $msg = new responseMsg (); $capturs = $this->captureParams (); $prefixJS = $capturs ['callback']; $token = $capturs ['token']; $newrow = $capturs ['newrow']; $tid = $newrow ['tid']; $date = ($newrow ['date']); // 接受前端传来时间 date_default_timezone_set ( 'PRC' ); // 设置时区 $time = time (); // 获取当前时间 $nowTime = date ( "Y-m-d", $time ); // 获取服务器当前年月日 // 判断时间同步 if (date ( 'Ymd', strtotime ( $nowTime ) ) == date ( 'Ymd', strtotime ( $date ) ) && ! $date == null && ! $tid == null) { // if(1==1) // { $beginDate = date ( 'Y-m-01', strtotime ( date ( "Y-m-d" ) ) ); // 获取当月第一天 $endDateOne = date ( 'Y-m-d', strtotime ( "$beginDate +1 month -1 day" ) ); // 获取本月最后1天 // 判断老师所有剩余课时 家长未确认 $querySql = 'select count(user_confirm)*2 as information from class_list c ,order_list o, teacher_info t where t.tid=o.teacher_tid and o.tid=c.order_tid and user_confirm=0 and t.tid=' . $tid; $model = spClass ( $this->tablename ); $resultno = $model->findSql ( $querySql ); // 判断统计不超过本月 if (date ( 'Ymd', strtotime ( $date ) ) >= date ( 'Ymd', strtotime ( $beginDate ) ) && date ( 'Ymd', strtotime ( $date ) ) <= date ( 'Ymd', strtotime ( $endDateOne ) )) { // $querySql='select count(user_confirm) as classNum,count()'; // 当月老师已完成课时总数 $querySql = 'select count(user_confirm)*2 as information from class_list c ,order_list o, teacher_info t where t.tid=o.teacher_tid and o.tid=c.order_tid and user_confirm=1 and c.class_start_date>="'.$beginDate.'" and c.class_start_date<="'.$endDateOne.'" and t.tid=' . $tid; $model = spClass ( $this->tablename ); $resultyes = $model->findSql ( $querySql ); // $yes_class_num=$resultyes['0']['yes_class_num']; // 统计教师所有学生数 $querySql = 'select count(distinct user_tid) as information from order_list where teacher_tid=' . $tid; $model = spClass ( $this->tablename ); $resultuser = $model->findSql ( $querySql ); // $user_num= $resultuser['0']['user_num']; $result = array_merge ( $resultno, $resultyes, $resultuser ); if ($result) { $msg->ResponseMsg ( 0, 'sucsess', $result, 0, $prefixJS ); } else { $msg->ResponseMsg ( 1, 'fail', $result, 0, $prefixJS ); } } else { $msg->ResponseMsg ( 1, '日期不能超过这个月!', $result, 0, $prefixJS ); } } else { $msg->ResponseMsg ( 1, '日期和系统日期不同步!', $result, 0, $prefixJS ); } return true; } // 教师调休 教师当月总课数达到70,其他无视 // 返回申请状态0、1 (家长端对应显示0、1)每时间断只能调整一次,需提前24小时申请 function teacherPaidLeave() { $msg = new responseMsg (); $capturs = $this->captureParams (); $prefixJS = $capturs ['callback']; $token = $capturs ['token']; $newrow = $capturs ['newrow']; $tid = $newrow ['tid']; $teacher_nowdate = ($newrow ['teacher_nowdate']); // 接受前端传来当前日期 $teacher_date = $newrow ['teacher_date']; // 获得教师需要调休的日期 $teacher_time = $newrow ['teacher_time']; // 获得教师需要调休的时间 // $teacher_time=($newrow['time']); //接受前端传来时间 date_default_timezone_set ( 'PRC' ); // 设置时区 $time = time (); // 获取当前时间 $nowTime = date ( "Y-m-d", $time ); // 获取服务器当前年月日 // echo $nowTime; // echo $teacher_date; if (date ( 'Ymd', strtotime ( $nowTime ) ) == date ( 'Ymd', strtotime ( $teacher_nowdate ) ) && ! $teacher_nowdate == null && ! $tid == null) { $time = time (); // 获取当前时间 $now = date ( "H:i:s", $time ); // 获取服务器当前时间 // echo $time.'==='; $now = strtotime ( $now ); // 当前时间戳 // $teacher_time=$teacher_time.':00'; //前段没有秒需要配上 $teacher_time = strtotime ( $teacher_time ); // 需调休的时间戳 // 教师需提前24小时申请 if ((date ( 'Ymd', strtotime ( $teacher_date ) ) - date ( 'Ymd', strtotime ( $nowTime ) ) >= 1 && $teacher_time >= $now && date ( 'Ymd', strtotime ( $teacher_date ) ) - date ( 'Ymd', strtotime ( $nowTime ) ) < 2) || date ( 'Ymd', strtotime ( $teacher_date ) ) - date ( 'Ymd', strtotime ( $nowTime ) ) >= 2) { // 新增和后状态改为1 申请中 $teacher_date = $newrow ['teacher_date']; // 获得教师需要调休的日期 $teacher_time = $newrow ['teacher_time']; // 获得教师需要调休的时间 $time = time (); // 获取当前时间 $nowTime = date ( "Y-m-d H:i:s", $time ); // 获取服务器当前年月日 $updateSql = 'update teacher_schedule set teacher_entry_state=1,teacher_apply_date="' . $nowTime . '" where schedule_date="' . $teacher_date . '" and schedule_time="' . $teacher_time . '" and teacher_tid=' . $tid; $model = spClass ( $this->tablename ); $upresult = $model->runSql ( $updateSql ); $msg->ResponseMsg ( 0, 'success', $result, 0, $prefixJS ); } else { $msg->ResponseMsg ( 1, '申请需提前24小时', $result, 0, $prefixJS ); } } else { $msg->ResponseMsg ( 1, '日期和系统日期不同步', $result, 0, $prefixJS ); } return true; } // 教师课程安排 // 接受当前时间,查询前、现在、下周的所有课程信(按时间段查询) 学生姓名以及在读年级会显示在课程日历中 function teacherCurriculum() { $msg = new responseMsg (); $capturs = $this->captureParams (); $prefixJS = $capturs ['callback']; $token = $capturs ['token']; $newrow = $capturs ['newrow']; $tid = $newrow ['tid']; $date = $newrow ['date']; // 当前时间 if (! $newrow) { $msg->ResponseMsg ( 1, 'not tid', flase, 0, $prefixJS ); } else { $nowdate = strtotime ( $date ); // 获取当前时间戳 $beginweek = strtotime ( '-' . (10) . 'day', $nowdate ); // 获取10天前的时间戳 $beginweek = date ( 'Y-m-d', $beginweek ); // 获取10天前的日期 // echo $beginweek.'--'; $afterweek = strtotime ( '+' . (10) . 'day', $nowdate ); // 获取10天后的时间戳 $afterweek = date ( 'Y-m-d', $afterweek ); // 获取10天后的日期 //请 不要修改代码 $querySql = 'select o.tid as order_tid,s.teacher_entry_state,s.teacher_rest_state,s.time_busy,s.schedule_date,s.schedule_time, u.user_name,o.class_content,s.tid,c.tid as class_tid from teacher_info t left join teacher_schedule s on t.tid=s.teacher_tid left join class_list c on s.class_tid=c.tid left join order_list o on c.order_tid=o.tid left join user_info u on o.user_tid=u.tid where s.schedule_date>="' . $beginweek . '" and schedule_date <="' . $afterweek . '" and t.tid=' . $tid . ' group by s.schedule_date,s.schedule_time'; // echo $querySql; // exit; $model = spClass ( $this->tablename ); if ($result = $model->findSql ( $querySql )) { $teacher_class = $newrow ['teacher_class']; //教师本月已上课时数 $beginDate = date ( 'Y-m-01', strtotime ( date ( "Y-m-d" ) ) ); // 获取当月第一天 $endDateOne = date ( 'Y-m-d', strtotime ( "$beginDate +1 month -1 day" ) ); // 获取本月最后1天 if ($teacher_class >= 70 && 0 == time_busy) {//当教师本月已完成课时超过70 且时间在当前到本月之间 的所有状态为闲时的记录 // 这里需要判断教师忙闲 $tid = $newrow ['tid']; $updateSql = 'update teacher_schedule set teacher_rest_state=1 where schedule_date>="' . $date . '" and schedule_date<="' . $endDateOne . '" and teacher_tid=' . $tid; $model = spClass ( $this->tablename ); $resultup = $model->runSql ( $updateSql ); } $msg->ResponseMsg ( 0, 'secsess', $result, 0, $prefixJS ); } else { $msg->ResponseMsg ( 0, 'not find', $result, 0, $prefixJS ); } } return true; } // 教师查看家长评价结果 function userEvaluationResults() { // echo aaa; // 课程记录页面返回家长评价结果 // 查询数据 返回12345 + 评论 状态 0/1 未评价/已评价 $msg = new responseMsg (); $capturs = $this->captureParams (); $prefixJS = $capturs ['callback']; $token = $capturs ['token']; $newrow = $capturs ['newrow']; $tid = $newrow ['tid']; if (! $newrow) { $msg->ResponseMsg ( 1, 'not null', $result, 0, $prefixJS ); exit; } else { $querySql = 'select * from user_evaluation where class_tid=' . $tid; $model = spClass ( $this->tablename ); if ($result = $model->findSql ( $querySql )) { $msg->ResponseMsg ( 0, 'secsess', $result, 0, $prefixJS ); } else { $msg->ResponseMsg ( 1, '教师没有上传教案', $result, 0, $prefixJS ); } } return true; } // 教师个人信息 现在只有评价 function teacherPersonalInformation() { $msg = new responseMsg (); $capturs = $this->captureParams (); $prefixJS = $capturs ['callback']; $token = $capturs ['token']; $newrow = $capturs ['newrow']; $tid = $newrow ['tid']; if (! $newrow) { $msg->ResponseMsg ( 1, 'not find tid', $result, 0, $prefixJS ); } else { $querySql = 'select t.teacher_name,avg(e.teacherOntime) as teacherOntimeSum,avg(e.lessonPlanReady) as lessonPlanReadySum,avg(e.classroomInteraction) as classroomInteractionSum,count(e.class_tid) as PNum from teacher_info t,order_list o,class_list c, user_evaluation e where o.teacher_tid=t.tid and c.order_tid=o.tid and e.class_tid=c.tid and t.tid=' . $tid; $model = spClass ( $this->tablename ); if ($result = $model->findSql ( $querySql )) { $msg->ResponseMsg ( 0, 'secsess', $result, 0, $prefixJS ); } else { $msg->ResponseMsg ( 1, '还没有学生对您评价!', $result, 0, $prefixJS ); } } return true; } //禁止以下action实例化基类 function query() { return false; } function delete() { return false; } function update() { return false; } function add() { return false; } }
true
9c9e2e1cf832bc30efce4d68cc8e91506ff8ada8
PHP
labelexe/PHP-Challenges
/List Of Challenges/71. Build Tower.php
UTF-8
1,804
3.765625
4
[]
no_license
<?php /* 71. Build Tower >Build Tower Build Tower by the following given argument: number of floors (integer and always greater than 0). Tower block is represented as * EXAMPLE: for example, a tower of 3 floors looks like below [ ' * ', ' *** ', '*****' ] and a tower of 6 floors looks like below [ ' * ', ' *** ', ' ***** ', ' ******* ', ' ********* ', '***********' ] NOTES: return an array */ $n = 3; $funzione = tower_builder($n); echo '<pre>'; print_r($funzione); echo '</pre'; function tower_builder($n) { $result = []; for ($i = 1; $i <= $n; $i++) { $result[] = str_repeat(' ', $n-$i) . str_repeat('*', ($i-1)*2+1) . str_repeat(' ', $n-$i); } return $result; } // another solution function tower_builder($n) { $base_num = 1; for ($i = 1; $i < $n; $i++) { // maximum asterisk last row $base_num += 2; } $spaces = ($base_num - 1) / 2; // number of spaces before and after the asterisk $n_asterisk = 1; $towe = []; for ($i = 1; $i <= $n; $i++) { $line = ''; for ($j = 1; $j <= $spaces; $j++) { // add the spaces before the asterisk $line .= ' '; } for ($j = 1; $j <= $n_asterisk; $j++) { // add the asterisk/s $line .= '*'; } for ($j = 1; $j <= $spaces; $j++) { // add the spaces after the asterisk $line .= ' '; } $n_asterisk += 2; // update the number of asterisk $spaces -= 1; // and spaces $towe[] = $line; } return $towe; } ?>
true
e72dfb44ca1d31591f9d2984d2552134b06027e0
PHP
mariovalney/rpg-companion-for-discord
/app/Support/Traits/Livewire/HasRollingParts.php
UTF-8
1,352
2.640625
3
[]
no_license
<?php namespace App\Support\Traits\Livewire; use App\Models\Rolling\RollingPart; use App\Models\Variable; trait HasRollingParts { /** * Get rolling parts * * @param string $value * @return Collection */ public function getRollingAttribute($parts) { $parts = json_decode($parts, true); if (empty($parts) || ! is_array($parts)) { return collect(); } $rolling = []; foreach ($parts as $key => $part) { $rolling[ $key ] = new RollingPart($part); $rolling[ $key ]->guild = $this->getGuildId(); } return collect($rolling); } /** * Set rolling parts * * @param string $value * @return void */ public function setRollingAttribute($parts) { if (empty($parts) || ! is_array($parts)) { $this->attributes['rolling'] = ''; } $rolling = []; foreach ($parts as $key => $part) { if (! is_a($part, RollingPart::class) && is_array($part)) { $part = new RollingPart($part); } if (is_a($part, RollingPart::class)) { $rolling[ $key ] = $part->toArray(); continue; } } $this->attributes['rolling'] = json_encode($rolling); } }
true
83d40b0870171c13008e49388fb833361b55e5d6
PHP
dsansyzbayev/phpCourseHW
/lab8/index.php
UTF-8
1,106
2.796875
3
[]
no_license
<?php include "Player.php"; include "Hero.php"; include "Logger.php"; $heroNames1 = ['Thanos', 'Galactus', 'Dormamu', 'Altron', 'Hitler']; $heroNames2 = ['Thor', 'Hulk', 'IronMan', 'Dr.Strange', 'Bakhtiar']; $heroes1 = $heroes2 = []; for($i = 0; $i < 5; $i++){ $heroes1[] = new Hero($heroNames1[$i], rand(1000,2500), rand(20,170)); $heroes2[] = new Hero($heroNames2[$i], rand(1000,2500), rand(20,170)); } $birzhan = new Player('Birzhan', $heroes1); $kazyna = new Player('Kazyna', $heroes2); $json=[ 'p1' => [ 'name' => $birzhan->name, 'heroes' => $birzhan->getHeroAsArray(), ], 'p2' => [ 'name' => $kazyna->name, 'heroes' => $kazyna->getHeroAsArray(), ] ]; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>.untitled</title> </head> <body> <script> var player = <?php echo json_encode($json); ?> </script> <script src="main.js"></script> </body> </html>
true
344e514c35618098522fefb8f416f1512ff3e020
PHP
zhangxiaoqqi/phpDesign
/sort.php
UTF-8
3,652
3.515625
4
[]
no_license
<?php /** * Created by PhpStorm. * User: Admin * Date: 2018/3/20 * Time: 17:40 */ //排序算法 /* * 冒泡排序 (效率比较低) * * 外层循环决定循环层数 * 内层,两两比较,交换位置 * 每层循环过后,后面的值总是有序的最大(最小)的值,下次就无需去比较他们。 * 加入变量flag,如果没有交换位置,则说明顺序是对的,可以跳出循环结束了 */ $arr = array(); $arr = array(1,98,5,34,23,87,54,23,12,0,456,123,45); $len = count($arr); for($i=1;$i<$len;$i++){ $flag = true; for($j=0;$j<$len-$i;$j++){ if($arr[$j]>$arr[$j+1]){ $flag = false; $temp = $arr[$j]; $arr[$j] = $arr[$j+1]; $arr[$j+1] =$temp; } } if($flag){ break; } } print_r($arr); /* * 选择排序 (比冒泡效率高) * * 外层决定循环层数 * 选择排序就是默认当前值为最小值,记录下标,然后进行循环比较,记录最小(最大)值的下标,最后交换两者的值。这样第一个值就是最小(最大)值。 * 然后,依次,循环下去。最后得到的就是有序的数组 */ $arr = array(); $arr = array(1,98,5,34,23,87,54,23,12,0,456,123,45); $len = count($arr); for($i=0;$i<$len-1;$i++){ $p = $i; //默认当前位置的值即为最小,记录下下标。 for($j=$p+1;$j<$len;$j++){ if($arr[$p]>$arr[$j]){ $p = $j; //如果当前值比默认值小。则记录其下标 } } if($p !=$i){ $temp = $arr[$p]; $arr[$p] = $arr[$i]; $arr[$i] = $temp; } } print_r($arr); /* * 插入排序 * * 外层决定循环层数,把当前值作为插入值去和前面的值进行比较 * 前面的值总是有序的,插入的值只需要和前面的值进行比较,确定最终位置就可以了 * 循环排序就好了 */ $arr = array(); $arr = array(1,98,5,34,23,87,54,23,12,0,456,123,45); $len = count($arr); for($i=1;$i<$len;$i++){ $temp = $arr[$i]; for($j=$i-1;$i>=0;$j--){ if($arr[$j]>$temp){ $arr[$j+1] = $arr[$j]; $arr[$j] = $temp; }else{ break; } } } print_r($arr); /* * 快速排序 * * 首先选取一个值,作为标尺,把大于他的放到right_array中,小于他的放到left_array中,递归调用 * 直到数组数为1,则返回,最后合并起来就是结果 */ function quick_sort($arr) { //先判断是否需要继续进行 $length = count($arr); if($length <= 1) { return $arr; } //如果没有返回,说明数组内的元素个数 多余1个,需要排序 //选择一个标尺 //选择第一个元素 $base_num = $arr[0]; //遍历 除了标尺外的所有元素,按照大小关系放入两个数组内 //初始化两个数组 $left_array = array();//小于标尺的 $right_array = array();//大于标尺的 for($i=1; $i<$length; $i++) { if($base_num > $arr[$i]) { //放入左边数组 $left_array[] = $arr[$i]; } else { //放入右边 $right_array[] = $arr[$i]; } } //再分别对 左边 和 右边的数组进行相同的排序处理方式 //递归调用这个函数,并记录结果 $left_array = quick_sort($left_array); $right_array = quick_sort($right_array); //合并左边 标尺 右边 return array_merge($left_array, array($base_num), $right_array); } $arr = array(1,98,5,34,23,87,54,23,12,0,456,123,45); $res = quick_sort($arr); print_r($res);die;
true
9d67043e71a88e49e2889e3079da06c781deb60b
PHP
mozartbrito/ci-start
/application/helpers/funcoes_helper.php
UTF-8
2,304
3.015625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php function gravaDateDB($data) { //dd/mm/aaaa => dd-Mes-aa //return date('d-M-y', strtotime($data)); //padrão para Oracle //dd/mm/aaaa => aaaa-mm-dd $data = date('d/m/Y', strtotime($data)); return date('Y-m-d', strtotime($data)); // padrão para MySQL } function viewDate($data) { return date('d/m/Y', strtotime($data)); } /** * [marcarBusca description] * Função criada para marcar os campos pesquisados em uma listagem * @param [type] $var [description] -> qual valor procurar * @param [type] $campo [description] -> em qual variável procurar * @return [type] [description] */ function marcarBusca($var, $campo) { if($var != '') { $before = '<strong style="background-color: yellow;">'; $after = '</strong>'; $new = str_replace($var, $before.$var.$after, $campo); $new = str_replace(strtolower($var), $before.strtolower($var).$after, $new); $new = str_replace(ucfirst($var), $before.ucfirst($var).$after, $new); $new = str_replace(strtoupper($var), $before.strtoupper($var).$after, $new); return $new; } return $campo; } function config_pagination($base_url, $num_rows, $limit, $segment) { $config['base_url'] = $base_url; $config['total_rows'] = $num_rows; $config['per_page'] = $limit; $config['uri_segment'] = $segment; $config['use_page_numbers'] = TRUE; $config['num_links'] = 5; $config['prev_link'] = '<i class="fa fa-angle-left"></i>'; $config['prev_tag_open'] = '<li class="page-item">'; $config['prev_tag_close'] = '</a></li>'; $config['next_link'] = '<i class="fa fa-angle-right" ></i>'; $config['next_tag_open'] = '<li class="page-item">'; $config['next_tag_close'] = '</li>'; $config['first_link'] = FALSE; $config['last_link'] = FALSE; $config['full_tag_open'] = '<ul class="pagination justify-content-center">'; $config['full_tag_close'] = '</ul>'; $config['first_tag_open'] = '<li class="page-item">'; $config['first_tag_close'] = '</li>'; $config['cur_tag_open'] = '<li class="page-item active"><a class="page-link">'; $config['cur_tag_close'] = '</a></li>'; $config['num_tag_open'] = '<li class="page-item">'; $config['num_tag_close'] = '</a></li>'; $config['attributes'] = array('class' => 'page-link'); return $config; } function debugger($var) { echo '<pre>'; print_r($var); echo '</pre>'; exit; }
true
8a0a067d601c74035a80ec0419da937d11b6685f
PHP
hxxy2003/backend
/backend/app/Models/AffiliateExtend.php
UTF-8
2,995
2.578125
3
[]
no_license
<?php namespace App\Models; /** * This is the model class for table "affiliates_extend". * @property integer $id int 自增ID * @property integer $affiliateid int 媒体ID * @property integer $ad_type tinyint * 广告类型 * 0(应用市场) * 1(Banner图文) * 2(Feeds) * 3 插屏半屏) * 4(插屏全屏) * 5(Banner文字链) * @property integer $revenue_type tinyint 计费类型 * @property integer $num smallint 转换个数 * @property string $updated_at datetime * @property string $created_at datetime * @property string $updated_time timestamp */ class AffiliateExtend extends BaseModel { // add your constant definition based on {field + meaning} // const STATUS_DISABLE = 0; // const STATUS_ENABLE = 1; /** * The database table used by the model. * * @var string */ protected $table = 'affiliates_extend'; /** * The primary key for the model. * * @var string */ protected $primaryKey = 'id'; /** * The name of the "created at" column. * * @var string */ const CREATED_AT = 'created_at'; /** * The name of the "updated at" column. * * @var string */ const UPDATED_AT = 'updated_time'; /** * Attributes that should be mass-assignable. * * @var array */ protected $fillable = [ 'affiliateid', 'ad_type', 'revenue_type', 'num', ]; /** * Returns the text label for the specified attribute or all attribute labels. * @param string $key the attribute name * @return array|string the attribute labels */ public static function attributeLabels($key = null) { $data = [ 'id' => trans('Id'), 'affiliateid' => trans('Affiliateid'), 'ad_type' => trans('Ad Type'), 'revenue_type' => trans('Revenue Type'), 'num' => trans('Num'), 'updated_at' => trans('Updated At'), 'created_at' => trans('Created At'), 'updated_time' => trans('Updated Time'), ]; if ($key !== null) { return isset($data[$key]) ? $data[$key] : null; } else { return $data; } } // Add relations here /** * return user default role * @return \Illuminate\Database\Eloquent\Relations\HasOne */ /*public function role() { return $this->hasOne('App\Models\Role', 'id', 'role_id'); }*/ // Add constant labels here /** * Get status labels * @param null $key * @return array|string */ /*public static function getStatusLabels($key = null) { $data = [ self::STATUS_DISABLE => trans('Disable'), self::STATUS_ENABLE => trans('Enable'), ]; if ($key !== null) { return isset($data[$key]) ? $data[$key] : null; } else { return $data; } }*/ }
true
488d433deae8fc8eb7091fdf96595d161efe4ae9
PHP
pelincicek/laravelblog
/app/Http/Controllers/ArticleController.php
UTF-8
1,276
2.5625
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Article; class ArticleController extends Controller { public function list() { $articles = Article::all(); return view('articles.list', compact('articles')); } public function create() { return view('articles.create'); } public function store(Request $request) { $article = new Article; $article->title = $request->title; $article->content = $request->content; $article->save(); return redirect()->route('articles'); } //burada bağımlılık sızdırma yapıyoruz. public function detail(Article $article) { return view('articles.detail', compact('article')); } public function edit(Article $article) { return view('articles.edit', compact('article')); } public function update(Article $article, Request $request) { $article->title = $request->title; $article->content = $request->content; $article->save(); return redirect()->route('articleDetail',$article); } public function delete(Article $article) { $article->delete(); return redirect()->route('articles'); } }
true
26048b3fec22ee5ae1694d653bfea6132011ed37
PHP
aptaq/CDV
/Technologie internetowe/PHP/1_zmienne.php
UTF-8
537
2.890625
3
[]
no_license
<?php //boolen $prawda = true; $falsz = false; $calkowita = 200; $hex =0xA; $oct =010; $bin = 0b1010; echo "$hex"; echo '$hex'; echo "<br>$bin"; //skladnia herdoc $imie = 'Filip'; $napis = <<< TEKST Mam na imię :$imie TEKST; echo $napis; echo<<<X <br>Mam na imie: $imie<br> Mieszkam w Poznaniu X; //skladnia nowdoc echo<<<'X' <hr>Mam na imie: $imie <br> Mieszkam w Poznaniu <hr> X; //konkatenacja . echo 'Mam na imie: '.$imie; echo 'Mam na imie: ',$imie; ?>
true
d88f294b983a60184170a3f79fcbda1142d8e28c
PHP
akononykhin/trustcare
/include/TrustCare/Model/Pharmacy.php
UTF-8
4,783
2.78125
3
[]
no_license
<?php /** * * Alexey Kononykhin * alexey.kononykhin@gmail.com * */ class TrustCare_Model_Pharmacy extends TrustCare_Model_Abstract { protected $_id; protected $_name; protected $_is_active; protected $_address; protected $_id_lga; protected $_id_country; protected $_id_state; protected $_id_facility; /** * @param int $value * @return TrustCare_Model_Pharmacy */ public function setId($value) { $this->_parameterChanged('id', $value); $this->_id = (int) $value; return $this; } /** * @return null|int */ public function getId() { return $this->_id; } /** * @param string $value * @return TrustCare_Model_Pharmacy */ public function setName($value) { $this->_parameterChanged('name', $value); $this->_name = (string) $value; return $this; } /** * @return null|string */ public function getName() { return $this->_name; } /** * @param string $value * @return TrustCare_Model_Pharmacy */ public function setIsActive($value) { $this->_parameterChanged('is_active', $value, true); $this->_is_active = !empty($value) ? true : false; return $this; } /** * @return null|string */ public function getIsActive() { return !empty($this->_is_active) ? true : false; } /** * @param string $value * @return TrustCare_Model_Pharmacy */ public function setAddress($value) { $this->_parameterChanged('address', $value); $this->_address = (string) $value; return $this; } /** * @return null|string */ public function getAddress() { return $this->_address; } /** * @param int $value * @return TrustCare_Model_Pharmacy */ public function setIdLga($value) { $this->_parameterChanged('id_lga', $value); $this->_id_lga = (int) $value; return $this; } /** * @return null|int */ public function getIdLga() { return $this->_id_lga; } /** * @param int $value * @return TrustCare_Model_Pharmacy */ public function setIdCountry($value) { $this->_parameterChanged('id_country', $value); $this->_id_country = (int) $value; return $this; } /** * @return null|int */ public function getIdCountry() { return $this->_id_country; } /** * @param int $value * @return TrustCare_Model_Pharmacy */ public function setIdState($value) { $this->_parameterChanged('id_state', $value); $this->_id_state = (int) $value; return $this; } /** * @return null|int */ public function getIdState() { return $this->_id_state; } /** * @param int $value * @return TrustCare_Model_Pharmacy */ public function setIdFacility($value) { $this->_parameterChanged('id_facility', $value); $this->_id_facility = (int) $value; return $this; } /** * @return null|int */ public function getIdFacility() { return $this->_id_facility; } public function isExists() { return !is_null($this->getId()); } /** * Find an entry by id * * @param string $id * @param array|null $options * @return TrustCare_Model_Pharmacy */ public static function find($id, array $options = null) { $newEntity = new TrustCare_Model_Pharmacy($options); $result = $newEntity->getMapper()->find($id, $newEntity); if(!$result) { unset($newEntity); $newEntity = null; } return $newEntity; } /** * Find an entry by name * * @param string $value - name * @param array|null $options * @return TrustCare_Model_Pharmacy */ public static function findByName($value, array $options = null) { $newEntity = new TrustCare_Model_Pharmacy($options); $result = $newEntity->getMapper()->findByName($value, $newEntity); if(!$result) { unset($newEntity); $newEntity = null; } return $newEntity; } public function delete() { parent::delete(); $this->id = null; } }
true
3929eb2ee5ffb473daaa21572d0d5e59e31ac8b5
PHP
rovast/design-pattern-talk
/src/Chapter16/v2/Work.php
UTF-8
1,195
3.203125
3
[ "MIT" ]
permissive
<?php namespace Rovast\DesignPatternTalk\Chapter16\v2; /** * Class Work. */ class Work { // 当前的工作时间 protected $hour; // 当前工作是否完成 protected $finished; /** * @var \Rovast\DesignPatternTalk\Chapter16\v2\State state */ protected $state; /** * 初始化为上午的状态 * Work constructor. */ public function __construct() { $this->setState(new ForenoonState()); } /** * @param mixed $finished */ public function setFinished($finished): void { $this->finished = $finished; } /** * @return mixed */ public function getFinished() { return $this->finished; } /** * @param mixed $hour */ public function setHour($hour): void { $this->hour = $hour; } /** * @param mixed $state */ public function setState(State $state): void { $this->state = $state; } /** * @return mixed */ public function getHour() { return $this->hour; } public function writeProgram() { $this->state->writeProgram($this); } }
true
4a4e965e27b471357f7091dd9435f9e752609357
PHP
luigif/WsdlToPhp
/samples/xignite-security/Map/XiSecurityServiceMap.php
UTF-8
5,459
2.59375
3
[]
no_license
<?php /** * Class file for XiSecurityServiceMap * @date 08/07/2012 */ /** * Class XiSecurityServiceMap * @date 08/07/2012 */ class XiSecurityServiceMap extends XiSecurityWsdlClass { /** * Method to call MapSecurity * Meta informations : * - documentation : Get the symbol, name, CUSIP, and CIK for a security. * @uses XiSecurityWsdlClass::getSoapClient() * @uses XiSecurityWsdlClass::setResult() * @uses XiSecurityWsdlClass::getResult() * @uses XiSecurityWsdlClass::saveLastError() * @uses XiSecurityTypeMapSecurity::getIdentifier() * @uses XiSecurityTypeMapSecurity::getIdentifierType() * @param XiSecurityTypeMapSecurity MapSecurity * @return XiSecurityTypeMapSecurityResponse */ public function MapSecurity(XiSecurityTypeMapSecurity $_XiSecurityTypeMapSecurity) { try { $this->setResult(self::getSoapClient()->MapSecurity(array('Identifier'=>$_XiSecurityTypeMapSecurity->getIdentifier(),'IdentifierType'=>$_XiSecurityTypeMapSecurity->getIdentifierType()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method to call MapSecurityDetail * Meta informations : * - documentation : Get the symbol, name, CUSIP, and CIK, Sector, and Industry for a security. * @uses XiSecurityWsdlClass::getSoapClient() * @uses XiSecurityWsdlClass::setResult() * @uses XiSecurityWsdlClass::getResult() * @uses XiSecurityWsdlClass::saveLastError() * @uses XiSecurityTypeMapSecurityDetail::getIdentifier() * @uses XiSecurityTypeMapSecurityDetail::getIdentifierType() * @param XiSecurityTypeMapSecurityDetail MapSecurityDetail * @return XiSecurityTypeMapSecurityDetailResponse */ public function MapSecurityDetail(XiSecurityTypeMapSecurityDetail $_XiSecurityTypeMapSecurityDetail) { try { $this->setResult(self::getSoapClient()->MapSecurityDetail(array('Identifier'=>$_XiSecurityTypeMapSecurityDetail->getIdentifier(),'IdentifierType'=>$_XiSecurityTypeMapSecurityDetail->getIdentifierType()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method to call MapSecurities * Meta informations : * - documentation : Get the symbol, name, CUSIP, and CIK for a list of securities. * @uses XiSecurityWsdlClass::getSoapClient() * @uses XiSecurityWsdlClass::setResult() * @uses XiSecurityWsdlClass::getResult() * @uses XiSecurityWsdlClass::saveLastError() * @uses XiSecurityTypeMapSecurities::getIdentifiers() * @uses XiSecurityTypeMapSecurities::getIdentifierType() * @param XiSecurityTypeMapSecurities MapSecurities * @return XiSecurityTypeMapSecuritiesResponse */ public function MapSecurities(XiSecurityTypeMapSecurities $_XiSecurityTypeMapSecurities) { try { $this->setResult(self::getSoapClient()->MapSecurities(array('Identifiers'=>$_XiSecurityTypeMapSecurities->getIdentifiers(),'IdentifierType'=>$_XiSecurityTypeMapSecurities->getIdentifierType()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method to call MapSecurityDetails * Meta informations : * - documentation : Get the symbol, name, CUSIP, and CIK, Sector, and Industry for a list of securities. * @uses XiSecurityWsdlClass::getSoapClient() * @uses XiSecurityWsdlClass::setResult() * @uses XiSecurityWsdlClass::getResult() * @uses XiSecurityWsdlClass::saveLastError() * @uses XiSecurityTypeMapSecurityDetails::getIdentifiers() * @uses XiSecurityTypeMapSecurityDetails::getIdentifierType() * @param XiSecurityTypeMapSecurityDetails MapSecurityDetails * @return XiSecurityTypeMapSecurityDetailsResponse */ public function MapSecurityDetails(XiSecurityTypeMapSecurityDetails $_XiSecurityTypeMapSecurityDetails) { try { $this->setResult(self::getSoapClient()->MapSecurityDetails(array('Identifiers'=>$_XiSecurityTypeMapSecurityDetails->getIdentifiers(),'IdentifierType'=>$_XiSecurityTypeMapSecurityDetails->getIdentifierType()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method to call MapSymbol * Meta informations : * - documentation : Convert a symbol from one methodology to another. * @uses XiSecurityWsdlClass::getSoapClient() * @uses XiSecurityWsdlClass::setResult() * @uses XiSecurityWsdlClass::getResult() * @uses XiSecurityWsdlClass::saveLastError() * @uses XiSecurityTypeMapSymbol::getSymbol() * @uses XiSecurityTypeMapSymbol::getFromType() * @uses XiSecurityTypeMapSymbol::getToType() * @param XiSecurityTypeMapSymbol MapSymbol * @return XiSecurityTypeMapSymbolResponse */ public function MapSymbol(XiSecurityTypeMapSymbol $_XiSecurityTypeMapSymbol) { try { $this->setResult(self::getSoapClient()->MapSymbol(array('Symbol'=>$_XiSecurityTypeMapSymbol->getSymbol(),'FromType'=>$_XiSecurityTypeMapSymbol->getFromType(),'ToType'=>$_XiSecurityTypeMapSymbol->getToType()))); } catch(SoapFault $fault) { return !$this->saveLastError(__METHOD__,$fault); } return $this->getResult(); } /** * Method returning the result content * * @return XiSecurityTypeMapSymbolResponse */ public function getResult() { return parent::getResult(); } /** * Method returning the class name * * @return string __CLASS__ */ public function __toString() { return __CLASS__; } } ?>
true
6eda8523c326afb098872cd3bb0f020a6c9abf01
PHP
w4x51m/QuiverCore
/src/Quiver/ChatFilter/ChatFilter.php
UTF-8
2,667
2.984375
3
[]
no_license
<?php namespace Quiver\ChatFilter; use Quiver\ChatFilter\chat\ChatClasser; use pocketmine\utils\TextFormat; /** * Class to check for allowed message * (prevent passwords in chat, prevent dating, short and repeating messages) */ class ChatFilter { /**@var ChatClasser*/ protected $profanityChecker; /**@var array*/ protected $recentMessages = array(); /**@var bool*/ protected $enableMessageFrequency; /**@var array*/ protected $recentChat = array(); public function __construct($enableMsgFrequency = true) { $this->profanityChecker = new ChatClasser(); $this->enableMessageFrequency = $enableMsgFrequency; } /** * Clears the recent chat filter (for spam protection) * * @return null */ public function clearRecentChat() { $this->recentChat = array(); } /** * Check for valid message * * @param LbPlayer $player * @param string $message * @param boolean $needCheck * @return boolean */ public function check($player, $message, $needCheck = true) { // Check the message and log the result. $checkResult = $this->profanityChecker->check($message); $errorMessage = $this->getErrorMessage($message, $player); if (!empty($errorMessage)) { $player->sendMessage($errorMessage); return false; } if($needCheck){ if ($this->enableMessageFrequency) { $this->recentChat[$player->getID()] = true; } $this->recentMessages[$player->getID()] = $message; } return true; } /** * Get message with suitable error * * @param string $message * @param Player $player * @return string */ private function getErrorMessage($message, $player) { $errorMsg = ''; if (strlen($message) === 0) { $errorMsg = TextFormat::RED . 'SkyPi> That message is too short.'; } elseif (isset($this->recentChat[$player->getID()])) { /* player already posted message in last 3 seconds */ $errorMsg = TextFormat::RED . 'SkyPi> You are messaging too fast.'; } elseif (isset($this->recentMessages[$player->getID()]) && $this->recentMessages[$player->getID()] === $message) { /* player's message repeated his previous message */ $errorMsg = TextFormat::RED . 'SkyPi> You repeated that message.'; } elseif ($this->profanityChecker->getIsProfane()) { $errorMsg = TextFormat::RED . 'SkyPi> That\'s an inappropriate message.'; } elseif ($this->profanityChecker->getIsDating()) { $errorMsg = TextFormat::RED . 'SkyPi> No dating.'; } elseif ($this->profanityChecker->getIsAdvertising()) { $errorMsg = TextFormat::RED . 'SkyPi> No advertising'; } return $errorMsg; } }
true
8ebece1a69b91ceef502ce3dd5b9871db23a0106
PHP
yfix/yf
/.dev/console/commands/yf_console_core_generate.class.php
UTF-8
1,206
2.5625
3
[]
no_license
<?php use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class yf_console_core_generate extends Command { protected function configure() { $this ->setName('core:generate') ->setDescription('YF project generation toolkit') ->addArgument('method', InputArgument::OPTIONAL, 'API method to call') ->addArgument('params', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Params for sub-command'); } protected function execute(InputInterface $input, OutputInterface $output) { global $yf_paths; require_once $yf_paths['db_setup_path']; init_yf(); $params = []; // Parse arguments like that: k1=v1 k2=v2 into array('k1' => 'v1', 'k2' => 'v2') foreach ((array) $input->getArgument('params') as $p) { list($k, $v) = explode('=', trim($p)); $k = trim($k); $v = trim($v); if (strlen($k) && strlen($v)) { $params[$k] = $v; } } // TODO } }
true
4edac8ab7c35a1a3c65055f659b2ba05a88634be
PHP
MatheusCruz1/Projects
/projects/cadastrar/cadastrarProjeto.php
UTF-8
1,580
2.703125
3
[]
no_license
<?php require ('conexao.php'); if(!isset($_SESSION)) // Verifica se existe alguma sessão. Senão existir, a função cria uma { session_start(); } if (!isset($_SESSION['id2'])) { // Destrói a sessão por segurança session_destroy(); // Redireciona o visitante de volta pro login header("Location: index.php"); exit; } if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } ?> <?php $nome = addslashes (strip_tags($_POST['nome'])); $descricao = addslashes (strip_tags($_POST['descricao'])); $max = $_POST['max']; $atual = $_POST['atual']; $status = $_POST['status']; $sql = "INSERT INTO projeto (nome_projeto, descricao, numero_max_participantes, numero_atual_participantes, statusProjeto_id) VALUES ('$nome', '$descricao', '$max', '$atual', '$status')"; if (mysqli_query($conexao, $sql)) { $proprietario = $_SESSION["id2"]; $tipo = 1; $sql2 = "SELECT id FROM projeto WHERE nome_projeto = '$nome' LIMIT 1"; $result = mysqli_query($conexao, $sql2); $row = mysqli_fetch_assoc($result); $idProjeto = $row["id"]; if ($sql2) { $sql3 = "INSERT INTO usuario_projeto (usuario_id, projeto_id, tipo_id) VALUES ('$proprietario', '$idProjeto', '$tipo')"; if (mysqli_query($conexao, $sql3)) { echo "<script>alert('Projeto ' + '$nome' + ' criado com sucesso!'); window.location.href='../meusProjetos.php'</script>"; mysqli_close($conexao); } } }else{ echo "<script>alert('Projeto já existe!'); history.back(0);</script>"; } ?>
true
fced36be6daab3bfb788bdfdd34269438d5ba207
PHP
Iuliana12/timesheet-test
/classes/Collection.php
UTF-8
2,984
3.625
4
[]
no_license
<?php //this is a generic collection of objects class Collection { public $name;//a name for this collection, this can be anything, including a refid to identify the collection private $items;//this is an array of objects public $length;//this is the length public function __construct($name = null,$items = null) { $this->items = Array(); $this->length = 0; $this->name = $name; if(isset($items) && is_array($items)) foreach($items as $key => $value) { $this->items[$key] = $value; ++$this->length; } } //this adds a new value to the Collection, if a key is specified then it will be used public function addItem($value,$key = null) { if($key !== null) { if(array_key_exists($key,$this->items) === FALSE) { $this->items[$key] = $value; ++$this->length; } else throw new Exception("key is already in the array"); } else { array_push($this->items,$value); ++$this->length; } } //this will remove an item, the key can either be a numeric value or a string public function removeItem($key) { if(is_numeric($key)) { if($key < $this->length) { $tmp = $this->items[$key]; $this->items = array_slice($this->items,$key,1,TRUE); --$this->length; return $tmp; } else throw new Exception("The '".$key."' position is not defined in the array"); } elseif(is_string($key)) { if(array_key_exists($key,$this->items) === TRUE) { $tmp = $this->items[$key]; unset($this->items[$key]); --$this->length; return $tmp; } else throw new Exception(" '".$key."' key not found in the array"); } else throw new Exception("Key is invalid"); } //return the element in the collection at the specified position or for the given key public function get($key) { if(is_numeric($key)) { if($key < $this->length) return $this->items[$key]; else throw new Exception("The '".$key."' position is not defined in the array"); } elseif(is_string($key)) { if(array_key_exists($key,$this->items) === TRUE) return $this->items[$key]; else throw new Exception(" '".$key."' key not found in the array"); } else throw new Exception("Key is invalid"); } //sets the value for an exisiting element at a given position or key public function set($key,$value) { if(is_numeric($key)) { if($key < $this->length) $this->items[$key] = $value; else throw new Exception("The '".$key."' position is not defined in the array"); } elseif(is_string($key)) { if(array_key_exists($key,$this->items) === TRUE) $this->items[$key] = $value; else throw new Exception(" '".$key."' key not found in the array"); } else throw new Exception("Key is invalid"); } public function __toString() { $ret = $this->name.": ["; foreach($this->items as $key => $value) { $ret .= " [".$key."] = '"; $ret .= $value->__toString(); $ret .= "' "; } $ret .= "]"; return $ret; } } ?>
true
83e0c5e2ebdd2b2e91c2894238c8b0c17db6ce63
PHP
spidfire/API-Generator
/src/DocParser.php
UTF-8
866
2.84375
3
[]
no_license
<?php class DocParser{ var $storage = null; function __construct(){ $this->storage = new DocParserStorage(); } function nextFile($filename){ $this->storage->addItem("file",$filename); } function nextDoc($doc_array,$extra_attr=array()){ list($full,$doc,$code) = $doc_array; $attr = $this->getAttributes($doc); $attr = array_merge($extra_attr,$attr); foreach ($attr as $key => $value) { $this->storage->addItem($value[0],$value[1]); } // $this->storage->addItem('source_code',$code); $this->storage->nextItem(); } function getAttributes($doc){ preg_match_all('/\s*\*[ \t]*\@(\w+)\s*(?::|=|)\s*?(\S[^\n\r]+)/is', $doc, $lines_raw,PREG_SET_ORDER); $lines = array(); foreach ( $lines_raw as $key => $value) { $lines[] = array($value[1], $value[2]); } return $lines; } function getStorage(){ return $this->storage; } }
true
536e8ddb5e845807dabbf6cba41685ad53ef848c
PHP
Mauriciozx1/Problock--Soporte-Metacognitivo
/app/AnswerQuestion.php
UTF-8
1,007
2.609375
3
[]
no_license
<?php namespace CSLP; use Illuminate\Database\Eloquent\Model; class AnswerQuestion extends Model { protected $table = 'questions_answer'; public static function getAnswer($idQuestion){ $answerQuestion = AnswerQuestion::where('question_id', '=',$idQuestion)->get(); $dataAnswer = []; $dataAnswer['student'] = []; foreach($answerQuestion as $answer){ $user = User::find($answer->user_id); $student = []; $student['id'] = $user->id; $student['name'] = $user->name; $student['flastName'] = $user->flastname; $student['mlastname'] = $user->mlastname; $student['answer'] = []; if($answer->points > 0 ){ $student['answer'] = $answer->points; }else{ $student['answer'] = $answer->answer; } array_push($dataAnswer['student'], $student); } return $dataAnswer; } }
true
a2a01d847083e8aa13b4c371588dcf00f213e873
PHP
arwinvdv/eBoekhoudenApi
/src/ValueObjects/AccountLedgerCode.php
UTF-8
908
3.125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
<?php namespace bobkosse\eBoekhouden\ValueObjects; /** * Class AccountLedgerCode * @package bobkosse\eBoekhouden\ValueObjects */ class AccountLedgerCode { /** * @var */ private $accountLedgerCode; /** * AccountLedgerCode constructor. * @param $accountLedgerCode * @throws \Exception */ public function __construct($accountLedgerCode = null) { if(mb_strlen($accountLedgerCode) < 11 || $accountLedgerCode === null) { $this->accountLedgerCode = $accountLedgerCode; return; } throw new \Exception("Account Ledger Code may not exceed the length of 10 characters or may be null", 107); } /** * @return mixed */ public function __toString() : string { if($this->accountLedgerCode === null) { return ''; } return $this->accountLedgerCode; } }
true
29fb56d0e377efe5dc069a53b5b4c27551c8f3c5
PHP
darknes94/P6
/includes/functions.php
UTF-8
21,464
2.65625
3
[]
no_license
<?php require_once('admin/db.inc'); function FormatearFechaBarras($fecha) { $date = new DateTime($fecha); $fechaNueva = $date->format('d/m/Y'); return $fechaNueva; } function FormatearFechaGuiones($fecha) { $date = new DateTime($fecha); $fechaNueva = $date->format('Y-m-d'); return $fechaNueva; } function CrearUsuarioEnBD($nombre, $password, $correo, $sexo, $fecha_nac, $ciudad, $paises, $foto){ $sexo_usuario=2; // Iniciamos como mujer if ($sexo == 'Hombre') $sexo_usuario=1; $fecha = FormatearFechaBarras($fecha_nac); $conexion = conecta(); $consulta = "INSERT INTO usuarios (NomUsuario, Clave, Email, Sexo, FNacimiento, Ciudad, Pais, Foto) VALUES ('$nombre',sha1('$password'),'$correo','$sexo_usuario','$fecha_nac','$ciudad','$paises','$foto')"; ejecutaConsulta($conexion, $consulta); $consulta = "select IdUsuario from usuarios where NomUsuario='".$nombre."'"; $resultado = ejecutaConsulta($conexion, $consulta); if ($resultado->num_rows > 0) { $fila = $resultado->fetch_object(); $id = $fila->IdUsuario; $_SESSION['usuario']['id'] = $fila->IdUsuario; $_SESSION['usuario']['nombre'] = $nombre; $_SESSION['usuario']['foto'] = $foto; $_SESSION['usuario']['correo'] = $correo; $_SESSION['usuario']['sexo'] = $sexo; $_SESSION['usuario']['fecha'] = $fecha; $_SESSION['usuario']['ciudad'] = $ciudad; $_SESSION['usuario']['pais'] = CargarPais($_POST['paises']); } else { $id = -1; } $resultado->close(); $conexion->close(); if ($id >= 0) { // Le creamos su carpeta de albumes mkdir("img/albumes/".$id); header("Location: menu_usuario.php"); } else { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "No se ha podido insertar el usuario."; header("Location:../".$_SESSION['error']['urlIniciarSesion']); } } function ActualizarUsuario($id, $variable, $valor) { // Obtenemos la cadena con los datos a modificar $cadena = ''; for ($i=0; $i<count($variable); $i++) { $cadena = $cadena.$variable[$i].' = '; if ($variable[$i] == 'FNacimiento') { $cadena = $cadena.'"'.FormatearFechaGuiones($valor[$i]).'"'; } else if (( $variable[$i] == 'Sexo') || ($variable[$i] == 'Pais')) { $cadena = $cadena.$valor[$i]; } else { $cadena = $cadena.'"'.$valor[$i].'"'; } if ((count($variable) > 1) && ($i < count($variable)-1)) { $cadena = $cadena.', '; } } $conexion = conecta(); $consulta = "UPDATE usuarios SET ".$cadena." where IdUsuario = ".$id; $resultado = ejecutaConsulta($conexion, $consulta); $conexion->close(); header("Location: menu_usuario.php"); } function CargarListaPaises() { $conexion = conecta(); $consulta = 'select IdPais, NomPais from paises'; $resultado = ejecutaConsulta($conexion, $consulta); if ($resultado->num_rows > 0) { while($fila = $resultado->fetch_object()) { echo '<option value="'.$fila->IdPais.'">'.$fila->NomPais.'</option>'; } } $resultado->close(); $conexion->close(); } function ComprobarNombreUsuario($usuario) { $conexion = conecta(); $consulta = "select NomUsuario from usuarios where NomUsuario = '$usuario'"; $resultado = ejecutaConsulta($conexion, $consulta); $existe = false; if ($resultado->num_rows > 0) { $fila = $resultado->fetch_object(); $existe = true; } $resultado->close(); $conexion->close(); return $existe; } function ComprobarLongitud($min, $max, $frase) { if( (strlen($frase) >= $min) && (strlen($frase) <= $max) ) return true; else return false; } function ComprobarMayusMinusNumeros($pass) { $minus = "([a-z]+)"; $mayus = "([A-Z]+)"; $num = "([0-9]+)"; if (ComprobarPatron($minus, $pass)) if (ComprobarPatron($mayus, $pass)) if (ComprobarPatron($num, $pass)) return true; return false; } function ComprobarPatron($patron, $nombre) { if(preg_match($patron, $nombre)) return true; else return false; } function ComprobarFecha($fecha) { $valores = explode('-', $fecha); $dia = $valores[2]; $mes = $valores[1]; $anyo = $valores[0]; if (count($valores) == 3 && checkdate($mes, $dia, $anyo)) { unset($valores); $hoy = getdate(); $anyoActual = $hoy['year']; $mesActual = $hoy['mon']; $diaActual = $hoy['mday']; if ($anyo == $anyoActual) { if ($mes < $mesActual) { return true; } else if ($mes == $mesActual) { if ($dia <= $diaActual) { return true; } } } else if ($anyo < $anyoActual) { return true; } } return false; } function ComprobarNombre($nombre) { $patronNom = "/^([a-zA-Z0-9]{3,15})$/"; if (ComprobarNombreUsuario($nombre)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "Usuario no disponible."; return false; // Comprobar longitud del nombre } else if (!ComprobarLongitud(3, 15, $nombre)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "El tamaño del nombre debe ser de 3 a 15 caracteres."; return false; // Comprobar caracteres del nombre } else if (!ComprobarPatron($patronNom, $nombre)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "El nombre sólo debe contener letras y números."; return false; } return true; } function ComprobarContrasenya($pass, $repassword) { $patronPass = "/^([a-zA-Z0-9_]{6,15})$/"; // Comprobar longitud contrasenya if (!ComprobarLongitud(6, 15, $pass)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "El tamaño de la contraseña debe ser de 6 a 15 caracteres."; return false; // Comprobar caracteres de la contrasenya } else if (!ComprobarPatron($patronPass, $pass)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "La contraseña sólo debe contener letras y números."; return false; // Comprobar mayus, minus y numero contrasenya } else if (!ComprobarMayusMinusNumeros($pass)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "La contraseña debe tener un nº, una letra minúscula y otra mayúscula."; return false; // Comparar contrasenya con repetir contrasenya } if (strcmp ($repassword, $pass) !== 0) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "Las contraseñas no coinciden."; return false; } return true; } function ComprobarMail($mail) { $patronMail = "/@([\w]{2,4})\./"; if (!ComprobarPatron($patronMail, $mail)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "Dominio principal de correo no válido. De 2 a 4 caracteres detrás del @."; return false; } return true; } function ComprobarFechaValida($fecha) { if (!ComprobarFecha($fecha)) { $_SESSION['error']['activado'] = true; $_SESSION['error']['descripcion'] = "Fecha no válida."; return false; } return true; } function ComprobarLogin($usuario, $pass) { $conexion = conecta(); $consulta = "select NomUsuario from usuarios where NomUsuario = '$usuario' and Clave = SHA1('$pass')"; $resultado = ejecutaConsulta($conexion, $consulta); $existe = false; if ($resultado->num_rows > 0) { $fila = $resultado->fetch_object(); $existe = true; } $resultado->close(); $conexion->close(); return $existe; } function CargarArrayPaises() { $conexion = conecta(); $consulta = 'select NomPais from paises order by IdPais'; $resultado = ejecutaConsulta($conexion, $consulta); $paises = array(); if ($resultado->num_rows > 0) { while($fila = $resultado->fetch_object()) { array_push ( $paises , $fila->NomPais ); } } $resultado->close(); $conexion->close(); return $paises; } function CargarPais($id) { $conexion = conecta(); $consulta = 'select NomPais from paises where IdPais = '.$id; $resultado = ejecutaConsulta($conexion, $consulta); if ($resultado->num_rows > 0) { $fila = $resultado->fetch_object(); return $fila->NomPais; } $resultado->close(); $conexion->close(); return ""; } function CargarListaAlbumesPorUsuario($idUsuario) { $conexion = conecta(); $consulta = 'select IdAlbum, Titulo from albumes where Usuario = '.$idUsuario; $resultado = ejecutaConsulta($conexion, $consulta); if ($resultado->num_rows > 0) { while($fila = $resultado->fetch_object()) { echo '<option value="'.$fila->IdAlbum.'">'.$fila->Titulo.'</option>'; } } $resultado->close(); $conexion->close(); } function CargarUltimasFotos() { $conexion = conecta(); $consulta = 'select IdFoto, Fichero, Titulo, DATE_FORMAT(Fecha, "%d/%m/%Y") As Fecha, NomPais from fotos inner join paises on Pais = IdPais order by FRegistro desc limit 0, 5'; $resultado = ejecutaConsulta($conexion, $consulta); $tab = 10; if ($resultado->num_rows > 0) { while($fila = $resultado->fetch_object()) { echo '<ul class="lista_fotos"> <li> <h3>'.$fila->Titulo.'</h3> <a href="detalle_foto.php?id='.$fila->IdFoto.'" title="Ver '.$fila->Titulo.'" tabindex="'.$tab.'"><img src="'.$fila->Fichero.'" alt="'.$fila->Titulo.'" width="200" height="150"/></a> <ul class="datos"> <li>'.$fila->Fecha.'</li> <li>'.$fila->NomPais.'</li> </ul> </li> </ul>'; $tab++; } } $resultado->close(); $conexion->close(); } function CargarDetalleFoto($id) { // Si el id no es numerico, salimos de la funcion if (!is_numeric($id)) return false; $conexion = conecta(); $consulta = 'select Fichero, f.Titulo as FTitulo, DATE_FORMAT(f.Fecha, "%d/%m/%Y") as FFecha, NomPais, a.Titulo as ATitulo, NomUsuario, f.Descripcion as Descripcion from fotos f inner join paises on Pais = IdPais inner join albumes a on Album = IdAlbum inner join usuarios on Usuario = IdUsuario where IdFoto = '.$id; $resultado = ejecutaConsulta($conexion, $consulta); $existe = false; if ($resultado->num_rows > 0) { $fila = $resultado->fetch_object(); $existe = true; echo '<h2>'.$fila->FTitulo.'</h2> <img src="'.$fila->Fichero.'" alt='.$fila->FTitulo.'" width="400" height="300"/> <aside> <h3>Detalles</h3> <p>Descripción: '.$fila->Descripcion.'</p> <p>Fecha: '.$fila->FFecha.'</p> <p>País: '.$fila->NomPais.'</p> <p>Álbum: '.$fila->ATitulo.'</p> <p>Usuario: '.$fila->NomUsuario.'</p> </aside>'; } $resultado->close(); $conexion->close(); return $existe; } function MostrarGraficoUltimosSiteDias(){ $grafica = imagecreatetruecolor(400, 400); $contador = 0; $conexion = conecta(); $blue = imagecolorallocate($grafica, 0x00, 0x33, 0xFF); $white = imagecolorallocatealpha($grafica, 0xFF, 0xFF, 0xFF, 1); $black = imagecolorallocate($grafica, 0x00, 0x00, 0x00); imagefill($grafica, 0, 0, $white); $y = 25; $x=15; $fotos = 0; echo '<h3> Fotografías subidas la última semana: </h3>'; imageline($grafica, $x-2, $y-20, $x-2, 396, $black); while($contador <= 7) { if($contador == 0) $texto = utf8_decode("fotos de hoy: "); else if($contador == 1) $texto = utf8_decode("fotos de hace $contador día: "); else $texto = utf8_decode("fotos de hace $contador días: "); $contador++; // TO DO: hacerlo con group by? $consulta = 'select Fichero, FRegistro from fotos where FRegistro BETWEEN DATE_SUB(NOW(),INTERVAL ' .$contador--. ' DAY) AND DATE_SUB(NOW(),INTERVAL ' .$contador. ' DAY)'; $resultado = ejecutaConsulta($conexion, $consulta); $fotos = $resultado->num_rows; imagefilledrectangle($grafica, $x, $y, 10*$fotos+$x, $y+20, $blue); imageline($grafica, $x-2, $y+22, 395, $y+22, $black); imagestring($grafica, 3, $x, $y-20, $texto, $black); imagestring($grafica, 3, 10*$fotos+$x+10, $y+3, $fotos, $black); $contador++; $y+=50; } ob_start(); imagepng($grafica); $img_src = "data:image/png;base64," . base64_encode(ob_get_contents()); ob_end_clean(); imagedestroy($grafica); echo '<img src="'.$img_src.'" alt= "grafica " width="400" height="400" class="sin_borde"/>'; } function MostrarFotoSeleccionada(){ $conexion = conecta(); $contador = 1; $elegida = rand(1, 10); $i=0; $resultado = ''; $directorio = './Fotos-seleccionadas/Selecciones.txt'; if(!file_exists($directorio)){ ContenidoNoExiste(); } else { $archivo = fopen($directorio, 'r'); while($contador<$elegida){ $contador++; while($i < 3){ $buffer = utf8_encode(fgets($archivo)); $i++; } $i=0; } while($i < 3){ $buffer = utf8_encode(fgets($archivo)); switch ($i) { case 0:{ $consulta='select Fichero, f.Titulo as FTitulo, DATE_FORMAT(f.Fecha, "%d/%m/%Y") as FFecha, NomPais, a.Titulo as ATitulo, NomUsuario from fotos f inner join paises on Pais = IdPais inner join albumes a on Album = IdAlbum inner join usuarios on Usuario = IdUsuario where IdFoto = '.$buffer; $resultado = ejecutaConsulta($conexion, $consulta); $fila = $resultado->fetch_object(); echo '<h2>'.$fila->FTitulo.'</h2> <img src="'.$fila->Fichero.'" alt='.$fila->FTitulo.'" width="400" height="300"/> <aside> <h3>Detalles</h3> <p>Fecha: '.$fila->FFecha.'</p> <p>País: '.$fila->NomPais.'</p> <p>Álbum: '.$fila->ATitulo.'</p> <p>Usuario: '.$fila->NomUsuario.'</p> </aside>'; break; } case 1:{ echo '<p>Nombre del seleccionador: ' .$buffer.'</p>'; break; } case 2:{ echo '<p>Motivo de la selección: ' .$buffer.'</p>'; break; } } $i++; } fclose($archivo); $resultado->close(); $conexion->close(); } } function CrearAlbum($titulo_album_creado, $descripcion_album, $date, $pais, $usuario) { $conexion = conecta(); $consulta = "INSERT INTO albumes (Titulo, Descripcion, Fecha, Pais, Usuario) VALUES ('$titulo_album_creado', '$descripcion_album', '$date', '$pais', '$usuario')"; ejecutaConsulta($conexion, $consulta); $conexion->close(); } function SubirFoto($titulo, $descripcion, $fecha, $pais, $album, $fichero) { $conexion = conecta(); $consulta = "INSERT INTO fotos (Titulo, Descripcion, Fecha, Pais, Album, Fichero) VALUES ('$titulo', '$descripcion', '$fecha', '$pais', '$album','$fichero')"; ejecutaConsulta($conexion, $consulta); $conexion->close(); } function GuardarSolicitud($album, $nombre, $titulo, $descripcion, $email, $direccion, $color_portada, $copias, $resolucion, $fecha, $color_fotos, $coste) { $conexion = conecta(); $consulta = "INSERT INTO solicitudes (Album, Nombre, Titulo, Descripcion, Email, Direccion, Color, Copias, Resolucion, Fecha, IColor, Coste) VALUES ('$album', '$nombre', '$titulo', '$descripcion', '$email', '$direccion', '$color_portada', '$copias', '$resolucion', '$fecha', '$color_fotos', '$coste')"; ejecutaConsulta($conexion, $consulta); $conexion->close(); } function CargarAlbumes($idUsuario) { $conexion = conecta(); $consulta = 'select IdAlbum, Titulo, Descripcion from albumes where Usuario = '.$idUsuario; $resultado = ejecutaConsulta($conexion, $consulta); $existe = false; // Si existe el usuario, sacamos todos los albumes if ($resultado->num_rows > 0) { $tab=9; while($fila = $resultado->fetch_object()){ $consulta = 'select Fichero from fotos f inner join albumes a on a.IdAlbum = f.Album where a.IdAlbum = '.$fila->IdAlbum; $resultado2 = ejecutaConsulta($conexion, $consulta); echo '<li class="lista_de_albumes">'; if ($resultado2->num_rows > 0){ $fila2 = $resultado2->fetch_object(); $extension = explode('.', $fila2->Fichero); switch ($extension[count($extension)-1]){ case "jpg": $foto = @imagecreatefromjpeg ($fila2->Fichero); break; case "png": $foto = @imagecreatefrompng ($fila2->Fichero); break; case "gif": $foto = @imagecreatefromgif ($fila2->Fichero); break; } if (!$foto) { $foto= @imagecreatefromstring(file_get_contents($fila2->Fichero)); } $foto_escalada = imagescale($foto, 200, 150, IMG_BILINEAR_FIXED); ob_start(); imagejpeg($foto_escalada); $img_src = "data:image/png;base64," . base64_encode(ob_get_contents()); ob_end_clean(); imagedestroy($foto); echo '<a href="ver_album.php?id='.$fila->IdAlbum.'&pagina=1" tabindex="'.$tab.'">'; echo '<img src="'.$img_src.'" alt="'.$fila->Titulo.'"/>'; } else { echo '<a href="ver_album.php?id='.$fila->IdAlbum.'&pagina=1" tabindex="'.$tab.'">'; echo 'Sin foto'; } $tab++; echo '</a><p> Título: '.$fila->Titulo.' </br> Descripión: '.$fila->Descripcion.' </br> <a href="ver_album.php?id='.$fila->IdAlbum.'&pagina=1" tabindex="'.$tab.'">Ver álbum</a></p></li>'; $tab++; } $resultado2->close(); $existe = true; } else { noHayContenido(); } $resultado->close(); $conexion->close(); return $existe; } function BuscarUsuario($idUsuario){ $conexion = conecta(); $consulta = 'select NomUsuario, Clave, Email, Sexo, FNacimiento, Ciudad, Pais, Foto from usuarios where IdUsuario = '.$idUsuario; $resultado = ejecutaConsulta($conexion, $consulta); if($resultado->num_rows>0) { $fila = $resultado->fetch_object(); } $resultado->close(); $conexion->close(); return $fila; } // Funciones para el formulario de busqueda function BuscarFotos($titulo, $fecha, $pais) { $i = -1; $variable = []; if ($titulo != "") { // Buscar por título $i++; $variable[$i] = 'Titulo like "%'.$titulo.'%"'; } if ($pais != "") { // Buscar por país $i++; $variable[$i] = 'IdPais = '.$pais; } if ($fecha != "") { // Buscar por fecha $i++; $variable[$i] = 'Fecha = "'.$fecha.'"'; } if ($i >= 0) { // Obtenemos la cadena con los datos a consultar $cadena = ''; for ($i=0; $i<count($variable); $i++) { $cadena = $cadena.$variable[$i]; if ((count($variable) > 1) && ($i < count($variable)-1)) { $cadena = $cadena.' and '; } } $conexion = conecta(); $consulta = 'select IdFoto, Fichero, Titulo, DATE_FORMAT(Fecha, "%d/%m/%Y") as Fecha, NomPais from fotos inner join paises on IdPais = Pais where '.$cadena; $resultado = ejecutaConsulta($conexion, $consulta); $tab = 13; if ($resultado->num_rows > 0) { while($fila = $resultado->fetch_object()) { echo '<ul class="lista_fotos"> <li> <h3>'.$fila->Titulo.'</h3> <a href="detalle_foto.php?id='.$fila->IdFoto.'" title="Ver '.$fila->Titulo.'" tabindex="'.$tab.'"><img src="'.$fila->Fichero.'" alt="'.$fila->Titulo.'" width="200" height="150"/></a> <ul class="datos"> <li>'.$fila->Fecha.'</li> <li>'.$fila->NomPais.'</li> </ul> </li> </ul>'; $tab++; } } else { echo '<p>No hay resultados.</p>'; } $resultado->close(); $conexion->close(); } else { // Si no hay datos, sacacmos el mensaje y salimos de la función echo '<p class="color_rojo">Introduce algunos datos para la búsqueda.</p>'; } } function CargarPaisSeleccionado($seleccionado) { $paises = CargarArrayPaises(); for ($i=0; $i<(count($paises)); $i++) { echo '<option value="'.($i+1).'"'; if (($i+1) == $seleccionado) echo' selected'; echo '>'.$paises[$i].'</option>'; } } function ContenidoNoExiste() { echo '<h2>404 Error</h2><p>El contenido que intentas buscar no existe.</p>'; } function ContenidoNoDisponible() { echo '<h2>CONTENIDO NO DISPONIBLE</h2><p>Debes iniciar sesión para poder ver este contenido.</p>'; } function albumSinContenido() { echo '<p>Este álbum no tiene contenido.</p>'; } function noHayContenido() { echo '<p>Todavía no tienes álbumes creados.</p>'; } function RenombrarFichero($nomdir, $nomFich) { $contador = 0; $auxNom = $nomFich; while (ComprobarFicherosIguales($nomdir, $auxNom)) { $auxNom = $contador.$nomFich; $contador++; } return $auxNom; } function ComprobarFicherosIguales($nomdir, $fichero2) { $dir = opendir($nomdir); while(($fichero1 = readdir($dir)) != FALSE) { if (strcmp($fichero1, $fichero2) == 0) { closedir($dir); return true; } } closedir($dir); return false; } function EliminarFotoPerfil($foto) { // Comprobamos que no sea la foto por defecto if ($foto !== 'img/perfiles/foto.jpg') unlink($foto); } function darseDeBaja($id) { $conexion = conecta(); $consulta = "delete from usuarios where IdUsuario=".$id; $resultado = ejecutaConsulta($conexion, $consulta); $conexion->close(); return $resultado; } ?>
true
d2df7e0add99de823c994332fd8b4231292c9dd1
PHP
ztao8/thankcms
/project/Application/Admin/Model/MenuModel.class.php
UTF-8
3,424
2.515625
3
[]
no_license
<?php /** * 菜单模型 */ namespace Admin\Model; use Common\Model\Model; class MenuModel extends Model { //自动验证 protected $_validate = array( //array(验证字段,验证规则,错误提示,验证条件,附加规则,验证时间) array('title', 'require', '菜单名称不能为空!', 1, 'regex', 3), array('app', 'require', '模块不能为空!', 1, 'regex', 3), array('controller', 'require', '控制器不能为空!', 1, 'regex', 3), array('action', 'require', '方法不能为空!', 1, 'regex', 3), array('status', array(0, 1), '状态值的范围不正确!', 2, 'in'), array('type', array(0, 1), '状态值的范围不正确!', 2, 'in'), ); //自动完成 protected $_auto = array(//array(填充字段,填充内容,填充条件,附加规则) ); /** * 按父ID查找菜单子项 * @param integer $parentid 父菜单ID * @param integer $with_self 是否包括他自己 */ public function admin_menu($parentid, $with_self = false) { //父节点ID $where = array(); $where['status'] = 1; $where['parentid'] = $parentid; $result = $this->where($where)->order(array("listorder" => "ASC"))->select(); if ($with_self) { $result2[] = $this->where(array('id' => $parentid))->find(); $result = array_merge($result2, $result); } //权限检查 if (session("role_id") == 1) { //如果角色为 1 直接通过 return $result; } $array = array(); foreach ($result as $v) { //方法 $action = $v['action']; //public开头的通过 if (preg_match('/^public_/', $action)) { $array[] = $v; } else { if ($v['type'] == 0) { $array[] = $v; } elseif (auth_check(admin_id(), $v['name'])) { $array[] = $v; } } } return $array; } //取得树形结构的菜单 public function get_tree($myid = FALSE, $parent = '', $Level = 1) { $data = $this->admin_menu($myid); $Level++; if (is_array($data)) { foreach ($data as $a) { $id = $a['id']; $name = strtolower($a['name']); $app = strtolower($a['app']); $controller = strtolower($a['controller']); $action = $a['action']; //附带参数 $fu = ""; if ($a['condition']) { $fu = "?" . htmlspecialchars_decode($a['condition']); } $array = array( "icon" => $a['icon'], "id" => $id . $app, "title" => $a['title'], "parentid" => $parent, "url" => U("{$name}{$fu}", array("menuid" => $id)), ); $ret[$id . $app] = $array; $child = $this->get_tree($a['id'], $id, $Level); //由于后台管理界面只支持三层,超出的不层级的不显示 if ($child && $Level <= 3) { $ret[$id . $app]['child'] = $child; } } return $ret; } return false; } /** * 更新缓存 * @param type $data * @return type */ public function menu_cache() { $data = F("Menu_cache_" . admin_id()); if (empty($data)) { $data = $this->get_tree(0); F("Menu_cache_" . admin_id(), $data); } return $data; } /** * 后台有更新/编辑则删除缓存 * @param type $data */ public function _before_write(&$data) { parent::_before_write($data); F("Menu_cache_" . admin_id(), NULL); } //删除操作时删除缓存 public function _after_delete($data, $options) { parent::_after_delete($data, $options); $this->_before_write($data); } }
true
448ec2c2a1726b9e63a5c2abbe18b70a2ef21f2f
PHP
Ceive/view-layer
/src/BlockType/BlockType.php
UTF-8
1,880
2.75
3
[]
no_license
<?php /** * @Creator Alexey Kutuzov <lexus27.khv@gmail.com> * @Author: Alexey Kutuzov <lexus27.khv@gmai.com> * @Project: ceive.view-layer */ namespace Ceive\View\Layer\BlockType; use Ceive\View\Layer\Block; use Ceive\View\Layer\Composition; use Ceive\View\Layer\Holder; use Ceive\View\Layer\Layer; use Ceive\View\Layer\LayerManager; abstract class BlockType{ const CASCADE = 'cascade'; const REPLACE = 'replace'; const DEFINE = 'define'; const PREPEND = 'prepend'; const APPEND = 'append'; public $key; protected static $defaultTypes = []; protected static function getDefaultBlockTypes(){ if(!self::$defaultTypes){ self::$defaultTypes = [ self::CASCADE => new BlockTypeCascade(), self::REPLACE => new BlockTypeReplace(), self::DEFINE => new BlockTypeDefine(), self::PREPEND => new BlockTypePrepend(), self::APPEND => new BlockTypeAppend(), ]; foreach(self::$defaultTypes as $key => $t){ $t->key = $key; } } return self::$defaultTypes; } public static function registerDefaults(LayerManager $manager){ $defaults = self::getDefaultBlockTypes(); foreach($defaults as $typeKey => $type){ $manager->registerType($typeKey, $type); } } /** * @param $type * @return mixed * @throws \Exception */ public static function requireBlockType($type){ $defaults = self::getDefaultBlockTypes(); if(isset($defaults[$type])){ return $defaults[$type]; } throw new \Exception("Required block type '{$type}' is not existing in default types"); } public function attachToHolder(Block $block, Holder $holder){ } public function detachFromHolder(Block $block, Holder $holder){ } public function searchHoldersForPick(Block $block, Layer $layer){ return []; } public function attachToComposition(Composition $composition, Block $block){ $block->composition = $composition; } }
true
9474500260c30c1065ffd0b4449deb4c2a2b2a18
PHP
pauloserafimtavares/lumen-with-mongodb
/lumen/app/ViewModels/v1/ResultViewModel.php
UTF-8
813
2.921875
3
[ "MIT" ]
permissive
<?php namespace App\ViewModels\v1; use App\ViewModels\v1\ViewModel; use Exception; class ResultViewModel extends ViewModel { public $success; public $data; public $errors; public $warnings; public function __construct() { $this->success = true; $this->errors = []; $this->warnings = []; } public function addMessageWarning(string $message): void { $this->warnings[] = $message; } public function addException(Exception $e): void { $this->success = false; $this->errors[] = "Ocorreu uma falha no arquivo {$e->getFile()} na linha {$e->getLine()}, {$e->getMessage()}"; } public function addMessageError(string $error): void { $this->errors[] = $error; $this->success = false; } }
true
5c218545130a4f05d57aff75cb67468888b50e31
PHP
Pugigugi26/grupo2ecommerceLARAVEL
/database/factories/DriverFactory.php
UTF-8
886
2.65625
3
[ "MIT" ]
permissive
<?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\Driver; use App\Family; use Faker\Generator as Faker; $factory->define(Driver::class, function (Faker $faker) { $families = Family::all(); // ACA ESTA TRAYENDO TODAS LAS FAMILIAS , TRAEME DE LA TABLA LAS FAMILIAS EXISTENTES // return [ // 'dim'=>$faker->userName, 'model'=> $faker->unique()->company, 'brand'=> $faker->unique()->userName, 'current'=>$faker->randomNumber(3,false), // 79907610 'voltage'=>$faker->randomNumber(3,false), 'price'=> $faker->randomFloat(2, 2000, 5000), 'description'=>$faker->text(255), 'image'=> "images/driverHelvar.jpg", 'family_id'=> $families->random()->id, // ACA ME ESTA GENERANDO UN FOREIGN KEY MENTIROSO, SI HUBIERA GENERADO LA RELACION NO PODRIA HACERLO // ]; });
true
0a71e40f9d6c0ffff69b85ab7592052aceb30f1f
PHP
PoturovicAnel/ClothingStore
/inc/Database.php
UTF-8
1,193
3.359375
3
[]
no_license
<?php class Database{ private $host = "localhost"; private $user = "root"; private $pass =""; private $dbname = "clothingstore"; private $dbh; private $error; private $stmt; public function __construct(){ // Set DSN $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname; // Set Options $options = array( PDO::ATTR_PERSISTENT => TRUE, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); // Create a new PDO instance try{ $this->dbh = new PDO ($dsn, $this->user, $this->pass, $options); $this->dbh->exec("set names utf8"); } // Catch any errors catch ( PDOException $e ) { $this->error = $e->getMessage(); } } public function query($query){ $this->stmt = $this->dbh->prepare($query); } public function execute(){ return $this->stmt->execute(); } public function resultset(){ $this->execute(); return $this->stmt->fetchAll(PDO::FETCH_OBJ); } public function single(){ $this->execute(); return $this->stmt->fetch(PDO::FETCH_OBJ); } } ?>
true
456c0543401e33bc109b38ee523ceea4c820842b
PHP
alfredostochiero/JWT_Hash
/jwt.php
UTF-8
756
3.28125
3
[]
no_license
<?php class JWT { public function create($data) { // Method that create the JWT. $header = json_encode(array("typ"=>"JWT", "alg"=>"HS256")); $payload = json_encode($data); $hbase = $this->base64url_encode($header); $pbase = $this->base64url_encode($payload); $signature = hash_hmac("sha256", $hbase.".".$pbase, "abC123!", true); // "abC123 is the 256bit secret" $bsig = $this->base64url_encode($signature); $jwt = $hbase.".".$pbase.".".$bsig; return $jwt; } private function base64url_encode( $data ){ return rtrim( strtr( base64_encode( $data ), '+/', '-_'), '='); } private function base64url_decode( $data ){ return base64_decode( strtr( $data, '-_', '+/') . str_repeat('=', 3 - ( 3 + strlen( $data )) % 4 )); } }
true
84ce29b30a57d496b8b19c9e3a7fb979ef083b51
PHP
tonyho96/pms
/painttrack/service/ItemService.php
UTF-8
343
2.6875
3
[]
no_license
<?php class ItemService { public static function uploadImage( $file ) { $targetDir = PMS_UPLOAD_PATH; $targetFile = md5(uniqid(rand(), true)) . basename( $file["name"] ); $fullPath = $targetDir . $targetFile; if ( move_uploaded_file( $file["tmp_name"], $fullPath ) ) { return "/uploads/$targetFile"; } return ""; } }
true
22eec0866f435c57bb7c92772ea9d1fa776dd2fd
PHP
DarkGhostHunter/RutUtils
/src/HasCallbacks.php
UTF-8
1,206
2.984375
3
[ "MIT" ]
permissive
<?php namespace DarkGhostHunter\RutUtils; use Closure; trait HasCallbacks { /** * Callbacks to execute after making many Ruts * * @var array */ protected static array $after = []; /** * Register a callback to be executed after making many Ruts * * @param \Closure $callback */ public static function after(Closure $callback) { static::$after[] = $callback; } /** * Returns all the Callbacks to be executed after making many Ruts * * @return array */ public static function getAfterCallbacks(): array { return static::$after; } /** * Flushes all after and before callbacks * * @return void */ public static function flushAfterCallbacks() { static::$after = []; } /** * Executes a closure without before and after callbacks * * @param \Closure $closure * @return mixed */ public static function withoutCallbacks(Closure $closure) { $after = static::$after; static::flushAfterCallbacks(); $result = $closure(); static::$after = $after; return $result; } }
true
888924bf03b8ede898f1a99b0acbd00768362229
PHP
Jimmy-JS/skripsibackend
/database/seeds/QuestionnaireQuestionSeeder.php
UTF-8
2,058
2.609375
3
[ "MIT" ]
permissive
<?php use App\Models\QuestionnaireQuestion; use Illuminate\Database\Seeder; class QuestionnaireQuestionSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // Built In Question QuestionnaireQuestion::create([ 'id' => 997, 'question' => 'Apakah kegiatan Anda setelah lulus sekarang ini ?', 'type' => 'Radio', 'required' => 1, 'built_in' => 1, ]); QuestionnaireQuestion::create([ 'id' => 998, 'question' => 'Menurut Anda, bagaimana relevansi pekerjaan Anda atau pekerjaan yang Anda harapkan dengan Bidang Ilmu yang saudara tempuh saat kuliah?', 'type' => 'Radio', 'required' => 1, 'built_in' => 1, ]); // Testing Question Non Built In QuestionnaireQuestion::create([ 'id' => 1, 'question' => 'Pada saat baru lulus, sebenarnya di mana Anda ingin bekerja?', 'type' => 'Checkbox', 'position' => 1, 'required' => 1, 'built_in' => 0, ]); QuestionnaireQuestion::create([ 'id' => 2, 'question' => 'Pada saat baru lulus, apakah Anda bersedia bekerja/ditempatkan di daerah?', 'type' => 'Yes or No', 'position' => 2, 'required' => 1, 'built_in' => 0, ]); QuestionnaireQuestion::create([ 'id' => 3, 'question' => 'Pada saat baru lulus, apakah Anda mengetahui cara/prosedur melamar pekerjaan? ', 'type' => 'Yes or No', 'position' => 3, 'required' => 1, 'built_in' => 0, ]); QuestionnaireQuestion::create([ 'id' => 4, 'question' => 'Menurut Anda, mata kuliah apa yang Anda dapatkan dari bangku kuliah yang paling relevan dengan pekerjaan Anda saat ini? (Catatan: jika menyebutkan lebih dari 1, pisahkan dengan koma)', 'type' => 'Text', 'position' => 4, 'required' => 1, 'built_in' => 0, ]); } }
true
682d4498bc539c459f052a39358c71d784446939
PHP
MatrenDev/CSV-chart-generator
/data.php
UTF-8
1,276
2.8125
3
[ "MIT" ]
permissive
<?php //JSON header('Content-Type: application/json'); //Baza $db_host = 'localhost'; $db_user = 'root'; $db_password = ''; $db_name = 'panda_rek2'; //Połączenie $mysqli = new mysqli($db_host, $db_user, $db_password, $db_name); if(!$mysqli) { die("Brak połączenia z bazą" . $mysqli->error); } $file = 'MOCK_DATA.csv'; $content = file($file); $array = array(); //Czyszczenie tabeli mysqli_query($mysqli, "DELETE FROM users"); //Zapisanie zawartości pliku *.csv do tablicy for($i = 0; $i < count($content); $i++) { $line = explode(',', $content[$i]); for($j = 0; $j < count($line); $j++) { $array[$i][$j + 1] = $line[$j]; } } //Dodanie rekordów do tabeli for($i = 1; $i < sizeof($array); $i++) { $sql = "INSERT INTO users SET id = '".$array[$i][1]."', first_name = '".$array[$i][2]."', last_name = '".$array[$i][3]."', country = '".$array[$i][4]."' "; $mysqli->query($sql); } //Pobieranie danych $query = sprintf("SELECT COUNT(first_name) as num, country FROM users GROUP BY country ORDER BY country"); //Wykonanie zapytania $result = $mysqli->query($query); $data = array(); foreach ($result as $row) { $data[] = $row; } $result->close(); //Zakończenie połączenia $mysqli->close(); //Print danych print json_encode($data);
true
a6f5221d88680a1ce42d510d3b54d5c8f883a3d2
PHP
nboldar/phplesson
/example3/engine/products.php
UTF-8
319
2.828125
3
[]
no_license
<?php function getAllProducts(){ return queryAll("SELECT * FROM products"); } function getProductById($id){ return queryOne("SELECT * FROM products WHERE id = {$id}"); } function getProductsByIds(array $ids){ $in = implode(", ", $ids); return queryAll("SELECT * FROM products WHERE id IN ({$in})"); }
true
2416e5c06f106cca681a2d2b0bd4a2273c6a0905
PHP
tasfe/my-weixin-api
/Common/common.php
UTF-8
4,212
2.53125
3
[]
no_license
<?php /** * 由数据库取出系统的配置 * * @access public * @param mix $name * * @return mix */ function MC($name) { $name = strtolower($name); if (S('cache_config')) { $sys_conf = S('cache_config'); } else { $sys_conf = M("Config")->where("status=1")->getField("name,val"); S("cache_config", $sys_conf, 3600); } return $sys_conf[$name]; } function time_format($time=0){ $return_str=''; if($time<60){ return $time.'秒'; } if(floor($time/86400)>0){ $return_str=floor($time/86400).'天'; $time-=floor($time/86400)*86400; } if(floor($time/3600)>0){ $return_str.=floor($time/3600).'小时'; $time-=floor($time/3600)*3600; } if(floor($time/60)>0){ $return_str.=floor($time/60).'分'; $time-=floor($time/60)*60; } if($time<=60){ $return_str.=$time.'秒'; } return $return_str; } /** * 获取秒杀商品剩余数量 * @param integer $id 秒杀活动ID * * @return integer 秒杀商品剩余数量 */ function get_seckill_surplus($id) { if (S('seckill_surplus_' . $id)) { $surplus_num=S('seckill_surplus_' . $id); } else { $SeckillGoods = M('SeckillGoods'); $SeckillRecord = M('SeckillRecord'); $sum_count = $SeckillGoods->where("id={$id}")->getField('goods_num'); $sell_num = $SeckillRecord->where("seckill_id={$id}")->count("id"); $surplus_num = $sum_count - $sell_num; S('seckill_surplus_' . $id,$surplus_num,0); } return $surplus_num; } function get_choujiang_type_name($str) { switch ($str) { case 'guaguaka': return '刮刮卡'; break; case 'zajindan': return '砸金蛋'; break; case 'dazhuanpan': return '大转盘'; break; default: return '无'; break; } } /** * 根据奖项ID获取奖项名称 */ function get_award_name($award_id = 0) { if (empty($award_id)) { return '无兑奖码'; } $award_id = intval($award_id); $award_name = M('ChoujiangAward')->where("id={$award_id}")->find(); if (empty($award_name)) { return '奖项信息不存在'; } return $award_name['name']; } /** * 获取兑换截止日期 */ function get_award_stop_time($choujiang_id=0){ $award_stop_time = M('Choujiang')->where("id={$choujiang_id}")->getField('award_stop_time'); if($award_stop_time==0){ return '无限期'; }else{ return get_date_full($award_stop_time); } } /** * 获取配置信息缓存版本 * @param String $cache_name 缓存版本名称 * @return string 缓存版本字符串 */ function get_cache_version($cache_name = 'cache_config_version') { $cache_name = strtolower($cache_name); if (S($cache_name)) { return S($cache_name); } else { $version = M('CacheVersion')->where("name='{$cache_name}'")->getField('version'); $version = empty($version) ? '1' : $version; S($cache_name, $version, 0); } } /** * 传递秒数 获取Y-m-d H:i:s格式的时间 * @author zibin.dou <zibin_5257@163.com> * @var Int $time 距离1970的秒数 */ function get_date_full($time='') { if ($time == '0') { return '无'; } else { $time = empty($time) ? time() : $time; return date('Y-m-d H:i:s', $time); } } /** * 传递秒数 获取Y-m-d格式的时间 * @author zibin.dou <zibin_5257@163.com> * @var Int $time 距离1970的秒数 */ function get_date($time='') { if ($time == '0') { return '无'; } else { $time = empty($time) ? time() : $time; return date('Y-m-d', $time); } } /** * 传递秒数 获取Y-m格式的月份 * @author zibin.dou <zibin_5257@163.com> * @var Int $time 距离1970的秒数 */ function get_year_month($time) { $time = empty($time) ? time() : $time; return date('Y-m', $time); } // 循环创建目录 function mk_dir($dir, $mode = 0777) { if (is_dir($dir) || @mkdir($dir, $mode)) return true; if (!mk_dir(dirname($dir), $mode)) return false; return @mkdir($dir, $mode); } ?>
true
19e5411a588eeadfce5b3ac084648ea3a324f097
PHP
brucewu16899/SingleSignOn
/app/Disk.php
UTF-8
2,551
2.8125
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; /** * App\Disk * * @property integer $id * @property integer $order * @property string $path * @property integer $capacity * @property integer $free_space * @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $updated_at * @property-read \Illuminate\Database\Eloquent\Collection|\App\DiskHistory[] $history * @method static \Illuminate\Database\Query\Builder|\App\Disk whereId($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk whereOrder($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk wherePath($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk whereCapacity($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk whereFreeSpace($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk whereCreatedAt($value) * @method static \Illuminate\Database\Query\Builder|\App\Disk whereUpdatedAt($value) * @mixin \Eloquent */ class Disk extends Model { /** * Creates a history object for the disk at its current setting. */ public function addToHistory() { $history = new DiskHistory(); $history->entry_date = $this->updated_at; $history->capacity = $this->capacity; $history->free_space = $this->free_space; $history->disk()->associate($this); $history->save(); } public function history() { return $this->hasMany(DiskHistory::class); } public function usedSpace() { return $this->capacity - $this->free_space; } public function percentageUsed() { if ($this->capacity === 0) { return 0; } return round(100 - (($this->free_space / $this->capacity) * 100), 2); } public function freeSpaceFormatted($precision = 2) { return Disk::renderBytes($this->free_space, $precision); } public function usedSpaceFormatted($precision = 2) { return Disk::renderBytes($this->usedSpace(), $precision); } public function capacityFormatted($precision = 2) { return Disk::renderBytes($this->capacity, $precision); } public static function renderBytes($bytes, $precision = 2) { if ($bytes === 0) { return '0.00 B'; } $factors = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; $factor = floor((strlen($bytes) - 1) / 3); return sprintf("%.{$precision}f %s", $bytes / pow(1024, $factor), $factors[(int)$factor]); } }
true
57dfcd905038e29bad887c28c5c96f5eda9b2c06
PHP
HagemanFulfilmentBV/wics-servicelayer-php-sdk
/src/Auth/Basic.php
UTF-8
303
2.78125
3
[ "MIT" ]
permissive
<?php namespace Hageman\Wics\ServiceLayer\Auth; class Basic { /** * @param string $key * @param string $secret * * @return string */ public static function hash(string $key, string $secret): string { return 'Basic ' . base64_encode("$key:$secret"); } }
true
7a91d8b0094a0cb989ea732d423f357d9d2e52f4
PHP
bazo/php-orientdb
/src/OrientDB/Protocols/Binary/Operations/AbstractOperation.php
UTF-8
7,693
3
3
[ "MIT" ]
permissive
<?php namespace OrientDB\Protocols\Binary\Operations; use OrientDB\Common\Binary; use OrientDB\Common\ConfigurableInterface; use OrientDB\Common\ConfigurableTrait; use OrientDB\Common\Math; use OrientDB\Exceptions\Exception; use OrientDB\Protocols\Binary\Socket; use OrientDB\Records\Deserializer; abstract class AbstractOperation implements ConfigurableInterface { use ConfigurableTrait; /** * @var int The op code. */ public $opCode; /** * @var int The session id, if any. */ public $sessionId = -1; /** * @var Socket The socket to write to. */ public $socket; /** * Write the data to the socket. */ abstract protected function write(); /** * Read the response from the socket. * * @return mixed the response. */ abstract protected function read(); /** * Write the request header. */ protected function writeHeader() { $this->writeByte($this->opCode); $this->writeInt($this->sessionId); } /** * Read the response header. * * @throws \OrientDB\Exceptions\Exception if the response indicates an error. */ protected function readHeader() { $status = $this->readByte(); $sessionId = $this->readInt(); if ($status === 1) { $this->readByte(); // discard the first byte of the error $error = $this->readError(); throw $error; } } /** * Execute the operation. * * @return mixed The response from the server. */ public function execute() { if (!$this->socket->negotiated) { $protocol = $this->readShort(); $this->socket->negotiated = true; } $this->writeHeader(); $this->write(); $this->readHeader(); return $this->read(); } /** * Write a byte to the socket. * * @param int $value */ protected function writeByte($value) { $this->socket->write(Binary::packByte($value)); } /** * Read a byte from the socket. * * @return int the byte read */ protected function readByte() { return Binary::unpackByte($this->socket->read(1)); } /** * Write a character to the socket. * * @param string $value */ protected function writeChar($value) { $this->socket->write(Binary::packByte(ord($value))); } /** * Read a character from the socket. * * @return int the character read */ protected function readChar() { return chr(Binary::unpackByte($this->socket->read(1))); } /** * Write a boolean to the socket. * * @param bool $value */ protected function writeBoolean($value) { $this->socket->write(Binary::packByte((bool) $value)); } /** * Read a boolean from the socket. * * @return bool the boolean read */ protected function readBoolean() { $value = $this->socket->read(1); return (bool) Binary::unpackByte($value); } /** * Write a short to the socket. * * @param int $value */ protected function writeShort($value) { $this->socket->write(Binary::packShort($value)); } /** * Read a short from the socket. * * @return int the short read */ protected function readShort() { return Binary::unpackShort($this->socket->read(2)); } /** * Write an integer to the socket. * * @param int $value */ protected function writeInt($value) { $this->socket->write(Binary::packInt($value)); } /** * Read an integer from the socket. * * @return int the integer read */ protected function readInt() { return Binary::unpackInt($this->socket->read(4)); } /** * Write a long to the socket. * * @param int $value */ protected function writeLong($value) { $this->socket->write(Binary::packLong($value)); } /** * Read a long from the socket. * * @return int the integer read */ protected function readLong() { return Binary::unpackLong($this->socket->read(8)); } /** * Write a string to the socket. * * @param string $value */ protected function writeString($value) { $this->socket->write(Binary::packString($value)); } /** * Read a string from the socket. * * @return string|null the string read, or null if it's empty. */ protected function readString() { $length = $this->readInt(); if ($length === -1) { return null; } else if ($length === 0) { return ''; } else { return $this->socket->read($length); } } /** * Write bytes to the socket. * * @param string $value */ protected function writeBytes($value) { $this->socket->write(Binary::packBytes($value)); } /** * Read bytes from the socket. * * @return string|null the bytes read, or null if it's empty. */ protected function readBytes() { $length = $this->readInt(); if ($length === -1) { return null; } else if ($length === 0) { return ''; } else { return $this->socket->read($length); } } /** * Read an error from the remote server and turn it into an exception. * * @return Exception the wrapped exception object. */ protected function readError() { $type = $this->readString(); $message = $this->readString(); $hasMore = $this->readByte(); if ($hasMore === 1) { $next = $this->readError(); } else { $javaStackTrace = $this->readBytes(); } return new Exception($type.': '.$message); } /** * Read a serialized object from the remote server. * * @return mixed */ protected function readSerialized() { $serialized = $this->readString(); return Deserializer::deserialize($serialized); } /** * Read a record from the remote server. * * @return array * @throws \OrientDB\Exceptions\Exception */ protected function readRecord() { $classId = $this->readShort(); $record = ['classId' => $classId]; if ($classId === -1) { throw new Exception('No class for record, cannot proceed!'); } else if ($classId === -2) { // null record $record['bytes'] = null; } else if ($classId === -3) { // reference $record['type'] = 'd'; $record['cluster'] = $this->readShort(); $record['position'] = $this->readLong(); } else { $record['type'] = $this->readChar(); $record['cluster'] = $this->readShort(); $record['position'] = $this->readLong(); $record['version'] = $this->readInt(); $record['bytes'] = $this->readBytes(); } return $record; } /** * Read a collection of records from the remote server. * * @return array */ protected function readCollection() { $records = []; $total = $this->readInt(); for ($i = 0; $i < $total; $i++) { $records[] = $this->readRecord(); } return $records; } }
true
de46849f90bd7228cdbba9eaa5a17a5cdb8daeb9
PHP
sasigit7/PersonalHomePHP
/PHP-Tasks/07.Task7 /Task7.php
UTF-8
835
4
4
[]
no_license
<h1>Local and Global Scope</h1> <?php $number = 10; // global scope echo $number."<br/>"; // outputs 10 /*This function accepts a parameter which needs to multiplied with a global variable*/ function multiply ($multiplyBy) { global $number; // Import global variable $number using "global" keyword inside the function return $number * $multiplyBy; } echo "Number Output: " . multiply (5); // Output: 50 ?> <hr> <h1>Static Variables</h1> <?php /* This function has a number variable. Use Static variable power so that variable value stays in memory */ function printNumber() { static $number = 0; // declare static variable $number = $number + 5; echo "$number"."<br/>"; } printNumber(); // 5 printNumber(); // 10 printNumber(); // 15 printNumber(); // 20 ?> <hr> <hr>
true
c52d3637a93c7931f644d85761ca6af68082cfaf
PHP
SinenhlanhlaKhumalo/Smart-Schools-Communicator
/scripts/filtering_functions.php
UTF-8
3,225
2.6875
3
[]
no_license
<?php function filtering_vehicles($conn,$province,$make,$minPrice,$maxPrice,$minYear,$maxYear) { $post=array(); $count=0; $sql=""; $response="nodata"; if($make=='Any' && $province=='All') { $sql ="SELECT * FROM vehicles where (vehicle_price BETWEEN $minPrice AND $maxPrice) AND (vehicle_year BETWEEN $minYear AND $maxYear) ORDER BY vehicle_id DESC"; } else if($make=='Any' || $province=='All') { if($make=='Any' && $province != 'All') { $sql ="SELECT * FROM vehicles where (vehicle_province = '$province')AND(vehicle_price BETWEEN $minPrice AND $maxPrice)AND (vehicle_year BETWEEN $minYear AND $maxYear)ORDER BY vehicle_id DESC"; } else if($make!='Any' && $province == 'All') { $sql ="SELECT * FROM vehicles where (vehicle_make = '$make')AND(vehicle_price BETWEEN $minPrice AND $maxPrice)AND (vehicle_year BETWEEN $minYear AND $maxYear)ORDER BY vehicle_id DESC"; } } else { $sql ="SELECT * FROM vehicles where (vehicle_province = '$province')AND(vehicle_make = '$make')AND(vehicle_price BETWEEN $minPrice AND $maxPrice)AND (vehicle_year BETWEEN $minYear AND $maxYear)ORDER BY vehicle_id DESC"; } $results = $conn->query($sql); $rows = $results->num_rows; if($results->num_rows > 0) { while($row = $results->fetch_assoc()) { $post[] = $row; $count++; } } if($count>0) { $count=0; echo json_encode($post); } else if($count==0) { echo $response; } } function getMinPrice($price) { $prices="10000"; switch ($price) { case 2: $prices = "100000"; break; case 3: $prices = "300000"; break; case 4: $prices = "500000"; break; case 5: $prices = "800000"; break; default: $prices="10000"; break; } return $prices; } function getMaxPrice($price) { $prices="999000"; switch ($price) { case 1: $prices = "99000"; break; case 2: $prices = "299000"; break; case 3: $prices = "499000"; break; case 4: $prices = "799000"; break; default: $prices="999000"; break; } return $prices; } function getMinYear($year) { $years="1990"; switch ($year) { case 2: $years = "1995"; break; case 3: $years = "2000"; break; case 4: $years = "2005"; break; case 5: $years = "2010"; break; case 6: $years = "2015"; break; case 7: $years = "2020"; break; default: $years="1990"; break; } return $years; } function getMaxYear($year) { $years="2024"; switch ($year) { case 1: $years = "1994"; break; case 2: $year = "1999"; break; case 3: $years = "2004"; break; case 4: $years = "2009"; break; case 5: $years = "2014"; break; case 6: $years = "2019"; break; default: $years="2024"; break; } return $years; } ?>
true
0925b3877d6ccf426e1bdcd9b336969c56f5a009
PHP
foxluck/otdelstroy
/system/lib/Registry.class.php
UTF-8
939
3.5
4
[]
no_license
<?php /** * Static class registry * */ class Registry { protected static $store = array(); /** * Security on new Registry * */ protected function __construct() {} /** * Check data exists by key * * @param string $name * @return bool */ public static function exists($name) { return isset(self::$store[$name]); } /** * Returns data by key or false if data not exists * * @param string $name * @return unknown */ public static function get($name) { return (isset(self::$store[$name])) ? self::$store[$name] : false; } /** * Save data in store * * @param string $name * @param unknown $obj * @return unknown */ public static function set($name, $obj) { return self::$store[$name] = $obj; } } ?>
true
7793750e9f38340ba41cdb10284efcb184dadc8e
PHP
zbigniewcichanski/reserve
/core/src/Service/Dm/Repository/LessonRepository.php
UTF-8
1,608
2.625
3
[ "MIT" ]
permissive
<?php /** * Created by PhpStorm. * @author: Zbyszek Cichanski * Date: 07.01.2017 * Time: 16:24 */ namespace Core\Service\Dm\Repository; use Core\Core\Repository; use Core\Service\Inf\LessonConvert; class LessonRepository extends Repository { /** * @var LessonConvert */ private $repository; public function __construct(LessonConvert $repository) { $this->repository = $repository; } public function getOnIdentity($identity) { try { $lesson = $this->repository->getOneByCriteria(['id' => $identity]); if (empty($lesson)) { return false; } return $lesson; } catch (\Exception $e){ throw new \Exception ("Błąd w procesie pobierania lekcji na podstawie id.".$e->getMessage()); } } public function getAll() { // TODO: Implement getAll() method. } public function getTeacherScheduleForDay($teacherId, $date) { } public function getTeacherScheduleForAWeek($teacherId, $startDate) { } public function getFreeTermsForDay($date): array { try { $lessonList = $this->repository->getByCriteria(['date' => $date, 'open'=>'1']); if (empty($lessonList)) { return []; } return $lessonList; } catch (\Exception $e){ throw new \Exception ("Błąd w procesie pobierania wolnych terminów w danym dniu.".$e->getMessage()); } } public function getFreeTermsTeacherThisWeek($teacherId, $startDate) { } }
true
9a3e4f4904c4f9ef4e32829a43687598c18deb0a
PHP
sabtain-sarwar/learningLaravel
/database/migrations/2019_06_18_094449_create_posts_table.php
UTF-8
1,481
2.84375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned()->index(); // the user will have many different posts $table->integer('category_id')->unsigned()->index(); $table->integer('photo_id')->unsigned()->index(); $table->string('title'); $table->text('body'); $table->timestamps(); // we're gonna use the object(table) here.We're gonna use a method foreign and the foreign key is going to be user_id // bcz we're going to relate.We're gonna put the constraint b/w the users table and the post.After that we are gonna // do references the ID.Now you see these 2 constraints(user_id and the id).user_id from the post to the id on the // users table.We refrence the id on users.And then we're gonna say is onDelete(we're going to cascade down and // delete everything) $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('posts'); } }
true
7263339577561fff3bcbf4c2af5da828d295d0e4
PHP
votch18/NoteThis
/controllers/accounts.controller.php
UTF-8
545
2.515625
3
[]
no_license
<?php class AccountsController extends Controller { public function __construct($data = array()) { parent::__construct($data); $this->model = new Account(); } public function logout() { Session::destroy(); setcookie("email", "", time()-86400, "/"); Router::redirect('/'); } public function ajax_index() { if ($_GET) { Session::set('theme', $_GET['value']); $this->data = json_encode($this->model->setTheme($_GET['value'])); } } }
true
15e8fa0c7d2d418f9411f7b10bb8d30b0f00d52a
PHP
gemeiosi/CustomCMSLoginSite
/includes/backend-search.php
UTF-8
1,458
2.84375
3
[]
no_license
<?php // Attempt server connection. include_once("config.php"); session_start(); if(isset($_SESSION['u_id'])){ if(isset($_REQUEST['term'])){ // Set parameters $param_term ='%'. $_REQUEST['term'] . '%'; // Prepare a select statement $sql = "SELECT * FROM kids_book WHERE book_Name LIKE '$param_term'"; $result = mysqli_query($conn,$sql); // Check number of rows in the result set if(mysqli_num_rows($result) > 0){ // Fetch result rows as an associative array while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){ echo "<p><a href='diglibrary.php?book={$row["books_id"]}'>" . $row["book_Name"] . "</a></p>"; } }else{ echo "<p>ΔΕΝ ΒΡΕΘΗΚΕ ΚΑΠΟΙΟ ΒΙΒΛΙΟ</p>"; } } else{ echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn); } }else{ echo '<div class=wrapper id="mustlogin">'; echo '<p>ΠΡΕΠΕΙ ΝΑ ΣΥΝΔΕΘΕΙΤΕ ΓΙΑ ΝΑ ΔΕΙΤΕ ΤΟ ΠΕΡΙΕΧΟΜΕΝΟ</p>'; echo '<a href="login.php">Login</a>'; echo '<p>ΑΝ ΔΕΝ ΕΙΣΤΕ ΜΕΛΟΣ ΠΑΡΑΚΑΛΩ ΕΓΓΡΑΦΕΙΤΕ</p>'; echo '<a href="signup.php">Sing Up</a>'; echo '</div>'; } ?>
true
c7f0ce7b3b49d5c799617b6969f0c66897c57e53
PHP
rhapsony/vm-hydrator
/tests/Fixtures/TestNestedViewModel.php
UTF-8
1,480
2.796875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Rhapsony\ViewModelHydrator\Tests\Fixtures; /** * @todo after the release of Symfony 5.4: remove initial property values */ class TestNestedViewModel { private string $string = ''; private int $int = 0; private float $float = 0; private bool $bool = false; /** * @return string */ public function getString(): string { return $this->string; } /** * @param string $string * @return $this */ public function setString(string $string): self { $this->string = $string; return $this; } /** * @return int */ public function getInt(): int { return $this->int; } /** * @param int $int * @return $this */ public function setInt(int $int): self { $this->int = $int; return $this; } /** * @return float */ public function getFloat(): float { return $this->float; } /** * @param float $float * @return $this */ public function setFloat(float $float): self { $this->float = $float; return $this; } /** * @return bool */ public function isBool(): bool { return $this->bool; } /** * @param bool $bool * @return $this */ public function setBool(bool $bool): self { $this->bool = $bool; return $this; } }
true
aa2f08cc2309170abc77396548c8da13219eb715
PHP
010Minds/api
/module/Stock/src/Follows/Model/FollowsTable.php
UTF-8
4,939
2.84375
3
[]
no_license
<?php namespace Follows\Model; use Zend\Db\TableGateway\TableGateway; /** * Class FollowsTable Model * @api * @author Alexsandro Andre <andre@010minds.com> */ class FollowsTable{ /** * propriedade que recebe o objeto */ protected $tableGateway; /** * Construtor */ public function __construct(TableGateway $tableGateway){ $this->tableGateway = $tableGateway; } /** * Metodo que lista todos os follows * @return array $resultSet */ public function fetchAll(){ $resultSet = $this->tableGateway->select(); return $resultSet; } /** * Metodo que lista um determinado Following * @param int $id do user que está querendo saber quem está seguindo * @return array $resultSet */ public function getFollowing($id){ $id = (int) $id; if($id == 0){ throw new \Exception("The user id can not be zero"); } $resultSet = $this->tableGateway->select(array('user_id' => $id)); if(empty($resultSet)){ throw new \Exception("Could not find following"); } return $resultSet; } /** * Metodo que lista um determinado follower * @param int $id do user que está querendo saber os seus seguidores * @return array $resultSet */ public function getFollowers($id){ $id = (int) $id; $resultSet = $this->tableGateway->select(array('following' => $id)); if(empty($resultSet)){ throw new \Exception("Could not find followers"); } return $resultSet; } public function myFollow($id,$userId){ $id = (int) $id; $resultSet = $this->tableGateway->select(array('following' => $id, 'user_id' => $userId)); $row = $resultSet->current(); if(!$row){ $row = false; } return $row; } /** * Metodo que retorna a quantidade de followers * @param int $id do user que está querendo saber os seus seguidores * @return int $resultSet */ public function fullFollowers($id){ $id = (int) $id; $resultSet = $this->tableGateway->select(array('following' => $id)); return (int) count($resultSet); } /** * Metodo que retorna a quantidade de Following * @param int $id do user que está querendo saber a quantidade de seguintes * @return int $resultSet */ public function fullFollowing($id){ $id = (int) $id; $resultSet = $this->tableGateway->select(array('user_id' => $id)); return (int) count($resultSet); } /** * Método que retorna o objeto follow (linha) * @param int $id id da linha do db * @return array $row */ public function getObjFollow($id){ $id = (int) $id; $resultSet = $this->tableGateway->select(array('id' => $id)); $row = $resultSet->current(); if(!$row){ throw new \Exception("Could not find row $id"); } return $row; } public function getPending($id){ $id = (int) $id; $resultSet = $this->tableGateway->select(array( 'following' => $id, 'permission' => 0, )); return $resultSet; } /** * Metodo generico para listar os Following * @param array array('user_id' => 1) or array('user_id' => 1,'permission' => false) * @return array $resultSet */ public function customFollowing($arrayParam){ if(empty($arrayParam)){ throw new \Exception("The array can not be empty"); } $resultSet = $this->tableGateway->select($arrayParam); if(empty($resultSet)){ throw new \Exception("Could not find following"); } return $resultSet; } /** * Responsável por cadastrar a listas de follows * @param objeto Follows * @return int $id */ public function follow(Follows $follows){ $data = array( 'user_id' => $follows->user_id, 'following' => $follows->id, 'permission' => $follows->permission, ); $id = (int) $follows->id; $this->tableGateway->insert($data); $id = $this->tableGateway->getLastInsertValue(); return $id; } /** * Método resposável por aceitar seguidor * @param obj follows */ public function acceptedFollow(Follows $follows) { $data = array( 'permission' => $follows->permission ? 1 : 0, ); $id = (int) $follows->id; return $this->tableGateway->update($data, array('id' => $id)); } /** * Método resposável por não aceitar o seguidor * @param int id id da tabela */ public function notAccpetedFollow($id) { $return = $this->tableGateway->delete(array( 'id' => $id, )); if(empty($return)){ throw new \Exception("User id does not exist. Please provide a valid id"); } return $return; } /** * Método resposável por executar unfollow (deixar de seguir) * @param int $user_id id do usuário * @param int $id id do following a ser deletado */ public function deleteFollow($user_id,$id){ $return = $this->tableGateway->delete(array( 'following' => $id, 'user_id' => $user_id )); if(empty($return)){ throw new \Exception("User id does not exist. Please provide a valid id"); } return $return; } }
true
f8f1ef48896f7428b176fba1bce4b4ac3418cfec
PHP
vorobey9/english
/models/ConsultPoints.php
UTF-8
6,248
2.796875
3
[]
no_license
<?php class ConsultPoints { private function checkIdTeacher($id) { $id = intval($id); if(isset($id)) { $db = Db::getConnection(); $result = $db->query("SELECT * FROM `teachers` WHERE id='$id'"); $result->setFetchMode(PDO::FETCH_ASSOC); $result = $result->fetch(); if($result) { return true; } else { return false; } } else { return false; } } public function add($array) { if(isset($array)) { $idTeacher = intval($array['idTeacher']); $dayStamp = intval($array['dayStamp']); if($this->checkIdTeacher($idTeacher)) { if($dayStamp < 8 && $dayStamp > 0) { if(is_numeric($dayStamp) && !$this->checkDayPoint($idTeacher, $dayStamp)) { if($this->checkTimeFormat($array['beginTime']) || $this->checkTimeFormat($array['endTime'])) { if(isset($array['room'])) { $beginTime = $array['beginTime']; $endTime = $array['endTime']; $description = $array['description']; $room = $array['room']; //////DATA BASE///////////////////// $db = Db::getConnection(); $result = $db->query("INSERT INTO `consultpoints` (idTeacher, beginTime, endTime, dayStamp, description, room) VALUES ('$idTeacher', '$beginTime', '$endTime', '$dayStamp', '$description', '$room')"); if($result) { return true; } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } else { return false; } } public function getAll() { $db = Db::getConnection(); $resQuery = $db->query("SELECT * FROM `consultpoints`"); $result = array(); if($resQuery) { $resQuery->setFetchMode(PDO::FETCH_ASSOC); $i = 0; while($row = $resQuery->fetch()) { $result[$i]['id'] = $row['id']; $result[$i]['idTeacher'] = $row['idTeacher']; $result[$i]['beginTime'] = $row['beginTime']; $result[$i]['endTime'] = $row['endTime']; $result[$i]['dayStamp'] = $row['dayStamp']; $result[$i]['description'] = $row['description']; $result[$i]['room'] = $row['room']; $i++; } return $result; } return false; } public function getById($id) { $id = intval($id); if(isset($id)) { $db = Db::getConnection(); $result = $db->query("SELECT * FROM `consultpoints` WHERE id='$id'"); if($result) { $result->setFetchMode(PDO::FETCH_ASSOC); $result = $result->fetch(); return $result; } } return false; } public function getByIdTeacher($idTeacher) { $idTeacher = intval($idTeacher); if(isset($idTeacher)) { $db = Db::getConnection(); $resQuery = $db->query("SELECT * FROM `consultpoints` WHERE idTeacher='$idTeacher' ORDER BY dayStamp ASC"); $result = array(); if($resQuery) { $resQuery->setFetchMode(PDO::FETCH_ASSOC); $i = 0; while($row = $resQuery->fetch()) { $result[$i]['id'] = $row['id']; $result[$i]['idTeacher'] = $row['idTeacher']; $result[$i]['beginTime'] = $row['beginTime']; $result[$i]['endTime'] = $row['endTime']; $result[$i]['dayStamp'] = $row['dayStamp']; $result[$i]['description'] = $row['description']; $result[$i]['room'] = $row['room']; $i++; } return $result; } return false; } } public function deleteById($id) { $id = intval($id); if(isset($id)) { $db = Db::getConnection(); $resQuery = $db->query('DELETE FROM `consultpoints` WHERE id='.$id); if($resQuery) { return true; } } return false; } public function updateParameter($parameterName, $newValue, $id) { $id = intval($id); if(isset($id)) { if ($parameterName == 'id') { return false; } $db = Db::getConnection(); $resQuery = $db->query("UPDATE `consultpoints` SET $parameterName='$newValue' WHERE id='$id'"); if($resQuery) { return true; } } return false; } private function checkDayPoint($idTeacher, $dayStamp) { $db = Db::getConnection(); $resQuery = $db->query("SELECT * FROM `consultpoints` WHERE idTeacher='$idTeacher' AND dayStamp='$dayStamp'"); $resQuery->setFetchMode(PDO::FETCH_ASSOC); $resQuery = $resQuery->fetch(); if($resQuery) { return true; } else { return false; } } private function checkTimeFormat($time) { if (preg_match('/^([0-1][0-9]|[2][0-3]):([0-5][0-9]):([0-5][0-9])$/', $time)) return true; else return false; } }
true
660dc434074c1dadeaa1e57368ae1ff5fdae7305
PHP
paulsnar/b3
/src/Db/SqlPlaceholder.php
UTF-8
362
2.90625
3
[ "ISC" ]
permissive
<?php declare(strict_types=1); namespace PN\B3\Db; class SqlPlaceholder { protected $sql, $values; public function __construct(string $sql, array $values) { $this->sql = $sql; $this->values = $values; } public function getSql(): string { return $this->sql; } public function getValues(): array { return $this->values; } }
true
86bac78c3d41e71c0c8f13b14f97c538b238d44f
PHP
piojo-zz/mimic
/components/node-spec.inc.php
UTF-8
1,246
2.875
3
[]
no_license
<?php class pSpec { function header($node, $short) { return("System Details"); } function detail($NODE, $SHORT) { //Look for node spec info $got = mysql_query("select os, cpus, speed, memory, disk, pbsscale, mac, date_format(time, '%e/%c/%Y at %H:%i'), INET_NTOA(ipmi_ip) from nodeinfo where name='".mysql_escape_string($NODE)."'"); if ($got and mysql_num_rows($got)) { $r = mysql_fetch_row($got); echo " <dl>\n"; if ($r[1] != "") echo " <dt>CPUs</dt><dd>".$r[1]."x ".$r[2]."MHz</dd>\n"; if ($r[3] != "") echo " <dt>RAM</dt> <dd>".$r[3]."MB</dd>\n"; if ($r[4] != "") echo " <dt>Disk</dt><dd>".$r[4]."GB</dd>\n"; if ($r[0] != "") echo " <dt>OS</dt> <dd>".$r[0]."</dd>\n"; if ($r[6] != "") echo " <dt>MAC</dt> <dd>".$r[6]."</dd>\n"; if ($r[5] != "") echo " <dt>PBS scale factor</dt><dd>{$r[5]}</dd>\n"; if ($r[8] != "") echo " <dt>IPMI IP Address</dt><dd><a href=\"http://{$r[8]}/\">{$r[8]}</a></dd>\n"; echo " </dl>\n"; if ($r[7] != "") echo " <p><span class=\"time\">&#8634;{$r[7]}</span></p>\n"; } else { echo " <p class=\"warning\">Unknown</p>\n"; } } } return new pSpec(); ?>
true
97186c4fe58b1b3cf5a72df306b73ac5cb2086b6
PHP
kevintweber/KtwDatabaseMenuBundle
/Repository/MenuItemRepository.php
UTF-8
1,822
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /* * This file is part of the KtwDatabaseMenuBundle package. * * (c) Kevin T. Weber <https://github.com/kevintweber/KtwDatabaseMenuBundle/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace kevintweber\KtwDatabaseMenuBundle\Repository; use Doctrine\ORM\EntityRepository; use Doctrine\ORM\Mapping\ClassMetadata; class MenuItemRepository extends EntityRepository implements MenuItemRepositoryInterface { /** @var boolean */ protected $cacheLoaded; /** @var array */ protected $nameArray; /** * Constructor. * * @param EntityManager $em The EntityManager to use. * @param ClassMetadata $class The class descriptor. */ public function __construct($em, ClassMetadata $class) { $this->cacheLoaded = false; $this->nameArray = array(); parent::__construct($em, $class); } public function getMenuItemByName($name) { $this->populateCache(); if (!array_key_exists($name, $this->nameArray)) { return null; } return $this->nameArray[$name]; } /** * Will query all the menu items at and sort them for the cache. */ protected function populateCache() { if (!$this->cacheLoaded) { // Query two levels deep. $allMenuItems = $this->createQueryBuilder('m') ->addSelect('children') ->leftJoin('m.children', 'children') ->getQuery() ->useResultCache(true) ->getResult(); foreach ($allMenuItems as $menuItem) { $this->nameArray[$menuItem->getName()] = $menuItem; } $this->cacheLoaded = true; } } }
true
055b93c66fe85fed806356f6a6ad318354c03afb
PHP
kevincaicedo2020/ProyectoNutricional
/Modelo/Php/Alimento.php
UTF-8
441
3.0625
3
[]
no_license
<?php namespace Modelo\Php; class Alimento{ public $nombreAlimento = ""; public $kcalAlimento = 0; const GRAMO_ALIMENTO = 100; public $nombreCategoria = ""; function __construct(string $nombreAlimento, int $kcalAlimento, string $nombreCategoria) { $this->nombreAlimento = $nombreAlimento; $this->kcalAlimento = $kcalAlimento; $this->nombreCategoria = $nombreCategoria; } } ?>
true
912a8705a45d9d4b6ef488504ffdff4d3e8566b8
PHP
FernandoNieto71/clase02rp2
/app/trans_F_C.php
UTF-8
705
3.671875
4
[]
no_license
<?php /* funciones para transformar temperatura de celsius a fahrenheit */ function fahrenheitCelsius($temperatura){ return ($temperatura-32)*5/9; } function celsiusFahrenheit($temperatura){ return ($temperatura * 9/5) + 32; } function mostrarTemperatura($valortermico, $operacion){ $valor = transformarA($valortermico, $operacion); if($operacion == "celsius"){ $otraop = "fahrenheit"; } else{ $otraop = "celsius"; } echo "La temperatura $valortermico en $otraop es igual a $valor en $operacion"; } function transformarA($valortermico, $operacion){ if($operacion=="celsius"){ return fahrenheitCelsius($valortermico); } else{ return celsiusFahrenheit($valortermico); } } ?>
true
19bd633e2f390435102ce6b405b7b0936d0ac277
PHP
vipsoft/ContextInitializerExtension
/src/VIPSoft/ContextInitializerExtension/Context/Initializer/ContextInitializer.php
UTF-8
2,193
2.8125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php /** * @copyright 2012 Anthon Pang * @license MIT */ namespace VIPSoft\ContextInitializerExtension\Context\Initializer; use Symfony\Component\DependencyInjection\ContainerInterface; use Behat\Behat\Context\Initializer\InitializerInterface, Behat\Behat\Context\ContextInterface; /** * A Context Initializer extension for Behat. * * @author Anthon Pang <apang@softwaredevelopment.ca> */ class ContextInitializer implements InitializerInterface { private $container; /** * Constructor * * @param ContainerInterface $container service container */ public function __construct($container) { $this->container = $container; } /** * {@inheritdoc} */ public function supports(ContextInterface $context) { return get_class($context) === $this->container->getParameter('behat.context.class'); } /** * {@inheritdoc} */ public function initialize(ContextInterface $context) { $classes = $this->container->getParameter('behat.contextinitializer.classes'); foreach ($classes as $name => $class) { $instance = $this->newInstance($class); $context->useContext($name, $instance); } } /** * Prefix root namespace * * @param string $className * * @return string */ private function prefixRootNamespace($className) { if (substr($className, 0, 1) !== '\\') { $className = '\\' . $className; } return $className; } /** * Instantiate subcontext * * @param string|array $classInfo * * @return object|null */ private function newInstance($classInfo) { $className = is_array($classInfo) ? array_shift($classInfo) : (is_string($classInfo) ? $classInfo : ''); $parameters = is_array($classInfo) ? $classInfo : array($this->container->getParameter('behat.context.parameters')); $reflection = new \ReflectionClass($this->prefixRootNamespace($className)); if (!$reflection->hasMethod('__construct')) { $parameters = array(); } return $reflection->newInstanceArgs($parameters); } }
true
1a8dfe90834a7d39f0cfd24308cbb60cf7b4740e
PHP
siripat1997/project-steps
/secret.php
UTF-8
1,294
2.9375
3
[]
no_license
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <center> <br><br><br><br><br><br><br><br><br><br><br> <?php if(!$_SESSION['member']){ header("Location: login.php"); } else{ $servername = "localhost"; $username = "root"; $password = ""; $db = "mydb"; $conn = new mysqli($servername, $username, $password, $db); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $show_info = "SELECT * FROM userlogin"; $result = $conn->query($show_info); if ($result->num_rows > 0) { echo "<table><tr><th>First Name</th><th>Last name</th><th>Sex</th><th>Username</th></tr>"; while($row = $result->fetch_assoc()) { echo "<tr> <td>" . $row["fname"]. " </td> <td>" . $row["lname"]. "</td> <td>". $row["sex"]. "</td> <td>" . $row["username"]. "</td> </tr>"; } } else { echo "0 results"; } $conn->close(); } ?> <caption align='bottom'> <form action='login.php' method="post"> <input type="submit" name="logout" value="Logout"> </form> </caption> </center> </body> </html>
true
77031ba8b254957c944469181c541fe402da7d20
PHP
lc-apps/2ipcb
/app/classes/Upload.php
UTF-8
1,257
2.890625
3
[]
no_license
<?php namespace app\classes; use app\classes\Config; use app\classes\Image; use PDO; class Upload { /** * @var mixed */ private $file; /** * @var mixed */ private $type; /** * @param $local * @param $field */ public function upload($local, $field) { $key = $local; $fields = $field; $config = Config::load('imagens'); //$this->mkDir($config->$key); $this->moveFile($config->$key, $field); } /** * @param $fields * @return mixed */ // pega a extensão da imagem -- ver como aproveitar a função do Validate private function getExtension($fields) { $field = $_FILES[$fields]; return strtolower(end(explode('.', $field['name']))); } /** * @param $folder */ private function mkDir($folder) { if (!is_dir($folder['folder'])) { mkdir($folder['folder']); } } /** * @param $folder * @param $field */ private function moveFile($folder, $field) { $file = $_FILES[$field]; $destination = $_SERVER['DOCUMENT_ROOT'] . $folder['folder'] . DIRECTORY_SEPARATOR . $file["name"]; if (move_uploaded_file($file["tmp_name"], $destination)) { echo "Upload realizado com sucesso !"; } else { throw new \Exception("Não foi possivel realizar o upload."); } } }
true
7b9049753cadd70cca3c2f2a54814d27a0798da8
PHP
edujudici/imagerepository
/app/Http/Api/CompanyInterface.php
UTF-8
283
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Api\Company; interface CompanyInterface { public function getAll(); public function save($request); public function delete($companyId); public function findById($companyId); public function findByToken($token); }
true
f3004e0258e1ec7ee68c2e14feea0abdd2f795cb
PHP
yanhub/ValueObject
/tests/unit/Web/PathTest.php
UTF-8
595
2.640625
3
[]
no_license
<?php declare(strict_types=1); namespace AdgoalCommon\ValueObject\Tests\Unit\Web; use AdgoalCommon\ValueObject\Tests\Unit\TestCase; use AdgoalCommon\ValueObject\Web\Path; class PathTest extends TestCase { public function testValidPath(): void { $pathString = '/path/to/resource.ext'; $path = new Path($pathString); $this->assertEquals($pathString, $path->toNative()); } /** @expectedException AdgoalCommon\ValueObject\Exception\InvalidNativeArgumentException */ public function testInvalidPath(): void { new Path('//valid?'); } }
true
1eebb01744898de971810f569c00e569237d4c91
PHP
langeland/S9.Quayo
/Classes/S9/Quayo/Controller/AuthenticationController.php
UTF-8
1,516
2.59375
3
[]
no_license
<?php namespace S9\Quayo\Controller; /* * * This script belongs to the TYPO3 Flow package "S9.Quayo". * * * * */ use TYPO3\Flow\Annotations as Flow; /** * Authentication controller for the S9.Quayo package * * @Flow\Scope("singleton") */ class AuthenticationController extends \TYPO3\Flow\Security\Authentication\Controller\AbstractAuthenticationController { /** * Redirects to a potentially intercepted request. Returns an error message if there has been none. * * @param \TYPO3\Flow\Mvc\ActionRequest $originalRequest The request that was intercepted by the security framework, NULL if there was none * @return string */ protected function onAuthenticationSuccess(\TYPO3\Flow\Mvc\ActionRequest $originalRequest = NULL) { $this->addFlashMessage('Successfully logged in'); if ($originalRequest !== NULL) { $this->addFlashMessage('Redirecting to original request'); $this->redirectToRequest($originalRequest); } $this->addFlashMessage('Redirecting to Standard/index'); $this->redirect('index','Standard'); } public function logoutAction() { $this->authenticationManager->logout(); $this->addFlashMessage('Successfully logged out.'); $this->addFlashMessage('Redirecting to Standard/index'); $this->redirect('index', 'Standard'); } } ?>
true
88b1fbb17f20e310d8536adb328433c39b91b8e0
PHP
zhangdebiao/TeamCenter
/Application/User/Model/UserModel.class.php
UTF-8
1,904
2.78125
3
[]
no_license
<?php namespace User\Model; use Think\Model; class UserModel extends Model{ /* 用户模型自动验证 */ protected $_validate = array( /* 验证用户名 */ array('username', '1,8', -1, self::EXISTS_VALIDATE, 'length'), //用户名长度不合法 //array('username', 'checkDenyMember', -2, self::EXISTS_VALIDATE, 'callback'), //用户名禁止注册 array('username', '', -3, self::EXISTS_VALIDATE, 'unique'), //用户名被占用 /* 验证密码 */ array('password', '6,16', -4, self::EXISTS_VALIDATE, 'length'), //密码长度不合法 /* 验证邮箱 */ array('email', 'email', -5, self::EXISTS_VALIDATE), //邮箱格式不正确 array('email', '1,32', -6, self::EXISTS_VALIDATE, 'length'), //邮箱长度不合法 array('email', '', -8, self::EXISTS_VALIDATE, 'unique'), //邮箱被占用 ); /* 用户模型自动完成 */ protected $_auto = array( array('password', 'md5', self::MODEL_BOTH, 'function'), ); /* 注册用户 $username 用户名 $password 密码 $email 邮箱 return 注册成功返回用户信息,注册失败返回错误编号 */ public function register($username,$password,$email){ $data = array( 'username' => $username, 'password' => $password, 'email' => $email ); //添加用户 if($this->create($data)){ $uid = $this->add(); return $uid ? $uid : 0; } else { return $this->getError(); } } //用户登录 public function login($email,$password){ $find = array('email' => $email ); $user = $this->where($find)->find(); if($user['password']==md5($password)){ $info = array( 'email' => $user['email'], 'username' => $user['username'], 'uid' => $user['uid'] ); return $info; } else { return 0; } } //修改用户信息 public function user_update($data){ if($this->save($data) !== false) return true; else return false; } } ?>
true
a475523566e529352e324fb6b3b8624c75b7b550
PHP
Yarogithub/System-for-creating-reports
/entities/ReportEnt.php
UTF-8
2,312
2.90625
3
[]
no_license
<?php class ReportEnt { protected $completedTasks; protected $numberOfHours; protected $updatedAt; protected $createdAt; protected $reportDate; protected $userid; protected $reportid; /** * @return mixed */ public function getReportDate() { return $this->reportDate; } /** * @param mixed $reportDate */ public function setReportDate($reportDate) { $this->reportDate = $reportDate; } /** * @return mixed */ public function getCompletedTasks() { return $this->completedTasks; } /** * @param mixed $completedTasks */ public function setCompletedTasks($completedTasks) { $this->completedTasks = $completedTasks; } /** * @return mixed */ public function getNumberOfHours() { return $this->numberOfHours; } /** * @param mixed $numberOfHours */ public function setNumberOfHours($numberOfHours) { $this->numberOfHours = $numberOfHours; } /** * @return mixed */ public function getUpdatedAt() { return $this->updatedAt; } /** * @param mixed $updatedAt */ public function setUpdatedAt($updatedAt) { $this->updatedAt = $updatedAt; } /** * @return mixed */ public function getReportid() { return $this->reportid; } /** * @param mixed $reportid */ public function setReportid($reportid) { $this->reportid = $reportid; } public function __construct() { $this->createdAt = new DateTime(); } /** * @return mixed */ public function getUserid() { return $this->userid; } /** * @param mixed $userid */ public function setUserid($userid) { $this->userid = $userid; } /** * @return mixed */ public function getCreatedAt() { return $this->createdAt; } /** * @param mixed $createdAt */ public function setCreatedAt($createdAt) { $this->createdAt = $createdAt; } }
true
c986172dc49b845236c1302d50bdb62f0e889496
PHP
konstantinB1/portfolio
/myblog/module/Application/src/Service/AdminPostsService.php
UTF-8
6,141
2.78125
3
[]
no_license
<?php namespace Application\Service; use Application\Mapper\PostsMapper; use Application\Filter\AdminPostAddFilter; use Application\Entity\Posts; use Zend\Authentication\AuthenticationService; class AdminPostsService { /** * @var $mapper; */ public $mapper; /** * @var $filter; */ public $filter; /** * @var $authService; */ public $authService; /** * Posts Service Constructor * * @param PostsMapper $mapper [description] * @param AdminPostAddFilter $filter [description] * @param AuthenticationService $authService [description] */ public function __construct( PostsMapper $mapper, AdminPostAddFilter $filter, AuthenticationService $authService ) { $this->mapper = $mapper; $this->filter = $filter; $this->authService = $authService; } /** * Returns admin auth id, in this case email * * @return [sting] [description] */ private function identity() { return $this->authService->getIdentity()->admin_email; } /** * Fetch all posts * * @return [type] [description] */ public function fetchAll() { return $this->mapper->fetchAll('post_id DESC'); } /** * Fetch last post in database * * @return [type] [description] */ public function fetchLast() { return $this->mapper->fetchLast(); } /** * Delete post and comment where post id * * @param [type] $postId [description] * @return [type] [description] */ public function deletePosts($posts) { $this->mapper->deletePosts($posts); return true; } /** * Checks if entry exists with where clause * * @param array $data * @param int $postId * @return [bool] */ public function updateField(array $data, $postId) { return $this->mapper->update($data, ['post_id' => $postId]); return true; } /** * Add new post * * @param [array] $posts [description] * @return [ResultSet Object] [description] * * Pogledaj comment na entityExchange() funkciji prvo. * Ovo je super stvar ovde, dakle u ovakvim situcijama metodu koja zelis da ti vrati clean podatke za * storage treba da stavis u Entity sam jer je to deo njegove prirode. * * Takodje mozes ovde pozivati tipa * $this->mapper->insert($posts->getStorageArray()); * Ali mozes i proslediti ceo post u maper pa tamo raditi $post->getStorageArray(); * ako hoces cimni me uzivo da prodiskutujemo... * * * [EDIT] Aaaa tek sam sad video ti pozivas metode insert() i update() direkt iz mapera, * mozes tako ali ne bi bilo lose da imas odvojene metode u tvom custom maperu tipa: * savePost(\Application\Entity\Post $post) * * pa u njemu: * if($post->getId()) { // znaci ako postoji ID moramo raditi update * $this->>update($post->getStorageData()); * } * else{ * $this->>insert($post->getStorageData()); * } * * I na kraju ovo fetchLast(); je cool ali nema potrebe, mozes samo vratiti $post jer je isti rezultat! */ public function newPost($post) { $data = [ 'post_title' => (string) $post->getTitle(), 'post_desc' => (string) $post->getDesc(), 'post_content' => (string) $post->getContent(), 'post_created' => (string) $post->getCreated(), 'post_allow_comments' => (int) $post->getAllowComments(), 'post_url_slug' => (string) $post->getUrlSlug(), 'post_writer' => (string) $this->identity(), 'post_visible' => (int) $post->getVisible() ]; unset($data['post_created']); $this->mapper->insert($data); } /** * Edit existing post * * @param [array] $posts [description] * @param [int] $postId [description] * @return [ResultSet Object] [description] */ public function editPost($post, $postId) { $data = [ 'post_title' => (string) $post->getTitle(), 'post_desc' => (string) $post->getDesc(), 'post_content' => (string) $post->getContent(), 'post_created' => (string) $post->getCreated(), 'post_allow_comments' => (int) $post->getAllowComments(), 'post_url_slug' => (string) $post->getUrlSlug(), 'post_writer' => (string) $this->identity(), 'post_visible' => (int) $post->getVisible() ]; unset($data['post_created']); $this->mapper->update($data, ['post_id' => $postId]); return $this->mapper->fetchLast(); } /** * Edit or add post * * @param [object] $post [description] * @param [int] $postId [description] * @return [object] [description] */ public function postManagement($post, $postId = 0) { $filter = $this->filter->getInputFilter()->setData($post); $identity = $this->identity(); if (!$filter->isValid()) { return ['error', $filter->getMessages()]; } $entity = new Posts(); $entity->exchangeArray($post); if ($postId !== 0) { return $this->editPost($entity, $postId); } $this->newPost($entity); return true; } /** * Get post by id * * @param [int] $id [description] * @return [ResultSet Object] [description] */ public function requestPost($id) { $where = ['post_id' => $id]; if ($this->mapper->entryExists($where)) { return $this->mapper->fetchWhere($where); } } }
true
1998ff593e4a529f46eb4b11963cf7bb50b9c236
PHP
AngryChimps/ac2
/src/AngryChimps/NormBundle/realms/Norm/mysql/base/MemberBase.php
UTF-8
3,325
2.71875
3
[ "MIT" ]
permissive
<?php namespace Norm\mysql\base; use norm\core\NormBaseObject; class MemberBase extends NormBaseObject { /** @var string */ protected static $primaryDatastoreName = ''; /** @var string */ protected static $cacheDatastoreName = ''; /** @var string */ protected static $realm = 'mysql'; /** @var string */ protected static $tableName = 'member'; /** @var string[] */ protected static $fieldNames = array('id', 'member_key', 'email', 'password', 'first', 'last', 'dob', 'photo', 'address', 'lat', 'long', 'status', 'blocked_company_keys', 'managed_company_keys', 'ad_flag_keys', 'message_flag_keys', 'created_at', 'updated_at'); /** @var string[] */ protected static $fieldTypes = array('int', 'string', 'string', 'string', 'string', 'string', 'Date', 'string', 'sring', 'float', 'float', 'int', 'string[]', 'string[]', 'string[]', 'string[]', 'DateTime', 'DateTime'); /** @var string[] */ protected static $propertyNames = array('id', 'memberKey', 'email', 'password', 'first', 'last', 'dob', 'photo', 'address', 'lat', 'long', 'status', 'blockedCompanyKeys', 'managedCompanyKeys', 'adFlagKeys', 'messageFlagKeys', 'createdAt', 'updatedAt'); /** @var string[] */ protected static $primaryKeyFieldNames = array('id'); /** @var string[] */ protected static $primaryKeyPropertyNames = array('id'); /** @var string[] */ protected static $autoIncrementFieldName = ''; /** @var string[] */ protected static $autoIncrementPropertyName = ''; /** @var bool */ protected static $hasPrimaryKey = true; /** @var bool */ protected static $hasAutoIncrement = false; const ActiveStatus = 1; const DeletedStatus = 2; const BannedStatus = 3; /** @var int */ public $id; /** @var string */ public $memberKey; /** @var string */ public $email; /** @var string */ public $password; /** @var string */ public $first; /** @var string */ public $last; /** @var Date */ public $dob; /** @var string */ public $photo; /** @var sring */ public $address; /** @var float */ public $lat; /** @var float */ public $long; /** @var int */ public $status; /** @var string[] */ public $blockedCompanyKeys; /** @var string[] */ public $managedCompanyKeys; /** @var string[] */ public $adFlagKeys; /** @var string[] */ public $messageFlagKeys; /** @var DateTime */ public $createdAt; /** @var DateTime */ public $updatedAt; /** * @param $pk * @return Member */ public static function getByPk($pk) { return parent::getByPk($pk); } /** * @param $where string The WHERE clause (excluding the word WHERE) * @param array $params The parameter count * @return Member */ public static function getByWhere($where, $params = array()) { return parent::getByWhere($where, $params); } /** * @param $sql The complete sql statement with placeholders * @param array $params The parameter array to replace placeholders in the sql * @return Member */ public static function getBySql($sql, $params = array()) { return parent::getBySql($sql, $params); } }
true
5c47b18d6fac6e250a4c2e1f68555a79e7ccc345
PHP
phucvinhnguyen/bistro-cafe
/app/Http/Controllers/EmployeeController.php
UTF-8
3,286
2.5625
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Repositories\Interfaces\EmployeeRepository; use App\Repositories\Interfaces\RolesRepository; use Gate; use Toastr; class EmployeeController extends Controller { private $empRepo; private $empRoleRepo; public function __construct(EmployeeRepository $emp, RolesRepository $role) { $this->empRepo = $emp; $this->empRoleRepo = $role; } public function index(Request $request) { $emps = $this->empRepo->all(); $roles = $this->empRoleRepo->all(); return view('pages.emp.index', compact(['emps', 'roles'])); } public function profile(Request $request, $id) { $emp = $this->empRepo->find($id); return view('pages.emp.profile', compact(['emp'])); } public function store(Request $request) { $input = $request->only('name', 'phone', 'password', 'birthday', 'start_date', 'sex'); $input['role'] = "3"; $input['password'] = bcrypt($input['password']); $this->empRepo->create($input); Toastr::success('Thêm thành công.'); return redirect()->route('employees.index'); } public function update(Request $request, $id) { // Check deny update user if (Gate::denies('update', [auth()->user(), $id])) return redirect()->route('employees.index'); if (!auth()->user()->hasRole('admin')) $input = $request->only('name', 'sex', 'old_pwd', 'password', 'birthday', 'start_date', 'address'); else $input = $request->only('name', 'phone', 'sex', 'old_pwd', 'password', 'birthday', 'start_date', 'address', 'salary', 'fileID'); if (isset($input['old_pwd']) && isset($input['password'])) { $input['password'] = bcrypt($input['password']); if (Hash::check($input['old_pwd'], $this->empRepo->find($id)->password)){ $this->empRepo->update($input, $id); Toastr::success('Cập nhật thành công'); return redirect()->route('employees.index'); } Toastr::error('Mật khẩu cũ không đúng'); return redirect()->route('employees.profile', $id); } $input = array_filter($input, function($var){return !is_null($var);}); if ($this->empRepo->update($input, $id)) { Toastr::success('Cập nhật thành công'); return redirect()->route('employees.index'); } unset($input); Toastr::error('Không sửa được thông tin.'); return redirect()->route('employees.profile', $id); } public function destroy(Request $request) { if (Gate::denies('delete', auth()->user())) { Toastr::error('Bạn không được quyền xóa.'); return redirect()->route('employees.index'); } try { $this->empRepo->deleteMultiRecord($request->emps); } catch (Exception $e) { dd($e); } Toastr::success('Xóa thành công ['. count($request->emps) .'] nhân viên'); return redirect()->route('employees.index'); } }
true
bdbe2f94b713699353dabb3f906f700e8ab8fc8f
PHP
darinelcruzz/brica
/app/helpers.php
UTF-8
852
2.9375
3
[]
no_license
<?php use Jenssegers\Date\Date; function printPublic($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec($ch); curl_close($ch); return $data; } function usesas($ctrl, $fun, $as = null) { if ($as) { return ['uses' => "$ctrl@$fun", 'as' => $as]; } return ['uses' => "$ctrl@$fun", 'as' => $fun]; } function fdate($original_date, $format = 'Y-m-d', $original_format = 'Y-m-d H:i:s') { if ($original_date) { $date = Date::createFromFormat($original_format, $original_date); return $date->format($format); } return '-'; } function drawHeader(...$titles) { echo "<template slot=\"header\"><tr>"; foreach ($titles as $title) { echo "<th>" . ucfirst($title) . "</th>"; } echo "</tr></template>"; }
true
356eba200597bff391b9f6500655bf5fe94e3e30
PHP
AnnotateFramework/annotate
/packages/Collections/src/NestedSet.php
UTF-8
2,320
3.03125
3
[]
no_license
<?php namespace Annotate\Collections; use Annotate\Collections\Exceptions\DuplicateItemException; use ArrayAccess; use IteratorAggregate; use Nette\Object; use Nette\Utils\ArrayHash; use RecursiveArrayIterator; use UnexpectedValueException; /** * @method onAddItem */ class NestedSet extends Object implements ArrayAccess, IteratorAggregate { public $onAddItem = []; private $type; /** @var array|NestedSet[] of items */ private $items = []; public function __construct($type) { if (!$type) { throw new UnexpectedValueException('$type attribute cannot must be set'); } $this->type = $type; } public function offsetExists($offset) { return isset($this->items[$offset]); } /** * @param mixed * @return NestedSet|mixed */ public function offsetGet($offset) { return $this->items[$offset]; } /** * @param mixed * @param mixed * @throws Exceptions\DuplicateItemException */ public function offsetSet($offset, $value) { $this->addItem($offset, $value); } /** * @param mixed */ public function offsetUnset($offset) { unset($this->items[$offset]); } /** * @param mixed * @param mixed * * @return NestedSet|mixed * @throws Exceptions\DuplicateItemException * @throws UnexpectedValueException */ public function addItem($key, $item) { if (is_object($item)) { if (get_class($item) !== $this->type) { $type = get_class($item); throw new UnexpectedValueException( "Cannot add item. Expected instance of '{$this->type}' got instance of '{$type}'" ); } } elseif (gettype($item) != $this->type) { $type = gettype($item); if ($this->type == Type::TYPE_ARRAY_HASH && $type == Type::TYPE_ARRAY) { $item = ArrayHash::from($item); } else { throw new UnexpectedValueException( "Cannot add item. Expected type '{$this->type}' got item of type '{$type}'" ); } } if (in_array($item, $this->items)) { throw new DuplicateItemException("Cannot add item. Same item already exist in set"); } $this->onAddItem($item, $this); $this->items[$key] = $item; return $item; } public function getIterator() { return new RecursiveArrayIterator($this->items); } public function getItems() { return $this->items; } }
true
f59ebd6bfdd44822e7fc295498dd27c753307bf9
PHP
JBalkhamishvili/PHP_Blog
/src/Blog/BlogController.php
UTF-8
703
2.5625
3
[]
no_license
<?php namespace App\Blog; use App\Core\AbstractController; use App\Blog\BloggerRepository; class BlogController extends AbstractController { /** * BlogController constructor. * @param BloggerRepository $bloggerRepository */ public function __construct(BloggerRepository $bloggerRepository) { $this->bloggerRepository = $bloggerRepository; } /** * Controller method for calling the method adPost() from bloggerRepository */ public function showAdPost() { $this->render("posts/adPost", []); } public function savePost() { $posts = $this->bloggerRepository->adPost(); header("Location: blog"); } }
true
82f42a39d31f322a7f5443a1bff32e7b347e8769
PHP
ker0x/messenger
/src/Model/ProfileSettings/HomeUrl.php
UTF-8
1,845
2.71875
3
[ "MIT" ]
permissive
<?php declare(strict_types=1); namespace Kerox\Messenger\Model\ProfileSettings; use Kerox\Messenger\Helper\ValidatorTrait; use Kerox\Messenger\Model\Common\Button\WebUrl; class HomeUrl implements \JsonSerializable { use ValidatorTrait; /** * @var string */ protected $url; /** * @var string */ protected $webviewHeightRation; /** * @var string */ protected $webviewShareButton; /** * @var bool */ protected $inTest; /** * HomeUrl constructor. * * @throws \Kerox\Messenger\Exception\InvalidUrlException */ public function __construct( string $url, string $webviewHeightRation = WebUrl::RATIO_TYPE_TALL, string $webviewShareButton = 'hide', bool $inTest = true ) { $this->isValidUrl($url); $this->url = $url; $this->webviewHeightRation = $webviewHeightRation; $this->webviewShareButton = $webviewShareButton; $this->inTest = $inTest; } /** * @throws \Kerox\Messenger\Exception\InvalidUrlException * * @return \Kerox\Messenger\Model\ProfileSettings\HomeUrl */ public static function create( string $url, string $webviewHeightRation = WebUrl::RATIO_TYPE_TALL, string $webviewShareButton = 'hide', bool $inTest = true ): self { return new self($url, $webviewHeightRation, $webviewShareButton, $inTest); } public function toArray(): array { return [ 'url' => $this->url, 'webview_height_ration' => $this->webviewHeightRation, 'webview_share_button' => $this->webviewShareButton, 'in_test' => $this->inTest, ]; } public function jsonSerialize(): array { return $this->toArray(); } }
true
e1fd8c4b2781555533dc3c6b1f73b7d9670f8e09
PHP
HueJack/logicasoft.cashback
/lib/usercashbackhandler.php
UTF-8
3,058
2.578125
3
[ "MIT" ]
permissive
<?php /** * Created by: Nikolay Mesherinov * Email: mnikolayw@gmail.com **/ namespace Logicasoft\Cashback; use Bitrix\Main\Event; use Bitrix\Main\Localization\Loc; /** * Класс предоставляет методы для добавления и отмены кэшбека * * Class UserCashbackHandler * @package Logicasoft\Cashback */ class UserCashbackHandler { public static function addCashback(float $cashbackValue, string $currency, int $userId, int $orderId) { $saleUserAccount = \CSaleUserAccount::GetByUserID($userId, $currency); //Сразу не будем устанавливать сумму, иначе счет создастся, но без транзакции if (empty($saleUserAccount)) { \CSaleUserAccount::Add( [ 'USER_ID' => $userId, 'CURRENCY' => $currency, 'NOTE' => Loc::getMessage('LLC_CASHBACK_NOTE') ] ); } \CSaleUserAccount::UpdateAccount( $userId, $cashbackValue, $currency, 'Кэшбек', $orderId ); $event = new Event( 'logicasoft.cashback', 'onAfterCashbackAdd', [ 'CASHBACK_AMOUNT' => $cashbackValue, 'CURRENCY' => $currency, 'ORDER_ID' => $orderId, 'USER_ID' => $userId, ] ); $event->send(); } public static function rollbackCashback(int $userId, int $orderId, string $currency) { $transactIterator = \CSaleUserTransact::GetList( [], [ 'USER_ID' => $userId, 'ORDER_ID' => $orderId, 'DEBIT' => 'Y', '!NOTES' => 'CANCELED' ], false, false, [ 'ID', 'AMOUNT' ] ); $cashbackValue = 0; while ($item = $transactIterator->Fetch()) { //Будем сразу добавлять и обновлять, чтобы в случае выключенного света была минимальная потеря \CSaleUserAccount::UpdateAccount( $userId, -(float)$item['AMOUNT'], $currency, Loc::getMessage('LLC_CASHBACK_CANCEL_CASHBACK_DESCR'), $orderId ); \CSaleUserTransact::Update( $item['ID'], [ 'NOTES' => 'CANCELED' ] ); $cashbackValue += $item['AMOUNT']; } $event = new Event( 'logicasoft.cashback', 'onAfterCashbackRollback', [ 'CASHBACK_AMOUNT' => $cashbackValue, 'CURRENCY' => $currency, 'ORDER_ID' => $orderId, 'USER_ID' => $userId ] ); $event->send(); } }
true
f6963090dec0d55025b8d0c6a81aaa3370c04618
PHP
adamelso/ordering-test
/src/Offer/OfferContainer.php
UTF-8
5,711
3.046875
3
[]
no_license
<?php namespace FeelUnique\Ordering\Offer; use FeelUnique\Ordering\Model\Rule; use FeelUnique\Ordering\Model\Action; use FeelUnique\Ordering\Model\ProductOffer; use FeelUnique\Ordering\Model\Category; /** * @author Adam Elsodaney <adam.elso@gmail.com> */ class OfferContainer implements \ArrayAccess, \IteratorAggregate { /** * @var array */ protected $offers; /** * @param array $data */ public function __construct(array $data = array()) { foreach ($data as $offerName => $offerData) { if ($offerData['active']) { if (array_key_exists('offer', $offerData)) { $offer = $this->createOfferFromName($offerData['offer']); } else { $rules = array(); foreach ($offerData['rules'] as $ruleData) { $rules[] = $this->createRule($ruleData['type'], $ruleData['configuration']); } $offer = $this->createOffer( $offerData['name'], $rules, $offerData['actions'] ); } $this->offsetSet($offerName, $offer); } } } /** * @return \Iterator */ public function getIterator() { return count($this->offers) ? new \ArrayIterator($this->offers) : new \EmptyIterator() ; } /** * @param string $offerName * @param ProductOffer offerName */ public function offsetSet($offerName, $offer) { $this->offers[$offerName] = $offer; } /** * @param string $offerName * @return ProductOffer */ public function offsetGet($offerName) { return $this->offers[$offerName]; } /** * @param string $offerName * @return boolean */ public function offsetExists($offerName) { return array_key_exists($offerName, $this->offers); } /** * @param string $offerName */ public function offsetUnset($offerName) { unset($this->values[$offerName]); } /** * Create offer rule of given type and configuration. * * @param string $type * @param array $configuration * @return Rule */ public static function createRule($type, array $configuration) { $rule = new Rule(); $rule->setType($type); $rule->setConfiguration($configuration); return $rule; } /** * Create offer action of given type and configuration. * * @param string $type * @param array $configuration * @return Action */ public static function createAction($type, array $configuration) { $action = new Action(); $action->setType($type); $action->setConfiguration($configuration); return $action; } /** * Create offer with set of rules and actions. * * @param string $name * @param array $rules * @param array $actions * @return ProductOffer */ public static function createOffer($name, array $rules, array $actions) { $offer = new ProductOffer(); $offer->setName($name); foreach ($rules as $rule) { $offer->addRule($rule); } foreach ($actions as $action) { $offer->addAction($action); } return $offer; } /** * @param string $name * @return ProductOffer * @throws \InvalidArgumentException */ public static function createOfferFromName($name) { switch (true) { case preg_match('/^(\d{1,2}) for the price of (\d{1,2})$/', $name, $matches): return static::createBulkOffer($name, $matches[1]); case preg_match('/^Buy ([A-z\'\-\ ]+) & get ([A-z\'\-\ ]+) for (100|\d{1,2})% off$/', $name, $matches): return static::createCombinationOffer($name, $matches[1], $matches[2], $matches[3]); default: throw new \InvalidArgumentException(sprintf("'%s' is not a recognized offer", $name)); } } /** * @param string $name * @param string $categoryQualifier * @param string $categoryDiscountable * @param float $discountPercentage * @return ProductOffer */ public static function createCombinationOffer($name, $categoryQualifier, $categoryDiscountable, $discountPercentage) { $comboCategoryRule = static::createRule(Rule::PRODUCT_CATEGORY_COMBINATION_RULE, array( 'qualifier' => $categoryQualifier, 'discountable' => $categoryDiscountable, 'count' => 1, )); $halfDiscountAction = static::createAction(Action::PERCENTAGE_DISCOUNT_ACTION, array( 'amount' => 50, 'category' => $categoryDiscountable, )); return static::createOffer($name, array($comboCategoryRule), array($halfDiscountAction)); } /** * @param string $name * @param integer $productCount * @return ProductOffer */ public static function createBulkOffer($name, $productCount) { $bulkCountRule = static::createRule(Rule::PRODUCT_COUNT_RULE, array( 'count' => $productCount )); $bulkCategoryRule = static::createRule(Rule::PRODUCT_CATEGORY_RULE, array( 'category' => null, )); $fullDiscountAction = static::createAction(Action::PERCENTAGE_DISCOUNT_ACTION, array( 'amount' => 100 )); return static::createOffer($name, array($bulkCountRule), array($fullDiscountAction)); } }
true
265d7b80ee1512a3d1a188874a792d53e5453c3d
PHP
RedaMALI/HelloLaravel
/app/Library/Services/GoogleLoginService.php
UTF-8
1,484
2.6875
3
[]
no_license
<?php namespace App\Library\Services; class GoogleLoginService { protected $client; public function __construct(\Google_Client $client) { $this->client = $client; $this->client->setClientId(\Config::get('google.client_id')); $this->client->setClientSecret(\Config::get('google.client_secret')); $this->client->setDeveloperKey(\Config::get('google.api_key')); $this->client->setRedirectUri(\Config::get('app.url') . "/loginCallback"); $this->client->setScopes([ 'https://www.googleapis.com/auth/youtube', 'https://www.googleapis.com/auth/youtube.readonly', ]); $this->client->setAccessType('offline'); } public function isLoggedIn() { if (\Session::has('google_token')) { $this->client->setAccessToken(\Session::get('google_token')); } else { return false; } if ($this->client->isAccessTokenExpired()) { \Session::put('google_token', $this->client->getRefreshToken()); } return !$this->client->isAccessTokenExpired(); } public function login($code) { $this->client->authenticate($code); $token = $this->client->getAccessToken(); \Session::put('google_token', $token); return $token; } public function logout() { \Session::put('google_token', NULL); } public function getLoginUrl() { $authUrl = $this->client->createAuthUrl(); return $authUrl; } }
true
24cf0d9f70d7da80714bd545026c2a7e5e4156f3
PHP
chkir/humhub
/protected/humhub/commands/MessageController.php
UTF-8
3,623
2.515625
3
[]
no_license
<?php /** * @link https://www.humhub.org/ * @copyright Copyright (c) 2015 HumHub GmbH & Co. KG * @license https://www.humhub.com/licences */ namespace humhub\commands; use Yii; use yii\console\Controller; use yii\console\Exception; use yii\helpers\Console; use yii\helpers\FileHelper; use yii\helpers\VarDumper; use yii\i18n\GettextPoFile; /** * Extracts messages to be translated from source files. * * @inheritdoc */ class MessageController extends \yii\console\controllers\MessageController { /** * Extracts messages for a given module from source code. * * @param string $moduleId */ public function actionExtractModule($moduleId) { $module = Yii::$app->getModule($moduleId); $configFile = Yii::getAlias('@humhub/config/i18n.php'); $config = array_merge([ 'translator' => 'Yii::t', 'overwrite' => false, 'removeUnused' => false, 'sort' => false, 'format' => 'php', 'ignoreCategories' => [], ], require($configFile)); $config['sourcePath'] = $module->getBasePath(); if (!is_dir($config['sourcePath'] . '/messages')) { @mkdir($config['sourcePath'] . '/messages'); } $files = FileHelper::findFiles(realpath($config['sourcePath']), $config); $messages = []; foreach ($files as $file) { $messages = array_merge_recursive($messages, $this->extractMessages($file, $config['translator'], $config['ignoreCategories'])); } foreach ($config['languages'] as $language) { $dir = $config['messagePath'] . DIRECTORY_SEPARATOR . $language; if (!is_dir($dir)) { @mkdir($dir); } $this->saveMessagesToPHP($messages, $dir, $config['overwrite'], $config['removeUnused'], $config['sort']); } } /** * @inheritdoc */ protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort) { $dirNameBase = $dirName; foreach ($messages as $category => $msgs) { /** * Fix Directory */ $module = $this->getModuleByCategory($category); if ($module !== null) { // Use Module Directory $dirName = str_replace(Yii::getAlias("@humhub/messages"), $module->getBasePath() . '/messages', $dirNameBase); preg_match('/.*?Module\.(.*)/', $category, $result); $category = $result[1]; } else { // Use Standard HumHub Directory $dirName = $dirNameBase; } $file = str_replace("\\", '/', "$dirName/$category.php"); $path = dirname($file); FileHelper::createDirectory($path); $msgs = array_values(array_unique($msgs)); $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]); $this->stdout("Saving messages to $coloredFileName...\n"); $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category); } } /** * Returns module instance by given message category. * * @param string $category * @return \yii\base\Module */ protected function getModuleByCategory($category) { if (preg_match('/(.*?)Module\./', $category, $result)) { $moduleId = strtolower($result[1]); $module = Yii::$app->getModule($moduleId, true); return $module; } return null; } }
true
64d3535d990510fc31465293f01c39301dd8a1de
PHP
apachish/b2b
/database/seeds/MembershipSeed.php
UTF-8
1,458
2.53125
3
[]
no_license
<?php use App\Membership; use Illuminate\Database\Seeder; class MembershipSeed extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $memberships = array( array('id' => '1','plan_name' => 'Gold','price' => '150','duration' => '8','product_upload' => '9','no_of_category' => '7','no_of_enquiry' => '10','locale' => 'fa','status' => '1','created_at' => '2019-06-09 00:00:00','updated_at' => '2019-06-09 00:00:00'), array('id' => '2','plan_name' => 'نقره ای ','price' => '100000','duration' => '3','product_upload' => '5','no_of_category' => '4','no_of_enquiry' => '5','locale' => 'fa','status' => '1','created_at' => '2019-06-09 00:00:00','updated_at' => '2019-06-09 00:00:00'), array('id' => '3','plan_name' => 'Bronze','price' => '5000','duration' => '3','product_upload' => '2','no_of_category' => '5','no_of_enquiry' => '4','locale' => 'fa','status' => '1','created_at' => '2019-06-09 00:00:00','updated_at' => '2019-06-09 00:00:00'), array('id' => '4','plan_name' => 'ازاد','price' => '0','duration' => '12','product_upload' => '15','no_of_category' => '11','no_of_enquiry' => '5','locale' => 'fa','status' => '1','created_at' => '2019-06-09 00:00:00','updated_at' => '2019-06-09 00:00:00') ); foreach (array_chunk($memberships, 250) as $set) { Membership::insert($set); } } }
true
c348609781c95b6588f4b0e902b1222503374357
PHP
ProfessorFrancken/ProfessorFrancken
/tests/Francken/Association/Members/BirthdateTest.php
UTF-8
1,752
3.015625
3
[]
no_license
<?php declare(strict_types=1); namespace Francken\Tests\Association\Members; use DateTimeImmutable; use Francken\Association\Members\Birthdate; use InvalidArgumentException; use PHPUnit\Framework\TestCase; class BirthdateTest extends TestCase { /** @test */ public function it_can_be_constructed_from_a_string() : void { $birthdate = Birthdate::fromString('2019-01-01'); $this->assertSame('2019-01-01', $birthdate->toString()); } /** @test */ public function it_does_not_allow_invalid_formats_when_constructing_from_a_string() : void { $this->expectException(InvalidArgumentException::class); Birthdate::fromString('01-2019-01'); } /** @test */ public function it_can_be_constructed_from_a_datetime() : void { $birthdate = Birthdate::fromDateTime( DateTimeImmutable::createFromFormat('Y-m-d', '2019-01-01') ); $this->assertSame('2019-01-01', $birthdate->toString()); } /** @test */ public function it_has_no_time_information_when_converting_to_datetime() : void { $birthdate = Birthdate::fromDateTime( DateTimeImmutable::createFromFormat('Y-m-d', '2019-01-01') ); $this->assertEquals( '2019-01-01T00:00:00', $birthdate->toDateTime()->format('Y-m-d\TH:i:s') ); } /** @test */ public function it_finds_the_age_of_a_person_at_a_given_date() : void { $birthdate = Birthdate::fromDateTime( DateTimeImmutable::createFromFormat('Y-m-d', '1993-01-01') ); $this->assertEquals( 26, $birthdate->ageAt(DateTimeImmutable::createFromFormat('Y-m-d', '2019-01-01')) ); } }
true
5122a6262f7864244f59171270f47253815c7fe8
PHP
esirbis5732/LS
/DZ1/Zadanie1.php
UTF-8
158
3.265625
3
[]
no_license
<pre> <?php $name = 'Sergei'; $age = '25'; echo "Меня зовут: $name" . PHP_EOL; echo "Мне '.$age.' лет" . PHP_EOL; echo "\"!|\/'\"\\" .PHP_EOL;
true
7b9b345a06cbf3c29c377138fc9d992161f33e86
PHP
marianna-stiller/forraskod_serulekenyseg_elemzes
/machine_learning_app/tanulo_adatok/sql-injection-in-php_safeupdate.php
UTF-8
921
2.96875
3
[]
no_license
<?php if ( isset( $_GET['first_name'], $_GET['last_name'], $_GET['birth_date'] ) ) { $update_query = "UPDATE students SET first_name=:first_name, last_name=:last_name, birth_date=:birth_date WHERE id=:id"; $prepared_statement = $pdo->prepare( $update_query ); $prepared_statement->bindParam( 'first_name', $_GET['first_name'] ); $prepared_statement->bindParam( 'last_name', $_GET['last_name'] ); $prepared_statement->bindParam( 'birth_date', $_GET['birth_date'] ); $prepared_statement->bindParam( 'id', $_GET['id'] ); $prepared_statement->execute(); $result = $prepared_statement->rowCount(); if ( $result ) { ?> <div class="alert alert-success" role="alert"> User updated </div> <?php } else { ?> <div class="alert alert-warning" role="alert"> There was a problem while updating the user. </div> <?php } ?> <a class="btn btn-primary active" href="?action=search">Back</a> <?php }
true
a6f671a91189423e01087693ed115c7db033940c
PHP
codemossaka/pandora-2.0
/core/libs/lib.rules.php
UTF-8
2,566
2.953125
3
[]
no_license
<?php namespace core\libs; use Exception; use debug; class rules { private static $rules = []; public static function ruleInt(&$value, $params) { $valid = preg_match('/^[+-]?[0-9]+$/', $value); $message = ''; if (!$valid) { $message = 'Введите целое число'; } else { $value = (int) $value; } return [$valid, $message]; } /* public static function ruleFile($value, $params) { } */ public static function ruleEmail($value, $params) { $valid = preg_match('/^[\w\.-_]+@[\w\.-_]+\.[\w\.]+$/', $value); $message = ''; if (!$valid) { $message = 'Введите адрес электронной почты в правильном формате, напрмиер: kelThuzad@undead.com'; } return [$valid, $message]; } public static function ruleRegexp($value, $params) { if (!isset($params['param'])) { throw new Exception(debug::_('RULES_RULE_REGEXP_PATTERN_NOT_SET'), E_WARNING); } $valid = preg_match($params['param'], $value); $message = ''; if (!$valid) { $message = 'Неверный вормат поля "{$field_name}"'; } return [$valid, $message]; } public static function ruleFloat(&$value, $params) { $valid = preg_match('/^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/', $value); $message = ''; if (!$valid) { $message = 'Введите целое или дробное число'; } else { $value = (float) $value; } return [$valid, $message]; } public static function ruleTrim(&$value, $params) { $value = trim($value); return [true, '']; } public static function ruleRequired($value, $params) { $valid = ($value != ''); $message = ''; if (!$valid) { $message = 'Заполните поле "{$field_name}"'; } return [$valid, $message]; } public static function add($rule, $rulesCallback) { $rule = 'rule'.ucfirst($rule); if (method_exists(__CLASS__, $rule)) { throw new Exception(debug::_('RULES_ADD_DEFAULT_RULE_CAN_NOT_OVERRIDE'), E_WARNING); } if (!is_function($rulesCallback)) { throw new Exception(debug::_('RULES_ADD_CALLBACK_MUST_BE_FUNCTION'), E_WARNING); } self::$rules[$rule] = $rulesCallback; } public static function validate($rule, &$value, $params) { $rule = 'rule'.ucfirst($rule); if (method_exists(__CLASS__, $rule)) { $validator = [__CLASS__, $rule]; } else { $validator = self::$rules[$rule] ?? null; if (!$validator) { throw new Exception(debug::_('RULES_VALIDATE_RULE_NOT_REGISTERED', $rule), E_WARNING); } } return call_user_func_array($validator, [&$value, $params]); } }
true
3827037c659cf1946f815afaef4af82d832fcba1
PHP
Koc/portfolio
/3-services/src/Reporting/Report/Weekly/WeeklySpreadsheetStyler.php
UTF-8
4,081
2.5625
3
[]
no_license
<?php namespace App\Reporting\Report\Weekly; use App\Reporting\Generated\Cell; use App\Reporting\Renderer\SpreadsheetStyler; use App\Reporting\Renderer\SpreadsheetStylerUtil; use PhpOffice\PhpSpreadsheet\Cell\Cell as ExcelCell; use PhpOffice\PhpSpreadsheet\Style; use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet; class WeeklySpreadsheetStyler implements SpreadsheetStyler { public function applySheetStyling(Worksheet $worksheet): void { //FIXME: UBUNTU XLSX ширина столбцов в cм показывается, но измеряется в своих единицах $worksheet->getColumnDimension('A')->setWidth("13.75"); $worksheet->getColumnDimension('B')->setWidth("7.2"); $worksheet->getColumnDimension('C')->setWidth("9.5"); $worksheet->getColumnDimension('D')->setWidth("9.41"); $worksheet->getColumnDimension('E')->setWidth("5.25"); $worksheet->getColumnDimension('F')->setWidth("5.25"); $worksheet->getColumnDimension('G')->setWidth("5.25"); $worksheet->getColumnDimension('H')->setWidth("5.25"); $worksheet->getColumnDimension('I')->setWidth("5.25"); $worksheet->getColumnDimension('J')->setWidth("5.25"); $worksheet->getColumnDimension('K')->setWidth("4.5"); $worksheet->getColumnDimension('L')->setWidth("4.5"); // //FIXME: высота 1 = 0.04см // $worksheet->getRowDimension(4)->setRowHeight("28.25"); } public function applyCellStyling(ExcelCell $excelCell, Cell $cell): void { //FIXME: смотри DailySpreadsheetStyler и делай как там $styles = [ 'font' => [ 'bold' => false, 'name' => 'Arial Cyr', 'size' => '8', 'color' => ['rgb' => '130000'], ], 'borders' => [ 'allBorders' => [ 'borderStyle' => Style\Border::BORDER_THIN, ], ], ]; switch ($cell->getPurpose()) { case WeeklyCellPurpose::COLUMN_CAPTION: $styles['alignment']['wrapText'] = true; $styles['alignment']['horizontal'] = Style\Alignment::HORIZONTAL_CENTER; $styles['alignment']['vertical'] = Style\Alignment::VERTICAL_CENTER; $styles['font']['bold'] = true; $styles['fill'] = [ 'fillType' => Style\Fill::FILL_SOLID, 'startColor' => [ 'rgb' => 'C0C0C0', ], 'endColor' => [ 'rgb' => 'C0C0C0', ], ]; break; case WeeklyCellPurpose::ROW_CAPTION: $styles['alignment']['wrapText'] = true; $styles['font']['bold'] = true; break; case WeeklyCellPurpose::SIMPLE: break; case WeeklyCellPurpose::CHANGE_ODD: $styles['alignment']['horizontal'] = Style\Alignment::HORIZONTAL_RIGHT; break; case WeeklyCellPurpose::CHANGE_POSITIVE_ODD: $styles['font']['color'] = ['rgb' => '008000']; break; case WeeklyCellPurpose::CHANGE_NEGATIVE_ODD: $styles['font']['color'] = ['rgb' => '7F0028']; break; case WeeklyCellPurpose::TABLE_CAPTION: $styles['font']['bold'] = true; $styles['font']['size'] = 14; $styles['fill'] = [ 'fillType' => Style\Fill::FILL_SOLID, 'startColor' => [ 'rgb' => 'FFCC99', ], 'endColor' => [ 'rgb' => 'FFCC99', ], ]; break; } SpreadsheetStylerUtil::applyNoteStyle($excelCell, ['bold' => true]); SpreadsheetStylerUtil::applyStylesFromArray($excelCell, $styles); } }
true
6863a78d345d0e1de01ed2f3be103431babe6309
PHP
qingsongsun/vgj
/system/library/session.php
UTF-8
800
2.6875
3
[]
no_license
<?php class Session { public $data = array(); public function __construct() { // $redis=new Redis(); // $redis->connect('127.0.0.1',6379); if (!session_id()) { ini_set('session.use_only_cookies', 'Off'); ini_set('session.use_trans_sid', 'On'); ini_set('session.cookie_httponly', 'Off'); // ini_set("session.save_handler","redis"); // ini_set("session.save_path","tcp://127.0.0.1:6379"); session_set_cookie_params(0, '/'); if (isset($_GET['session_id'])) { session_id($_GET['session_id']); } // if ($redis->get('session_id')) { // session_id($redis->get('session_id')); // } session_start(); } $this->data =& $_SESSION; } public function getId() { return session_id(); } public function destroy() { return session_destroy(); } }
true
e7a6ba77757e11a2bbf2001e9dd1d2b16bfb6dc5
PHP
CorinaHebristean/crud-application
/list.php
UTF-8
868
2.53125
3
[]
no_license
<?php require_once "dbconfig.php"; require_once "functions.php"; if (isset($_SESSION['user_id'])) { $user_id = $_SESSION["user_id"]; } $users = get_all_users(); session_message(); logged_in_user_header(); ?> <p> <a href="register_form.php">Register users</a> </p> <?php if (check_authentication()): ?> <p> <a href="update_form.php?id=<?php echo $user_id ?>" >Edit my profile</a> </p> <?php endif; ?> <table border=1> <tr> <th>ID</th> <th>Username</th> <th>Email</th> <?php if ( check_authentication()): ?> <th>Password</th> <?php endif; ?> <th>City</th> <?php if ( check_authentication()): ?> <th>Actions</th> <?php endif; ?> </tr> <?php foreach ($users as $user): ?> <?php include "user_row.php"; ?> <?php endforeach ?> </table>
true
42040c569b0fe5db864cc35fc5e961d4553ae15b
PHP
yubinchen18/blackjackproject
/includes/functions.php
UTF-8
3,257
3.046875
3
[]
no_license
<?php /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $originalCardDeck = array ( "diamonds" => array ( 1 => '1','2','3','4','5','6','7','8','9','10','11','12','13' ), "clubs" => array ( 1 => '1','2','3','4','5','6','7','8','9','10','11','12','13' ), "hearts" => array ( 1 => '1','2','3','4','5','6','7','8','9','10','11','12','13' ), "spades" => array ( 1 => '1','2','3','4','5','6','7','8','9','10','11','12','13' ) ); //Randomly draws one card out of card deck, determines its face value, then removes the card from the deck. returns array[][display]/[value] //Initial ACE value = 11 function DrawCards(&$deck, $amount = 1) { for ($i=1; $i<=$amount;$i++) { $suit = array_rand($deck); $faceCard = array_rand($deck[$suit]); unset($deck[$suit][$faceCard]); if ($faceCard > 10) $faceValue = 10; else $faceValue = (int)$faceCard; if ($faceCard == 1) $cardName = "ace"; elseif ($faceCard>1 && $faceCard<11) $cardName = $faceCard; elseif ($faceCard == 11) $cardName = "jack"; elseif ($faceCard == 12) $cardName = "queen"; elseif ($faceCard == 13) $cardName = "king"; $returnValue[] = array ('display' => "$cardName"."_of_"."$suit.png", 'value' => $faceValue); } return $returnValue; } // Count remaining cards in deck. function CountRemainingCards($deck) { $cards = 0; foreach ($deck as $value) $cards = $cards + count($value); return $cards; } // Sum up values of cards in an array. function SumOflValues($cards) { $sum = 0; foreach ($cards as $card) { $sum = $sum + $card['value']; } return $sum; } //Display cards on middle of the screen. function DisplayCards($cards, $folder) { foreach ($cards as $card) { echo "<img src='".$folder.$card['display']."' align= \"left\" heights= \"145.2\" width= \"100\" hspace=\"5\">"; } } //Reset. //Find key value pair in array function FindCard($array, $key, $val) { foreach ($array as $item) if (isset($item[$key]) && $item[$key] == $val) return true; return false; } function ChangeAceValue(&$array,$oldval,$newval) { $key = 'value'; foreach ($array as &$item) { if (isset($item[$key]) && $item[$key] == $oldval) { $item[$key] = $newval; } } } $spinWheel = array("hearts" => array(1 => '1','2','3','4','5','6','7','8','9','10','11','12','13'));
true
cbbb887351ed05b921060a1292d1220b9b100b33
PHP
jesusrv1103/blog
/database/seeds/PostsTableSeeder.php
UTF-8
1,693
2.703125
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Seeder; use App\Post; use Carbon\Carbon; class PostsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { Post::truncate(); $post = new Post; $post->title = "Mi primer Post"; $post->excerpt ="Extracto de mi primer post"; $post->body= "<p>Contenido de mi primer post</p>"; $post->category_id=1; $post->published_at= Carbon::now()->subDays(4); $post->save(); $post = new Post; $post->title = "Mi segundo Post"; $post->excerpt ="Extracto de mi segundo post"; $post->body= "<p>Contenido de mi segundo post</p>"; $post->category_id=1; $post->published_at= Carbon::now()->subDays(3); $post->save(); $post = new Post; $post->title = "Mi tercer Post"; $post->excerpt ="Extracto de mi tercer post"; $post->body= "<p>Contenido de mi tercer post</p>"; $post->category_id=1; $post->published_at= Carbon::now()->subDays(2); $post->save(); $post = new Post; $post->title = "Mi cuarto Post"; $post->excerpt ="Extracto de mi cuarto post"; $post->body= "<p>Contenido de mi cuarto post</p>"; $post->category_id=2; $post->published_at= Carbon::now(); $post->save(); $post = new Post; $post->title = "Mi quinto Post"; $post->excerpt ="Extracto de mi quinto post"; $post->body= "<p>Contenido de mi quinto post</p>"; $post->category_id=2; $post->published_at= Carbon::now()->subDays(1); $post->save(); } }
true
0f2afd48db1af4c3e0e38a97558617a080ca87a9
PHP
9feed/senses-engine
/modules/Template.php
UTF-8
4,778
3.171875
3
[ "MIT" ]
permissive
<?php /** * Template constructor (template param in messages.send) * @author slmatthew * @package keyboard */ class Template { /** * @ignore */ private $type = 'carousel'; /** * @ignore */ private $elements = []; /** * Template constructor * @param string $type Template type * @return void * @since v0.6 */ public function __construct(string $type = 'carousel') { $this->type = $type; } /** * Add carousel element to template * @param array $buttons Buttons array. Can be obtain via TemplateButtons * @param string $title Card title * @param string $description Card description * @param string $photo_id Photo ID * @param array $action Docs: https://vk.cc/a8hzdu * @return void */ public function addCarouselElement(array $buttons, string $title = '', string $description = '', string $photo_id = '', array $action = []) { if($this->type !== 'carousel') throw new ParameterException(); if(empty($buttons) || (!$photo_id && !$title) || ($title && !$description)) throw new ParameterException(); $element = []; if($title) $element['title'] = $title; if($description) $element['description'] = $description; if($photo_id) $element['photo_id'] = $photo_id; if($buttons) $element['buttons'] = $buttons; if($action) $element['action'] = $action; $this->elements[] = $element; } /** * Get template * @param bool $json Should function return array or json * @return array|string * @since v0.6 */ public function get(bool $json = true) { $template = [ 'type' => $this->type, 'elements' => $this->elements ]; return $json ? $this->toJson($template) : $template; } /** * @ignore */ private function toJson(array $array): string { return json_encode($array, JSON_UNESCAPED_UNICODE); } } /** * Buttons constructor for templates * @author slmatthew * @package keyboard */ class TemplateButtons { /** * @ignore */ public $buttons = []; public const PRIMARY_BUTTON = 'primary'; public const SECONDARY_BUTTON = 'secondary'; public const NEGATIVE_BUTTON = 'negative'; public const POSITIVE_BUTTON = 'positive'; /** * Button constructor * @param array $action https://vk.com/dev/bots_docs_3 * @param string $color Button color * @return TemplateButtons * @since v0.6 */ public function addButton(array $action, string $color = ''): TemplateButtons { if(isset($action['payload'])) $action['payload'] = json_encode($action['payload'], JSON_UNESCAPED_UNICODE); if(isset($action['type']) && $action['type'] === 'text') { $this->buttons[] = [ 'action' => $action, 'color' => $color ]; } else { $this->buttons[] = [ 'action' => $action ]; } return $this; } /** * Text button constructor * @param string $label Text on the button * @param array $payload Payload * @param string $color Button color * @return TemplateButtons * @since 0.6 */ public function addTextButton(string $label, array $payload = [], string $color = self::PRIMARY_BUTTON): TemplateButtons { $this->addButton([ 'type' => 'text', 'label' => $label, 'payload' => $this->toJson($payload) ], $color); return $this; } /** * Location button constructor * @param array $payload Payload * @return TemplateButtons * @since 0.6 */ public function addLocationButton(array $payload = []): TemplateButtons { $this->addButton([ 'type' => 'location', 'payload' => $this->toJson($payload) ]); return $this; } /** * VK Pay button constructor * @param array $hash Hash * @param array $payload Payload * @return TemplateButtons * @since 0.6 */ public function addPayButton(array $hash, array $payload = []): TemplateButtons { $this->addButton([ 'type' => 'vkpay', 'hash' => http_build_query($hash), 'payload' => $this->toJson($payload) ]); return $this; } /** * Text button constructor * @param int $app_id Your application ID * @param int $owner_id Community or user id (for user ids owner_id < 0) * @param string $label Text on the button * @param string $hash Hash: https://vk.com/app123#{hash} * @param array $payload * @return TemplateButtons * @since 0.6 */ public function addAppButton(int $app_id, int $owner_id, string $label, string $hash = '', array $payload = []): TemplateButtons { $this->addButton([ 'type' => 'open_app', 'app_id' => $app_id, 'owner_id' => $owner_id, 'label' => $label, 'hash' => $hash, 'payload' => $this->toJson($payload) ]); return $this; } /** * Buttons getter * @return array * @since v0.6 */ public function get(): array { return $this->buttons; } /** * @ignore */ private function toJson(array $array): string { return json_encode($array, JSON_UNESCAPED_UNICODE); } } ?>
true
79eb55a2c0b034e90576e97c3fb81e77d93f234a
PHP
ministryofjustice/opg-use-an-lpa
/service-front/app/src/Common/src/Service/Csrf/SessionCsrfGuard.php
UTF-8
1,875
2.734375
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
<?php declare(strict_types=1); namespace Common\Service\Csrf; use Mezzio\Csrf\CsrfGuardInterface; use Mezzio\Session\SessionInterface; use function bin2hex; use function random_bytes; class SessionCsrfGuard implements CsrfGuardInterface { private string $requestId; public function __construct(private SessionInterface $session) { $this->requestId = bin2hex(random_bytes(8)); } /** * @inheritDoc */ public function generateToken(string $keyName = '__csrf'): string { $tokens = $this->cleanupTokens($this->session->get($keyName, [])); $newToken = bin2hex(random_bytes(16)); $tokens[$newToken] = $this->requestId; $this->session->set($keyName, $tokens); return $this->formatHash($newToken, $this->requestId); } /** * @inheritDoc */ public function validateToken(string $token, string $csrfKey = '__csrf'): bool { $storedTokens = $this->session->get($csrfKey, []); $tokenParts = $this->splitHash($token); $tokenId = $tokenParts['token']; return array_key_exists($tokenId, $storedTokens) && $token === $this->formatHash($tokenId, $storedTokens[$tokenId]); } protected function cleanupTokens(array $tokens): array { $currentRequestId = $this->requestId; return array_filter($tokens, function ($requestId) use ($currentRequestId) { return $requestId === $currentRequestId; }); } protected function formatHash(string $token, string $requestId): string { return sprintf('%s-%s', $token, $requestId); } protected function splitHash(string $hash): array { $data = explode('-', $hash); return [ 'token' => $data[0] ?? null, 'requestId' => $data[1] ?? null, ]; } }
true
53d0e87688b5b95c104e32b21a7b8df66e837923
PHP
doctor2/mySiteMvc
/www/controllers/articlesController.php
UTF-8
1,510
2.53125
3
[]
no_license
<?php class ArticlesController extends Controller { private $modelComment; private $modelRate; private $path = 'article/'; function __construct() { parent::__construct(); $this->model = new ArticleModel(); $this->modelComment = new CommentModel(); $this->modelRate = new RateModel(); } function index() { unset($_SESSION['SEARCH']); if (!empty($this->params['page'])){ $records = $this->model->getLimitedRecords($this->params['page']); $this->view->set('pageNumber', $this->params['page']); } else{ $records = $this->model->getLimitedRecords(1); $this->view->set('pageNumber', 1); } $this->view->set('numberOfLike', $this->modelRate->numberOfLike()); $this->view->set('numberOfRecords', $this->model->getNumberOfRecords()); $this->view->set('records', $records); $this->view->set('path', "/articles/page/"); $this->view->generate('Главная',$this->path.'articles.php'); } function article() { if (empty($this->params['id'])) Route::errorPage404(); if (@$_POST['enter'] && $this->params['id']) $this->modelComment->addComment($this->params['id'],$_SESSION['USER_ID'],$_POST['date'], $_POST['comment']); $record = $this->model->getRecord($this->params['id']); if (empty($record)) Route::errorPage404(); $comments = $this->modelComment->getAllComments($this->params['id']); $this->view->set('record', $record); $this->view->set('comments', $comments); $this->view->generate($record['title'],$this->path.'article.php'); } } ?>
true
7dd89baf48d1cbea4beb957fc27f6d1e2ae271d3
PHP
cstromquist/Appointment-Reminder
/app/models/reminder.php
UTF-8
2,248
2.6875
3
[]
no_license
<?php /** * Reminder model * * Email reminders which are generated using GD * * @package appointment reminder */ class Reminder extends AppModel { public $belongsTo = array( 'Technician', 'Company', 'CompanyService' ); public $validate = array( 'fname' => array( 'rule' => 'notEmpty', 'allowEmpty' => false, 'required' => true ), 'lname' => array( 'rule' => 'notEmpty', 'allowEmpty' => false, 'required' => true, 'message' => 'Please specify a last name.' ), 'service_message' => array( 'rule' => 'notEmpty', 'allowEmpty' => false, 'required' => true ), 'email' => array( 'rule' => 'email', 'allowEmpty' => false, 'required' => true, 'message' => 'Please enter a valid email.' ), 'features_benefits' => array( 'rule' => array('checkMaxList', 8), 'allowEmpty' => false, 'required' => true ), 'services' => array( 'rule' => array('checkMaxList', 10), 'allowEmpty' => false, 'required' => true ), 'other_services' => array( 'rule' => array('checkMaxList', 8), 'allowEmpty' => false, 'required' => true ) ); function checkMaxList($check, $limit) { $value = array_shift($check); $array_items = explode("\n", $value); $over_by = count($array_items) - $limit; if(count($array_items) > $limit) { return 'Please limit to '.$limit.' list items. You currently have ' . count($array_items) . ' items listed. Please remove ' . $over_by . ' items.'; } return true; } /** * Search name * * @param string $query * @return array */ function search($query) { $fields = array('id', 'fname', 'lname', 'email'); // check for first/last name and search by ONLY last name $array = explode(' ', $query); if(count($array) > 1) $find = $array[1]; else $find = $query; $results = $this->find( 'all', array( 'conditions' => "{$this->name}.lname LIKE '%$find%' OR {$this->name}.fname LIKE '%$find%'", 'fields' => $fields ) ); return $results; } }
true
9aff81c1957bc2cfea9a6570ff2b1094e6d5e759
PHP
hyperzecters/denliner
/ticket.php
UTF-8
451
2.515625
3
[ "MIT" ]
permissive
<?php function addTicket($noTicket,$ticketName,$departure_date,$ticketType,$seat){ $koneksi = mysql_connect('localhost','root',''); mysql_select_db('mtrain', $koneksi); $query = "INSERT INTO `ticket` (no_ticket, ticketname, departure_date, ticket_type, seat) VALUES ". "('$noTicket', '$ticketName', '$departure_date', '$ticketType', '$seat')"; if (!mysql_query($query)){ echo "Ticket Error".mysql_error()."<br><br>"; } mysql_close(); } ?>
true
98b96badac6509e089c5f0227e20462e5bf77f44
PHP
corwien/digtime
/app/Models/Article.php
UTF-8
1,229
2.765625
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Auth; use Carbon\Carbon; class Article extends Model { protected $fillable = [ 'title', 'content', 'user_id', 'category_id', 'slug', 'subtitle', 'published_at', 'views_count', 'comments_count', ]; /** * 和用户关联 * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo(User::class); } /** * 获取所有问题的评论 */ public function comments() { return $this->morphMany('App\Models\Comment', 'commentable'); } /** * 修改时间属性 * @param $date * * @return mixed * @demo https://www.laravist.com/blog/post/use-carbon-to-format-datetime-in-laravel-project */ public function getCreatedAtAttribute($date) { // 将时间推后两个月 $date = date("Y-m-d H:i:s", strtotime($date)); if(Carbon::now() > Carbon::parse($date)->addDays(30)) { return Carbon::parse($date); } return Carbon::parse($date)->diffForHumans(); } }
true
c4b6d81483117844506dade0edf8549c1d27ef37
PHP
huarachiabi/practica_5
/ejercicio3.php
UTF-8
627
3.09375
3
[]
no_license
<html> <head lang ="es"> <meta charset="utf-8" /> <title>ejercicio_3</title> </head> <body> <h1>TABLA DE AJEDREZ </h1> <table border="1"> <?php define("n", "10"); $a=1; $sw=0; for($j=1; $j<=n;$j++) { ?> <tr> <?php for($i=1; $i<=n;$i++) { if($sw==0) { if($i%2==0) { echo "<td bgcolor='white'>$a</td>"; }else { echo "<td bgcolor='black'>$a</td>"; } }else{ if($i%2==0) { echo "<td bgcolor='black'>$a</td>"; }else { echo "<td bgcolor='white'>$a</td>"; } } $a=$a+1; } if($sw==0) { $sw=1; }else{ $sw=0; } ?> </tr> <?php } ?> </table> </body> </html>
true
306c65a5c5a6667c474393e59842ff2ca848a74d
PHP
elektricmaster7/IE-Admin
/app/Model/Setting.php
UTF-8
1,806
2.546875
3
[ "MIT" ]
permissive
<?php App::uses('AppModel', 'Model'); class Setting extends AppModel { var $name = 'Setting'; //TRANSLATION /* * function getTablesList($ignore_sys_tables) * This function gets all the tables from the database * @param $ignore_sys_tables This param ignores the system tables when returning the * result tables */ //TODO: Remove already translated ready models function getTablesList($ignore_sys_tables = false){ $system_tables = array('groups_users'=>'groups_users','rules'=>'rules','settings'=>'settings'); $table_schema = $this->query("SELECT TABLE_NAME AS name FROM INFORMATION_SCHEMA.TABLES AS Backend WHERE TABLE_SCHEMA<>'information_schema' AND TABLE_NAME NOT LIKE '%_translations'"); $table_list = array(); foreach($table_schema as $tables){ $table_list[$tables['Backend']['name']] = $tables['Backend']['name']; } if($ignore_sys_tables){ return $table_list; }else{ $tables_list_clear = array_diff($table_list, $system_tables); return $tables_list_clear; } } /* * function createTranslationTable($model) * This function creates a translation table for the table passed as param * @param $table_name Name of the table selected */ function createTranslationTable($table_name){ $tableName = Inflector::singularize($table_name); $this->query("CREATE TABLE `".$tableName."_translations` ( `id` INT(10) NOT NULL AUTO_INCREMENT, `locale` VARCHAR(6) NOT NULL, `model` VARCHAR(255) NOT NULL, `foreign_key` INT(10) NOT NULL, `field` VARCHAR(255) NOT NULL, `content` TEXT NULL, PRIMARY KEY (`id`), INDEX `locale` (`locale`), INDEX `model` (`model`), INDEX `row_id` (`foreign_key`), INDEX `field` (`field`) )COLLATE='utf8_general_ci' ENGINE=InnoDB;"); } } ?>
true
404a54d2b61a64cd8f04f54d21fcd5c399b5b1e4
PHP
BerilBBJ/scraperwiki-scraper-vault
/Users/H/hubscraper/pitchfork-reviews.php
UTF-8
2,452
2.90625
3
[]
no_license
<?php $url = sprintf('/reviews/albums/1/'); do { $dom = new DOMDocument; @$dom->loadHTMLFile('http://pitchfork.com' . $url); $xpath = new DOMXPath($dom); $nodes = $xpath->query('//a[starts-with(@href, "/reviews/albums/")]'); print "{$nodes->length} nodes\n"; if (!$nodes->length) { break; } foreach ($nodes as $node) { $url = $node->getAttribute('href'); $dateNodes = $xpath->query('div/h4', $node); if (!$dateNodes->length) { continue; } $date = $dateNodes->item(0)->textContent; preg_match('/(\d+)$/', $date, $matches); $year = $matches ? $matches[1] : null; $data = array( 'artist' => $xpath->query('div/h1', $node)->item(0)->textContent, 'title' => $xpath->query('div/h2', $node)->item(0)->textContent, 'url' => $url, 'date' => $date, 'year' => $year, ); scraperwiki::save(array('url'), $data); } $nextNodes = $xpath->query('//a[@class="next"][starts-with(@href, "/reviews/albums/")]'); if (!$nextNodes->length) { break; } $url = $nextNodes->item(0)->getAttribute('href'); } while ($url); <?php $url = sprintf('/reviews/albums/1/'); do { $dom = new DOMDocument; @$dom->loadHTMLFile('http://pitchfork.com' . $url); $xpath = new DOMXPath($dom); $nodes = $xpath->query('//a[starts-with(@href, "/reviews/albums/")]'); print "{$nodes->length} nodes\n"; if (!$nodes->length) { break; } foreach ($nodes as $node) { $url = $node->getAttribute('href'); $dateNodes = $xpath->query('div/h4', $node); if (!$dateNodes->length) { continue; } $date = $dateNodes->item(0)->textContent; preg_match('/(\d+)$/', $date, $matches); $year = $matches ? $matches[1] : null; $data = array( 'artist' => $xpath->query('div/h1', $node)->item(0)->textContent, 'title' => $xpath->query('div/h2', $node)->item(0)->textContent, 'url' => $url, 'date' => $date, 'year' => $year, ); scraperwiki::save(array('url'), $data); } $nextNodes = $xpath->query('//a[@class="next"][starts-with(@href, "/reviews/albums/")]'); if (!$nextNodes->length) { break; } $url = $nextNodes->item(0)->getAttribute('href'); } while ($url);
true
a8b4e4acf0516c934ab17abab6ec949accb41837
PHP
ramonsodoma/omp
/controllers/modals/editorDecision/form/InitiateReviewForm.inc.php
UTF-8
2,596
2.578125
3
[]
no_license
<?php /** * @file controllers/modals/editorDecision/form/InitiateReviewRoundForm.inc.php * * Copyright (c) 2003-2008 John Willinsky * Distributed under the GNU GPL v2. For full terms see the file docs/COPYING. * * @class InitiateReviewForm * @ingroup controllers_modal_editorDecision_form * * @brief Form for creating the first review round for a submission */ import('controllers.modals.editorDecision.form.EditorDecisionForm'); class InitiateReviewForm extends EditorDecisionForm { /** * Constructor. * @param $monograph Monograph */ function InitiateReviewForm($monograph) { parent::EditorDecisionForm($monograph, 'controllers/modals/editorDecision/form/initiateReviewForm.tpl'); // Validation checks for this form $this->addCheck(new FormValidatorPost($this)); } // // Overridden template methods // /** * Fetch the modal content * @param $request PKPRequest * @see Form::fetch() */ function fetch(&$request) { $templateMgr =& TemplateManager::getManager(); $monograph =& $this->getMonograph(); $this->setData('round', $monograph->getCurrentRound()); return parent::fetch($request); } /** * Assign form data to user-submitted data. * @see Form::readInputData() */ function readInputData() { $this->readUserVars(array('selectedFiles')); } /** * Start review stage * @param $args array * @param $request PKPRequest * @see Form::execute() */ function execute($args, &$request) { // 1. Increment the monograph's workflow stage $monograph =& $this->getMonograph(); $monograph->setCurrentStageId(WORKFLOW_STAGE_ID_INTERNAL_REVIEW); $monographDao =& DAORegistry::getDAO('MonographDAO'); $monographDao->updateMonograph($monograph); // 2. Create a new internal review round // FIXME #6102: What to do with reviewType? $reviewRoundDao =& DAORegistry::getDAO('ReviewRoundDAO'); $reviewRoundDao->build($monograph->getId(), REVIEW_TYPE_INTERNAL, 1, 1, REVIEW_ROUND_STATUS_PENDING_REVIEWERS); // 3. Assign the default users import('classes.submission.common.Action'); Action::assignDefaultStageParticipants($monograph->getId(), WORKFLOW_STAGE_ID_INTERNAL_REVIEW); // 4. Add the selected files to the new round $selectedFiles = $this->getData('selectedFiles'); if(is_array($selectedFiles)) { $filesForReview = array(); foreach ($selectedFiles as $selectedFile) { $filesForReview[] = explode("-", $selectedFile); } $reviewRoundDAO =& DAORegistry::getDAO('ReviewRoundDAO'); $reviewRoundDAO->setFilesForReview($monograph->getId(), REVIEW_TYPE_INTERNAL, 1, $filesForReview); } } } ?>
true
ea98e4701cbab065366d93ab0601c85d57d40653
PHP
johnnyGZG/PruebasCodigo
/database/migrations/2017_02_15_023715_crear_productos_tabla.php
UTF-8
921
2.6875
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CrearProductosTabla extends Migration { /** * Run the migrations. * * @return void */ public function up() { // Realizar Cambios Schema::create('productos', function(Blueprint $tabla) { $tabla->increments("id"); // Valor autoincrementable $tabla->integer("user_id")->unsigned()->index(); $tabla->string("titulo"); $tabla->text("descripcion"); $tabla->decimal("precio",9,2); //centavos $tabla->timestamps(); // Fecha Creacion y actualizacion }); } /** * Reverse the migrations. * * @return void */ public function down() { // revertir los mismos cambios Schema::drop('productos'); } }
true
1cfc8ffe0856bb16f61960bb12c6a44ed1e9d937
PHP
FdoEstefania/proyecto_oee
/inc/tblOrdenes.php
UTF-8
757
2.703125
3
[]
no_license
<?php $id = $_SESSION['fk_empresa']; $control = new OrdenesControl(); $retorno = $control->getOrdenes($id); ?> <!-- Tabla HTML que muestar los datos de ordenes existentes--> <table class="table table-hover table-bordered table-striped" id="tblOrden"> <thead> <tr> <th scope="col">N° orden</th> <th scope="col">Cod. articulo</th> <th scope="col">T. lote</th> </tr> </thead> <tbody> <?php foreach($retorno as $row){ ?> <tr> <td scope="row"><?php echo $row["num_orden"] ;?></td> <td><?php echo $row["cod_articulo"] ;?></td> <td><?php echo $row["tamano_lote"] ;?></td> </tr> <?php } ?> </tbody> </table>
true
9c774b2b4e908c3de03f0361dc9c28252f339c2c
PHP
kukurykum/tsai
/master/backend/App/Model/Entity/ModelEntity.php
UTF-8
473
2.921875
3
[]
no_license
<?php namespace App\Model\Entity; use App\Database\Entity\Entity; class ModelEntity extends Entity { private $id; private $name; /** * @return mixed */ public function getId() { return $this->id; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name) { $this->name = $name; } }
true
2664616b3932a5606c1bf4af2c2375403e0bf83b
PHP
eduardaarosaa/SystemCS
/api_bistamp.php
UTF-8
1,122
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php $link = mysqli_connect("localhost", "root", "", "sistema"); $url= "https://www.bitstamp.net/api/ticker/"; $request_headers = array(); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 60); curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $data = curl_exec($ch); if (curl_errno($ch)) { print "Error: " . curl_error($ch); } else { // Show me the result // passo de JSON para array var_dump($transaction = json_decode($data, TRUE)); if($transaction == true){ echo "conexão Ok"; }else{ echo "Eroor"; } print_r($transaction['last']); print_r($transaction['volume']); $valor = $transaction['last']; $volume = $transaction['volume']; print_r($valor); print_r($volume); curl_close($ch); } $inserir = "insert into bitstamp (valor,volume) values ('$valor','$volume')"; $resultado = mysqli_query($link,$inserir); if($resultado = true){ echo "dados adicionado ao banco"; }else{ echo "Error!"; } ?>
true
c1479e3ca1503be995e5973e0664a9685844f4dd
PHP
nxwzj0/INCIDENT
/dto/ConditionDtDto.php
UTF-8
1,100
2.59375
3
[]
no_license
<?php //***************************************************************************** // システム名   :インシデント管理システム // サブシステム名 : // 処理名     :ConditionDtDto // 作成日付・作成者:2018.01.19 NEWTOUCH)newtouch // 修正履歴    : //***************************************************************************** require_once('./dto/CommonDto.php'); /** * Class ConditionDto * * @property String $condFld * @property String $condVal */ class ConditionDtDto extends CommonDto{ private $condFld; private $condVal; /** * @return String */ public function getCondFld() { return $this->condFld; } /** * @param String $condFld */ public function setCondFld($condFld) { $this->condFld = $condFld; } /** * @return String */ public function getCondVal() { return $this->condVal; } /** * @param String $condVal */ public function setCondVal($condVal) { $this->condVal = $condVal; } }
true
37cad39e5a4925deb32a24047f8c79be715a1082
PHP
zhenxun/psychol
/app/Controllers/Admin/LocationController.php
UTF-8
4,573
2.640625
3
[]
no_license
<?php namespace Leopard\Controllers\Admin; use Slim\Router; use Slim\Flash\Messages; use Slim\Views\Twig; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Leopard\Controllers\Admin\Contracts\HandlerInterface; use Leopard\Models\Admin\Locations; class LocationController{ protected $view; protected $router; protected $flash; protected $interface; protected $location; public function __construct(Twig $view, Router $router, Messages $flash, HandlerInterface $interface, Locations $location) { $this->view = $view; $this->router = $router; $this->flash = $flash; $this->interface = $interface; $this->location = $location; } public function index(Request $request, Response $response) { $data = $this->getAllData(); $action_route = 'location.create'; $user = $this->interface->getUserInfo(); $setActive = $this->is_active(); return $this->view->render($response, 'admin/location/index.twig', compact('action_route','data','user')); } public function create(Request $request, Response $response){ $lang = $request->getParam('lang'); $map = $request->getUploadedFiles(); $fileMap = $map['map']; $filename = $fileMap->getClientFilename(); $fileExtension = explode('.', $filename); $hash_filename = hash('crc32', $filename); $uploadFilename = date('YmdHsi').'_'.$hash_filename.'.'.$fileExtension[1]; if($lang !="" && $filename!= "") { $uri = $this->getSystemUploadPath().'/map/'.$uploadFilename; if ($fileMap->getError() === UPLOAD_ERR_OK) { $fileMap->moveTo($uri); $location = $this->location->create([ 'lang' => $lang, 'map' => $uploadFilename ]); } else { $this->flash->addMessage('error', '資料儲存失敗!(照片上傳錯誤,請重新嘗試或聯絡管理人員)'); return $response->withRedirect($this->router->pathFor('location.index')); } $this->flash->addMessage('success', '資料儲存成功'); return $response->withRedirect($this->router->pathFor('location.index')); } else { $this->flash->addMessage('error', '資料填寫不完整'); return $response->withRedirect($this->router->pathFor('location.index')); } } public function update(Request $request, Response $response){ $id = $request->getParam('update-id'); $lang = $request->getParam('lang'); $map = $request->getUploadedFiles(); $fileMap = $map['map']; $filename = $fileMap->getClientFilename(); $fileExtension = explode('.', $filename); $hash_filename = hash('crc32', $filename); $uploadFilename = date('YmdHsi').'_'.$hash_filename.'.'.$fileExtension[1]; if($id!="" && $lang!="" && $filename!="" ) { $uri = $this->getSystemUploadPath().'/map/'.$uploadFilename; if ($fileMap->getError() === UPLOAD_ERR_OK) { $fileMap->moveTo($uri); $location_update = $this->location->where('id',$id)->update([ 'lang' => $lang, 'map' => $uploadFilename ]); } else { $this->flash->addMessage('error', '資料儲存失敗!(照片上傳錯誤,請重新嘗試或聯絡管理人員)'); return $response->withRedirect($this->router->pathFor('location.index')); } $this->flash->addMessage('success', '資料儲存成功'); return $response->withRedirect($this->router->pathFor('location.search',[ 'id' => $id ])); } else { $this->flash->addMessage('error', '資料填寫不完整'); return $response->withRedirect($this->router->pathFor('location.index')); } } public function search($id, Request $request, Response $response) { $location_own = $this->location->where('id', $id)->first(); $data = $this->getAllData(); $action_route = 'location.update'; $user = $this->interface->getUserInfo(); $setActive = $this->is_active(); return $this->view->render($response, 'admin/location/index.twig', compact('action_route','location_own','data','user')); } public function delete($id, Request $request, Response $response) { $doDel = $this->location->where('id',$id)->delete(); if($doDel) { echo 1; } else { echo 0; } } private function getAllData(){ return $this->location->get(); } private function getSystemUploadPath(){ if(PHP_OS == 'Darwin' ) { // MAC upload path $upload_dir = env('MAC_UPLOAD_PATH'); } else { //window upload path $upload_dir = env('WIN_UPLOAD_PATH'); } return $upload_dir; } private function is_active(){ $this->view->getEnvironment()->addGlobal('active',['location' => true]); } }
true
51640143519205d76b5aa8eeeb28f815a3b9ead5
PHP
khinezarthwe/php_learning_in_DL
/loop.php
UTF-8
109
3.109375
3
[]
no_license
$f = -50; while ($f <= 50){ $c = ($f - 32)*(5/9); printf ("%d degrees F = %d degree C \n",$f,$c); $f+=5; }
true
abc62758ce3bf908794e975b2be5ccf09a9ab7ee
PHP
jstucken/Python-Overdrive
/www/html/includes/classes/car.class.php
UTF-8
2,672
3.484375
3
[ "MIT" ]
permissive
<?php /** * Our car class * handles GUI car related tasks */ class car { //public $db_name; /* * Gets all the Anki cars in the database * returns multidimensional array of all cars */ public function getAllSavedCars() { // make a custom field (type_readable) which replaces underscores with spaces $select_sql = " SELECT car_id, mac_address, type, REPLACE(type, '_',' ') as type_readable, description, created, modified FROM cars ORDER BY car_id ASC"; $saved_cars = db::getRows($select_sql); // make more user-friendly, readable car types by Title casing names foreach ($saved_cars as $key => $saved_car) { $type_readable = $saved_car['type_readable']; $type_readable = ucwords($type_readable); // save new variable into our results array $saved_cars[$key]['type_readable'] = $type_readable; } return $saved_cars; } /* * Gets all the cars used for a particular class * param int $class_id - the class id to search for * returns associative array containing all the cars */ public static function getCarsInClass($class_id) { if (empty($class_id) OR !is_numeric($class_id)) { trigger_error('Error - $class_id cannot be empty and must be numeric', E_USER_ERROR); } // array to hold our final list of cars $class_car_ids = array(); // get class cars from DB $select_sql = " SELECT s.class_id, sc.student_id, sc.car_id FROM students_cars sc LEFT JOIN students s ON (sc.student_id = s.student_id) WHERE s.class_id='$class_id' ORDER BY sc.car_id ASC"; $cars = db::getRows($select_sql); // loop through results and ensure no duplicates foreach ($cars as $car) { $car_id = $car['car_id']; // add to our final array, if not already in it if (!in_array($car_id,$class_car_ids)) { $class_car_ids[] = $car_id; } } // our final data containing info about each car, no duplicates $cars_data = array(); foreach ($class_car_ids as $car_id) { $car = self::getCar($car_id); $cars_data[] = $car; } return $cars_data; } /* * Gets all data for a particular car * param int $car_id - the car_id you want * returns assoc array with car data */ public static function getCar($car_id) { if (empty($car_id) OR !is_numeric($car_id)) { trigger_error('Error - $car_id cannot be empty and must be numeric', E_USER_ERROR); } // get car data $select_sql = "SELECT * FROM cars WHERE car_id='$car_id'"; $car_data = db::getRow($select_sql); return $car_data; } } ?>
true
3c65efc312dd9cb76d8c037cbb68ea696cc2f72f
PHP
OpenPHPCMS/prototype
/admin/menu.php
UTF-8
2,866
2.53125
3
[]
no_license
<?PHP /* * * Import init * **/ if(!defined('__SITE_PATH')) require('admin_init.php'); if( !secure()->hasUserAccess(__ROLE_DEV) ){ display_error('no access!'); load_view(); die(); } $data['id'] = ''; $data['name'] = ''; $data['link'] = ''; $data['parent'] = ''; load_class('Menu', 'core'); $db = new OPC_Database(); $menu = new OPC_Menu($db); // Save menu item // ------------------------------------------------------------------------ if(isset($_POST['menu_submit'])) { $data['name'] = $_POST['name']; $data['link'] = $_POST['link']; $data['parent'] = $_POST['parrent']; //add validation $binds['name'] = $data['name']; $binds['link'] = $data['link']; $binds['parent'] = $data['parent']; $binds['order_number'] = $menu->latestOrderNumber()+1; $db->insert('OPC_Menu', $binds); display_succes("Menu item added."); } // ------------------------------------------------------------------------ // Save menu order // ------------------------------------------------------------------------ if(isset($_POST['menu_save'])) { unset($_POST['menu_save']); foreach ($_POST as $key => $value) { $binds['order_number'] = $value; $db->where('id', $key); $db->update('OPC_Menu', $binds); } } // ------------------------------------------------------------------------ // Create all the options for all the pages // ------------------------------------------------------------------------ $data['parents'] = '<option value="0"> - </option>'; foreach ($menu->getMenuItems() as $item) { $data['parents'] .= "<option".($item['name'] == $data['parent'] ? 'selected': '')." value='".$item['id']."'>".$item['name']."</option>\n"; } // ------------------------------------------------------------------------ $data['menu'] = ''; $menuItems = $menu->getMenu(); $itemCount = count($menuItems); $itemNr = 1; //Create table rows for menu items // ------------------------------------------------------------------------ foreach ($menuItems as $item) { $childCount = count($item['childeren']); $data['menu'] .= "<tr><td>".$item['name']."</td>\n" ."<td>".$item['link']."</td>\n" ."<td><select name='".$item['id']."'>\n"; for($index=1; $index <= $itemCount; $index++) $data['menu'] .= "<option ".($index == $item['order_number'] ? 'selected': '').">".$index."</option>\n"; $data['menu'] .= "</select></td></tr>\n"; foreach ($item['childeren'] as $child) { $data['menu'] .= "<tr><td> - ".$child['name']."</td>\n" ."<td> - ".$child['link']."</td>\n" ."<td> - <select name='".$child['id']."'>\n"; for($index=1; $index <= $childCount; $index++) $data['menu'] .= "<option ".($index == $child['order_number'] ? 'selected': '').">".$index."</option>\n"; $data['menu'] .= "</select></td></tr>\n"; } $itemNr++; } // ------------------------------------------------------------------------ load_view('menu', $data);
true
2dd0e68c34dae85d9c1d6f7ce4de37d59e8a374c
PHP
eternalphp/framework
/src/framework/Util/Html/Form.php
UTF-8
1,708
3.046875
3
[]
no_license
<?php namespace framework\Util\Html; class Form { private $name; private $id; private $action; private $method; private $type; private $options = array(); public function __construct($id,$action = ''){ $this->id = $id; $this->name = $id; $this->value = $value; $this->type = 'form'; $this->method = 'post'; } /** * set input value * @param string $value * @return $this */ public function name($name){ $this->name = $name; return $this; } /** * set input value * @param string $value * @return $this */ public function target($target){ $this->options['target'] = $target; return $this; } /** * set input value * @param string $value * @return $this */ public function method($method){ $this->method = $method; return $this; } /** * set input value * @param string $value * @return $this */ public function action($action){ $this->action = $action; return $this; } /** * set attr class * @param string $class * @return $this */ public function class($class){ $this->options['class'] = $class; return $this; } /** * set attr class * @param string $class * @return $this */ public function attr($name,$value){ $this->options[$name] = $value; return $this; } public function create(){ $attrs = array(); foreach($this->options as $key=>$val){ if($val !=''){ $attrs[] = sprintf('%s="%s"',$key,$val); } } return sprintf('<form id="%s" name="%s" action="%s" method="%s" %s />@yield("form")</form>',$this->id,$this->name,$this->action,$this->method,implode(' ',$attrs)); } } ?>
true
58466e181cea5d0df151b7676628be7c31824ed2
PHP
guoyu07/pretty-sms
/src/Middleware/TencentyunMiddleware.php
UTF-8
3,470
2.59375
3
[]
no_license
<?php namespace Godruoyi\PrettySms\Middleware; use Closure; use Godruoyi\PrettySms\Client; use Godruoyi\PrettySms\Support\Collection; use Godruoyi\PrettySms\Support\Response; class TencentyunMiddleware { /** * Client Instance * * @var Client */ protected $app; /** * Register Client * * @param Client $app */ public function __construct(Client $app) { $this->app = $app; } /** * @param array $requestParams * @param Closure $next * @return function */ public function handle(Collection $request, Closure $next) { //php5.3只能这样写,我有什么办法 $templateId = $request->get('template'); $template = $request->get('template_data'); $appkey = $this->app['config']->get('configs.tencentyun.appKey'); $signName = $this->app['config']->get('configs.tencentyun.sign_name'); $appId = $this->app['config']->get('configs.tencentyun.appId'); if (empty($templateId)) { return Response::error('[腾讯云]模板ID不能为空', -1000); } elseif (empty($template)) { return Response::error('[腾讯云]模板参数不能为空', -1000); } elseif (empty($appkey)) { return Response::error('[腾讯云]APPKEY不能为空', -1000); } elseif (empty($signName)) { return Response::error('[腾讯云]签名不能为空', -1000); } elseif (empty($appId)) { return Response::error('[腾讯云]APPID不能为空', -1000); } $request = $this->rebuildRequest($request); return $next($request); } /** * 根据平台模板ID获取腾讯云模板ID * * @param Collection $request * @return Collection */ public function rebuildRequest(Collection $request) { $oldTemplateId = $request->get('template'); $configs = $this->app->make('dayuw\api\app\Service\TemplateConfigService') ->findByAttributes(array( 'type' => 'tencentcloud', 'source_id' => $oldTemplateId )); if (!$configs || empty($configs->target_id)) { throw new \Exception("[腾讯云]未配置的模板ID"); } if (empty($configs->tencent_cloud_setting)) { throw new \Exception("[腾讯云]服务端未指定模板顺序"); } $request['template'] = $configs->target_id; $request['template_data'] = $this->buildTemplateData($request['template_data'], $configs->tencent_cloud_setting); return $request; } /** * 根据腾讯云模板ID * * @param mixed $templateData * @param mixed $sort * @return mixed */ public function buildTemplateData($templateData, $sort) { $templateData = json_decode($templateData, true); $sort = json_decode($sort, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception("[腾讯云]模板参数格式化失败"); } $realtemplateData = array(); foreach ($sort as $key) { if (empty($templateData[$key])) { throw new \Exception("[腾讯云]模板参数缺少或为空({$key})"); } $realtemplateData[] = $templateData[$key]; } return $realtemplateData; } }
true