Jump to content

crautcher

User
  • Posts

    95
  • Joined

  • Last visited

Everything posted by crautcher

  1. в класе фейсбук написал метод: function SetAppLg($local){ global $lg; $ulg = FacebookApp :: getLgByLocale($local); if ($ulg == 'ru' || $ulg='lt') $lg = $ulg ; else $lg = 'lt' ; } класс экстендс этот , вызываю метод function ExecDefault(){ $Fb = facebook::getAuthorized() ; $facebook = new facebook; if ( $Fb['profile']) { $this -> SetAppLg ($Fb['profile']['locale']); //tut $sql = Sql::getInstance('horo'); $Fb ['profile'] ['Token'] = $facebook ->getAccessToken() ; $this -> AutoregFbUser ( $Fb ['profile']); $this -> AutoLogin ($Fb ['profile'] ); $this -> setVar ('logoutLink', $facebook->getLogoutUrl () ); } else { $this -> setVar ( 'loginLink' , $facebook-> getLoginUrl ( array ( 'canvas' => 1, 'scope' => 'email,offline_access,publish_stream,user_birthday', 'redirect_uri' => facebook::getConfig( 'appUrl' ) ) ) ); } $this -> setVar ('redirect','http://'. facebook::getConfig( "domain" ) .'/'); $this -> output ( "fbapp" ); } пишет , чет за фак ? другии методы то пашут Fatal error: Call to undefined method ActionFbApp::SetAppLg() in /var/www/absolux/astro/action/action.fbapp.php on line 9
  2. я обычно куки ставлю через яваскрипт ,такчто echo "<script type='text/javascript> ...";
  3. А, ну понял, благодарю за наводку на мысль. В общем, решил проблему так: поскольку человек перемещается между сайтами не особо часто и это возможно только при нажатии на соответствующие кнопки в меню, то я в качестве ссылок сделал им следующее: example.com/?key=%айдишник_сессии% где %айдишник_сессии% это тот айдишник, который получил пользователь при первом заходе на любой из сайтов. Ну и в самом начале делаю так if (!empty($_GET['key'])) { setcookie("PHPSESSID", $_GET['key'], time()+86400, "/"); $_COOKIE['PHPSESSID']=$_GET['key']; } session_start(); и всё работает как следует. В принципе, всё логично — сессия ведь определяется по значению в куке. дадада у нас также всё
  4. ну у нас тоже 1 движок на кучу сайтов ,определяется всё через сид (session id) и хранистя какраз в сессии. вопрос то в чем , в чем проблема ?
  5. победил я эту регистрацию , отладил вчера , всё отлично работает
  6. а каким вы видите класс работы с базой данных ? сделал конструктор: class SQL { private $server , $user , $password , $database ; public $connected , $count; function __construct($server,$user,$password,$base) { $this -> count = 0; $this -> connected = false; $this -> server = $server; $this -> user = $user; $this -> password = $password; $this -> SetBase($base); $this -> connect(); } ... } include_once "class.sql.php"; class Register { private $sql; public $login , $password , $email , $error , $errors ; function __construct($login,$pw1,$pw2,$email) // че тянуть резину , если можно сразу в конструкторе падать данные {global $sql; $this -> error =false; $this -> errors= array(); $this -> SetData($login,$pw1,$pw2,$email); $this -> sql = $sql; } function AddError($error) //избавились от хтмл оформления внутри класа { $this->error = true; $this->errors [] = trim($error) ; } function SetData($login,$pw1,$pw2,$email) { $this->login = trim($login); $this->password = trim($pw1); $pw2= trim($pw2); $this->email = trim($email); $this->CheckLogin( $this->login ); $this->CheckPassword( $this->password ); $this->CheckPassword( $pw2 ); if ($this->password != $this->$pw2) $this->AddError('Поле Пароль и его Подтверждение не совпадают!'); $this->CheckEmail( $this-> email ); } function CheckLogin($login) { if (empty($login)) $this->AddError('Вы не заполнели поле Имя пользователя!'); elseif (!preg_match('/^[a-z0-9]{4,25}$/i', $login)) $this->AddError('Убедитесь что Логин содержит от 4 до 12 символов, и состоит из латинских символов и цифр'); else $this-> sql ->query("select `id` from `users` where `login` = '". $login ."' limit 1 "); if ($this->count > 0) { $this->AddError('Такое имя существует !'); $this->count = 0 ; } } function CheckPassword($password) { if (empty($password)) $this->AddError('Вы не заполнили поле Пароль!'); elseif (!preg_match('/^[a-z0-9]{6,255}$/i', $password )) $this->AddError('Убедитесь что Пароль содержит от 6 символов, и состоит из латинских символов и цифр'); } function CheckEmail($email) { if (empty($email)) $this->AddError('Вы не заполнили поле E-Mail!'); elseif (!preg_match('/^[a-z][a-z0-9_\.\-]{1,24}@([a-z][a-z0-9\-]{1,24}\.){1,3}[a-z]{2,7}$/i',$email)) $this->AddError('Не правильно заполнено поле E-Mail. E-mail должен иметь вид user@somehost.com !'); else $this -> sql -> query("select `id` from `users` where `email` = '". $email ."' limit 1 "); if ($this->count > 0) { $this->AddError('Такой эмаил существует !'); $this->count = 0 ; } } function GetErrors() { if ($this->IsError()) return $this->errors ; } function IsError() { return $this->error; } function AddToBase(); { if (!$this -> sql -> connected) $this -> sql -> connect() ; $result = $this->sql ->run("INSERT INTO `users` (`login`, `pass`,`email`) VALUES('". $this->login ."', '". md5 ($this-> password) ."', '". $email ."' "); if ($result) return true; return false; } } if ($_POST) { include_once "clases/class.sql.php"; include_once "clases/class.register.php"; $sql = new SQL('******','*****','*****','*****'); $reg = new Register($_POST['rlogin'] , $_POST['rpass'] , $_POST['rpassr'] , isset($_POST['email']); if ( $reg->IsError() ) { $errors = $reg -> GetErrors(); echo "<p>При регистрации на сайте произошли следующие ошибки:</p><ul>"; foreach ($errors as $er) echo "<li>".$er."</li>"; echo "</ul>"; } elseif ($reg -> AddToBase()) echo('<p>Вы успешно зарегистрированы на сайте!</p>'); else echo('<p>Не удалось !</p>'); } }
  7. майскул класс : class SQL { public $server= '*****' ,$user='******',$password='******',$database='****', $connected , $count; function SetBase($base) { $this->database = trim($base); } function connect() { if ($this->connected) mysql_close(); $curent = mysql_connect ($this->server, $this->user, $this->password); if (!$curent) { $this->connected = false; die("some error : ".mysql_error() ); }else $this -> connected = true ; $this -> CreateBase( $this->database ); mysql_select_db ($this->database) or die("some problem with database : ". mysql_error() ); $this->connected = true; } function CreateBase($name) { $this -> run ("CREATE DATABASE IF NOT EXISTS `".trim($name)."` "); } function query($query,$type='array') { if (!$this->connected) $this->connect(); $result = $this->run($query); if (!$result) return(mysql_error()); $this->count = mysql_num_rows($result); if (!$this->count) return 0; $d = array (); if ($type == 'object') while ($row = mysqli_fetch_object($result)) $d[] = $row; if ($type == 'row') while ($row = mysqli_fetch_row($result)) $d[] = $row; if ($type == 'assoc') while ($row = mysql_fetch_assoc($result)) $d[] = $row; else while ($row = mysql_fetch_array($result)) $d[] = $row; return $d; } function run($query) { if (!$this->connected) $this->connect(); $query = trim($query); $result = mysql_query($query); return $result; } } далее идет класс регистрации: class Register extends SQL { public $login , $password , $password_r , $email , $error , $errortext ; function __construct() { $this -> count = 0; $this -> connected = false; $this -> error =false; $this -> errortext = '<p>При регистрации на сайте произошли следующие ошибки:</p><ul>'; } function install() { $this -> run ("CREATE TABLE IF NOT EXISTS `users` ( `id` INT( 10 ) NOT NULL AUTO_INCREMENT , `login` VARCHAR( 12 ) NOT NULL , `pass` TEXT NOT NULL , `email` TEXT NOT NULL , PRIMARY KEY ( `id` ) )"); } function AddError($error) { $this->error = true; $this->errortext .= '<li>'.trim($error).'</li>'; } function SetData($login,$pw1,$pw2,$email) { $this->login = trim($login); $this->password = trim($pw1); $this->password_r = trim($pw2); $this->email = trim($email); $this->CheckLogin( $this->login ); $this->CheckPassword( $this->password ); $this->CheckPassword( $this->password_r ); if ($this->password != $this->password_r) $this->AddError('Поле Пароль и его Подтверждение не совпадают!'); $this->CheckEmail( $this-> email ); } function CheckLogin($login) { if (empty($login)) $this->AddError('Вы не заполнели поле Имя пользователя!'); elseif (!preg_match('/^[a-z0-9]{4,12}$/i',$login)) $this->AddError('Убедитесь что Логин содержит от 4 до 12 символов, и состоит из латинских символов и цифр'); else $this->query("select `id` from `users` where `login` = '".addslashes($login)."' limit 1 "); if ($this->count > 0) { $this->AddError('Такое имя существует !'); $this->count = 0 ; } } function CheckPassword($password) { if (empty($password)) $this->AddError('Вы не заполнили поле Пароль!'); elseif (!preg_match('/^[a-z0-9]{6,20}$/i',$password)) $this->AddError('Убедитесь что Пароль содержит от 6 до 20 символов, и состоит из латинских символов и цифр'); } function CheckEmail($email) { if (empty($email)) $this->AddError('Вы не заполнили поле E-Mail!'); elseif (!preg_match('/^[-0-9a-z_\.]+@[-0-9a-z^\.]+\.[a-z]{2,4}$/i',$email)) $this->AddError('Не правильно заполнено поле E-Mail. E-mail должен иметь вид user@somehost.com !'); else $this->query("select `id` from `users` where `email` = '".addslashes($email)."' limit 1 "); if ($this->count > 0) { $this->AddError('Такой эмаил существует !'); $this->count = 0 ; } } function ShowErrors() { if ($this->IsError()) echo $this->errortext . '</ul>'; } function IsError() { return $this->error; } function AddToBase(); { $result = $this->run("INSERT INTO `users` (`login`, `pass`,`email`) VALUES('".addslashes($this->login)."', '".md5 ($this-> password)."', '".addslashes($email)."' "); if ($result) return true; return false; } } непосдредственно сама страница рега <?php if ($_POST) { include_once "clases/class.sql.register.php"; $reg = new Register; $reg -> SetData($_POST['rlogin'] , $_POST['rpass'] , $_POST['rpassr'] , isset($_POST['email']); if ($reg->IsError) $reg -> ShowErrors(); else { $reg->connect(); $reg->install(); if ($reg -> AddToBase()) echo('<p>Вы успешно зарегистрированы на сайте!</p>'); else echo('<p>Не удалось !</p>'); } } ?> <form id="register_form" name="register_form" method="post" action=""> <table width="508" height="231" border="1" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="251" align="right">Login:</td> <td width="251" align="center"> <input type="text" name="rlogin" id="rlogin" <?php if ($_POST && $reg->error && isset($_POST['rlogin'])) echo('value="'.$_POST['rlogin'].'" '); ?>/> </td> </tr> <tr> <td align="right">Password:</td> <td align="center"><input type="password" name="rpass" id="rpass" <?php if ($_POST && $reg->error && isset($_POST['rpass'])) echo(‘value="’.$_POST['rpass'].’" ‘); ?>/></td> </tr> <tr> <td align="right">Repeat Password:</td> <td align="center"><input type="password" name="rpass_r" id="rpass_r" <?php if ($_POST && $reg->error && isset($_POST['rpass_r'])) echo('value="'.$_POST['rpass_r'].'" '); ?>/></td> </tr> <tr> <td align="right">E-Mail:</td> <td align="center"><input type="text" name="email" id="email" <?php if ($_POST && $reg->error && isset($_POST['email'])) echo('value="'.$_POST['email'].'" '); ?>/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" name="reg_button" id="reg_button" value=" Register " /> </td> </tr> </table> </form>
  8. ты имеешь в виду дополнительно ? или счтоб текущая сменилась на новую , если текущая , то ответ был
  9. в общем табличка <table id="tmap" border=3 > <tr ><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/sneg.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td></tr> <tr ><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/sneg.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td></tr> <tr ><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/sneg.jpg"></td><td BACKGROUND="img/map/les1.jpg">U</td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td></tr> <tr ><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/sneg.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td></tr> <tr ><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/sneg.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td><td BACKGROUND="img/map/les1.jpg"></td></tr> </table> она меняет размер в зависимости от размера окна (длина и ширина дива и самой таблицы в процентах) #tmap { border: 4px solid #000000; width: 100%; height: 100%; } всё отлично , красивые квадраты , но как только добавил текст , буку "u" для теста - колонка стала в 2 раза шире, а остальные сузились , хотя там места дохрена еще, как сделать чтобы размер каждой ячейки был одинаковым ?
  10. да я пока ждал , подумал и решил нарезать карту на штуку мелких подкарт (макросом в проге) и теперь: function MakeMap() { $this->map = array(); for ( $i = -5; $i< ($this->maxX + 6) ;$i++) for ($j= -5;$j< ($this->maxY + 6) ;$j++) { $this->map[$i][$j] = '<img src="img/map/map_part".$i.$j.".jpg" width=10px height=10px>'; } }
  11. будет большая картинка карты , мне надо её разделить на 1000 (100x100)условных секторов , чтоб я какбы ходить по ней мог , а в низу будет в зависимости от сектора менятся контент . вот типо клас прогулки : class world { private $maxX , $maxY; public $gps = array(); function __construct() { $this -> gps ['x'] = false; $this -> gps ['y'] = false; $this -> maxX = 100; $this -> maxY = 100; } public function SetLocation($x,$y) { if ($x > $this->maxX ) $x = $this->maxX; elseif ($x < 0) $x = 0; if ($y > $this->maxY ) $y = $this->maxY; elseif ($y < 0 ) $y = 0; $this -> gps ['x'] = (int)$x; $this -> gps ['y'] = (int)$y; } function GetDirection() { if ($this->gps ['x'] === false || $this->gps ['y'] === false) return false; $data = ''; if ($this->gps ['y'] < $this->maxY) $data .= '{up}'; if ($this->gps ['y'] > 0) $data .= '{down}'; if ($this->gps ['x'] < $this -> maxX) $data .= '{right}'; if ($this->gps ['x'] > 0) $data .= '{left}'; return $data; } function GoUp() { if ($this -> gps ['y'] < $this->maxY ) ++$this -> gps ['y'] ; } function GoDown() { if ($this -> gps ['y'] > 0 ) --$this -> gps ['y'] ; } function GoRight() { if ($this -> gps ['x'] < $this->maxX ) ++$this -> gps ['x'] ; } function GoLeft() { if ($this -> gps ['x'] > 0 ) --$this -> gps ['x'] ; } } тип задаём сектор на котором находимся , получаем набор спец тегов вроде {down} которые потом заменяются на линки перехода на другой сектор , и координаты меняются . меня интересует часть работы с самой картинкой , как можно реализовать разбивание на части ?
  12. во чередной раз сам тупанул , не обновил страницу ) в топку тему
  13. <script type="text/javascript"> var check='error',id='error', http = false ; function dataSet(value,value2) { if (value == 'on') check = 1 ; else check =0; id = value2; alert(id + check); } </script> foreach($result as $row){ if ($row[2] == "1"){ $bb="<input type=checkbox name='". $row[0] ."' checked onclick='javascript: dataSet( this.value , this.name )'>"; }else{ $bb="<input type=checkbox name='". $row[0] ."' onclick='javascript: dataSet( this.value , this.name )'>"; } }немогу я понять логику яваскрипта , по отдельности работает , а 2 разом переменные не работает
  14. crautcher

    аяксег

    пока чинил одно поломал другое и понять не могу что не так ? если пришло сообщение 'clear' должен очистится див function talk() { http.abort(); if (msg2 == 'notext') { http.open("GET", "mind.php?msg=" + msg , true); } else { http.open("GET", "mind.php?msg=" + 'ЗАДАТЬ_ОТВЕТ/' + msg2 , true); } http.onreadystatechange=function() { if(http.readyState == 4) { if (http.responseText == "clear" || http.responseText == "clear ") // tut ! { document.getElementById('chat').innerHTML = "<font color='red'><b>Vicky</b></font> :Очищено<br>"; }else{ if (count < 15 ){ document.getElementById('chat').innerHTML = document.getElementById('chat').innerHTML + http.responseText; count = count+1; } else{ document.getElementById('chat').innerHTML = http.responseText; count = 0; } } } } а соощение "клир" мы должны получить от сценария если передадим "очисти" $vicky -> Hear($msg); получили собщение , что там дальше не важно так как команда должна убить сценарий. Hear($msg); if (!$this -> SeakOrNot()); if (!$this-> AdminCommands($msg)) ... проверка команд перехватывает сообщение что там дальше опять не важно. строка в AdminCommands($msg): if ($msg=="очисти" || $msg=="очистить") { $this -> SendLog("[m:AdminCommands:s3] Command detected : Clear "."\n"); die('clear'); } и вот какбы должно всё быть хорошо , и было , но теперь вместо очистки ДОБОВЛЯЕТСЯ текст "clear" в див. что странно , раз приходит "clear" значит сценарий работает верно .
  15. ну я коменты писал для этого . Что услышать ? Ну незнаю , вы же тут все люди с опытом , указать на недостатки. ладно в топку тему
  16. еслиб я все класы которые используются сюда выложил , никтоб даже и не подумал смотреть всю эту кучу кода ...
  17. и стоит ли разбить метод на более мелкии составные части , дабы улучшить конструктивность? <?php function Hear($msg) #Обрабатывает сообщение и отправляет юзeру Ответ + вопрос { $this -> SetMinds('Со мной что то не тaк !'); //задаём ответ который не должен появится , если появится - действительно чтото не так if (!$this -> SeakOrNot()); //проверка готовности к работе if (!$this-> AdminCommands($msg)) //Не является ли текст командой $this->GenerateAnswer($msg);//Выделяет вопрос из полученого сообщения или задаёт фолс if (!$this->foundQ) $this -> Dunno(); //Вывод сообщений когда незнаем что хотят $answer =$this -> GetA( $this -> GetQID($this -> foundQ ) ); //получаем ответ на заданный вопрос if (!empty($answer)) $this-> SetMinds ( $answer ); //шлем ответ юзеру else { $this -> LastQuestion = $this->asked; $this -> Dunno(); } if ($this->LastQuestion) //если был задан вопрос в прошлом сообщении { $id = $this -> GetQID($this->LastQuestion); //пытаемся получить айдишник последнего вопроса if (!empty($id)) { $answer = GetAnswer($msg); //выделяем ответ на вопрос из сообщения if ($answer != '') { if (!($this -> sql -> query("select text from answers where text='".$answer."' AND questionId = '".$id."' "))) $this->AddA($answer,$id); //добавляем ответ если такого нет } } } $this->LastQuestion= $this -> GenerateQuestion(); //спрашиваем юзера $this -> SendMind( $this->LastQuestion ); } ?>
  18. ну есть 2 варианта , 1ый легче - это не удалять , а наоборот рисовать див <? // if (условие какое вам надо) echo '<div class="A">text1</div>'; else echo '<div class="B">text1</div>'; и второй вариант , это замена : <? $divs = '<div class="A">text1</div> <div class="A B">text3</div>'; // if (условие какое вам надо) $divs = str_replace ('class="A"' , 'class="B"', $divs); echo $divs; и самое банальное , почему бы вам не задать клас дива сразу значением переменной <? echo '<div class="'. $X .'">text1</div> <div class="A B">text3</div>';
  19. такой ощущение что твой цикл еще в одном цикле
  20. а сессию достаточно будет открыть в сценарии , или нужно еще в аякс файле ?
  21. ну во первых выводи ошибки $msconnect = mysql_connect($mshost, $msuser, $mspassword)or die(mysql_error()); mysql_select_db($msname, $msconnect)or die(mysql_error()); mysql_query("CREATE TABLE rooms ( n_room int, color text)", $msconnect)or die(mysql_error()); везде где запросы к базе. если чтото пойдет не так ты узнаешь , напиши что вышло.
  22. С вопросами покончено , теперь мне нужно обрабатывать ответы. Юзеру задаётся вопрос ,он на него отвечает , если нет похожего в базе добавляем ответ в базу. (функционал оброботки похожести уже есть) проблема вот в чем - в сценарий обработки мы подаём переменную(ответ) аяксом , а сценарий должен уже всё сделать, но как мне достать заданный вопрос (он каждый раз разный)
  23. crautcher

    Алгоритм

    если последняя буква глассная беру и отсекаю её (или совподает со списком других таких как "ой" и т.д. в русском языке окончаний не много) , окончание не может быть согласной или не иметь гласную букву на конце в форме без окончания - чайник (последняя "к" - не катит) , (мама , маме , маму) - отсекается под "мам" , (армия , армию) - отсекается под "арми" это к существительным!
  24. crautcher

    Алгоритм

    омг , в них я найду "коров" , еще раз говорю я отсекаю окончание, в любом случае когда доделаю проет кину линк и посмотришь что всё работает
  25. в дримвювере встроенный сервер , поэтому он показывает пхп
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy