- 1
- 2
- 3
- 4
$a = null;
var_dump($a, $a[0], $a); // NULL, NULL, NULL // what the fuck?
$a[0] = null;
var_dump($a); // array(0 => NULL)
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+154
$a = null;
var_dump($a, $a[0], $a); // NULL, NULL, NULL // what the fuck?
$a[0] = null;
var_dump($a); // array(0 => NULL)
"PHP и type juggling", том третий. При этом на первый вызов $a[0] не ругается, будто при приведении NULL к пустому массиву в нем появляется нулевой элемент.
+154
class Session {
.....
public function getIdUser()
{
if ($this->isAnonymous()) {
return null;
}
return (int)$this->attributes[self::ATTR_ID_USER];
}
public function isAnonymous()
{
return empty($this->attributes[self::ATTR_ID_USER]);
}
....
}
............
$userId = $session->isAnonymous() ? null : (int)$session->getIdUser();
+154
class Registration{
protected $data;
protected $linc = "reg.php";
protected $v_log;
protected $query_login;
protected $v_pass;
protected $v_r_pass;
protected $v_pass_r_pass;
protected $v_mail;
public function __construct() {
$this->data = array('login'=> NULL, 'password'=> NULL, 'r_password'=> NULL, 'mail'=> NULL);
foreach($this->data as $key => $val) {
$this->data[$key] = $_POST[$key];
}
$this->v_log = $this->ver_login($this->data['login']);
$this->v_pass = $this->ver_pass($this->data['password']);
$this->v_r_pass = $this->ver_r_pass($this->data['r_password']);
$this->v_pass_r_pass = $this->ver_pass_r_pass($this->data['password'],$this->data['r_password']);
$this->v_mail = $this->ver_mail($this->data['mail']);
$this->error_reporting($this->v_log,$this->v_pass,$this->v_r_pass,$this->v_pass_r_pass,$this->v_mail, $this->error_log($this->linc));
}
protected function error_log($linc){
return("<p>В поле введены неверные данные!</p></br>"
. "<form action='$linc' metod='get'>"
. "<p>Вернуться и проверить<input type = 'submit' value = 'вернуться'></p>"
. "</form>");
}
protected function ver_login($login) {
if(empty($login) or (!preg_match("/^\A(\w){6,20}\Z/", $login))) {
$login = FALSE;
unset($login);
}else{
$login == TRUE;
$this->ver_db($login);
return($login);
}
}
protected function ver_db($log) {
$q = mysql_query("SELECT id FROM users WHERE login = '$log'");
$f = mysql_fetch_array($q);
if(empty($f['id']) or $f['id'] == '') {
return($log);
}else{
echo('Есть такой');
}
}
protected function ver_pass($pass) {
if(empty($pass) or (!preg_match("/^\A(\w){6,20}\Z/", $pass))) {
$pass == FALSE;
unset($pass);
}else {
$pass == TRUE;
$pass = md5($pass);
return($pass);
}
}
protected function ver_r_pass($r_pass) {
if(empty($r_pass) or (!preg_match("/^\A(\w){6,20}\Z/", $r_pass))) {
$r_pass == FALSE;
unset($r_pass);
}else {
$r_pass == TRUE;
$r_pass = md5($r_pass);
return($r_pass);
}
}
protected function ver_pass_r_pass($pass,$r_pass) {
if($pass != $r_pass) {
return(FALSE);
}else {
return (TRUE);
}
}
protected function ver_mail($mail) {
if(empty($mail) or (!preg_match("/^[a-zA-Z0-9_\.\-]+@([a-zA-Z0-9\-]+\.)+[a-zA-Z]{2,6}$/", $mail))) {
$mail == FALSE;
unset($mail);
}else {
$mail == TRUE;
return($mail);
}
}
protected function reg_ins($log,$pass,$mail) {
$date = date("d.m.y");
$const = ACCES_KEY_DEFAULT;
$ins_query = "INSERT INTO users(login,password,mail,date,acces) VALUES ('$log','$pass','$mail','$date','$const')";
$insert = mysql_query($ins_query);
if(!$insert){
echo('error');
} else {
echo('ok');
}
}
protected function error_reporting($log,$pass,$r_pass,$pass_r_pass,$mail,$error) {
if($log == FALSE or $pass == FALSE or $r_pass == FALSE or $pass_r_pass == FALSE or $mail == FALSE){
echo($error);
} else {
//выполняем если все данные введены верно
$this->reg_ins($log, $pass, $mail);
}
:)
+155
// Отладочная информация
if(1)
{
print "<!--\r\n";
$time_end = microtime(true);
$exec_time = $time_end-$time_start;
if(function_exists('memory_get_peak_usage'))
print "memory peak usage: ".memory_get_peak_usage()." bytes\r\n";
print "page generation time: ".$exec_time." seconds\r\n";
print "-->";
}
Simpla CMS, красавцы! :D
+158
<?php
include 'config.php';
$title = "Форум - $maintitle";
$topic = $_GET['topic'];
$board = $_GET['board'];
$main = $_GET['main'];
include 'core/funcs.php';
include 'core/pdoconnect.php';
include 'te/heads.php';
echo '
<div class="clear"></div>
<!-- Content Section -->
<div id="content_sec">
<!-- Column 1 -->
<div class="col1">
<!-- Featured Playlist -->
<div class="featured_playlist">
<h3 class="heading">',$title,'</h3>
';
if (isset($topic)){
echo '<table>
<tbody>
<tr><th> Тема</th><th>Автор</th><th>Посл.обн.</th>
</tr>';
}
if ($board > 0){
echo '<table>
<tbody>
<tr><th> Тема</th><th>Автор</th><th>Посл.обн.</th>
</tr>';
$prepare = $db->prepare("SELECT * from `forum` where `board_id` = :bo_id order by `last_update` DESC");
$prepare->bindParam(":bo_id", $board, PDO::PARAM_INT);
$prepare -> execute();
//print_r($prepare->errorinfo());
if ($prepare->rowCount() == 0){
echo '<p class = "error-box">В этом разделе еще не создано ни одной темы!</p>';
}else{
while($bo = $prepare->fetch(PDO::FETCH_BOTH)){
echo '<tr><td><a href="forum-topic',$bo['id'],' "> ',$bo['title'],' </a></td><td> ',$bo['author'],'</td><td> ',$bo['last_author'],'</td></tr>';
}
}
}
if (isset($_GET['main'])){
$i = 1;
echo '
<table>
<tbody>
<tr>
<th>Основной</th><th>Новое</th>
</tr>
<tr><td><a href = "forum-board',$i++,' ">Работа сайта</a></td><td>',$last['0'],'</td></tr>
<tr><td><a href = "forum-board',$i++,' ">Пожелания и предложения</a></td><td>',$last['1'],'</td>
<tr><th>Общение</th><th>Новое</th></tr>
<tr><td><a href = "forum-board',$i++,' ">Общение</a></td><td>',$last['2'],'</td></tr>
<tr><th>Работа</th><th>Новое</th></tr>
<tr><td><a href = "forum-board',$i++,' ">Оффтоп</td><td>$last['3']</td></tr>
<tr><td><a href = "forum-board',$i++,' ">Студенты</td><td>$last['4']</td></tr>
<tr><td><a href = "forum-board',$i++,' ">Преподаватели</td><td>$last['5']</td></tr>
<tr><td><a href = "forum-board',$i++,' ">Помощь</td><td>$last['6']</td></tr>
<tr><td><a href = "forum-board',$i++,' ">Литература</td><td>$last['7']</td></tr>
';
}
echo '</tbody></table></div></div>';
include 'te/foot.php';
?>
В общем, добрался до исходников сайта нашего инста.
Сам сайт имеет всего несколько частей - форум, лента новостей и ЛК.
Это скрипт "форума".
К слову, написано преподавателем со стажем работы 6 лет, как сам он нам доказывал и доказывает - часто фрилансит и все довольны. Чет не верится.
И этот человек учит других...
+158
class TestThis
{
public $property = 'property';
public function test1()
{
$this->this($this, new ArrayObject);
$this['wierd'] = true;
print_r($this);
print_r($this->property . PHP_EOL);
return $this;
}
public function test2()
{
print_r($this);
}
public function this(&$object, $value)
{
$object = $value;
}
}
(new TestThis)->test1()->test2();
Вопрос к самому похапе.
Так вот нельзя:
$this = че-нибудь
"Cannot re-assign $this"
А вот как выше можно!
+156
foreach($PROP as $k1 => $val1)
{
if(is_array($val1))
{
foreach($val1 as $k2 => $val2)
{
$text_name = preg_replace("/([^a-z0-9])/is", "_", "PROP[".$k1."][".$k2."][VALUE][TEXT]");
if(array_key_exists($text_name, $_POST))
{
$type_name = preg_replace("/([^a-z0-9])/is", "_", "PROP[".$k1."][".$k2."][VALUE][TYPE]");
$PROP[$k1][$k2]["VALUE"] = array(
"TEXT" => $_POST[$text_name],
"TYPE" => $_POST[$type_name],
);
}
}
}
}
foreach($PROP as $k1 => $val1)
{
if(is_array($val1))
{
foreach($val1 as $k2 => $val2)
{
if(!is_array($val2))
$PROP[$k1][$k2] = array("VALUE" => $val2);
}
}
}
bitrix
как вам организация цикла(ов)
+158
if( is_numeric((int)$_GET['id1']) && is_numeric((int)$_GET['id2']) && is_numeric((int)$_GET['id3']) ){
}
Капитан очевидность)
+155
<?php
$valid = false;
if (!isset($month))
{
$valid = true;
$month = date('m');
}
if (!isset($year))
$year = date('Y');
if ($month == '12')
$next_year = $year + 1;
else
$next_year = $year;
$Month_r = array(
"1" => "Январь",
"2" => "Февраль",
"3" => "Март",
"4" => "Апрель",
"5" => "Май",
"6" => "Июнь",
"7" => "Июль",
"8" => "Август",
"9" => "Сентябрь",
"10" => "Октябрь",
"11" => "Ноябрь",
"12" => "Декабрь");
$first_of_month = mktime(0, 0, 0, $month, 1, $year);
// Массив имен всех дней в неделю
$day_headings = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
$maxdays = date('t', $first_of_month);
$date_info = getdate($first_of_month);
$month = $date_info['mon'];
$year = $date_info['year'];
// Вычитаем один день с первого дня месяца,
//чтобы получить в конец прошлого месяца
$timestamp_last_month = $first_of_month - (24 * 60 * 60);
$last_month = date("m", $timestamp_last_month);
// Проверяем, что если месяц декабрь,
//на следующий месяц равен 1, а не 13
if ($month == '12')
$next_month = '1';
else
$next_month = $month + 1;
$calendar = "
<div class=\"block-on-center\">
<table cellpadding=\"0\" cellspacing=\"0\" class=\"calendar\">
<tr style='background: #933692;' height='40px'>
<td colspan='7' class='navi'>" . $Month_r[$month] . " " . $year . "
<a style='margin-left: 10px; color: #ffffff;' href='/calendar/" . $quest->id . "/" . $next_month . "/" . $next_year . "'>>></a>
</td>
</tr>
<tr class='calendar-row'>
<td class='calendar-day-head'>Пн</td>
<td class='calendar-day-head'>Вт</td>
<td class='calendar-day-head'>Ср</td>
<td class='calendar-day-head'>Чт</td>
<td class='calendar-day-head'>Пт</td>
<td class='calendar-day-head'>Сб</td>
<td class='calendar-day-head'>Вс</td>
</tr>
<tr class='calendar-row'>";
$class = "";
$weekday = $date_info['wday'];
$weekday = $weekday - 1;
if ($weekday == -1)
$weekday = 6;
$day = 1;
for ($i = 0; $i < $weekday; $i++)
{
$calendar .= "<td class=\"calendar-day-np\"> </td>";
}
$blocks = '';
while ($day <= $maxdays)
{
// если суббота, выволдим новую колонку.
if ($weekday == 7)
{
$calendar .= "</tr><tr>";
$weekday = 0;
}
$days = array('0' => 'Воскресенье', '1' => 'Понедельник', '2' => 'Вторник', '3' => 'Среда', '4' => 'Четверг', '5' => 'Пятница', '6' => 'Суббота');
$linkDate = mktime(0, 0, 0, $month, $day, $year);
$day_an = date("w", $linkDate);
// проверяем, если распечатанная дата является сегодняшней датой.
//если так, используем другой класс css, чтобы выделить её
Вьюшка календарика, сам сайт на Kohana.
+154
switch($step) {
case 0:
setup_config_display_header();
?>
<p><?php _e( 'Welcome to WordPress. Before getting started, we need some information on the database. You will need to know the following items before proceeding.' ) ?></p>
<ol>
<li><?php _e( 'Database name' ); ?></li>
<li><?php _e( 'Database username' ); ?></li>
<li><?php _e( 'Database password' ); ?></li>
<li><?php _e( 'Database host' ); ?></li>
<li><?php _e( 'Table prefix (if you want to run more than one WordPress in a single database)' ); ?></li>
</ol>
<p><strong><?php _e( "If for any reason this automatic file creation doesn’t work, don’t worry. All this does is fill in the database information to a configuration file. You may also simply open <code>wp-config-sample.php</code> in a text editor, fill in your information, and save it as <code>wp-config.php</code>." ); ?></strong></p>
<p><?php _e( "In all likelihood, these items were supplied to you by your Web Host. If you do not have this information, then you will need to contact them before you can continue. If you’re all ready…" ); ?></p>
<p class="step"><a href="setup-config.php?step=1<?php if ( isset( $_GET['noapi'] ) ) echo '&noapi'; ?>" class="button button-large"><?php _e( 'Let’s go!' ); ?></a></p>
<?php
break;
case 1:
setup_config_display_header();
//...
case 2:
foreach ( array( 'dbname', 'uname', 'pwd', 'dbhost', 'prefix' ) as $key )
$$key = trim( wp_unslash( $_POST[ $key ] ) );
$tryagain_link = '</p><p class="step"><a href="setup-config.php?step=1" onclick="javascript:history.go(-1);return false;" class="button button-large">' . __( 'Try again' ) . '</a>';
if ( empty( $prefix ) )
wp_die( __( '<strong>ERROR</strong>: "Table Prefix" must not be empty.' . $tryagain_link ) );
// Validate $prefix: it can only contain letters, numbers and underscores.
if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
wp_die( __( '<strong>ERROR</strong>: "Table Prefix" can only contain numbers, letters, and underscores.' . $tryagain_link ) );
// Test the db connection.
/**#@+
* @ignore
*/
define('DB_NAME', $dbname);
define('DB_USER', $uname);
define('DB_PASSWORD', $pwd);
define('DB_HOST', $dbhost);
/**#@-*/
// We'll fail here if the values are no good.
require_wp_db();
// еще двести строк свитча с html, обработкой данных прямо на лету и даже небольшим количеством инлайн-js
Захотел я подцепиться к внутреннему api установки вордпресса, чтобы эту самую установку делать через конфиг-файлы и композер. В результате проще оказалось имитировать окружение веб-сервера, заполнять всякие $_GET-$_POST и просто подключать нужный файл. А как они сами с этим адом работают - для меня остается загадкой
Целиком https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-admin/setup-config.php и https://core.trac.wordpress.org/browser/tags/3.9.2/src/wp-admin/install.php