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

    +164

    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
    function price($cost)
    {
       if($cost > 0)
       {
          $tmp = explode('.', $cost);
          $cost = $tmp[0];
    
          if($cost >= 1000 && $cost <= 9999)
          {
             $cost = substr($cost, 0, 1)." ".substr($cost, 1);
          }
          elseif($cost >= 10000 && $cost <= 99999)
          {
             $cost = substr($cost, 0, 2)." ".substr($cost, 2);
          }
          elseif($cost >= 100000 && $cost <= 999999)
          {
             $cost = substr($cost, 0, 3)." ".substr($cost, 3);
          }
          $cost .= ' руб.';
       }
       else $cost = '';
    
       return $cost;
    }

    Вывод цены в форматированном виде) Ну да, зачем использовать автоформат по локализации, лучше поговнокодить)

    greevex, 08 Февраля 2011

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

    +161

    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
    <?php
    
    //////////....................................
    
    	static function Request($module="__global",$action='__global',$route=null){
    		if(!$route && !empty(self::$route)) $route=self::$route;
            else $route=self::setRoute(APP_ModuleContext::getContext());
            $action=strtolower($action);
    		$module=strtolower($module);
    
    		$ro=array();
            if(!empty($route['allow'][$module])){
    			$ro=$route['allow'][$module];
                $dis=!empty($route['disallow'][$module])?$route['disallow'][$module]:array();
    			if(!empty($dis) && $dis['__global']===true) return new throw APP_Exceptions_PluginBox("Плагины для модуля '$module' отключены");
    			 
    			 if(empty($ro['__global'])) $ro['__global']=array();
    			 if(empty($ro[$action])) $ro[$action]=array();
    			 $ro=array_merge($ro['__global'],$ro[$action]);
                 if(!empty($ro)){
    				 $ro=array_unique($ro);
                     if(!empty($dis)){
    					 if(empty($dis['__global'])) $dis['__global']=array();
    					 if(empty($dis[$action])) $dis[$action]=array();
    					 $dis=array_merge($dis['__global'],$dis[$action]);
    					 if(!empty($dis)){
                            $dis=array_unique($dis);
    						$ro=array_diff($ro,$dis);
    					 }
    				 }
    				 if(!empty($ro)){
                        $res=array();
    		 	        foreach($ro as $plugin){
                            $res[$plugin]=self::getContents($plugin);
    			        }
    			        return $res;
    				 }else return new throw APP_Exceptions_PluginBox("Все плагины были отключены для '$module - $action'");
    			 }else return new throw APP_Exceptions_PluginBox("Нет плагинов для запроса '$module - $action'");
    		}
    		
    		return false;
    	}
    
    /////////////..........................................
    ?>

    Роутеры роутят

    Zho, 07 Февраля 2011

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

    +158

    1. 1
    2. 2
    3. 3
    4. 4
    $arTime = localtime();
    //формируем ядро номера заказа, которое будем подцеплять к разным префиксам
    
    $orderNumberCore = str_pad($arTime[4]+1, 2, "0", STR_PAD_LEFT).str_pad($arTime[3], 2, "0", STR_PAD_LEFT).str_pad($arTime[2], 2, "0", STR_PAD_LEFT).str_pad($arTime[1], 2, "0", STR_PAD_LEFT).str_pad($arTime[0], 2, "0", STR_PAD_LEFT);

    Формируется номер заказав интернет-магазине из даты/времени. Но при этом не учитывается год.

    $orderNumberCore -- это дата в формате dmhis.

    kost, 07 Февраля 2011

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

    +163

    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
    <?
    class Thread {
    <...>
    	function Thread($proc_id) {
    		$this->db=new ezSQL_mssql(s_login, s_password, s_db_name_threads, s_host);
    		$this->proc_id=$proc_id;
    		$this->timeout=500;
    		$this->last_busy=0;
    		$this->notactive_num=0;
    		$query="INSERT INTO threads(proc_id, last_beat) VALUES('".$this->proc_id."','".(time()+60)."');";
    		$this->db->query($query);
    	}
    	static function Create($url,$proc_id) {
    		$t = new Thread($proc_id);
    		
    		//### execute thread
    		//NB!!!
    		//BE CAREFUL WITH LOG PATHS, IF YOU MISS OR MISSPEL THE PATH, IT IS HARDLY POSSIBLE TO DEBUG
    		//IF YOU MISSPELL THE PATH YOU CAN FACE THE PROBLEM OF THREADS SIMPLY DO NOT START OR DO NOT LOG WITHOUT ANY NOTIFICATION
    		//USE YOUR OWN PATHS FOR PHP, LOGS AND COMMAND LINE COMMANDS AD PARAMETERS FOR YOUR SPECIFIC OS, WINDOWS EXAMPLE IS BELOW
    		//start /B will execute background process in windows, > symbol will store the output of current process into log file
    		//you can call threads from another server via http request etc.
    		pclose(popen("start /B \"$proc_id\" C:\php\php.exe D:\wwwroot\\newimport\elko\import_ignitor_thread.php > D:\globalimport\logs\\".$proc_id.".txt $proc_id","r"));		
    		
    		//give some time to start the thread
    		Sleeper(1000);
    		return $t;
    	}
    	
    	//check is Thread active or not
    	//check active, busy, last beat etc.
    	//you can put here your own business logic how thread should be checked for statused etc.
    	function isActive () {
        if($this->state==3){
    			return false;
    		}elseif ($this->last_busy==1){
    			return true;
    		}
    		$cur_time=time();
    		if($cur_time>$this->last_beat){
    			$result=$this->db->get_var("SELECT last_beat FROM threads WHERE proc_id=".$this->proc_id);
    			$this->state=$this->db->get_var("SELECT state FROM threads WHERE proc_id=".$this->proc_id);
    			if($cur_time<$result){
    				return true;
    			}
    		}else{
    			return true;
    		}
    		return true;
    	}
    	
    	//check is Thread is busy or not, in order to give a new task/job
    	//it is similat to the previous procedure
    	function isBusy() {
    		//$this->tell("ping"); - this could be implemented in the future
    		$cur_time=time();
    		if($cur_time>$this->last_beat or $this->last_busy==0){
    			$result=$this->db->get_var("SELECT busy FROM threads WHERE proc_id=".$this->proc_id);
    			$this->last_busy=$result;
    			if($result==1){
    				return true;
    			}else{
    				return false;
    			}
    		}else{
    			return false;
    		}
    	}
    	
    	//tells a command to the thread
    	function tell($thought, $params = NULL) {
    		$param=base64_encode(serialize($params));
    		$query="INSERT INTO cmd(proc_id, cmd, param) VALUES('".$this->proc_id."','".$thought."','".$param."');";
    		$this->db->query($query);
    	}
    }

    'многопоточность'

    xXx_totalwar, 07 Февраля 2011

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

    +157

    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
    <?php
    function Sleeper($mSec)
    {
    	//    For dummies like me who spent 5 minutes
    	//    wondering why socket_create wasn't defined
    	if(!function_exists('socket_create')){
    		die("Please enable extension php_sockets.dll");
    	}
    	//    So the socket is only created once
    	static $socket=false;
    	if($socket===false){
    		$socket=array(socket_create(AF_INET,SOCK_RAW,0));
    	}
    	$pSock=$socket;
    	//    Calc time
    	$uSex = $mSec * 1000;
    	//    Do the waiting
    	socket_select($read=NULL,$write=NULL,$pSock,0,$uSex);
    	//    OCD
    	return true;
    }

    что бы гк делал без этого чудесного языка..

    xXx_totalwar, 07 Февраля 2011

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

    +160

    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
    <?php
    ...
    while (OCIFetch($stmt))
                                        {
                                            $kID = OCIResult($stmt, 'KID');
                                            $kModel = OCIResult($stmt,'KMODEL');
                                            $pName = OCIResult($stmt,'PNAME');
                                            $sWidth = OCIResult($stmt,'SWIDTH');
                                            $sHeight = OCIResult($stmt,'SHEIGHT');
                                            $sRadius = OCIResult($stmt,'SRADIUS');
                                            $kPrice_opt = OCIResult($stmt,'KPRICE_OPT');
                                            $kPrice_rozn = OCIResult($stmt,'KPRICE_ROZN');
                                            $kKolvo = OCIResult($stmt,'KKOLVO');
    echo "                                <tr>
                                            <td align='center'><input type=radio name=tUP value ='$kID'/></td>
                                            <td align='center'>$kID</td>
                                            <td align='center'>$kModel</td>
                                            <td align='center'>",$sWidth,"/",$sHeight,"/",$sRadius,"</td>
                                            <td align='center'>$pName</td>
                                            <td align='center'>$kPrice_opt</td>
                                            <td align='center'>$kPrice_rozn</td>
                                            <td align='center'>$kKolvo</td>
                                            <td align='center'>
                                                <a href='images/kolesa/",$pName,"/",$kModel,".jpeg' rel='lytebox'>
                                                    <img height='20' width='20' src='images/pic.jpg'/>
                                                </a>
                                            </td>
                                        </tr>";
    }
    ....
    ?>

    1_and_0, 07 Февраля 2011

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

    +164

    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
    for($i=0;$i<count($ads_garage);$i++){
    switch($ads_garage[$i]['adv_type']){
      case "buy":
        $adv_type='покупка';
      break;
      case "sell":
        $adv_type='продажа';  
      break;
      case "exchange":
        $adv_type='обмен';
      break;
      case "lease":
        $adv_type='аренда';  
      break;
      case "rent":
        $adv_type='прокат';  
      break;
      case "candidate":
        $adv_type='кандидатура';  
      break;
      case "vacancy":
        $adv_type='вакансия';  
      break;
      case "":
        $adv_type='-';
      break;
    }

    тут такого ещё наверно не было

    DrFreez, 06 Февраля 2011

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

    +167

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    <?if(count($errors)>0){?>
    <input type="text" name="engine" id="engine" class="adv_input" style="width:30px;" maxlength="4" value="<?=$engine?>">
    <?}else{?>
    <input type="text" name="engine" id="engine" class="adv_input" style="width:30px;" maxlength="4" value="<?=$adv['engine']?>">
    <?}?>

    DrFreez, 06 Февраля 2011

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

    +163

    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
    function IndexDownloadsAddVote()
    {
    	global $db, $config, $site, $user;
    	
    	$ip = getip();
    	$file = SafeEnv($_GET['file'], 11, int); // ид файла
    	$cat = SafeEnv($_GET['cat'], 11, int); // категория
    	$vote = SafeEnv($_POST['vote'], 1, int); // голос
    
    	$site->OtherMeta .= '<meta http-equiv="REFRESH" content="2; URL=index.php?name=downloads&amp;op=full&amp;cat='.$cat.'&amp;file='.$file.'">';
    
    	$where = "`id`='$file' and `active`='1'"; // where для downloads
    	$ex_where = GetWhereByAccess('view'); // видимость
    
    	if($ex_where != ''){
    		$where .= ' and ('.$ex_where.')';
    	}
    
    	$db->Select('downloads', $where); // ищем файл
    
    	if($db->NumRows() > 0){ // существует ли файл
    		$dfile = $db->FetchRow(); // пищем файл в переменную
    		if($dfile['allow_votes']=='1'){ // оценки разрешены
    			if($user->Auth) {
    				$where = "`user_id` = '".$user->Get('u_id')."'";
    			} else {
    				$where = "`ip` = '".$ip."'";
    			}
    
    			$db->Select('downloads_rating', $where); // Делаем запрос
    
    			if($vote==0){
    				$site->AddTextBox('','<center>Вы не выбрали оценку.<br /><br /><a href="javascript:history.go(-1)">Назад</a></center>');
    			} else {
    
    				$user->ChargePoints($config['points']['download_rating']);
    
    				$time = time();
    
    				if($db->NumRows()>0) {
    					$db->Update('downloads_rating', "`vote` = '$vote'", "(`user_id` = '".($user->Auth ? $user->Get('u_id') : 0)."' or `ip` = '$ip') and `downid` = '$file'");
    					
    					$numvotes = SafeDB($dfile['votes_amount'],11,int);
    				} else {
    					$db->Insert('downloads_rating',"'','$file','$ip','$time','$vote','".($user->Auth ? $user->Get('u_id') : 0)."'");
    					
    					$numvotes = SafeDB($dfile['votes_amount'],11,int)+1;
    				}
    				$vote = SafeDB($dfile['votes'],11,int)+$vote;
    				$db->Update('downloads',"votes_amount='$numvotes',votes='$vote'","`id`='$file'");
    				$site->AddTextBox('','<center>Спасибо за вашу оценку.<br><br><a href="javascript:history.go(-1)">Назад</a></center>');
    			}
    		}else{
    		//Оценка запрещена
    		$site->AddTextBox('','<center>Извините, оценка этого файла запрещена.<br><br><a href="javascript:history.go(-1)">Назад</a></center>');
    		}
    	}else{
    	//Файл не существует
    	$site->AddTextBox('','<center>Произошла ошибка. Файл, который вы пытаетесь оценить, не найден в нашем файловом архиве. Возможно он был удален.<br><br><a href="javascript:history.go(-1)">Назад</a></center>');
    	}
    }

    Функция оценки файла из русской CMS

    Мартин, 06 Февраля 2011

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

    +144

    1. 1
    -=== 5555 GET ===-

    qbasic, 06 Февраля 2011

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