1. PHP / Говнокод #15847

    +153

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    // Заполняем листы целиком одним махом. Что бы про PHP ни говорили, он весьма крут.
    $curr_griddles = array_merge($curr_griddles, array_fill(0, $gqty, array('total_qty' => $piesPerList, $pieId => $piesPerList)));
                                    
       ...
    
    // Выбираем наименее загруженного работника. А вот тут PHP демонстрирует корявость. Правда непонятно, мою или свою...
    asort($workersLoad); reset($workersLoad); $kv = each($workersLoad); $workerId = $kv['key'];

    DIX315, 25 Апреля 2014

    Комментарии (1)
  2. PHP / Говнокод #15845

    +150

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    <?php
    	require_once("inc/mysql.php");
    	sleep(3); //Для ajax запроса, потом удалить
    
    	// Проверяем, что к нам идёт Ajax запрос
    	if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    		$city1 = $_POST['city1'];
    	}else{
    		exit(); // Заканчиваем работу скрипта, если это не ajax запрос
    	}
    
    	if (isset($city1)) {
    		$query = "SELECT id_city, id_region, id_country FROM cities WHERE city_name_ru LIKE '$city1'";
    		$result = mysqli_query($link, $query);// or trigger_error(mysql_error($link)." ".$query);
    		$row = mysqli_fetch_array($result);
    		$country = $row['id_country'];
    		//echo $country;
    		//echo '<br>';
    		$region = $row['id_region'];
    		//echo $region;
    		//echo '<br>';
    		$query1 = "SELECT country_name_ru FROM countries WHERE id_country = '$country'";
    		$result1 = mysqli_query($link, $query1);// or trigger_error(mysql_error($link)." ".$query);
    		$row1 = mysqli_fetch_array($result1);
    		echo '<p class=\'country\'>Страна '.$row1['0'].'</p>';
    		//echo '<br>';
    		$query2 = "SELECT region_name_ru FROM regions WHERE id_region = '$region'";
    		$result2 = mysqli_query($link, $query2);// or trigger_error(mysql_error($link)." ".$query);
    		$row2 = mysqli_fetch_array($result2);
    		echo '<p class=\'reqion\'>Область '.$row2['0'].'</p>';
    	}
    ?>

    Прокомментируйте, пожалуйста, как улучшить этот говнокод.

    eprivalov1, 25 Апреля 2014

    Комментарии (13)
  3. PHP / Говнокод #15841

    +154

    1. 1
    2. 2
    3. 3
    foreach(array_keys(get_defined_vars())as$__v)$__refs[$__v]=&$$__v;
    do_action("ws_plugin__s2member_before_paypal_api_response", get_defined_vars());
    unset /* Unset defined __refs, __v. */($__refs, $__v);

    И опять s2member для wordpress

    antongorodezkiy, 24 Апреля 2014

    Комментарии (0)
  4. PHP / Говнокод #15813

    +158

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    function commerce_auction_dividable($big, $small) {
      $div = $big / $small;
    
      if (!is_numeric(strpos($div, '.')) === TRUE) {
        return TRUE;
      }
      return FALSE;
    }

    https://drupal.org/node/1721568

    Int, 22 Апреля 2014

    Комментарии (37)
  5. PHP / Говнокод #15811

    +153

    1. 1
    print implode('-', array_reverse(explode('-', trim(substr($project->start_date, 0, count($project->start_date) - 9)))));

    Форматирует дату с Y-m-d в d-m-Y. Альтернатива для
    date_format(new DateTime($project->start_date), 'd-m-Y');

    djumpen, 22 Апреля 2014

    Комментарии (2)
  6. PHP / Говнокод #15808

    +157

    1. 1
    setcookie('password', $passHash , time() + $this::TIME_COOKIE * 1000 +  $remember ? $this::TIME_COOKIE_REMEMBER : 0  * 1000 );

    И я то думал, почему кука не появляется...

    Dart_Sergius, 21 Апреля 2014

    Комментарии (82)
  7. PHP / Говнокод #15799

    +149

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    function rawToStructuredDataTree($data) {
            $structured_array = array();
            foreach ($data as $cid => $node) {
                $data[$cid]['children'] = array();
                if ($node['parent_id'] == $cid || $node['parent_id'] == 0) {
                    $structured_array[$cid] = &$data[$cid];
                } else {
                    $data[$node['parent_id']]['children'][$cid] = & $data[$cid];
                }
            }
            return $structured_array;
      }

    Вот такое выдал мой ученик (школьник, 8 класс), когда его попросили из массива id - parent_id построить дерево.

    imissyouso, 20 Апреля 2014

    Комментарии (30)
  8. PHP / Говнокод #15795

    +155

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    /**
    * Handles Registration Links.
    *
    * @package s2Member\Registrations
    * @since 3.5
    *
    * @attaches-to ``add_action("init");``
    *
    * @return null Or exits script execution after redirection.
    */
    public static function register ()
    {
    	do_action ("ws_plugin__s2member_before_register", get_defined_vars ());
    
    	if (!empty ($_GET["s2member_register"])) // If they're attempting to access the registration system.
    		{
    			while (@ob_end_clean ()); // Clean any existing output buffers.
    
    			$msg_503 = _x ('<strong>Your Link Expired:</strong><br />Please contact Support if you need assistance.', "s2member-front", "s2member");
    
    			if (is_array ($register = preg_split ("/\:\.\:\|\:\.\:/", c_ws_plugin__s2member_utils_encryption::decrypt (trim (stripslashes ((string)$_GET["s2member_register"]))))))
    				{
    					if (count ($register) === 6 && $register[0] === "subscr_gateway_subscr_id_custom_item_number_time" /* Does the checksum value match up here? */)
    						{
    							if (is_numeric ($register[5]) && $register[5] <= strtotime ("now") && $register[5] >= strtotime ("-" . apply_filters ("ws_plugin__s2member_register_link_exp_time", "2 days", get_defined_vars ())))
    								{
    									$_COOKIE["s2member_subscr_gateway"] = /* For ``reg_cookies_ok ()``. */ c_ws_plugin__s2member_utils_encryption::encrypt ($register[1]);
    									$_COOKIE["s2member_subscr_id"] = /* For ``reg_cookies_ok ()``. */ c_ws_plugin__s2member_utils_encryption::encrypt ($register[2]);
    									$_COOKIE["s2member_custom"] = /* For ``reg_cookies_ok ()``. */ c_ws_plugin__s2member_utils_encryption::encrypt ($register[3]);
    									$_COOKIE["s2member_item_number"] = /* For ``reg_cookies_ok ()``. */ c_ws_plugin__s2member_utils_encryption::encrypt ($register[4]);
    
    									if (($reg_cookies = c_ws_plugin__s2member_register_access::reg_cookies_ok ()) && extract ($reg_cookies) /* Needed? */)
    										{
    											status_header(200); // Send a 200 OK status header.
    											header("Content-Type: text/html; charset=UTF-8"); // Content-Type with UTF-8.
    
    											setcookie ("s2member_subscr_gateway", $_COOKIE["s2member_subscr_gateway"], time () + 31556926, COOKIEPATH, COOKIE_DOMAIN) . setcookie ("s2member_subscr_gateway", $_COOKIE["s2member_subscr_gateway"], time () + 31556926, SITECOOKIEPATH, COOKIE_DOMAIN);
    											setcookie ("s2member_subscr_id", $_COOKIE["s2member_subscr_id"], time () + 31556926, COOKIEPATH, COOKIE_DOMAIN) . setcookie ("s2member_subscr_id", $_COOKIE["s2member_subscr_id"], time () + 31556926, SITECOOKIEPATH, COOKIE_DOMAIN);
    											setcookie ("s2member_custom", $_COOKIE["s2member_custom"], time () + 31556926, COOKIEPATH, COOKIE_DOMAIN) . setcookie ("s2member_custom", $_COOKIE["s2member_custom"], time () + 31556926, SITECOOKIEPATH, COOKIE_DOMAIN);
    											setcookie ("s2member_item_number", $_COOKIE["s2member_item_number"], time () + 31556926, COOKIEPATH, COOKIE_DOMAIN) . setcookie ("s2member_item_number", $_COOKIE["s2member_item_number"], time () + 31556926, SITECOOKIEPATH, COOKIE_DOMAIN);
    
    											do_action ("ws_plugin__s2member_during_register", get_defined_vars ());
    
    											if (is_multisite () && c_ws_plugin__s2member_utils_conds::is_multisite_farm () && is_main_site () && ($location = c_ws_plugin__s2member_utils_urls::wp_signup_url ()))
    												{
    													echo '<script type="text/javascript">' . "\n";
    													echo "window.location = '" . c_ws_plugin__s2member_utils_strings::esc_js_sq ($location) . "';";
    													echo '</script>' . "\n";
    												}
    											else if (($location = c_ws_plugin__s2member_utils_urls::wp_register_url ()))
    												{
    													echo '<script type="text/javascript">' . "\n";
    													echo "window.location = '" . c_ws_plugin__s2member_utils_strings::esc_js_sq ($location) . "';";
    													echo '</script>' . "\n";
    												}
    											exit (); // Clean exit. The browser will now be redirected to ``$location``.
    										}
    									else
    										status_header(503) . header ("Content-Type: text/html; charset=UTF-8") . exit ($msg_503);
    								}
    							else
    								status_header(503) . header ("Content-Type: text/html; charset=UTF-8") . exit ($msg_503);
    						}
    					else
    						status_header(503) . header ("Content-Type: text/html; charset=UTF-8") . exit ($msg_503);
    				}
    			else
    				status_header(503) . header ("Content-Type: text/html; charset=UTF-8") . exit ($msg_503);
    		}
    
    	do_action ("ws_plugin__s2member_after_register", get_defined_vars ());
    }

    Концовка особенно захватывающа.

    Плагин для Wordpress - s2member, https://www.s2member.com/codex/stable/source/s2member/includes/classes/register-in.inc.php

    antongorodezkiy, 20 Апреля 2014

    Комментарии (5)
  9. PHP / Говнокод #15787

    +152

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    function locate($info) {
        $name = sprintf("%s_%02d_%02d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s_%02d_%03d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03d.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03d-%03d.jpg", $info['prefix'], $info['vol'], $info['page'], $info['page']+1);
        if (file_exists($name))
            return $name;
        $name = sprintf("%s%d_%03dcover.jpg", $info['prefix'], $info['vol'], $info['page']);
        if (file_exists($name))
            return $name;
        return false;
    }

    Онлайн читалка манги. Эта функция ищет картинку по номеру тома/страницы.

    Как считаете, я сильно наговнокодила? ^_^

    kitty, 19 Апреля 2014

    Комментарии (91)
  10. PHP / Говнокод #15783

    +162

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    <?php
    /**
     * Project:     Smarty: the PHP compiling template engine
     * File:        Smarty.class.php
     *
     * This library is free software; you can redistribute it and/or
     * modify it under the terms of the GNU Lesser General Public
     * License as published by the Free Software Foundation; either
     * version 2.1 of the License, or (at your option) any later version.
     *
     * This library is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     * Lesser General Public License for more details.
     *
     * You should have received a copy of the GNU Lesser General Public
     * License along with this library; if not, write to the Free Software
     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     *
     * For questions, help, comments, discussion, etc., please join the
     * Smarty mailing list. Send a blank e-mail to
     * [email protected] 
     *
     * @link http://www.smarty.net/
     * @copyright 2001-2005 New Digital Group, Inc.
     * @author Monte Ohrt <monte at ohrt dot com>
     * @author Andrei Zmievski <[email protected]>
     * @package Smarty
     * @version 2.6.26
     */
    
    /* $Id: Smarty.class.php 3163 2009-06-17 14:39:24Z monte.ohrt $ */
    
    /**
     * DIR_SEP isn't used anymore, but third party apps might
     */
     echo ".";
     ?>

    Itareo, 18 Апреля 2014

    Комментарии (34)