public function testGeneral()
 {
     $link = new Link();
     $link->render();
     $link->add('bootstrap.css', 'style/bootstrap.css');
     $link->add('slider.css', ['href' => 'style/slider.css', 'type' => 'text/css', 'rel' => 'stylesheet']);
     $link->addAll(['more.css' => 'style/more.css', 'more2.css' => ['href' => 'style/more2.css']]);
     $link->prependAll(['first0' => 'style/first0.css', 'fist1' => ['href' => 'style/first1.css', 'type' => 'text/css', 'rel' => 'stylesheet']]);
     $this->assertNotEmpty($link->get('more.css'));
     $link->remove('more.css');
     $this->assertEmpty($link->get('more.css'));
     $link->prepend('first_of_first', 'style/bootstrap.css');
     $link->prepend('first_of_first', ['href' => 'style/bootstrap.css', 'rel' => 'stylesheet']);
     $link->render();
 }
Exemple #2
0
 /**
  * Index action.
  *
  * @return Bengine_Game_Controller_MSG
  */
 protected function indexAction()
 {
     $select = array("f.folder_id", "f.label", "f.is_standard", "COUNT(m.msgid) AS messages", "SUM(m.read) AS `read`", "SUM(LENGTH(m.message)) AS `storage`");
     $joins = "LEFT JOIN " . PREFIX . "message m ON (m.mode = f.folder_id AND m.receiver = '" . Core::getUser()->get("userid") . "')";
     $where = Core::getDB()->quoteInto("f.userid = ? OR f.is_standard = '1'", Core::getUser()->get("userid"));
     $result = Core::getQuery()->select("folder f", $select, $joins, $where, "", "", "f.folder_id");
     $folders = array();
     foreach ($result->fetchAll() as $row) {
         $unreadMessages = $row["messages"] - (int) $row["read"];
         if ($unreadMessages > 1) {
             $read = "UNREAD";
             $newMessages = sprintf(Core::getLanguage()->getItem("F_NEW_MESSAGES"), fNumber($unreadMessages));
         } else {
             if ($unreadMessages > 0) {
                 $read = "UNREAD";
                 $newMessages = Core::getLanguage()->getItem("F_NEW_MESSAGE");
             } else {
                 $read = "READ";
                 $newMessages = "";
             }
         }
         $label = $row["is_standard"] ? Core::getLang()->get($row["label"]) : $row["label"];
         $link = "game/" . SID . "/MSG/ReadFolder/" . $row["folder_id"];
         $folders[] = array("image" => Link::get("game/" . SID . "/MSG/markasread/" . $row["folder_id"], Image::getImage(strtolower($read) . ".gif", Core::getLang()->get($read))), "label" => Link::get($link, $label, Core::getLang()->get($read)), "messages" => fNumber($row["messages"]), "newMessages" => $newMessages, "size" => File::bytesToString($row["storage"]));
     }
     $result->closeCursor();
     Core::getTPL()->addLoop("folders", $folders);
     return $this;
 }
Exemple #3
0
 /**
  * @return Bengine_Admin_Controller_News
  */
 protected function indexAction()
 {
     if ($this->getParam("add")) {
         $this->add($this->getParam("language_id"), $this->getParam("title"), $this->getParam("text"));
     }
     $first = true;
     $i = 1;
     $news = array();
     $result = Core::getQuery()->select("news", array("news_id", "title", "text", "time", "enabled", "sort_index"), "", "", "sort_index ASC, news_id DESC");
     $total = $result->rowCount();
     foreach ($result->fetchAll() as $row) {
         $down = "";
         $up = "";
         if (!$first) {
             $up = Image::getImage("admin/up.gif", "", 16, 16);
             $up = Link::get("admin/news/moveup/" . $row["news_id"], $up);
         }
         $first = false;
         if ($i < $total) {
             $down = Image::getImage("admin/down.gif", "", 16, 16);
             $down = Link::get("admin/news/movedown/" . $row["news_id"], $down);
         }
         $i++;
         $news[] = array("news_id" => $row["news_id"], "title" => $row["title"], "text" => $row["text"], "time" => Date::timeToString(1, $row["time"]), "enabled" => $row["enabled"], "edit" => Link::get("admin/news/edit/" . $row["news_id"], Core::getLang()->get("Edit")), "delete" => Link::get("admin/news/delete/" . $row["news_id"], Core::getLang()->get("Delete")), "enable" => Link::get("admin/news/enable/" . $row["news_id"], Core::getLang()->get("Enable"), "", "green"), "disable" => Link::get("admin/news/disable/" . $row["news_id"], Core::getLang()->get("Disable"), "", "red"), "down" => $down, "up" => $up);
     }
     Core::getTemplate()->addLoop("news", $news);
     $languages = $this->getLanguages();
     Core::getTPL()->assign("languageCount", count($languages));
     if (count($languages) == 1) {
         Core::getTPL()->assign("languages", key($languages));
     } else {
         Core::getTPL()->assign("languages", $this->getLanguageSelect());
     }
     return $this;
 }
Exemple #4
0
 /**
  * @return array
  */
 public function render()
 {
     foreach ($this->getModules() as $module) {
         if ($module["enable"]) {
             $name = $module["name"];
             $translate = true;
             if (is_array($name)) {
                 $translate = $name["noLangVar"];
                 $name = $name["value"];
             }
             if ($translate) {
                 $name = Core::getLang()->get($name);
             }
             $uri = $module["link"];
             if (is_array($uri)) {
                 $package = isset($uri["package"]) ? $uri["package"] : "admin";
                 $controller = isset($uri["controller"]) ? $uri["controller"] : "index";
                 $action = isset($uri["action"]) ? $uri["action"] : "index";
                 $uri = "{$package}/{$controller}/{$action}";
             }
             $this->menu[] = Link::get($uri, $name, "", isset($module["class"]) ? $module["class"] : "");
         }
     }
     return $this->menu;
 }
Exemple #5
0
 /**
  * Index action.
  *
  * @return Bengine_Game_Controller_Friends
  */
 protected function indexAction()
 {
     Core::getLanguage()->load(array("Statistics", "Buddylist"));
     if ($this->isPost()) {
         if ($this->getParam("delete")) {
             $this->remove($this->getParam("remove", array()));
         }
         if ($this->getParam("accept")) {
             $this->acceptRequest($this->getParam("relid"));
         }
     }
     $bl = array();
     $select = array("b.relid", "b.friend1", "b.friend2", "b.accepted", "u1.username as user1", "u1.points as points1", "u1.last as lastlogin1", "u2.points as points2", "u2.username as user2", "u2.last as lastlogin2", "a1.tag as ally1", "a1.aid as allyid1", "a2.tag as ally2", "a2.aid as allyid2", "g1.galaxy as gala1", "g1.system as sys1", "g1.position as pos1", "g2.galaxy as gala2", "g2.system as sys2", "g2.position as pos2");
     $joins = "LEFT JOIN " . PREFIX . "user u1 ON (u1.userid = b.friend1)";
     $joins .= "LEFT JOIN " . PREFIX . "user u2 ON (u2.userid = b.friend2)";
     $joins .= "LEFT JOIN " . PREFIX . "galaxy g1 ON (g1.planetid = u1.hp)";
     $joins .= "LEFT JOIN " . PREFIX . "galaxy g2 ON (g2.planetid = u2.hp)";
     $joins .= "LEFT JOIN " . PREFIX . "user2ally u2a1 ON (u2a1.userid = b.friend1)";
     $joins .= "LEFT JOIN " . PREFIX . "user2ally u2a2 ON (u2a2.userid = b.friend2)";
     $joins .= "LEFT JOIN " . PREFIX . "alliance a1 ON (a1.aid = u2a1.aid)";
     $joins .= "LEFT JOIN " . PREFIX . "alliance a2 ON (a2.aid = u2a2.aid)";
     $result = Core::getQuery()->select("buddylist b", $select, $joins, Core::getDB()->quoteInto("b.friend1 = ? OR b.friend2 = ?", Core::getUser()->get("userid")), "u1.points DESC, u2.points DESC, u1.username ASC, u2.username ASC");
     foreach ($result->fetchAll() as $row) {
         Hook::event("ShowBuddyFirst", array(&$row));
         if ($row["friend1"] == Core::getUser()->get("userid")) {
             if ($row["lastlogin2"] > TIME - 900) {
                 $status = Image::getImage("on.gif", getTimeTerm(TIME - $row["lastlogin2"]));
             } else {
                 $status = Image::getImage("off.gif", getTimeTerm(TIME - $row["lastlogin2"]));
             }
             $username = Link::get("game/" . SID . "/MSG/Write/" . rawurlencode($row["user2"]), Image::getImage("pm.gif", Core::getLanguage()->getItem("WRITE_MESSAGE"))) . " " . Link::get("game/" . SID . "/Profile/Page/" . $row["friend2"], $row["user2"]);
             $points = $row["points2"];
             $position = getCoordLink($row["gala2"], $row["sys2"], $row["pos2"]);
             $ally = Link::get("game/" . SID . "/Alliance/Page/" . $row["allyid2"], $row["ally2"]);
         } else {
             if ($row["lastlogin1"] > TIME - 900) {
                 $status = Image::getImage("on.gif", getTimeTerm(TIME - $row["lastlogin1"]));
             } else {
                 $status = Image::getImage("off.gif", getTimeTerm(TIME - $row["lastlogin1"]));
             }
             $username = Link::get("game/" . SID . "/MSG/Write/" . rawurlencode($row["user1"]), Image::getImage("pm.gif", Core::getLanguage()->getItem("WRITE_MESSAGE"))) . " " . Link::get("game/" . SID . "/Profile/Page/" . $row["friend1"], $row["user1"]);
             $points = $row["points1"];
             $position = getCoordLink($row["gala1"], $row["sys1"], $row["pos1"]);
             $ally = Link::get("game/" . SID . "/Alliance/Page/" . $row["allyid1"], $row["ally1"]);
         }
         $bl[$row["relid"]]["f1"] = $row["friend1"];
         $bl[$row["relid"]]["f2"] = $row["friend2"];
         $bl[$row["relid"]]["relid"] = $row["relid"];
         $bl[$row["relid"]]["username"] = $username;
         $bl[$row["relid"]]["accepted"] = $row["accepted"];
         $bl[$row["relid"]]["points"] = fNumber($points);
         $bl[$row["relid"]]["status"] = $status;
         $bl[$row["relid"]]["position"] = $position;
         $bl[$row["relid"]]["ally"] = $ally;
         Hook::event("ShowBuddyLast", array($row, &$bl));
     }
     $result->closeCursor();
     Core::getTPL()->addLoop("buddylist", $bl);
     return $this;
 }
 /**
  * Alliance page action.
  *
  * @return Bengine_Comm_Controller_Alliance
  */
 public function pageAction()
 {
     Core::getLanguage()->load("Alliance");
     Core::getTPL()->clearHTMLHeaderFiles();
     Core::getTPL()->addHTMLHeaderFile("game.css", "css");
     Core::getTPL()->addHTMLHeaderFile("lib/jquery.js", "js");
     $tag = $this->getParam("1");
     $fNumber = array("member", "points", "rpoints", "fpoints", "dpoints");
     $attr = array("a.aid", "a.name", "a.tag", "a.logo", "a.textextern", "a.homepage", "a.showhomepage", "COUNT(u2a.userid) AS member", "SUM(u.points) AS points", "SUM(u.rpoints) AS rpoints", "SUM(u.fpoints) AS fpoints", "SUM(u.dpoints) AS dpoints");
     $joins = "LEFT JOIN " . PREFIX . "user2ally u2a ON (u2a.aid = a.aid) ";
     $joins .= "LEFT JOIN " . PREFIX . "user u ON (u2a.userid = u.userid) ";
     $result = Core::getQuery()->select("alliance a", $attr, $joins, Core::getDB()->quoteInto("tag = ?", $tag), "", 1, "a.aid");
     $row = $result->fetchRow();
     if ($row) {
         foreach ($fNumber as $field) {
             $row[$field] = fNumber($row[$field]);
         }
         $parser = new Bengine_Game_Alliance_Page_Parser($row["aid"]);
         if (Str::length(strip_tags($row["textextern"])) > 0) {
             $row["textextern"] = $parser->startParser($row["textextern"]);
         } else {
             $row["textextern"] = Core::getLang()->get("WELCOME");
         }
         $row["homepage"] = $row["homepage"] != "" ? Link::get($row["homepage"], $row["homepage"], $row["homepage"]) : "";
         $row["logo"] = $row["logo"] != "" ? Image::getImage($row["logo"], "") : "";
         Hook::event("ShowPublicAlliancePage", array(&$row));
         $this->assign($row);
         $this->setIsAjax();
     } else {
         $this->setNoDisplay(true);
     }
     return $this;
 }
 /**
  * Displays the moderator form to edit users.
  *
  * @return Bengine_Game_Controller_Moderator
  */
 protected function indexAction()
 {
     if ($this->isPost()) {
         if ($this->getParam("proceedban")) {
             $this->proceedBan($this->getParam("ban"), $this->getParam("timeend"), $this->getParam("reason"), $this->getParam("b_umode"));
         }
         if ($this->getParam("proceed")) {
             $this->updateUser($this->getParam("username"), $this->getParam("usertitle"), $this->getParam("email"), $this->getParam("delete"), $this->getParam("umode"), $this->getParam("activation"), $this->getParam("ipcheck"), $this->getParam("usergroupid"), $this->getParam("points"), $this->getParam("fpoints"), $this->getParam("dpoints"), $this->getParam("rpoints"), $this->getParam("password"), $this->getParam("languageid"), $this->getParam("templatepackage"), $this->getParam("theme"), $this->getParam("js_interface"));
         }
     }
     $select = array("u.userid", "u.username", "u.usertitle", "u.email", "u.temp_email", "u.languageid", "u.templatepackage", "u.theme", "u.js_interface", "u.points", "u.fpoints", "u.dpoints", "u.rpoints", "u.ipcheck", "u.activation", "u.last", "u.umode", "u.umode", "u.delete", "u.regtime", "a.tag", "a.name", "u2g.usergroupid");
     $joins = "LEFT JOIN " . PREFIX . "user2ally u2a ON (u2a.userid = u.userid)";
     $joins .= "LEFT JOIN " . PREFIX . "alliance a ON (a.aid = u2a.aid)";
     $joins .= "LEFT JOIN " . PREFIX . "user2group u2g ON (u.userid = u2g.userid)";
     $result = Core::getQuery()->select("user u", $select, $joins, Core::getDB()->quoteInto("u.userid = ?", $this->userid));
     if ($row = $result->fetchRow()) {
         $result->closeCursor();
         Hook::event("ModerateUser", array(&$row));
         $row["deletion"] = $row["delete"];
         unset($row["delete"]);
         $row["vacation"] = $row["umode"];
         unset($row["umode"]);
         $row["last"] = Date::timeToString(1, $row["last"]);
         $row["regtime"] = Date::timeToString(1, $row["regtime"]);
         Core::getTPL()->assign($row);
         if ($row["usergroupid"] == 4) {
             Core::getTPL()->assign("isMod", true);
         } else {
             if ($row["usergroupid"] == 2) {
                 Core::getTPL()->assign("isAdmin", true);
             }
         }
         $result = Core::getQuery()->select("languages", array("languageid", "title"), "", "", "title ASC");
         Core::getTPL()->addLoop("langs", $result);
         Core::getTPL()->assign("loginLink", Link::get("game/" . SID . "/Moderator/SwitchUser/" . $row["userid"], Core::getLang()->get("SWITCH_USER")));
         $bans = array();
         $i = 0;
         $result = Core::getQuery()->select("ban_u", array("`banid`", "`to`", "`reason`"), "", Core::getDB()->quoteInto("userid = ?", $this->userid));
         foreach ($result->fetchAll() as $row) {
             $bans[$i]["reason"] = $row["reason"];
             $bans[$i]["to"] = Date::timeToString(1, $row["to"]);
             if ($row["to"] > TIME) {
                 $bans[$i]["annul"] = Link::get("game/" . SID . "/Moderator/AnnulBan/" . $row["banid"], Core::getLanguage()->getItem("ANNUL"));
             } else {
                 $bans[$i]["annul"] = Core::getLanguage()->getItem("ANNUL");
             }
             $i++;
         }
         $result->closeCursor();
         Core::getTPL()->addLoop("bans", $bans);
         Core::getTPL()->assign("eBans", $i);
         Core::getTPL()->assign("sessionsLink", Link::get("game/" . SID . "/Moderator/Sessions?id=" . $this->userid, "Sessions"));
     }
     return $this;
 }
Exemple #8
0
 /**
  * Loads all menu items.
  *
  * @return Bengine_Comm_CMS
  */
 protected function loadMenuItems()
 {
     $result = Core::getQuery()->select("page", array("position", "title", "label", "link"), "", Core::getDB()->quoteInto("languageid = ?", $this->langid), "displayorder ASC");
     foreach ($result->fetchAll() as $row) {
         $position = $row["position"];
         if (!empty($row["link"])) {
             $this->menuItems[$position][]["link"] = Link::get($row["link"], $row["title"], $row["title"]);
         } else {
             $this->menuItems[$position][]["link"] = Link::get(LANG . "index/" . $row["label"], $row["title"], $row["title"]);
         }
     }
     Hook::event("CommLoadMenu", array(&$this->menuItems, $this));
     return $this;
 }
Exemple #9
0
 /**
  * @return Bengine_Admin_Controller_Cronjob
  */
 protected function indexAction()
 {
     if ($this->getParam("add_cronjob")) {
         $this->add($this->getParam("month"), $this->getParam("day"), $this->getParam("weekday"), $this->getParam("hour"), $this->getParam("minute"), $this->getParam("class"));
     }
     $minute = "";
     $hour = "";
     $weekday = "";
     $day = "";
     $month = "";
     $i = 0;
     while ($i < 60) {
         $minute .= createOption($i, $i, 0);
         $i += 5;
     }
     for ($i = 0; $i < 24; $i++) {
         $hour .= createOption($i, $i, 0);
     }
     $wds = array(1 => "Mon", 2 => "Tue", 3 => "Wed", 4 => "Thu", 5 => "Fri", 6 => "Sat", 7 => "Sun");
     for ($i = 1; $i <= 7; $i++) {
         $weekday .= createOption($i, $wds[$i], 0);
     }
     for ($i = 1; $i <= 31; $i++) {
         $day .= createOption($i, $i, 0);
     }
     for ($i = 1; $i <= 12; $i++) {
         $month .= createOption($i, $i, 0);
     }
     Core::getTPL()->assign("minute", $minute);
     Core::getTPL()->assign("hour", $hour);
     Core::getTPL()->assign("weekday", $weekday);
     Core::getTPL()->assign("day", $day);
     Core::getTPL()->assign("month", $month);
     $tabs = array();
     $result = Core::getQuery()->select("cronjob", array("cronid", "class", "xtime", "last", "active"), "ORDER BY xtime ASC");
     foreach ($result->fetchAll() as $row) {
         $id = $row["cronid"];
         $tabs[$id]["cronid"] = $row["cronid"];
         $tabs[$id]["class"] = $row["class"];
         $tabs[$id]["xtime"] = empty($row["xtime"]) ? Core::getLang()->get("NEVER") : date("Y-m-d H:i:s", $row["xtime"]);
         $tabs[$id]["last"] = empty($row["last"]) ? Core::getLang()->get("NEVER") : date("Y-m-d H:i:s", $row["last"]);
         $tabs[$id]["delete"] = Link::get("admin/cronjob/delete/" . $id, Core::getLanguage()->getItem("Delete"));
         $tabs[$id]["exec"] = Link::get("admin/cronjob/execute/" . $id, Core::getLanguage()->getItem("Execute"));
         $tabs[$id]["edit"] = Link::get("admin/cronjob/edit/" . $id, Core::getLanguage()->getItem("Edit"));
         $tabs[$id]["active"] = $row["active"] ? Link::get("admin/cronjob/disable/" . $id, "<span class=\"green\">On</span>", Core::getLanguage()->getItem("Disable")) : Link::get("admin/cronjob/enable/" . $id, "<span class=\"red\">Off</span>", Core::getLanguage()->getItem("Enable"));
     }
     Core::getTPL()->addLoop("crontabs", $tabs);
     return $this;
 }
Exemple #10
0
 /**
  * Formats the message.
  *
  * @param Bengine_Game_Model_Message $message
  *
  * @return Bengine_Game_MessageFolder_User
  */
 protected function _format(Bengine_Game_Model_Message $message)
 {
     $sender = $message->get("sender");
     if (!empty($sender)) {
         $url = "game/" . SID . "/MSG/Write/" . rawurlencode($message->get("username")) . "/" . Link::urlEncode("RE: " . $message->get("subject"));
         $reply = Link::get($url, Image::getImage("pm.gif", Core::getLanguage()->getItem("REPLY")));
         $message->set("reply_link", $reply);
         $sender = $message->get("username") . " " . getCoordLink($message->get("galaxy"), $message->get("system"), $message->get("position"));
     } else {
         $sender = "System";
     }
     $message->set("sender", $sender);
     $this->replaceForeignSessionId($message);
     return $this;
 }
 /**
  * @var int $user
  * @return Bengine_Game_Controller_Achievements
  */
 public function userAction($user)
 {
     Core::getLanguage()->load(array("Achievements"));
     $user = Application::getModel("game/user")->load((int) $user);
     /* @var Bengine_Game_Model_Collection_Achievement $achievements */
     $achievements = Application::getCollection("game/achievement");
     $achievements->addUserJoin($user->get("userid"), true)->addDefaultSorting();
     $this->view->addLoop("achievements", $achievements);
     $this->view->assign("user", $user);
     $this->language->assign("leftXP", $user->getLeftXPForNextLevel());
     $this->language->assign("nextLevel", $user->get("level") + 1);
     $this->language->assign("xp", $user->get("xp"));
     $this->language->assign("level", $user->get("level"));
     $this->language->assign("achievementUser", Link::get("game/" . SID . "/Profile/Page/" . $user->get("userid"), $user->get("username")));
 }
Exemple #12
0
 /**
  * Index page
  *
  * @return Bengine_Admin_Controller_Cms
  */
 protected function indexAction()
 {
     if ($this->getParam("update_pages")) {
         $this->updatePagesAction($this->getParam("delete"), $this->getParam("pages"));
     }
     $pages = array();
     $result = Core::getQuery()->select("page", array("pageid", "position", "displayorder", "title"), "", "", "position DESC, displayorder ASC");
     foreach ($result->fetchAll() as $row) {
         $id = $row["pageid"];
         $pages[$id]["pageid"] = $id;
         $pages[$id]["position"] = $row["position"];
         $pages[$id]["displayorder"] = $row["displayorder"];
         $pages[$id]["title"] = $row["title"];
         $pages[$id]["edit_link"] = Link::get("admin/cms/edit/" . $id, Core::getLanguage()->getItem("Edit"));
     }
     Core::getTPL()->addLoop("pages", $pages);
     return $this;
 }
 /**
  * @return Bengine_Admin_Controller_Commercial
  */
 protected function indexAction()
 {
     if ($this->isPost()) {
         if ($this->getParam("add_ad")) {
             $this->addAd($this->getParam("name"), $this->getParam("position"), $this->getParam("max_views"), $this->getParam("enabled", 0), $this->getParam("html_code"));
         } else {
             if ($this->getParam("delete")) {
                 $this->delete($this->getParam("ads"));
             }
         }
     }
     $ads = array();
     $result = Core::getQuery()->select("ad", array("*"));
     foreach ($result->fetchAll() as $row) {
         $row["edit_link"] = Link::get("admin/commercial/edit/" . $row["ad_id"], Core::getLang()->get("Edit"));
         $row["reset_link"] = Link::get("admin/commercial/reset/" . $row["ad_id"], "Reset");
         $ads[] = $row;
     }
     Core::getTPL()->addLoop("ads", $ads);
     return $this;
 }
 /**
  * @return Bengine_Admin_Controller_Usergroups
  */
 protected function indexAction()
 {
     if ($this->getParam("delete_usergroups")) {
         $this->delete($this->getParam("delete"));
     } else {
         if ($this->getParam("add_usergroup")) {
             $this->add($this->getParam("grouptitle"), $this->getParam("permissions"));
         }
     }
     $groups = array();
     $result = Core::getQuery()->select("usergroup", array("usergroupid", "grouptitle", "standard"), "ORDER BY grouptitle ASC");
     foreach ($result->fetchAll() as $row) {
         $id = $row["usergroupid"];
         $groups[$id]["usergroupid"] = $id;
         $groups[$id]["grouptitle"] = $row["grouptitle"];
         $groups[$id]["edit"] = Link::get("admin/usergroups/edit/" . $id, Core::getLanguage()->getItem("Edit"));
         $groups[$id]["standard"] = $row["standard"];
     }
     Core::getTPL()->addLoop("groups", $groups);
     return $this;
 }
Exemple #15
0
 /**
  * Formats the message.
  *
  * @param Bengine_Game_Model_Message $message
  *
  * @return Bengine_Game_MessageFolder_Alliance
  */
 protected function _format(Bengine_Game_Model_Message $message)
 {
     $senderName = $message->get("username");
     $sender = !empty($senderName) ? Core::getLanguage()->getItem("ALLIANCE_GLOBAL_MAIL") . " (" . $senderName . ")" : Core::getLanguage()->getItem("ALLIANCE");
     $message->set("sender", $sender);
     $this->replaceForeignSessionId($message);
     if (Core::getUser()->get("aid")) {
         $subject = "RE: " . preg_replace("#((RE|FW):\\s)+#is", "\\1", $message->get("subject"));
         $subject = rawurlencode($subject);
         $linkUrl = "game/";
         if (URL_SESSION) {
             $linkUrl .= SID . "/";
         }
         $linkUrl .= "Alliance/GlobalMail/" . $subject;
         if (!empty($senderName)) {
             $replyImg = Image::getImage("pm.gif", Core::getLanguage()->getItem("REPLY_ALLIANCE_MAIL"));
             $message->set("reply_link", Link::get($linkUrl, $replyImg));
         }
     }
     return $this;
 }
Exemple #16
0
 /**
  * Check input data.
  *
  * @return Bengine_Game_Login
  */
 public function checkData()
 {
     $this->dataChecked = true;
     $select = array("u.userid", "u.username", "p.password", "u.activation", "b.banid", "b.reason", "u.umode");
     $joins = "LEFT JOIN " . PREFIX . "password p ON (u.userid = p.userid)";
     $joins .= "LEFT JOIN " . PREFIX . "ban_u b ON (b.userid = u.userid AND b.to > '" . TIME . "')";
     $result = Core::getQuery()->select("user u", $select, $joins, Core::getDB()->quoteInto("u.username = ?", $this->usr), "b.to DESC");
     if ($row = $result->fetchRow()) {
         $result->closeCursor();
         if (Str::compare($row["username"], $this->usr) && Str::compare($row["password"], $this->pw) && Str::length($row["activation"]) == 0 && !$row["banid"]) {
             $this->userid = $row["userid"];
             Core::getQuery()->delete("loginattempts", "ip = ? OR username = ?", null, null, array(IPADDRESS, $this->usr));
             Core::getQuery()->update("sessions", array("logged" => "0"), "userid = ?", array($this->userid));
             if ($row["umode"]) {
                 Core::getQuery()->update("planet", array("last" => TIME), "userid = ?", array($row["userid"]));
             }
             $this->canLogin = true;
         } else {
             $this->canLogin = false;
             if (!Str::compare($row["username"], $this->usr)) {
                 $this->loginFailed("USERNAME_DOES_NOT_EXIST");
             }
             if (Str::length($row["activation"]) > 0) {
                 $this->loginFailed("NO_ACTIVATION");
             }
             if ($row["banid"]) {
                 Core::getLanguage()->load(array("Prefs"));
                 Core::getLanguage()->assign("banReason", empty($row["reason"]) ? Core::getLanguage()->get("NO_BAN_REASON") : $row["reason"]);
                 Core::getLanguage()->assign("pilloryLink", Link::get(Core::getLanguage()->getOpt("langcode") . "/pillory", Core::getLanguage()->get("PILLORY")));
                 $this->loginFailed("ACCOUNT_BANNED");
             }
             $this->loginFailed("PASSWORD_INVALID");
         }
     } else {
         $result->closeCursor();
         $this->canLogin = false;
         $this->loginFailed("USERNAME_DOES_NOT_EXIST");
     }
     return $this;
 }
Exemple #17
0
 /**
  * Index action.
  *
  * @return Bengine_Game_Controller_Galaxy
  */
 protected function indexAction()
 {
     if ($this->isPost()) {
         $this->setCoordinatesByPost($this->getParam("galaxy"), $this->getParam("system"), $this->getParam("submittype"));
     }
     $this->validateInputs()->subtractHydrogen();
     // Star surveillance
     $canMonitorActivity = false;
     if (Game::getPlanet()->getBuilding("STAR_SURVEILLANCE") > 0) {
         $range = pow(Game::getPlanet()->getBuilding("STAR_SURVEILLANCE"), 2) - 1;
         $diff = abs(Game::getPlanet()->getData("system") - $this->system);
         if ($this->galaxy == Game::getPlanet()->getData("galaxy") && $range >= $diff) {
             $canMonitorActivity = true;
         }
     }
     Core::getTPL()->assign("canMonitorActivity", $canMonitorActivity);
     // Images
     $rockimg = Image::getImage("rocket.gif", Core::getLanguage()->getItem("ROCKET_ATTACK"));
     // Get sunsystem data
     $select = array("g.planetid", "g.position", "g.destroyed", "g.metal", "g.silicon", "g.moonid", "p.picture", "p.planetname", "p.last as planetactivity", "u.username", "u.usertitle", "u.userid", "u.points", "u.last as useractivity", "u.umode", "u.level", "m.planetid AS moon", "m.picture AS moonpic", "m.planetname AS moonname", "m.diameter AS moonsize", "m.temperature", "m.last as moonactivity", "a.tag", "a.name", "a.showmember", "a.homepage", "a.showhomepage", "u2a.aid", "b.to");
     $joins = "LEFT JOIN " . PREFIX . "planet p ON (p.planetid = g.planetid)";
     $joins .= "LEFT JOIN " . PREFIX . "user u ON (u.userid = p.userid)";
     $joins .= "LEFT JOIN " . PREFIX . "planet m ON (m.planetid = g.moonid)";
     $joins .= "LEFT JOIN " . PREFIX . "user2ally u2a ON (u2a.userid = u.userid)";
     $joins .= "LEFT JOIN " . PREFIX . "alliance a ON (a.aid = u2a.aid)";
     $joins .= "LEFT JOIN " . PREFIX . "ban_u b ON (b.userid = u.userid AND b.to > '" . TIME . "')";
     $where = Core::getDB()->quoteInto("g.galaxy = ? AND g.system = ?", array($this->galaxy, $this->system));
     $result = Core::getQuery()->select("galaxy g", $select, $joins, $where);
     $UserList = new Bengine_Game_User_List();
     $UserList->setKey("position");
     $UserList->setNewbieProtection(true);
     $UserList->setFetchRank(true);
     $UserList->setTagAsLink(false);
     $UserList->load($result);
     $sys = $UserList->getArray();
     Hook::event("SolarSystemDataBefore", array($this, &$sys));
     for ($i = 1; $i <= 15; $i++) {
         if (isset($sys[$i]) && !$sys[$i]["destroyed"]) {
             $sys[$i]["systempos"] = $i;
             if ($sys[$i]["tag"] != "") {
                 $sys[$i]["allydesc"] = sprintf(Core::getLanguage()->getItem("GALAXY_ALLY_HEADLINE"), $sys[$i]["tag"], $sys[$i]["alliance_rank"]);
             }
             $sys[$i]["metal"] = fNumber($sys[$i]["metal"]);
             $sys[$i]["silicon"] = fNumber($sys[$i]["silicon"]);
             $sys[$i]["picture"] = Image::getImage("planets/small/s_" . $sys[$i]["picture"] . Core::getConfig()->get("PLANET_IMG_EXT"), $sys[$i]["planetname"], 30, 30);
             $sys[$i]["picture"] = Link::get("game/" . SID . "/Mission/Index/" . $this->galaxy . "/" . $this->system . "/" . $i, $sys[$i]["picture"]);
             $sys[$i]["planetname"] = Link::get("game/" . SID . "/Mission/Index/" . $this->galaxy . "/" . $this->system . "/" . $i, $sys[$i]["planetname"]);
             $sys[$i]["moonpicture"] = $sys[$i]["moonpic"] != "" ? Image::getImage("planets/small/s_" . $sys[$i]["moonpic"] . Core::getConfig()->get("PLANET_IMG_EXT"), $sys[$i]["moonname"], 22, 22) : "";
             $sys[$i]["moon"] = sprintf(Core::getLanguage()->getItem("MOON_DESC"), $sys[$i]["moonname"]);
             $sys[$i]["moonsize"] = fNumber($sys[$i]["moonsize"]);
             $sys[$i]["moontemp"] = fNumber($sys[$i]["temperature"]);
             if ($sys[$i]["moonactivity"] > $sys[$i]["planetactivity"]) {
                 $activity = $sys[$i]["moonactivity"];
             } else {
                 $activity = $sys[$i]["planetactivity"];
             }
             if ($activity > TIME - 900 && $sys[$i]["userid"] != Core::getUser()->get("userid")) {
                 $sys[$i]["activity"] = "(*)";
             } else {
                 if ($activity > TIME - 3600 && $sys[$i]["userid"] != Core::getUser()->get("userid")) {
                     $sys[$i]["activity"] = "(" . floor((TIME - $activity) / 60) . " min)";
                 } else {
                     $sys[$i]["activity"] = "";
                 }
             }
             if (Game::getPlanet()->getBuilding("ROCKET_STATION") > 3 && $sys[$i]["userid"] != Core::getUser()->get("userid") && $this->inMissileRange()) {
                 $sys[$i]["rocketattack"] = Link::get("game/" . SID . "/RocketAttack/Index/" . $sys[$i]["planetid"], $rockimg);
                 $sys[$i]["moonrocket"] = "<tr><td colspan=\"3\" class=\"center\">" . Link::get("game/" . SID . "/RocketAttack/Index/" . $sys[$i]["moonid"] . "/1", Core::getLanguage()->getItem("ROCKET_ATTACK")) . "</td></tr>";
             } else {
                 $sys[$i]["rocketattack"] = "";
                 $sys[$i]["moonrocket"] = "";
             }
             $sys[$i]["allypage"] = Str::replace("\"", "", Link::get("game/" . SID . "/Alliance/Page/" . $sys[$i]["aid"], Core::getLanguage()->getItem("ALLIANCE_PAGE"), 1));
             if (($sys[$i]["showhomepage"] || $sys[$i]["aid"] == Core::getUser()->get("aid")) && $sys[$i]["homepage"] != "") {
                 $sys[$i]["homepage"] = "<tr><td>" . Str::replace("'", "\\'", Link::get($sys[$i]["homepage"], Core::getLanguage()->getItem("HOMEPAGE"), 2)) . "</td></tr>";
             } else {
                 $sys[$i]["homepage"] = "";
             }
             if ($sys[$i]["showmember"]) {
                 $sys[$i]["memberlist"] = "<tr><td>" . Str::replace("\"", "", Link::get("game/" . SID . "/Alliance/Memberlist/" . $sys[$i]["aid"], Core::getLanguage()->getItem("SHOW_MEMBERLIST"), 3)) . "</td></tr>";
             }
             $sys[$i]["debris"] = Image::getImage("debris.jpg", "", 25, 25);
         } else {
             if (empty($sys[$i]["destroyed"])) {
                 $sys[$i] = array();
                 $sys[$i]["destroyed"] = false;
                 $sys[$i]["metal"] = 0;
                 $sys[$i]["silicon"] = 0;
                 $sys[$i]["debris"] = "";
                 $sys[$i]["picture"] = "";
                 $sys[$i]["planetname"] = "";
                 $sys[$i]["planetid"] = "";
             } else {
                 $sys[$i]["metal"] = fNumber($sys[$i]["metal"]);
                 $sys[$i]["silicon"] = fNumber($sys[$i]["silicon"]);
                 $sys[$i]["debris"] = Image::getImage("debris.jpg", "", 25, 25);
                 $sys[$i]["picture"] = Image::getImage("planets/small/s_" . $sys[$i]["picture"] . Core::getConfig()->get("PLANET_IMG_EXT"), $sys[$i]["planetname"], 30, 30);
                 $sys[$i]["picture"] = Link::get("game/" . SID . "/Mission/Index/" . $this->galaxy . "/" . $this->system . "/" . $i, $sys[$i]["picture"]);
                 $sys[$i]["planetname"] = Core::getLanguage()->getItem("DESTROYED_PLANET");
                 $sys[$i]["planetname"] = Link::get("game/" . SID . "/Mission/Index/" . $this->galaxy . "/" . $this->system . "/" . $i, $sys[$i]["planetname"]);
             }
             $sys[$i]["systempos"] = $i;
             $sys[$i]["userid"] = null;
             $sys[$i]["moon"] = "";
             $sys[$i]["moonid"] = "";
             $sys[$i]["username"] = "";
             $sys[$i]["alliance"] = "";
             $sys[$i]["activity"] = "";
             $sys[$i]["moonpicture"] = "";
             $sys[$i]["user_status_long"] = "";
         }
     }
     ksort($sys);
     Hook::event("SolarSystemDataAfter", array($this, &$sys));
     Core::getTPL()->assign("sendesp", Image::getImage("esp.gif", Core::getLanguage()->getItem("SEND_ESPIONAGE_PROBE")));
     Core::getTPL()->assign("monitorfleet", Image::getImage("binocular.gif", Core::getLanguage()->getItem("MONITOR_FLEET_ACTIVITY")));
     Core::getTPL()->assign("moon", Str::replace("\"", "", Image::getImage("planets/mond" . Core::getConfig()->get("PLANET_IMG_EXT"), Core::getLanguage()->getItem("MOON"), 75, 75)));
     Core::getTPL()->addLoop("sunsystem", $sys);
     Core::getTPL()->assign("debris", Str::replace("\"", "", Image::getImage("debris.jpg", Core::getLanguage()->getItem("DEBRIS"), 75, 75)));
     Core::getTPL()->assign("galaxy", $this->galaxy);
     Core::getTPL()->assign("system", $this->system);
     return $this;
 }
Exemple #18
0
 /**
  * Generic template assignments.
  *
  * @return void
  */
 protected static function globalTPLAssigns()
 {
     // JavaScript & CSS
     Core::getTPL()->addHTMLHeaderFile("game.css", "css");
     // TODO: change to responsive
     Core::getTPL()->addHTMLHeaderFile("jquery-ui.css", "css");
     Core::getTPL()->addHTMLHeaderFile("lib/jquery.js", "js");
     Core::getTPL()->addHTMLHeaderFile("lib/jquery-ui.js", "js");
     Core::getTPL()->addHTMLHeaderFile("main.js", "js");
     // Set planets for right menu and fill planet stack.
     $planets = array();
     $i = 0;
     $order = "p.sort_index ASC, p.planetid ASC";
     $joins = "LEFT JOIN " . PREFIX . "galaxy g ON (g.planetid = p.planetid)";
     $joins .= "LEFT JOIN " . PREFIX . "planet m ON (g.moonid = m.planetid)";
     $atts = array("p.planetid", "p.ismoon", "p.planetname", "p.picture", "g.galaxy", "g.system", "g.position", "m.planetid AS moonid", "m.planetname AS moon", "m.picture AS mpicture");
     $where = Core::getDB()->quoteInto("p.userid = ?", Core::getUser()->get("userid"));
     $where .= Core::getDB()->quoteInto(" AND p.ismoon = ?", 0);
     $result = Core::getQuery()->select("planet p", $atts, $joins, $where, $order);
     unset($order);
     foreach ($result->fetchAll() as $row) {
         $planets[$i] = $row;
         $coords = $row["galaxy"] . ":" . $row["system"] . ":" . $row["position"];
         $coords = "[" . $coords . "]";
         $planets[$i]["coords"] = $coords;
         $planets[$i]["picture"] = Image::getImage("planets/small/s_" . $row["picture"] . Core::getConfig()->get("PLANET_IMG_EXT"), $row["planetname"] . " " . $coords, 60, 60);
         if ($row["moonid"]) {
             $planets[$i]["mpicture"] = Image::getImage("planets/small/s_" . $row["mpicture"] . Core::getConfig()->get("PLANET_IMG_EXT"), $row["moon"] . " " . $coords, 20, 20);
         }
         self::$planetStack[] = $row["planetid"];
         $i++;
     }
     $result->closeCursor();
     Hook::event("GamePlanetList", array(&$planets));
     Core::getTPL()->addLoop("planetHeaderList", $planets);
     // Menu
     Core::getTPL()->addLoop("navigation", new Bengine_Game_Menu("Menu"));
     // Assignments
     $planet = self::getPlanet();
     Core::getTPL()->assign("themePath", Core::getUser()->get("theme") ? Core::getUser()->get("theme") : HTTP_HOST . REQUEST_DIR);
     Core::getTPL()->assign("planetImageSmall", Image::getImage("planets/small/s_" . $planet->getData("picture") . Core::getConfig()->get("PLANET_IMG_EXT"), $planet->getData("planetname"), 88, 88));
     Core::getTPL()->assign("currentPlanet", Link::get("game/" . SID . "/Index/PlanetOptions", $planet->getData("planetname")));
     Core::getTPL()->assign("currentCoords", $planet->getCoords());
     // Show message if user is in vacation or deletion mode.
     $delete = false;
     if (Core::getUser()->get("delete") > 0) {
         $delete = Core::getLanguage()->getItem("ACCOUNT_WILL_BE_DELETED");
     }
     $umode = false;
     if (Core::getUser()->get("umode")) {
         $umode = Core::getLanguage()->getItem("UMODE_ENABLED");
     }
     Core::getTPL()->assign("delete", $delete);
     Core::getTPL()->assign("umode", $umode);
     return;
 }
 /**
  * Shows all building information.
  *
  * @param integer $id
  * @throws Recipe_Exception_Generic
  * @return Bengine_Game_Controller_Constructions
  */
 protected function infoAction($id)
 {
     $select = array("name", "demolish", "basic_metal", "basic_silicon", "basic_hydrogen", "basic_energy", "prod_metal", "prod_silicon", "prod_hydrogen", "prod_energy", "special", "cons_metal", "cons_silicon", "cons_hydrogen", "cons_energy", "charge_metal", "charge_silicon", "charge_hydrogen", "charge_energy");
     $result = Core::getQuery()->select("construction", $select, "", Core::getDB()->quoteInto("buildingid = ? AND (mode = '1' OR mode = '2' OR mode = '5')", $id));
     if ($row = $result->fetchRow()) {
         $result->closeCursor();
         Core::getLanguage()->load("info,Resource");
         Hook::event("BuildingInfoBefore", array(&$row));
         // Assign general building data
         Core::getTPL()->assign("buildingName", Core::getLanguage()->getItem($row["name"]));
         Core::getTPL()->assign("buildingDesc", Core::getLanguage()->getItem($row["name"] . "_FULL_DESC"));
         Core::getTPL()->assign("buildingImage", Image::getImage("buildings/" . $row["name"] . ".gif", Core::getLanguage()->getItem($row["name"]), null, null, "leftImage"));
         Core::getTPL()->assign("edit", Link::get("game/" . SID . "/Construction_Edit/Index/" . $id, "[" . Core::getLanguage()->getItem("EDIT") . "]"));
         // Production and consumption of the building
         $prodFormula = false;
         if (!empty($row["prod_metal"])) {
             $prodFormula = $row["prod_metal"];
             $baseCost = $row["basic_metal"];
         } else {
             if (!empty($row["prod_silicon"])) {
                 $prodFormula = $row["prod_silicon"];
                 $baseCost = $row["basic_metal"];
             } else {
                 if (!empty($row["prod_hydrogen"])) {
                     $prodFormula = $row["prod_hydrogen"];
                     $baseCost = $row["basic_hydrogen"];
                 } else {
                     if (!empty($row["prod_energy"])) {
                         $prodFormula = $row["prod_energy"];
                         $baseCost = $row["basic_energy"];
                     } else {
                         if (!empty($row["special"])) {
                             $prodFormula = $row["special"];
                             $baseCost = 0;
                         }
                     }
                 }
             }
         }
         $consFormula = false;
         if (!empty($row["cons_metal"])) {
             $consFormula = $row["cons_metal"];
         } else {
             if (!empty($row["cons_silicon"])) {
                 $consFormula = $row["cons_silicon"];
             } else {
                 if (!empty($row["cons_hydrogen"])) {
                     $consFormula = $row["cons_hydrogen"];
                 } else {
                     if (!empty($row["cons_energy"])) {
                         $consFormula = $row["cons_energy"];
                     }
                 }
             }
         }
         // Production and consumption chart
         $chartType = false;
         if ($prodFormula != false || $consFormula != false) {
             $chart = array();
             $chartType = "cons_chart";
             if ($prodFormula && $consFormula) {
                 $chartType = "prod_and_cons_chart";
             } else {
                 if ($prodFormula) {
                     $chartType = "prod_chart";
                 }
             }
             if (Game::getPlanet()->getBuilding($id) - 7 < 0) {
                 $start = 7;
             } else {
                 $start = Game::getPlanet()->getBuilding($id);
             }
             $productionFactor = (double) Core::getConfig()->get("PRODUCTION_FACTOR");
             if (!empty($row["prod_energy"])) {
                 $productionFactor = 1;
             }
             $currentProduction = 0;
             if ($prodFormula) {
                 $currentProduction = parseFormula($prodFormula, $baseCost, Game::getPlanet()->getBuilding($id)) * $productionFactor;
             }
             $currentConsumption = 0;
             if ($consFormula) {
                 $currentConsumption = parseFormula($consFormula, 0, Game::getPlanet()->getBuilding($id));
             }
             for ($i = $start - 7; $i <= Game::getPlanet()->getBuilding($id) + 7; $i++) {
                 $chart[$i]["level"] = $i;
                 $chart[$i]["s_prod"] = $prodFormula ? parseFormula($prodFormula, $baseCost, $i) * $productionFactor : 0;
                 $chart[$i]["s_diffProd"] = $prodFormula ? $chart[$i]["s_prod"] - $currentProduction : 0;
                 $chart[$i]["s_cons"] = $consFormula ? parseFormula($consFormula, 0, $i) : 0;
                 $chart[$i]["s_diffCons"] = $consFormula ? $currentConsumption - $chart[$i]["s_cons"] : 0;
                 $chart[$i]["prod"] = fNumber($chart[$i]["s_prod"]);
                 $chart[$i]["diffProd"] = fNumber($chart[$i]["s_diffProd"]);
                 $chart[$i]["cons"] = fNumber($chart[$i]["s_cons"]);
                 $chart[$i]["diffCons"] = fNumber($chart[$i]["s_diffCons"]);
             }
             Hook::event("BuildingInfoProduction", array(&$chart));
             Core::getTPL()->addLoop("chart", $chart);
         }
         if ($chartType) {
             Core::getTPL()->assign("chartType", "game/constructions/" . $chartType);
         }
         // Show demolish function
         $factor = floatval($row["demolish"]);
         if (Game::getPlanet()->getBuilding($id) > 0 && $factor > 0.0) {
             Core::getTPL()->assign("buildingLevel", Game::getPlanet()->getBuilding($id));
             Core::getTPL()->assign("demolish", true);
             $metal = "";
             $_metal = 0;
             $silicon = "";
             $_silicon = 0;
             $hydrogen = "";
             $_hydrogen = 0;
             if ($row["basic_metal"] > 0) {
                 $_metal = 1 / $factor * parseFormula($row["charge_metal"], $row["basic_metal"], Game::getPlanet()->getBuilding($id));
                 $metal = Core::getLanguage()->getItem("METAL") . ": " . fNumber($_metal);
             }
             Core::getTPL()->assign("metal", $metal);
             if ($row["basic_silicon"] > 0) {
                 $_silicon = 1 / $factor * parseFormula($row["charge_silicon"], $row["basic_silicon"], Game::getPlanet()->getBuilding($id));
                 $silicon = Core::getLanguage()->getItem("SILICON") . ": " . fNumber($_silicon);
             }
             Core::getTPL()->assign("silicon", $silicon);
             if ($row["basic_hydrogen"] > 0) {
                 $_hydrogen = 1 / $factor * parseFormula($row["charge_hydrogen"], $row["basic_hydrogen"], Game::getPlanet()->getBuilding($id));
                 $hydrogen = Core::getLanguage()->getItem("HYDROGEN") . ": " . fNumber($_hydrogen);
             }
             Core::getTPL()->assign("hydrogen", $hydrogen);
             $time = getBuildTime($_metal, $_silicon, self::BUILDING_CONSTRUCTION_TYPE);
             Core::getTPL()->assign("dimolishTime", getTimeTerm($time));
             $showLink = Game::getPlanet()->getData("metal") >= $_metal && Game::getPlanet()->getData("silicon") >= $_silicon && Game::getPlanet()->getData("hydrogen") >= $_hydrogen;
             if ($id == 12 && Game::getEH()->getResearchEvent()) {
                 $showLink = false;
             }
             $shipyardSize = Game::getEH()->getShipyardEvents()->getCalculatedSize();
             if (($id == 8 || $id == 7) && $shipyardSize > 0) {
                 $showLink = false;
             }
             Core::getTPL()->assign("showLink", $showLink && !$this->event && !Core::getUser()->get("umode"));
             Core::getTPL()->assign("demolishNow", Link::get("game/" . SID . "/Constructions/Demolish/{$id}", Core::getLanguage()->getItem("DEMOLISH_NOW")));
         } else {
             Core::getTPL()->assign("demolish", false);
         }
         Hook::event("BuildingInfoAfter", array(&$row));
     } else {
         $result->closeCursor();
         throw new Recipe_Exception_Generic("Unkown building. You'd better don't manipulate the URL. We see everything ;)");
     }
     return $this;
 }
if ($tbs = $db->get_col("select trackback_id from trackbacks where trackback_link_id = {$link->id} and trackback_status='pendent'")) {
    foreach ($tbs as $tb_id) {
        $tb = new Trackback();
        $tb->id = $tb_id;
        if ($tb->read()) {
            $res = $tb->send($link);
        }
    }
}
// Send pingbacks for link inside the text
preg_match_all('/([\\(\\[:\\.\\s]|^)(https*:\\/\\/[^ \\t\\n\\r\\]\\(\\)\\&]{5,70}[^ \\t\\n\\r\\]\\(\\)]*[^ .\\t,\\n\\r\\(\\)\\"\'\\]\\?])/i', $link->content, $matches);
foreach ($matches[2] as $match) {
    $tb = new Trackback();
    $tb->link = clean_input_url($match);
    $tb->link_id = $link->id;
    $tb->author = $link->author;
    if (!$tb->read()) {
        $tmp = new Link();
        if (!$tmp->get($match, 2000, false)) {
            echo "couldn't get {$match}\n";
            next;
        }
        if (!$tmp->pingback()) {
            echo "couldn't get pingback {$match}\n";
            next;
        }
        $tb->link = clean_input_url($match);
        $tb->url = clean_input_url($tmp->trackback);
        $tb->send($link);
    }
}
Exemple #21
0
 /**
  * Parses an event.
  *
  * @param Bengine_Game_Model_Event $f
  *
  * @return array	Parsed event data
  */
 protected function parseEvent(Bengine_Game_Model_Event $f)
 {
     if ($f->getCode() == "game/alliedFleet" && $f->getUserid() != Core::getUser()->get("userid")) {
         return false;
         // Hide foreign formations
     }
     $event = array();
     $event["time_r"] = $f->getTimeLeft();
     $event["time"] = $f->getFormattedTimeLeft();
     $event["eventid"] = $f->getEventid();
     $event["time_finished"] = Date::timeToString(1, $f->getTime());
     $event["raw_coordinates"] = $f->getDestinationCoords(false);
     Core::getLanguage()->assign("rockets", $f->getData("rockets", 0));
     Core::getLanguage()->assign("planet", !$f->getData("oldmode") || $f->getData("oldmode") != 9 ? $f->getPlanetname() : Core::getLanguage()->getItem("DEBRIS"));
     // TODO: Old mode should be translated to code
     Core::getLanguage()->assign("coords", $f->getPlanetCoords());
     Core::getLanguage()->assign("target", $f->getCode() != "game/recycling" ? $f->getDestinationPlanetname() : Core::getLanguage()->getItem("DEBRIS"));
     Core::getLanguage()->assign("targetcoords", $f->getDestinationCoords());
     Core::getLanguage()->assign("metal", fNumber($f->getData("metal", 0)));
     Core::getLanguage()->assign("silicon", fNumber($f->getData("silicon", 0)));
     Core::getLanguage()->assign("hydrogen", fNumber($f->getData("hydrogen", 0)));
     Core::getLanguage()->assign("username", $f->getUsername());
     Core::getLanguage()->assign("message", Link::get("game/" . SID . "/MSG/Write/" . rawurlencode($f->getUsername()), Image::getImage("pm.gif", Core::getLanguage()->getItem("WRITE_MESSAGE"))));
     Core::getLanguage()->assign("mission", $f->getCode() == "game/return" ? $f->getOrgModeName() : $f->getModeName());
     Core::getLanguage()->assign("fleet", $f->getFleetString());
     $event["class"] = $f->getCssClass();
     if ($f->getCode() == "game/allianceAttack") {
         if ($f->getUserid() == Core::getUser()->get("userid")) {
             $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_OWN");
         } else {
             $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_OTHER");
         }
         $allyFleets = Game::getEH()->getFormationFleets($f->getEventid());
         foreach ($allyFleets as $af) {
             $coords = $af->getPlanetCoords();
             $msg = Core::getLanguage()->getItem("FLEET_MESSAGE_FORMATION");
             $msg = sprintf($msg, $af->getUsername(), $af->getPlanetname(), $coords, $af->getFleetString());
             $event["message"] .= $msg;
         }
     } else {
         if ($f->getCode() == "game/alliedFleet") {
             $mainFleet = Game::getModel("game/event")->load($f->getParentId());
             if ($mainFleet->getUsierid() == Core::getUser()->get("userid")) {
                 return false;
             }
             $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_OWN");
             $allyFleets = Game::getEH()->getFormationFleets($mainFleet->getEventid());
             $allyFleets->add($mainFleet);
             foreach ($allyFleets as $af) {
                 if ($af->getUserid() == Core::getUser()->get("userid")) {
                     continue;
                 }
                 $coords = $af->getPlanetCoords();
                 $msg = Core::getLanguage()->getItem("FLEET_MESSAGE_FORMATION");
                 $msg = sprintf($msg, $af->getUsername(), $af->getPlanetname(), $coords, $af->getFleetString());
                 $event["message"] .= $msg;
             }
         } else {
             if ($f->getCode() == "game/holding" && $f->getUserid() == Core::getUser()->get("userid")) {
                 $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_HOLDING_1");
             } else {
                 if ($f->getCode() == "game/holding") {
                     $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_HOLDING_2");
                 } else {
                     if ($f->getCode() == "game/return" && $f->getUserid() == Core::getUser()->get("userid")) {
                         $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_RETURN");
                     } else {
                         if ($f->getUserid() == Core::getUser()->get("userid") && $f->getCode() == "game/missileAttack") {
                             $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_ROCKET_ATTACK");
                         } else {
                             if ($f->getCode() == "game/missileAttack") {
                                 $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_ROCKET_ATTACK_FOREIGN");
                             } else {
                                 if ($f->getUserid() == Core::getUser()->get("userid")) {
                                     $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_OWN");
                                 } else {
                                     $event["message"] = Core::getLanguage()->getItem("FLEET_MESSAGE_OTHER");
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $event;
 }
 /**
  * Returns the current link object
  *
  * @return Link
  **/
 public function getLinkObject()
 {
     $requestID = Controller::curr()->request->requestVar('LinkID');
     if ($requestID == '0') {
         return;
     }
     if (!$this->linkObject) {
         $id = $this->Value() ? $this->Value() : $requestID;
         if ((int) $id) {
             $this->linkObject = Link::get()->byID($id);
         }
     }
     return $this->linkObject;
 }
Exemple #23
0
function do_submit1()
{
    global $main_smarty, $db, $dblang, $current_user, $the_template;
    $url = htmlspecialchars(sanitize($_POST['url'], 3));
    $url = str_replace('&amp;', '&', $url);
    $url = html_entity_decode($url);
    if (strpos($url, 'http') !== 0) {
        $url = "http://{$url}";
    }
    $linkres = new Link();
    $linkres->randkey = sanitize($_POST['randkey'], 3);
    if (Submit_Show_URL_Input == false) {
        $url = "http://";
        $linkres->randkey = rand(10000, 10000000);
    }
    $Submit_Show_URL_Input = Submit_Show_URL_Input;
    if ($url == "http://" || $url == "") {
        $Submit_Show_URL_Input = false;
    }
    $edit = false;
    if (is_numeric($_GET['id'])) {
        $linkres->id = $_GET['id'];
        $linkres->read(FALSE);
        $trackback = $_GET['trackback'];
    } else {
        $linkres->get($url);
        if ($_POST['title']) {
            $linkres->title = stripslashes(sanitize($_POST['title'], 4, $Story_Content_Tags_To_Allow));
        }
        if ($_POST['tags']) {
            $linkres->tags = stripslashes(sanitize($_POST['tags'], 4));
        }
        if ($_POST['description']) {
            $linkres->content = stripslashes(sanitize($_POST['description'], 4, $Story_Content_Tags_To_Allow));
        }
        if ($_POST['category']) {
            $cats = explode(',', $_POST['category']);
            foreach ($cats as $cat) {
                if ($cat_id = $db->get_var("SELECT category_id FROM " . table_categories . " WHERE category_name='" . $db->escape(trim($cat)) . "'")) {
                    $linkres->category = $cat_id;
                    break;
                }
            }
        }
        $trackback = $linkres->trackback;
    }
    $main_smarty->assign('randkey', $linkres->randkey);
    $main_smarty->assign('submit_url', $url);
    $data = parse_url($url);
    $main_smarty->assign('url', $url);
    $main_smarty->assign('url_short', 'http://' . $data['host']);
    $main_smarty->assign('Submit_Show_URL_Input', $Submit_Show_URL_Input);
    $main_smarty->assign('Submit_Require_A_URL', Submit_Require_A_URL);
    // check if URL is valid format
    $pattern = '/^(([\\w]+:)?\\/\\/)?(([\\d\\w]|%[a-fA-f\\d]{2,2})+(:([\\d\\w]|%[a-fA-f\\d]{2,2})+)?@)?([\\d\\w]([-\\d\\w]{0,253}[\\d\\w])?\\.)+[\\w]{2,4}(:[\\d]+)?(\\/([-+_~.,\\d\\w]|%[a-fA-f\\d]{2,2})*)*(\\?(&?([-+_~.,\\d\\w]|%[a-fA-f\\d]{2,2})=?)*)?(#([-+_~.,\\/\\d\\w]|%[a-fA-f\\d]{2,2})*)?$/';
    #	$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?([\d\w]([-\d\w]{0,253}[\d\w])?\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.,\d\w]|%[a-fA-f\d]{2,2})*)*(\??(&?([-+_~.,\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.,\/\d\w]|%[a-fA-f\d]{2,2})*)?$/';
    #	$pattern = '/^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)?(\d\w?)+[\w]{2,4}(:[\d]+)?(([\/#!+-~.,\d\w]+|%[a-fA-f\d]{2,2}))(\??(&?([-+~.,\d\w]|%[a-fA-f\d]{2,2})=?))?(#([-+_~.,\/\d\w]|%[a-fA-f\d]{2,2}))?$/';
    $isLink = preg_match($pattern, $url);
    // Returns true if a link
    if ($url == "http://" || $url == "") {
        if (Submit_Require_A_URL == false) {
            $linkres->valid = true;
        } else {
            $linkres->valid = false;
        }
        $linkres->url_title = "";
    } elseif ($isLink == false) {
        $linkres->valid = false;
    }
    $vars = array("url" => $url, 'linkres' => $linkres);
    check_actions('submit_validating_url', $vars);
    $linkres = $vars['linkres'];
    if (!$linkres->valid) {
        $main_smarty->assign('submit_error', 'invalidurl');
        $main_smarty->assign('tpl_center', $the_template . '/submit_errors_center');
        $main_smarty->display($the_template . '/pligg.tpl');
        return;
    }
    if (Submit_Require_A_URL == true || $url != "http://" && $url != "") {
        if (!is_numeric($_GET['id']) && $linkres->duplicates($url) > 0) {
            $main_smarty->assign('submit_search', getmyurl("search_url", htmlentities($url)));
            $main_smarty->assign('submit_error', 'dupeurl');
            $main_smarty->assign('tpl_center', $the_template . '/submit_errors_center');
            define('pagename', 'submit');
            $main_smarty->assign('pagename', pagename);
            $main_smarty->display($the_template . '/pligg.tpl');
            return;
        }
    }
    $vars = array("url" => $url);
    check_actions('submit_validating_url', $vars);
    totals_adjust_count('discard', 1);
    //echo 'id'.$current_user->user_id;
    $linkres->status = 'discard';
    $linkres->author = $current_user->user_id;
    $linkres->store();
    $main_smarty->assign('StorySummary_ContentTruncate', StorySummary_ContentTruncate);
    $main_smarty->assign('SubmitSummary_Allow_Edit', SubmitSummary_Allow_Edit);
    $main_smarty->assign('enable_tags', Enable_Tags);
    $main_smarty->assign('submit_url_title', str_replace('"', "&#034;", $linkres->url_title));
    $main_smarty->assign('submit_url_description', $linkres->url_description);
    $main_smarty->assign('submit_id', $linkres->id);
    $main_smarty->assign('submit_type', $linkres->type());
    if (isset($link_title)) {
        $main_smarty->assign('submit_title', str_replace('"', "&#034;", $link_title));
    }
    if (isset($link_content)) {
        $main_smarty->assign('submit_content', $link_content);
    }
    $main_smarty->assign('submit_trackback', $trackback);
    $main_smarty->assign('submit_link_field1', $linkres->link_field1);
    $main_smarty->assign('submit_link_field2', $linkres->link_field2);
    $main_smarty->assign('submit_link_field3', $linkres->link_field3);
    $main_smarty->assign('submit_link_field4', $linkres->link_field4);
    $main_smarty->assign('submit_link_field5', $linkres->link_field5);
    $main_smarty->assign('submit_link_field6', $linkres->link_field6);
    $main_smarty->assign('submit_link_field7', $linkres->link_field7);
    $main_smarty->assign('submit_link_field8', $linkres->link_field8);
    $main_smarty->assign('submit_link_field9', $linkres->link_field9);
    $main_smarty->assign('submit_link_field10', $linkres->link_field10);
    $main_smarty->assign('submit_link_field11', $linkres->link_field11);
    $main_smarty->assign('submit_link_field12', $linkres->link_field12);
    $main_smarty->assign('submit_link_field13', $linkres->link_field13);
    $main_smarty->assign('submit_link_field14', $linkres->link_field14);
    $main_smarty->assign('submit_link_field15', $linkres->link_field15);
    $main_smarty->assign('submit_link_group_id', $linkres->link_group_id);
    //	$main_smarty->assign('submit_id', $_GET['id']);
    $main_smarty->assign('submit_title', str_replace('"', "&#034;", $linkres->title));
    $main_smarty->assign('submit_content', str_replace("<br />", "\n", $linkres->content));
    $main_smarty->assign('storylen', utf8_strlen(str_replace("<br />", "\n", $linkres->content)));
    $main_smarty->assign('submit_summary', $linkres->link_summary);
    $main_smarty->assign('submit_group', $linkres->link_group_id);
    $main_smarty->assign('submit_category', $linkres->category);
    $main_smarty->assign('submit_additional_cats', $linkres->additional_cats);
    $main_smarty->assign('tags_words', $linkres->tags);
    include_once mnminclude . 'dbtree.php';
    $array = tree_to_array(0, table_categories, FALSE);
    $array = array_values(array_filter($array, "allowToAuthorCat"));
    $main_smarty->assign('submit_lastspacer', 0);
    $main_smarty->assign('submit_cat_array', $array);
    /*include_once(mnminclude.'group.php');
    	$group_arr=array();
    	$group_arr = get_groupdetail_user();
    	//echo "group".print_r($group_arr);
    	$main_smarty->assign('submit_group_array', get_groupdetail_user());*/
    //to display group drop down
    if (enable_group == "true") {
        $output = '';
        $group_membered = $db->get_results("SELECT group_id,group_name FROM " . table_groups . " \n\t\t\tLEFT JOIN " . table_group_member . " ON member_group_id=group_id\n\t\t\tWHERE member_user_id = {$current_user->user_id} AND group_status = 'Enable' \n\t\t\t\tAND member_status='active'\n\t\t\t\tAND (member_role != 'banned' && member_role != 'flagged') \n\t\t\tORDER BY group_name ASC");
        if ($group_membered) {
            $output .= "<select name='link_group_id' tabindex='3' class='form-control submit_group_select'>";
            $output .= "<option value = ''>" . $main_smarty->get_config_vars('PLIGG_Visual_Group_Select_Group') . "</option>";
            foreach ($group_membered as $results) {
                $output .= "<option value = " . $results->group_id . ($linkres->link_group_id ? ' selected' : '') . ">" . $results->group_name . "</option>";
            }
            $output .= "</select>";
        }
        $main_smarty->assign('output', $output);
    }
    if ($current_user->authenticated != TRUE) {
        $vars = '';
        check_actions('register_showform', $vars);
    }
    $main_smarty->assign('tpl_extra_fields', $the_template . '/submit_extra_fields');
    $main_smarty->assign('tpl_center', $the_template . '/submit_step_2_center');
    define('pagename', 'submit');
    $main_smarty->assign('pagename', pagename);
    $vars = '';
    check_actions('do_submit1', $vars);
    $_SESSION['step'] = 1;
    $main_smarty->display($the_template . '/pligg.tpl');
}
function do_submit1()
{
    global $main_smarty, $db, $dblang, $current_user, $the_template;
    $linkres = new Link();
    $linkres->randkey = sanitize($_POST['randkey'], 3);
    $edit = false;
    if (is_numeric($_GET['id'])) {
        $linkres->id = $_GET['id'];
        $trackback = $_GET['trackback'];
    } else {
        if ($_FILES['wrapper']['error'] > 0) {
            $main_smarty->assign('submit_error', 'wrongtype');
            $main_smarty->assign('tpl_center', $the_template . '/submit_errors');
            $main_smarty->display($the_template . '/pligg.tpl');
            return;
        }
        $error = $linkres->get($_FILES['wrapper']);
        if ($error) {
            $main_smarty->assign('submit_error', $error);
            $main_smarty->assign('tpl_center', $the_template . '/submit_errors');
            $main_smarty->display($the_template . '/pligg.tpl');
            return;
        }
        $fname = $_FILES["wrapper"]["name"];
        $sname = explode('.', $fname);
        $linkres->title = $sname[0];
        $author = $current_user->user_id;
        $datetime = date("Y-m-d H:i:s", mktime(date('H'), date('i'), date('s'), date('m'), date('d'), date('Y')));
        $_SESSION['EntryDate'] = $datetime;
        $sql = "INSERT INTO " . table_prefix . "sourceinfo (UserId, EntryDate, Status) VALUES ('{$author}','{$datetime}','discard');";
        //$sql="INSERT INTO ".table_prefix."links (link_author, link_date, link_status) VALUES ('$author','$datetime','discard');" ;
        $rs = $db->query($sql);
        if ($rs) {
            //get sid returned from insert
            $newSid = mysql_insert_id();
        }
        $newSid = mysql_insert_id();
        $_SESSION['newSid'] = $newSid;
        $linkres->newSid = $newSid;
        $target_path = "temp/";
        //echo $target_path;
        $target_path = $target_path . "{$newSid}.ktr";
        move_uploaded_file($_FILES['wrapper']['tmp_name'], $target_path);
        //echo $_FILES['wrapper']['tmp_name'];
        $current_timestamp = $datetime;
        $sql = 'INSERT INTO ' . table_prefix . 'executeinfo (Sid ,Userid ,TimeStart)VALUES (' . $newSid . ' , ' . $author . ',CURRENT_TIMESTAMP);';
        //print($sql);
        $rs = $db->query($sql);
        if ($rs) {
            //get eid returned from the insert
            $logID = mysql_insert_id();
            //print $logID;
        } else {
            //print (mysql_error());
            //rollback();
            $main_smarty->assign('mysql_error', mysql_error());
            $main_smarty->assign('submit_error', 'mysql_error');
            $main_smarty->assign('tpl_center', $the_template . '/submit_errors');
            $main_smarty->display($the_template . '/pligg.tpl');
            return;
        }
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $locationOfPan = realpath(dirname(__FILE__)) . '\\kettle-data-integration\\Pan_WHDV.bat';
            $command = 'cmd.exe /C ' . $locationOfPan . ' /file:"' . realpath(dirname(__FILE__)) . '\\' . $target_path . '" ' . '"-param:Sid=' . $newSid . '"' . ' "-param:Eid=' . $logID . '"';
        } else {
            $locationOfPan = realpath(dirname(__FILE__)) . '/kettle-data-integration/pan.sh';
            $command = 'sh ' . $locationOfPan . ' -file="' . realpath(dirname(__FILE__)) . '/' . $target_path . '" ' . '-param:Sid=' . $newSid . ' -param:Eid=' . $logID;
        }
        $ret = exec($command, $outA, $returnVar);
        if (strpos($ret, 'ended successfully') === false) {
            $num = 0;
            $sql = "UPDATE " . table_prefix . "executeinfo SET ExitStatus=0, ErrorMessage='" . mysql_real_escape_string(implode("\n", $outA)) . "', RecordsProcessed='" . $num . "', TimeEnd=CURRENT_TIMESTAMP WHERE EID=" . $logID;
            $rs = $db->query($sql);
            if (!$rs) {
                print mysql_error();
                //rollback();
                die;
            }
            //echo 'Dataset cannot be immigrated at this time.<br />';
            $error = implode("<br />", $outA);
            //print($error);
            $errora = array();
            $errorb = array();
            $re1 = '(at)';
            $re2 = '( )';
            for ($i = 0; $i < count($outA); $i++) {
                if (strstr($outA[$i], 'ERROR') != FALSE) {
                    break;
                }
            }
            $n = $i;
            for ($j = $n + 1; $j < count($outA); $j++) {
                if ($c = preg_match_all("/" . $re1 . $re2 . '/is', $outA[$j], $matches)) {
                    break;
                }
            }
            for ($i; $i < $j; $i++) {
                array_push($errora, $outA[$i]);
            }
            for ($o = 0; $o < count($outA); $o++) {
                if ($c = preg_match_all("/" . $re1 . $re2 . '/is', $outA[$o], $matches)) {
                    array_push($errorb, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $outA[$o]);
                }
            }
            $main_smarty->assign('mysql_error', implode("<br />", $errora));
            $main_smarty->assign('mysql_errordetail', implode("<br />", $errorb));
            $main_smarty->assign('submit_error', 'wrongktr');
            $main_smarty->assign('tpl_center', $the_template . '/submit_errors');
            $main_smarty->display($the_template . '/pligg.tpl');
            return;
            die;
        } else {
            //TODO parse msg to get num inserted
            $lastLine = $outA[count($outA) - 1];
            preg_match("/d+\\s{1}[0-9]+\\s{1}l+/", $lastLine, $matches);
            $m = explode(' ', $matches[0]);
            $numProcessed = $m[1];
            $sql = "UPDATE " . table_prefix . "executeinfo SET ExitStatus=1, RecordsProcessed='" . $numProcessed . "', TimeEnd=CURRENT_TIMESTAMP WHERE EID=" . $logID;
            //print($sql);
            $rs = $db->query($sql);
            if (!$rs) {
                print mysql_error();
                //rollback();
                die;
            }
            $main_smarty->assign('randkey', $linkres->randkey);
            //$main_smarty->assign('submit_url', $url);
            //$data = parse_url($url);
            //$main_smarty->assign('url', $url);
            //$main_smarty->assign('url_short', 'http://'.$data['host']);
            //$main_smarty->assign('Submit_Show_URL_Input', $Submit_Show_URL_Input);
            //$main_smarty->assign('Submit_Require_A_URL', Submit_Require_A_URL);
            $linkres->author = $current_user->user_id;
            $main_smarty->assign('StorySummary_ContentTruncate', StorySummary_ContentTruncate);
            $main_smarty->assign('SubmitSummary_Allow_Edit', SubmitSummary_Allow_Edit);
            $main_smarty->assign('enable_tags', Enable_Tags);
            $main_smarty->assign('submit_url_title', str_replace('"', "&#034;", $linkres->url_title));
            $main_smarty->assign('submit_url_description', $linkres->url_description);
            $main_smarty->assign('submit_id', $linkres->id);
            if (isset($link_title)) {
                $main_smarty->assign('submit_title', str_replace('"', "&#034;", $link_title));
            }
            if (isset($link_content)) {
                $main_smarty->assign('submit_content', $link_content);
            }
            $main_smarty->assign('submit_trackback', $trackback);
            $main_smarty->assign('submit_link_group_id', $linkres->link_group_id);
            //	$main_smarty->assign('submit_id', $_GET['id']);
            $main_smarty->assign('submit_title', str_replace('"', "&#034;", $linkres->title));
            $main_smarty->assign('submit_content', str_replace("<br />", "\n", $linkres->content));
            $main_smarty->assign('storylen', utf8_strlen(str_replace("<br />", "\n", $linkres->content)));
            $main_smarty->assign('submit_summary', $linkres->link_summary);
            $main_smarty->assign('submit_group', $linkres->link_group_id);
            $main_smarty->assign('submit_category', $linkres->category);
            $main_smarty->assign('submit_additional_cats', $linkres->additional_cats);
            $main_smarty->assign('tags_words', $linkres->tags);
            include_once mnminclude . 'dbtree.php';
            $array = tree_to_array(0, table_categories, FALSE);
            $array = array_values(array_filter($array, "allowToAuthorCat"));
            $main_smarty->assign('submit_lastspacer', 0);
            $main_smarty->assign('submit_cat_array', $array);
        }
    }
    //to display group drop down
    if (enable_group == "true") {
        $output = '';
        $group_membered = $db->get_results("SELECT group_id,group_name FROM " . table_groups . "\r\n\t\t\t\tLEFT JOIN " . table_group_member . " ON member_group_id=group_id\r\n\t\t\t\tWHERE member_user_id = {$current_user->user_id} AND group_status = 'Enable' AND member_status='active'\r\n\t\t\t\tORDER BY group_name ASC");
        if ($group_membered) {
            $output .= "<select name='link_group_id'>";
            $output .= "<option value = ''>" . $main_smarty->get_config_vars('PLIGG_Visual_Group_Select_Group') . "</option>";
            foreach ($group_membered as $results) {
                $output .= "<option value = " . $results->group_id . ($linkres->link_group_id ? ' selected' : '') . ">" . $results->group_name . "</option>";
            }
            $output .= "</select>";
        }
        $main_smarty->assign('output', $output);
    }
    if ($current_user->authenticated != TRUE) {
        $vars = '';
        check_actions('register_showform', $vars);
    }
    $main_smarty->assign('Spell_Checker', Spell_Checker);
    $main_smarty->assign('tpl_extra_fields', $the_template . '/submit_extra_fields');
    $main_smarty->assign('tpl_center', $the_template . '/submit_step_2');
    define('pagename', 'submit');
    $main_smarty->assign('pagename', pagename);
    $vars = '';
    check_actions('do_submit1', $vars);
    $_SESSION['step'] = 1;
    $main_smarty->display($the_template . '/pligg.tpl');
}
Exemple #25
0
function do_submit1()
{
    global $db, $dblang, $current_user, $globals;
    do_navbar(_('enviar noticia ') . '&#187;' . _(' paso 2: detalles'));
    echo '<div id="genericform-contents">' . "\n";
    if ($globals['min_karma_for_links'] > 0 && $current_user->user_karma < $globals['min_karma_for_links']) {
        echo '<p class="error"><strong>' . _('no tienes el mínimo de karma para enviar una nueva historia') . '</strong></p> ';
        echo '<br style="clear: both;" />' . "\n";
        echo '</div>' . "\n";
        return;
    }
    // avoid spams, an extra security check
    $from = time() - 7200;
    $same_user = $db->get_var("select count(*) from links where link_date > from_unixtime({$from}) and link_author={$current_user->user_id}");
    $same_ip = $db->get_var("select count(*) from links, votes where link_date > from_unixtime({$from}) and vote_type='links' and vote_link_id = link_id and vote_user_id = link_author and vote_ip_int = " . $globals['user_ip_int']);
    echo "<!-- Same user: {$same_user} -->\n";
    echo "<!-- Same IP: {$same_ip} -->\n";
    if ($same_user > 4 || $same_ip > 4) {
        echo '<p class="error"><strong>' . _('debes esperar, ya se enviaron varias con el mismo usuario o dirección IP') . '</strong></p>';
        echo '<br style="clear: both;" />' . "\n";
        echo '</div>' . "\n";
        return;
    }
    $url = clean_input_url($_POST['url']);
    $linkres = new Link();
    $edit = false;
    if ($found = $linkres->duplicates($url)) {
        echo '<p class="error"><strong>' . _('noticia repetida!') . '</strong></p> ';
        echo '<p class="error-text">' . _('lo sentimos') . '</p>';
        echo '<p class="error-text"><a href="' . $globals['base_url'] . '?search=' . htmlspecialchars($found) . '">' . _('haz clic aquí para votar o comentar la noticia que enviaron antes') . '</a>';
        echo '<br style="clear: both;" /><br style="clear: both;" />' . "\n";
        echo '<form id="genericform">';
        echo '<input class="genericsubmit" type=button onclick="window.history.go(-1)" value="' . _('&#171; retroceder') . '" />';
        echo '</form>' . "\n";
        echo '</div>' . "\n";
        return;
    }
    if (!$linkres->get($url)) {
        echo '<p class="error"><strong>' . _('URL inválido') . ':</strong> ' . htmlspecialchars($url) . '</p>';
        echo '<p>' . _('URL inválido, incompleto o no permitido') . '</p>';
        // If the domain is banned, decrease user's karma
        if ($linkres->banned) {
            $db->query("update users set user_karma = user_karma - 0.1 where user_id = {$current_user->user_id}");
        }
        print_empty_submit_form();
        echo '</div>' . "\n";
        return;
    }
    $trackback = $linkres->trackback;
    $linkres->randkey = intval($_POST['randkey']);
    if (!$linkres->valid) {
        echo '<p class="error"><strong>' . _('error leyendo el url') . ':</strong> ' . htmlspecialchars($url) . '</p>';
        // Dont allow new users with low karma to post wrong URLs
        if ($current_user->user_karma < 7 && $current_user->user_level == 'normal') {
            echo '<p>' . _('URL inválido, incompleto o no permitido') . '</p>';
            print_empty_submit_form();
            return;
        }
        echo '<p>' . _('no es válido, está fuera de línea, o tiene mecanismos antibots, <strong>continúa</strong>, pero asegúrate que sea correcto') . '</p>';
    }
    // check that the user also votes, not only sends links
    if ($current_user->user_karma < 7) {
        $from = time() - 3600 * 24;
        $user_votes = $db->get_var("select count(*) from votes where vote_type='links' and vote_date > from_unixtime({$from}) and vote_user_id={$current_user->user_id}");
        $user_links = 1 + $db->get_var("select count(*) from links where link_author={$current_user->user_id} and link_date > from_unixtime({$from}) and link_status != 'discard'");
        $total_links = $db->get_var("select count(*) from links where  link_date > from_unixtime({$from}) and link_status = 'queued'");
        $min_votes = min(4, intval($total_links / 20)) * $user_links;
        if ($user_votes < $min_votes) {
            $needed = $min_votes - $user_votes;
            echo '<p class="error"><strong>' . _('no tienes el mínimo de votos necesarios para enviar una nueva historia') . '</strong></p> ';
            echo '<p class="error-text">' . _('necesitas votar como mínimo a') . " {$needed} " . _('noticias') . ', ';
            echo '<a href="' . $globals['base_url'] . 'shakeit.php" target="_blank">' . _('haz clic aquí para ir a votar') . '</a></p>';
            echo '<br style="clear: both;" />' . "\n";
            echo '</div>' . "\n";
            return;
        }
    }
    $linkres->status = 'discard';
    $linkres->author = $current_user->user_id;
    /***** Currently commented out until we find if it makes sense here
    	// First delete last drafts, just in case to avoid triggering the anti spam measure
    	$from = time() - 1800;
    	$db->query("delete from links where link_date > from_unixtime($from) and link_author=$current_user->user_id and link_status='discard' and link_votes = 0");
    	*****/
    $linkres->create_blog_entry();
    // avoid auto-promotion (autobombo)
    $hours = 2;
    $from = time() - 3600 * $hours;
    $same_blog = $db->get_var("select count(*) from links where link_date > from_unixtime({$from}) and link_author={$current_user->user_id} and link_blog={$linkres->blog} and link_votes > 0");
    if ($same_blog > 0 && $current_user->user_karma < 12) {
        echo '<p class="error"><strong>' . _('ya has enviado un enlace al mismo sitio hace poco tiempo') . '</strong></p> ';
        echo '<p class="error-text">' . _('debes esperar') . " {$hours} " . _(' horas entre cada envío al mismo sitio. Es para evitar "spams" y "autobombo"') . ', ';
        echo '<a href="' . $globals['base_url'] . 'faq-' . $dblang . '.php">' . _('lee el FAQ') . '</a></p>';
        echo '<br style="clear: both;" />' . "\n";
        echo '</div>' . "\n";
        return;
    }
    // Now stores new draft
    $linkres->store();
    echo '<h2>' . _('envío de una nueva noticia: paso 2 de 3') . '</h2>' . "\n";
    echo '<div id="genericform">' . "\n";
    echo '<form action="submit.php" method="post" id="thisform" name="thisform">' . "\n";
    echo '<input type="hidden" name="url" id="url" value="' . htmlspecialchars($linkres->url) . '" />' . "\n";
    echo '<input type="hidden" name="phase" value="2" />' . "\n";
    echo '<input type="hidden" name="randkey" value="' . intval($_POST['randkey']) . '" />' . "\n";
    echo '<input type="hidden" name="id" value="' . $linkres->id . '" />' . "\n";
    echo '<fieldset><legend><span class="sign">' . _('info de la noticia') . '</span></legend>' . "\n";
    echo '<p class="genericformtxt"><label for="url_title" accesskey="1">' . _('título de la página') . ': </label> ' . "\n";
    echo $linkres->url_title;
    if ($linkres->type() === 'blog') {
        echo '<br /> (' . _('parece ser un blog') . ')</p>' . "\n";
    } else {
        echo "</p>\n";
    }
    echo '</fieldset>' . "\n";
    echo '<fieldset><legend><span class="sign">' . _('detalles de la noticia') . '</span></legend>' . "\n";
    echo '<label for="title" accesskey="2">' . _('título de la noticia') . ':</label>' . "\n";
    echo '<p><span class="genericformnote">' . _('título de la noticia. máximo: 120 caracteres') . '</span>' . "\n";
    echo '<br/><input type="text" id="title" name="title" value="' . $link_title . '" size="80" maxlength="120" /></p>' . "\n";
    echo '<label for="tags" accesskey="4">' . _('etiquetas') . ':</label>' . "\n";
    echo '<p><span class="genericformnote"><strong>' . _('pocas palabras, genéricas, cortas y separadas por "," (coma)') . '</strong> Ejemplo: <em>web, programación, software libre</em></span>' . "\n";
    echo '<br/><input type="text" id="tags" name="tags" value="' . $link_tags . '" size="70" maxlength="70" /></p>' . "\n";
    echo '<div style="float: right;">';
    print_simpleformat_buttons('bodytext');
    echo '</div>';
    echo '<p><label for="bodytext" accesskey="3">' . _('descripción de la noticia') . ':</label>' . "\n";
    echo '<br /><span class="genericformnote">' . _('describe la noticia con tus palabras. entre dos y cinco frases es suficiente. sé cuidadoso.') . '</span>' . "\n";
    echo '<br /><textarea name="bodytext"  rows="10" cols="60" id="bodytext" onKeyDown="textCounter(document.thisform.bodytext,document.thisform.bodycounter,550)" onKeyUp="textCounter(document.thisform.bodytext,document.thisform.bodycounter,550)"></textarea>' . "\n";
    echo '<br /><input readonly type="text" name="bodycounter" size="3" maxlength="3" value="550" /> <span class="genericformnote">' . _('caracteres libres') . '</span>';
    echo '</p>' . "\n";
    echo '<p><label accesskey="5">' . _('categoría') . ':</label><br />' . "\n";
    echo '<span class="genericformnote">' . _('selecciona la categoría más apropiada') . '</span></p>' . "\n";
    echo '<div class="column-list">' . "\n";
    echo '<div class="categorylist">' . "\n";
    echo '<ul>' . "\n";
    $categories = $db->get_results("SELECT category_id, category_name FROM categories WHERE category_lang='{$dblang}' ORDER BY category_name ASC");
    foreach ($categories as $category) {
        echo '<li><input name="category" type="radio" value="' . $category->category_id . '"/>' . _($category->category_name) . '</li>' . "\n";
    }
    // TODO: no standard
    echo '<br style="clear: both;" />' . "\n";
    echo '</ul></div></div>' . "\n";
    echo '<p><label for="trackback">' . _('trackback') . ':</label><br />' . "\n";
    echo '<span class="genericformnote">' . _('puedes agregar o cambiar el trackback si ha sido detectado automáticamente') . '</span>' . "\n";
    echo '<input type="text" name="trackback" id="trackback" value="' . $trackback . '" class="form-full" /></p>' . "\n";
    echo '<input class="genericsubmit" type="button" onclick="window.history.go(-1)" value="' . _('&#171; retroceder') . '" />&nbsp;&nbsp;' . "\n";
    echo '<input class="genericsubmit" type="submit" value="' . _('continuar &#187;') . '" />' . "\n";
    echo '</fieldset>' . "\n";
    echo '</form>' . "\n";
    echo '</div>' . "\n";
    echo '</div>' . "\n";
}
Exemple #26
0
 /**
  * @param integer $langid
  * @param integer $groupid
  * @return Bengine_Admin_Controller_Language
  */
 protected function showfromgroupAction($langid, $groupid)
 {
     if ($this->getParam("save_phrases")) {
         $this->savePhrases($this->getParam("phraseid"));
     }
     $langs = array();
     $result = Core::getQuery()->select("languages", array("languageid", "title"), "ORDER BY title ASC");
     foreach ($result->fetchAll() as $row) {
         $id = $row["languageid"];
         $langs[$id]["title"] = $row["title"];
     }
     $groups = array();
     $result = Core::getQuery()->select("phrasesgroups", array("phrasegroupid", "title"), "ORDER BY title ASC");
     foreach ($result->fetchAll() as $row) {
         $id = $row["phrasegroupid"];
         $groups[$id]["title"] = $row["title"];
     }
     $phrases = array();
     $where = Core::getDB()->quoteInto("p.languageid = ? AND p.phrasegroupid = ?", array($langid, $groupid));
     $result = Core::getQuery()->select("phrases p", array("p.phraseid", "p.languageid", "p.phrasegroupid", "p.title", "p.content"), "", $where);
     foreach ($result->fetchAll() as $row) {
         $id = $row["phraseid"];
         $phrases[$id]["phraseid"] = $id;
         $phrases[$id]["title"] = $row["title"];
         $phrases[$id]["content"] = $row["content"];
         $phrases[$id]["delete"] = Link::get("admin/language/deletephrase/" . $langid . "/" . $groupid . "/" . $id . "/", Core::getLanguage()->getItem("Delete"));
         $phrases[$id]["lang"] = "";
         foreach ($langs as $key => $value) {
             $phrases[$id]["lang"] .= createOption($key, $value["title"], $key == $row["languageid"] ? 1 : 0);
         }
         $phrases[$id]["groups"] = "";
         foreach ($groups as $key => $value) {
             $phrases[$id]["groups"] .= createOption($key, $value["title"], $key == $row["phrasegroupid"] ? 1 : 0);
         }
     }
     Core::getTPL()->addLoop("vars", $phrases);
     return $this;
 }
Exemple #27
0
 /**
  * Shows the candidates and their application.
  *
  * @return Bengine_Game_Controller_Alliance
  */
 protected function showCandidatesAction()
 {
     if ($this->isPost()) {
         $this->manageCadidates($this->getParam("receipt"), $this->getParam("refuse"), $this->getParam("users"));
     }
     if ($this->getRights(array("CAN_SEE_APPLICATIONS"))) {
         $apps = array();
         $result = Core::getQuery()->select("allyapplication a", array("a.userid", "a.date", "a.application ", "u.username", "u.points", "g.galaxy", "g.system", "g.position"), "LEFT JOIN " . PREFIX . "user u ON (u.userid = a.userid) LEFT JOIN " . PREFIX . "galaxy g ON (g.planetid = u.hp)", Core::getDB()->quoteInto("a.aid = ?", $this->aid), "u.username ASC, a.date ASC");
         foreach ($result->fetchAll() as $row) {
             $apps[$row["userid"]]["date"] = Date::timeToString(1, $row["date"]);
             $apps[$row["userid"]]["message"] = Link::get("game/" . SID . "/MSG/Write/" . $row["username"], Image::getImage("pm.gif", Core::getLanguage()->getItem("WRITE_MESSAGE")));
             $apps[$row["userid"]]["apptext"] = nl2br($row["application"]);
             $apps[$row["userid"]]["userid"] = $row["userid"];
             $apps[$row["userid"]]["username"] = $row["username"];
             $apps[$row["userid"]]["points"] = fNumber(floor($row["points"]));
             $apps[$row["userid"]]["position"] = getCoordLink($row["galaxy"], $row["system"], $row["position"]);
         }
         Core::getTPL()->assign("candidates", sprintf(Core::getLanguage()->getItem("CANDIDATES"), $result->rowCount()));
         $result->closeCursor();
         Hook::event("ShowAllianceCandidates", array(&$apps));
         Core::getTPL()->addLoop("applications", $apps);
     }
     return $this;
 }
function do_submit1() {
	global $db, $dblang, $current_user;

	do_navbar(_('enviar noticia ') . '&#187;'. _(' paso 2: detalles'));
	echo '<div id="genericform-contents">'."\n";

	// avoid spams, an extra security check
	$from = time() - 3600;
	$same_user = $db->get_var("select count(*) from links where link_date > from_unixtime($from) and link_author=$current_user->user_id");
	if ($same_user > 4) {
		echo '<p class="error"><strong>'._('debes esperar').  '</strong></p>';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}
	
	$url = trim(preg_replace('/ /', '+', $_POST['url']));
	$linkres=new Link;

	$edit = false;
	$linkres->get($url);
	$trackback=$linkres->trackback;
	$linkres->randkey = intval($_POST['randkey']);
	if(!$linkres->valid) {
		echo '<p class="error"><strong>'._('url no válido').':</strong> ('.$url.')</p>';
		echo '<p>'._('prueba con otra dirección').'</p>';
		print_empty_submit_form();
		return;
	}

	// avoid auto-promotion (autobombo)
	$hours = 4;
	$from = time() - 3600*$hours;
	$same_blog = $db->get_var("select count(*) from links where link_date > from_unixtime($from) and link_author=$current_user->user_id and link_blog=$linkres->blog and link_votes > 0");
	if ($same_blog > 0 && $current_user->user_karma < 12) {
		echo '<p class="error"><strong>'._('ya has enviado un enlace al mismo sitio hace poco tiempo').'</strong></p> ';
		echo '<p class="error-text">'._('debes esperar'). " $hours " . _(' horas entre cada envío al mismo sitio. Es para evitar "spams" y "autobombo"') . ', ';
		echo '<a href="faq-'.$dblang.'.php">'._('lee el FAQ').'</a></p>';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}
	
	// check that the user also votes, not only sends links
	if ($current_user->user_karma < 10) {
		$from = time() - 3600*24;
		$user_votes = $db->get_var("select count(*) from votes where vote_type='links' and vote_date > from_unixtime($from) and vote_user_id=$current_user->user_id");
		$user_links = 1 + $db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > from_unixtime($from) and link_status != 'discard'");
		$total_links = $db->get_var("select count(*) from links where  link_date > from_unixtime($from) and link_status = 'queued'");
		$min_votes = intval($total_links/20) * $user_links;
		if ($user_votes < $min_votes) {
			$needed = $min_votes - $user_votes;
			echo '<p class="error"><strong>'._('no tienes el mínimo de votos necesarios para enviar una nueva historia').'</strong></p> ';
			echo '<p class="error-text">'._('necesitas votar como mínimo a'). " $needed " . _('noticias') . ', ';
			echo '<a href="shakeit.php" target="_blank">'._('haz clic aquí para ir a votar').'</a></p>';
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}
	
	if($linkres->duplicates($url) > 0) {
		echo '<p class="error"><strong>'._('noticia repetida!').'</strong></p> ';
		echo '<p class="error-text">'._('lo sentimos').'</p>';
		echo '<p class="error-text"><a href="index.php?search='.htmlentities($url).'">'._('haz clic aquí para votar o comentar la noticia que enviaron antes').'</a>';
		echo '<br style="clear: both;" /><br style="clear: both;" />' . "\n";
		echo '<form id="genericform">';
		echo '<input class="genericsubmit" type=button onclick="window.history.go(-1)" value="'._('&#171; retroceder').'" />';
		echo '</form>'. "\n";
		echo '</div>'. "\n";
		return;
	}
	$linkres->status='discard';
	$linkres->author=$current_user->user_id;

	/***** Currently commented out until we find if it makes sense here
	// First delete last drafts, just in case to avoid triggering the anti spam measure
	$from = time() - 1800;
	$db->query("delete from links where link_date > from_unixtime($from) and link_author=$current_user->user_id and link_status='discard' and link_votes = 0");
	*****/

	// Now stores new draft
	$linkres->store();
	
	echo '<h2>'._('envío de una nueva noticia: paso 2 de 3').'</h2>'."\n";


	echo '<div id="genericform">'."\n";
	echo '<form action="/submit.php" method="post" id="thisform">'."\n";

	echo '<input type="hidden" name="url" id="url" value="'.$url.'" />'."\n";
	echo '<input type="hidden" name="phase" value="2" />'."\n";
	echo '<input type="hidden" name="randkey" value="'.intval($_POST['randkey']).'" />'."\n";
	echo '<input type="hidden" name="id" value="'.$linkres->id.'" />'."\n";

	echo '<fieldset><legend><span class="sign">'._('info de la noticia').'</span></legend>'."\n";
	echo '<p class="genericformtxt"><label for="url_title" accesskey="1">'._('título de la página').': </label> '."\n";
	echo $linkres->url_title;
	if($linkres->type() === 'blog') {
		echo '<br /> ('._('parece ser un blog').')</p>'."\n";
	} else {
		echo "</p>\n";
	}
	echo '</fieldset>'."\n";

	echo '<fieldset><legend><span class="sign">'._('detalles de la noticia').'</span></legend>'."\n";

	echo '<label for="title" accesskey="2">'._('título de la noticia').':</label>'."\n";
	echo '<p><span class="genericformnote">'._('título de la noticia. máximo: 120 caracteres').'</span>'."\n";

	echo '<br/><input type="text" id="title" name="title" value="'.$link_title.'" size="60" maxlength="120" /></p>'."\n";

	echo '<label for="tags" accesskey="4">'._('etiquetas').':</label>'."\n";
	echo '<p><span class="genericformnote"><strong>'._('pocas palabras, genéricas, cortas y separadas por "," (coma)').'</strong> Ejemplo: <em>web, programación, software libre</em></span>'."\n";
	echo '<br/><input type="text" id="tags" name="tags" value="'.$link_tags.'" size="40" maxlength="40" /></p>'."\n";

	echo '<p><label for="bodytext" accesskey="3">'._('descripción de la noticia').':</label>'."\n";
	echo '<br /><span class="genericformnote">'._('describe la noticia con tus palabras. entre dos y cinco frases es suficiente. sé cuidadoso.').'</span>'."\n";
	echo '<br/><textarea name="bodytext"  rows="10" cols="60" id="bodytext" >'.$link_content.'</textarea></p>'."\n";
	echo '<p><label accesskey="5">'._('categoría').':</label><br />'."\n";
	echo '<span class="genericformnote">'._('selecciona la categoría más apropiada').'</span></p>'."\n";
	echo '<div class="column-list">'."\n";
	echo '<div class="categorylist">'."\n";
	echo '<ul>'."\n";
	$categories = $db->get_results("SELECT category_id, category_name FROM categories WHERE category_lang='$dblang' ORDER BY category_name ASC");
	foreach ($categories as $category) {
	 	echo '<li><input name="category" type="radio" value="'.$category->category_id.'"/>'._($category->category_name).'</li>'."\n";
	}
	// TODO: no standard
	echo '<br style="clear: both;" />' . "\n";
	echo '</ul></div></div>'."\n";
	echo '<p><label for="trackback">'._('trackback').':</label><br />'."\n";
	echo '<span class="genericformnote">'._('puedes agregar o cambiar el trackback si ha sido detectado automáticamente').'</span>'."\n";
	echo '<input type="text" name="trackback" id="trackback" value="'.$trackback.'" class="form-full" /></p>'."\n";
	echo '<input class="genericsubmit" type="button" onclick="window.history.go(-1)" value="'._('&#171; retroceder').'">&nbsp;&nbsp;'."\n";
	echo '<input class="genericsubmit" type="submit" value="'._('continuar &#187;').'" />'."\n";
	echo '</fieldset>'."\n";
	echo '</form>'."\n";
	echo '</div>'."\n";
	echo '</div>'."\n";
}
Exemple #29
0
 /**
  * Index action.
  *
  * @param integer $id	Construction ID
  *
  * @return Bengine_Game_Controller_Construction_Edit
  */
 protected function indexAction($id)
 {
     if ($this->isPost()) {
         if ($this->getParam("addreq")) {
             $this->addRequirement($id, $this->getParam("level"), $this->getParam("needs"));
         }
         if ($this->getParam("saveconstruction")) {
             $this->saveConstruction($this->getParam("name"), $this->getParam("name_id"), $this->getParam("allow_on_moon"), $this->getParam("desc"), $this->getParam("full_desc"), $this->getParam("prod_what"), $this->getParam("prod"), $this->getParam("cons_what"), $this->getParam("consumption"), $this->getParam("special"), $this->getParam("basic_metal"), $this->getParam("basic_silicon"), $this->getParam("basic_hydrogen"), $this->getParam("basic_energy"), $this->getParam("charge_metal"), $this->getParam("charge_silicon"), $this->getParam("charge_hydrogen"), $this->getParam("charge_energy"));
         }
     }
     $select = array("c.name AS name_id", "p.content AS name", "c.special", "c.allow_on_moon", "c.basic_metal", "c.basic_silicon", "c.basic_hydrogen", "c.basic_energy", "c.prod_metal", "c.prod_silicon", "c.prod_hydrogen", "c.prod_energy", "c.cons_metal", "c.cons_silicon", "c.cons_hydrogen", "c.cons_energy", "c.charge_metal", "c.charge_silicon", "c.charge_hydrogen", "c.charge_energy");
     $joins = "LEFT JOIN " . PREFIX . "phrases p ON (p.title = c.name)";
     $result = Core::getQuery()->select("construction c", $select, $joins, Core::getDB()->quoteInto("c.buildingid = ? AND p.languageid = ?", array($id, Core::getLanguage()->getOpt("languageid"))));
     if ($row = $result->fetchRow()) {
         $result->closeCursor();
         Hook::event("EditUnitDataLoaded", array(&$row));
         // Set production
         $prodWhat = "";
         if (!empty($row["prod_metal"])) {
             $row["prod"] = $row["prod_metal"];
             $prodWhat = "metal";
         } else {
             if (!empty($row["prod_silicon"])) {
                 $row["prod"] = $row["prod_silicon"];
                 $prodWhat = "silicon";
             } else {
                 if (!empty($row["prod_hydrogen"])) {
                     $row["prod"] = $row["prod_hydrogen"];
                     $prodWhat = "hydrogen";
                 } else {
                     if (!empty($row["prod_energy"])) {
                         $row["prod"] = $row["prod_energy"];
                         $prodWhat = "energy";
                     }
                 }
             }
         }
         // Set Consumption
         $consWhat = "";
         if (!empty($row["cons_metal"])) {
             $row["consumption"] = $row["cons_metal"];
             $consWhat = "metal";
         } else {
             if (!empty($row["cons_silicon"])) {
                 $row["consumption"] = $row["cons_silicon"];
                 $consWhat = "silicon";
             } else {
                 if (!empty($row["cons_hydrogen"])) {
                     $row["consumption"] = $row["cons_hydrogen"];
                     $consWhat = "hydrogen";
                 } else {
                     if (!empty($row["cons_energy"])) {
                         $row["consumption"] = $row["cons_energy"];
                         $consWhat = "energy";
                     }
                 }
             }
         }
         Core::getTPL()->assign("prodWhat", $this->getResourceSelect($prodWhat));
         Core::getTPL()->assign("consWhat", $this->getResourceSelect($consWhat));
         Core::getTPL()->assign($row);
         $result = Core::getQuery()->select("phrases", "content", "", Core::getDB()->quoteInto("languageid = ? AND title = ?", array(Core::getLanguage()->getOpt("languageid"), $row["name_id"] . "_DESC")));
         $_row = $result->fetchRow();
         $result->closeCursor();
         Core::getTPL()->assign("description", Str::replace("<br />", "", $_row["content"]));
         $result = Core::getQuery()->select("phrases", "content", "", Core::getDB()->quoteInto("languageid = ? AND title = ?", array(Core::getLanguage()->getOpt("languageid"), $row["name_id"] . "_FULL_DESC")));
         $_row = $result->fetchRow();
         $result->closeCursor();
         Core::getTPL()->assign("full_description", Str::replace("<br />", "", $_row["content"]));
         $req = array();
         $i = 0;
         $result = Core::getQuery()->select("requirements r", array("r.requirementid", "r.needs", "r.level", "p.content"), "LEFT JOIN " . PREFIX . "construction b ON (b.buildingid = r.needs) LEFT JOIN " . PREFIX . "phrases p ON (p.title = b.name)", Core::getDB()->quoteInto("r.buildingid = ? AND p.languageid = ?", array($id, Core::getLanguage()->getOpt("languageid"))));
         foreach ($result->fetchAll() as $row) {
             $req[$i]["delete"] = Link::get("game/sid:" . SID . "/Construction_Edit/DeleteRequirement/" . $row["requirementid"] . "/" . $id, "[" . Core::getLanguage()->getItem("DELETE") . "]");
             $req[$i]["name"] = Link::get("game/" . SID . "/Construction_Edit/Index/" . $row["needs"], $row["content"]);
             $req[$i]["level"] = $row["level"];
             $i++;
         }
         Core::getTPL()->addLoop("requirements", $req);
         $const = array();
         $i = 0;
         $result = Core::getQuery()->select("construction b", array("b.buildingid", "p.content"), "LEFT JOIN " . PREFIX . "phrases p ON (p.title = b.name)", "(b.mode = '1' OR b.mode = '2' OR b.mode = '5') AND p.languageid = " . Core::getDB()->quote(Core::getLanguage()->getOpt("languageid")), "p.content ASC");
         foreach ($result->fetchAll() as $row) {
             $const[$i]["name"] = $row["content"];
             $const[$i]["id"] = $row["buildingid"];
             $i++;
         }
         $result->closeCursor();
         Core::getTPL()->addLoop("constructions", $const);
     }
     return $this;
 }
Exemple #30
0
function do_submit1() {
	global $db, $dblang, $current_user, $globals;

	$url = clean_input_url($_POST['url']);
	$url = preg_replace('/^http:\/\/http:\/\//', 'http://', $url); // Some users forget to delete the foo http://
	if (! preg_match('/^\w{3,6}:\/\//', $url)) { // http:// forgotten, add it
		$url = 'http://'.$url;
	}
	$url = preg_replace('/#[^\/]*$/', '', $url); // Remove the "#", people just abuse

	echo '<div>'."\n";

	$new_user = false;
	if (!check_link_key()) {
		echo '<p class="error"><strong>'._('clave incorrecta').'</strong></p> ';
		echo '</div>'. "\n";
		return;
	}
	if ($globals['min_karma_for_links'] > 0 && $current_user->user_karma < $globals['min_karma_for_links'] ) {
		echo '<p class="error"><strong>'._('no tienes el mínimo de karma para enviar una nueva historia').'</strong></p> ';
		echo '</div>'. "\n";
		return;
	}

	// Don't allow to send a link by a clone
	$hours = intval($globals['user_links_clon_interval']);
	$clones = $current_user->get_clones($hours+1);
	if ($hours > 0 && $clones) {
		$l = implode(',', $clones);
		$c = (int) $db->get_var("select count(*) from links where link_status!='published' and link_date > date_sub(now(), interval $hours hour) and link_author in ($l)");
		if ($c > 0) {
			echo '<p class="error">'._('ya se envió con otro usuario «clon» en las últimas horas'). ", "._('disculpa las molestias'). ' </p>';
			syslog(LOG_NOTICE, "Meneame, clon submit ($current_user->user_login): $_POST[url]");
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}

	// Check the number of links sent by a user
	$queued_24_hours = (int) $db->get_var("select count(*) from links where link_status!='published' and link_date > date_sub(now(), interval 24 hour) and link_author=$current_user->user_id");

  if (!$globals['development'])
	if ($globals['limit_user_24_hours'] && $queued_24_hours > $globals['limit_user_24_hours']) {
		echo '<p class="error">'._('debes esperar, tienes demasiados envíos en cola de las últimas 24 horas'). " ($queued_24_hours), "._('disculpa las molestias'). ' </p>';
		syslog(LOG_NOTICE, "Meneame, too many queued in 24 hours ($current_user->user_login): $_POST[url]");
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}

	// check the URL is OK and that it resolves
	$url_components = @parse_url($url);
	if (!$url_components || ! $url_components['host'] || gethostbyname($url_components['host']) == $url_components['host']) {
		echo '<p class="error"><strong>'._('URL o nombre de servidor erróneo').'</strong></p> ';
		echo '<p>'._('el nombre del servidor es incorrecto o éste tiene problemas para resolver el nombre'). ' </p>';
		syslog(LOG_NOTICE, "Meneame, hostname error ($current_user->user_login): $url");
		print_empty_submit_form();
		echo '</div>'. "\n";
		return;
	}

	$enqueued_last_minutes = (int) $db->get_var("select count(*) from links where link_status='queued' and link_date > date_sub(now(), interval 3 minute)");
	if ($current_user->user_karma > $globals['limit_3_minutes_karma']) $enqueued_limit = $globals['limit_3_minutes'] * 1.5;
	else $enqueued_limit = $globals['limit_3_minutes'];

	if ($enqueued_last_minutes > $enqueued_limit) {
		echo '<p class="error"><strong>'._('exceso de envíos').':</strong></p>';
		echo '<p>'._('se han enviado demasiadas historias en los últimos 3 minutos'). " ($enqueued_last_minutes > $enqueued_limit), "._('disculpa las molestias'). ' </p>';
		syslog(LOG_NOTICE, "Meneame, too many queued ($current_user->user_login): $_POST[url]");
		echo '</div>'. "\n";
		return;
	}

	// Check the user does not have too many drafts
	$minutes = intval($globals['draft_time'] / 60) + 10;
	$drafts = (int) $db->get_var("select count(*) from links where link_author=$current_user->user_id  and link_date > date_sub(now(), interval $minutes minute) and link_status='discard' and link_votes = 0");
  if (!$globals['development'])
	if ($drafts > $globals['draft_limit']) {
		echo '<p class="error"><strong>'._('demasiados borradores').':</strong></p>';
		echo '<p>'._('has hecho demasiados intentos, debes esperar o continuar con ellos desde la'). ' <a href="shakeit.php?meta=_discarded">'. _('cola de descartadas').'</a></p>';
		syslog(LOG_NOTICE, "Meneame, too many drafts ($current_user->user_login): $_POST[url]");
		echo '</div>'. "\n";
		return;
	}
	// Delete dangling drafts
	if ($drafts > 0) {
		$db->query("delete from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 30 minute) and link_date < date_sub(now(), interval 10 minute) and link_status='discard' and link_votes = 0");
	}


	// Check for banned IPs
  if (!$globals['development'])
	if(($ban = check_ban($globals['user_ip'], 'ip', true)) || ($ban = check_ban_proxy())) {
		echo '<p class="error"><strong>'._('dirección IP no permitida para enviar').':</strong> '.$globals['user_ip'].'</p>';
		echo '<p><strong>'._('Razón').'</strong>: '.$ban['comment'].'</p>';
		if ($ban['expire'] > 0) {
			echo '<p class="note"><strong>'._('caduca').'</strong>: '.get_date_time($ban['expire']).'</p>';
		}
		syslog(LOG_NOTICE, "Meneame, banned IP $globals[user_ip] ($current_user->user_login): $url");
		print_empty_submit_form();
		echo '</div>'. "\n";
		return;
	}

	// Number of links sent by the user
	$total_sents = (int) $db->get_var("select count(*) from links where link_author=$current_user->user_id") - $drafts;
	if ($total_sents > 0) {
		$sents = (int) $db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 60 day)") - $drafts;
	} else {
		$new_user = true;
		$sents = 0;
	}

	$register_date = $current_user->Date();
	if ($globals['now'] - $register_date < $globals['new_user_time'] ) {
		$new_user = true;
	}

	// check that a new user also votes, not only sends links
	// it requires $globals['min_user_votes'] votes
	if ($new_user && $globals['min_user_votes'] > 0 && $current_user->user_karma < $globals['new_user_karma']) {
		$user_votes_total = (int) $db->get_var("select count(*) from votes where vote_type='links' and vote_user_id=$current_user->user_id");
		$user_votes = (int) $db->get_var("select count(*) from votes where vote_type='links' and vote_date > date_sub(now(), interval 72 hour) and vote_user_id=$current_user->user_id");
		$user_links = 1 + $db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 24 hour) and link_status != 'discard'");
		$total_links = (int) $db->get_var("select count(*) from links where link_date > date_sub(now(), interval 24 hour) and link_status = 'queued'");
		echo "<!-- $user_votes_total, $user_links, $total_links -->\n";
		if ($sents == 0) {
			// If is a new user, requires more votes, to avoid spam
			$min_votes = $globals['min_user_votes'];
		} else {
			$min_votes = min(4, intval($total_links/20)) * $user_links;
		}
		if (!$current_user->admin && $user_votes < $min_votes) {
			$needed = $min_votes - $user_votes;
			echo '<p class="error">';
			if ($new_user) {
				echo '<strong>'._('¿es la primera vez que envías una noticia?').'</strong></p> ';
				echo '<p class="error-text">'._('necesitas como mínimo'). " <strong>$needed " . _('votos') . '</strong><br/>';
			} else {
				echo '<strong>'._('no tienes el mínimo de votos necesarios para enviar una nueva historia').'</strong></p> ';
				echo '<p class="error-text">'._('necesitas votar como mínimo a'). " <strong>$needed " . _('envíos') . '</strong><br/>';
			}
			echo '<strong>'._('no votes de forma apresurada, penaliza el karma').'</strong><br/>';
			echo '<a href="'.$globals['base_url'].'shakeit.php" target="_blank">'._('haz clic aquí para ir a votar').'</a></p>';
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}

	// avoid spams, an extra security check
	// it counts the numbers of links in the last hours
	if ($new_user) {
		$user_links_limit = $globals['new_user_links_limit'];
		$user_links_interval = intval($globals['new_user_links_interval'] / 3600);
	} else {
		$user_links_limit = $globals['user_links_limit'];
		$user_links_interval = intval($globals['user_links_interval'] / 3600);
	}
	$same_user = (int) $db->get_var("select count(*) from links where link_date > date_sub(now(), interval $user_links_interval hour) and link_author=$current_user->user_id") - $drafts;
	$same_ip = (int) $db->get_var("select count(*) from links where link_date > date_sub(now(), interval $user_links_interval hour) and link_ip = '".$globals['user_ip']."'") - $drafts;
	if ($same_user >  $user_links_limit  || $same_ip >  $user_links_limit  ) {
		echo '<p class="error"><strong>'._('debes esperar, ya se enviaron varias con el mismo usuario o dirección IP').  '</strong></p>';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}

	// avoid users sending continuous "rubbish" or "propaganda", specially new users
	// it takes in account the number of positive votes in the last six hours
	if ($same_user > 1 && $current_user->user_karma < $globals['karma_propaganda']) {
		$positives_received = $db->get_var("select sum(link_votes) from links where link_date > date_sub(now(), interval $user_links_interval hour) and link_author = $current_user->user_id");
		$negatives_received = $db->get_var("select sum(link_negatives) from links where link_date > date_sub(now(), interval $user_links_interval hour) and link_author = $current_user->user_id");
		if ($negatives_received > 10 && $negatives_received > $positives_received * 1.5) {
			echo '<p class="error"><strong>'._('debes esperar, has tenido demasiados votos negativos en tus últimos envíos').  '</strong></p>';
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}
	
	$linkres=new Link;
	$linkres->url = $url;

	$edit = false;

	if(report_dupe($url)) return;


	if(!$linkres->check_url($url, true, true) || !$linkres->get($url)) {
		echo '<p class="error"><strong>'._('URL erróneo o no permitido').'</strong>: ';
		if ($linkres->ban && $linkres->ban['match']) {
			echo $linkres->ban['match'];
		} else {
			echo $linkres->url;
		}
		echo '</p>';
		echo '<p><strong>'._('Razón').':</strong> '. $linkres->ban['comment'].'</p>';
		if ($linkres->ban['expire'] > 0) {
			echo '<p class="note"><strong>'._('caduca').'</strong>: '.get_date_time($linkres->ban['expire']).'</p>';
		}
		print_empty_submit_form();
		echo '</div>'. "\n";
		return;
	}

	// If the URL has changed, check again is not dupe
	if($linkres->url != $url && report_dupe($linkres->url)) return;

	$linkres->randkey = intval($_POST['randkey']);
	if(!$linkres->valid) {
		echo '<p class="error"><strong>'._('error leyendo el url').':</strong> '.htmlspecialchars($url).'</p>';
		// Dont allow new users with low karma to post wrong URLs
		if ($current_user->user_karma < 8 && $current_user->user_level == 'normal') {
			echo '<p>'._('URL inválido, incompleto o no permitido. Está fuera de línea, o tiene mecanismos antibots.').'</p>';
			print_empty_submit_form();
			return;
		}
		echo '<p>'._('no es válido, está fuera de línea, o tiene mecanismos antibots. <strong>Continúa</strong>, pero asegúrate que sea correcto').'</p>';
	}

	$linkres->status='discard';
	$linkres->author=$current_user->user_id;

	if (!$linkres->pingback()) {
		$linkres->trackback();
	}
	$trackback=htmlspecialchars($linkres->trackback);
	$linkres->create_blog_entry();
	$blog = new Blog;
	$blog->id = $linkres->blog;
	$blog->read();

	$blog_url_components = @parse_url($blog->url);
	$blog_url = $blog_url_components['host'].$blog_url_components['path'];
	// Now we check again against the blog table
	// it's done because there could be banned blogs like http://lacotelera.com/something
	if(($ban = check_ban($blog->url, 'hostname', false, true))) {
		echo '<p class="error"><strong>'._('URL inválido').':</strong> '.htmlspecialchars($url).'</p>';
		echo '<p>'._('el sitio').' '.$ban['match'].' '. _('está deshabilitado'). ' ('. $ban['comment'].') </p>';
		if ($ban['expire'] > 0) {
			echo '<p class="note"><strong>'._('caduca').'</strong>: '.get_date_time($ban['expire']).'</p>';
		}
		syslog(LOG_NOTICE, "Meneame, banned site ($current_user->user_login): $blog->url <- $_POST[url]");
		print_empty_submit_form();
		echo '</div>'. "\n";
		/*
		// If the domain is banned, decrease user's karma
		if ($linkres->banned && $current_user->user_level == 'normal') {
			$db->query("update users set user_karma = user_karma - 0.05 where user_id = $current_user->user_id");
		}
		*/
		return;
	}


	// check for users spamming several sites and networks
	// it does not allow a low "entropy"
  // DISABLED BY MANEL: let the user send news from the same sources
  /*
	if ($sents > 30) {
		$ratio = (float) $db->get_var("select count(distinct link_blog)/count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 60 day)");
		$threshold = 1/log($sents, 2);
		if ($ratio <  $threshold ) {
			if ($db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 60 day) and link_blog = $blog->id") > 2) {
				syslog(LOG_NOTICE, "Meneame, forbidden due to low entropy: $ratio <  $threshold  ($current_user->user_login): $linkres->url");
				echo '<p class="error"><strong>'._('ya has enviado demasiados enlaces a los mismos sitios').'</strong></p> ';
				echo '<p class="error-text">'._('varía las fuentes, podría ser considerado spam').'</p>';
				echo '<br style="clear: both;" />' . "\n";
				echo '</div>'. "\n";
				return;
			}
		}
	}
  */

	// Check the user does not send too many images or vídeos
	// they think this is a fotolog
  // DISABLED BY MANEL: this could be a fotolog
  /*
	if ($sents > 5 && ($linkres->content_type == 'image' || $linkres->content_type == 'video')) {
		$image_links = intval($db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 60  day) and link_content_type in ('image', 'video')"));
		if ($image_links > $sents * 0.7) {
			syslog(LOG_NOTICE, "Meneame, forbidden due to too many images or video sent by user ($current_user->user_login): $linkres->url");
			echo '<p class="error"><strong>'._('ya has enviado demasiadas imágenes o vídeos').'</strong></p> ';
			//echo '<p class="error-text">'._('disculpa, no es un fotolog').'</p>';
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}
   */

	// Avoid users sending too many links to the same site in last hours
  // DISABLED BY MANEL
  /*
	$hours = 24;
	$same_blog = $db->get_var("select count(*) from links where link_date > date_sub(now(), interval $hours hour) and link_author=$current_user->user_id and link_blog=$linkres->blog and link_votes > 0");
	if ($same_blog > 2) {
		syslog(LOG_NOTICE, "Meneame, forbidden due to too many links to the same site in last $hours hours ($current_user->user_login): $linkres->url");
		echo '<p class="error"><strong>'._('demasiados enlaces al mismo sitio en las últimas horas').'</strong></p> ';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}
   */

	// avoid auto-promotion (autobombo)
  // DISABLED BY MANEL: autobombo permitido
  /*
	$minutes = 30;
	$same_blog = $db->get_var("select count(*) from links where link_date > date_sub(now(), interval $minutes minute) and link_author=$current_user->user_id and link_blog=$linkres->blog and link_votes > 0");
	if ($same_blog > 0 && $current_user->user_karma < 12) {
		syslog(LOG_NOTICE, "Meneame, forbidden due to short period between links to same site ($current_user->user_login): $linkres->url");
		echo '<p class="error"><strong>'._('ya has enviado un enlace al mismo sitio hace poco tiempo').'</strong></p> ';
		echo '<p class="error-text">'._('debes esperar'). " $minutes " . _('minutos entre cada envío al mismo sitio.') . ', ';
		echo '<a href="'.$globals['base_url'].'faq-'.$dblang.'.php">'._('lee el FAQ').'</a></p>';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}
   */

	// Avoid spam (autobombo), count links in last two months
  // DISABLED BY MANEL: autobombo permitido
  /*
	$same_blog = $db->get_var("select count(*) from links where link_author=$current_user->user_id and link_date > date_sub(now(), interval 60 day) and link_blog=$linkres->blog");

	$check_history =  $sents > 3 && $same_blog > 0 && ($ratio = $same_blog/$sents) > 0.5;
	if ($check_history) {
		echo '<p class="error"><strong>'._('has enviado demasiados enlaces a')." $blog->url".'</strong></p> ';
		if ($sents > 5 && $ratio > 0.75) {
			echo '<p class="error-text">'._('has superado los límites de envíos de este sitio').'</p>';
			// don't allow to continue
			syslog(LOG_NOTICE, "Meneame, warn, high ratio, process interrumped ($current_user->user_login): $linkres->url");
			return;
		} else {
			echo '<p class="error-text">'._('continúa, pero ten en cuenta podría recibir votos negativos').', ';
			echo '<a href="'.$globals['base_url'].'legal.php">'._('condiciones de uso').'</a>, ';
			echo '<a href="'.$globals['base_url'].'faq-'.$dblang.'.php">'._('el FAQ').'</a></p>';
			syslog(LOG_NOTICE, "Meneame, warn, high ratio, continue ($current_user->user_login): $linkres->url");
		}
	}
   */



	$links_12hs = $db->get_var("select count(*) from links where link_date > date_sub(now(), interval 12 hour)");

	// check there is no an "overflow" from the same site
  // DISABLED BY MANEL: could be an overflow 
  /*
	$site_links = intval($db->get_var("select count(*) from links where link_date > date_sub(now(), interval 12 hour) and link_blog=$linkres->blog and link_status in ('queued')"));
	if ($site_links > 8 && $site_links > $links_12hs * 0.04) { // Only 4% from the same site
		syslog(LOG_NOTICE, "Meneame, forbidden due to overflow to the same site ($current_user->user_login): $linkres->url");
		echo '<p class="error"><strong>'._('ya se han enviado demasiadas artículos del mismo sitio, espera unos minutos por favor').'</strong></p> ';
		echo '<p class="error-text">'._('total en 12 horas').": $site_links , ". _('el máximo actual es'). ': ' . intval($links_12hs * 0.04). '</p>';
		echo '<br style="clear: both;" />' . "\n";
		echo '</div>'. "\n";
		return;
	}
   */

	// check there is no an "overflow" of images
  // DISABLED BY MANEL: let the overflow begin
  /*
	if ($linkres->content_type == 'image' || $linkres->content_type == 'video') {
		$image_links = intval($db->get_var("select count(*) from links where link_date > date_sub(now(), interval 12 hour) and link_content_type in ('image', 'video')"));
		if ($image_links > 5 && $image_links > $links_12hs * 0.08) { // Only 8% images and videos
			syslog(LOG_NOTICE, "Meneame, forbidden due to overflow images ($current_user->user_login): $linkres->url");
			echo '<p class="error"><strong>'._('ya se han enviado demasiadas imágenes o vídeos, espera unos minutos por favor').'</strong></p> ';
			echo '<p class="error-text">'._('total en 12 horas').": $image_links , ". _('el máximo actual es'). ': ' . intval($links_12hs * 0.05). '</p>';
			echo '<br style="clear: both;" />' . "\n";
			echo '</div>'. "\n";
			return;
		}
	}
   */

	if(($ban = check_ban($linkres->url, 'punished_hostname', false, true))) {
		echo '<p class="error"><strong>'._('Aviso').' '.$ban['match']. ':</strong> <em>'.$ban['comment'].'</em></p>';
		echo '<p>'._('mejor enviar el enlace a la fuente original, sino será penalizado').'</p>';
	}

	
	// Now stores new draft
	$linkres->ip = $globals['user_ip'];
	$linkres->sent_date = $linkres->date=time();
	$linkres->store();
	
	echo '<h2>'._('envío de una nueva noticia: paso 2 de 3').'</h2>'."\n";


	echo '<div class="genericform">'."\n";
	echo '<form action="submit.php" method="post" id="thisform" name="thisform">'."\n";

	echo '<input type="hidden" name="url" id="url" value="'.htmlspecialchars($linkres->url).'" />'."\n";
	echo '<input type="hidden" name="phase" value="2" />'."\n";
	echo '<input type="hidden" name="randkey" value="'.intval($_POST['randkey']).'" />'."\n";
	echo '<input type="hidden" name="key" value="'.$_POST['key'].'" />'."\n";
	echo '<input type="hidden" name="id" value="'.$linkres->id.'" />'."\n";

	echo '<fieldset><legend><span class="sign">'._('información del enlace').'</span></legend>'."\n";
	echo '<p class="genericformtxt"><strong>';
	echo mb_substr($linkres->url_title, 0, 200);
	echo '</strong><br/>';
	echo htmlspecialchars($linkres->url);
	echo '</p> '."\n";
	echo '</fieldset>'."\n";

	echo '<fieldset><legend><span class="sign">'._('detalles de la noticia').'</span></legend>'."\n";

	echo '<label for="title" accesskey="1">'._('título de la noticia').':</label>'."\n";
	echo '<p><span class="note">'._('título de la noticia. máximo: 120 caracteres').'</span>'."\n";
	// Is it an image or video?
	echo '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	$linkres->print_content_type_buttons();

	echo '<br/><input type="text" id="title" name="title" value="'.$link_title.'" size="80" maxlength="120" />';
	echo '</p>'."\n";

	echo '<label for="tags" accesskey="2">'._('etiquetas').':</label>'."\n";
	echo '<p><span class="note"><strong>'._('pocas palabras, genéricas, cortas y separadas por «,» (coma)').'</strong> Ejemplo: <em>web, programación, software libre</em></span>'."\n";
	echo '<br/><input type="text" id="tags" name="tags" value="'.$link_tags.'" size="70" maxlength="70" /></p>'."\n";


  echo '<link rel="stylesheet" type="text/css" media="all" href="'.$globals['base_static'].'css/ui-lightness/jquery-ui-1.8.16.custom.css"/>' . "\n";
	echo '<script src="'.$globals['base_url'].'js/jquery-ui-1.8.16.custom.min.js" type="text/javascript" charset="utf-8"></script>' . "\n";
  echo '<script type="text/javascript">
$(document).ready( function() {
';
  echo "$.datepicker.regional['pt-BR'] = {
                closeText: 'Fechar',
                prevText: '&#x3c;Anterior',
                nextText: 'Pr&oacute;ximo&#x3e;',
                currentText: 'Hoje',
                monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
                'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
                monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
                'Jul','Ago','Set','Out','Nov','Dez'],
                dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
                dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
                dayNamesMin: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
                dateFormat: 'dd/mm/yy', firstDay: 0,
                isRTL: false};
        $.datepicker.setDefaults($.datepicker.regional['pt-BR']);
    ";
echo '
    $("[name=datepicker1]").datepicker();
    $("[name=datepicker2]").datepicker();
});
</script>';

  echo '<label>'._('Datas do Evento').'</label> <span class="note">(opcional) desde </span> ';
  echo '<input type="text" name="datepicker1" size="8"><span class="note"> '._('ata').'</span> <input type="text" name="datepicker2" size="8"></span>';

	print_simpleformat_buttons('bodytext');

	echo '<label for="bodytext" accesskey="3">'._('descripción de la noticia').':</label>'."\n";
	echo '<p><span class="note"><strong>'._('describe la noticia en castellano. entre dos y cinco frases es suficiente. no deformes el contenido.').'</strong></span>'."\n";
	echo '<br /><textarea name="bodytext"  rows="10" cols="60" id="bodytext" onKeyDown="textCounter(document.thisform.bodytext,document.thisform.bodycounter,550)" onKeyUp="textCounter(document.thisform.bodytext,document.thisform.bodycounter,550)">';
	if (mb_strlen($linkres->url_description) > 40) {
		echo $linkres->url_description;
	}
	echo '</textarea>'."\n";

	echo '<div style="margin-top:-7px"><input readonly type="text" name="bodycounter" size="3" maxlength="3" value="550" /> <span class="note">' . _('caracteres libres') . '</span></div>';
	echo '</p>'."\n";

	print_categories_form();

	echo '<p><label for="trackback">'._('trackback').':</label><br />'."\n";
	if (empty($trackback)) {
		echo '<span class="note">'._('puedes agregar o cambiar el trackback si ha sido detectado automáticamente').'</span>'."\n";
		echo '<input type="text" name="trackback" id="trackback" value="'.$trackback.'" class="form-full" /></p>'."\n";
	} else {
		echo '<span class="note">'.$trackback.'</span>'."\n";
		echo '<input type="hidden" name="trackback" id="trackback" value="'.$trackback.'"/></p>'."\n";
	}
	echo '<input class="button" type="button" onclick="window.history.go(-1)" value="&#171; '._('retroceder').'" />&nbsp;&nbsp;'."\n";
	echo '<input class="button" type="submit" value="'._('continuar').' &#187;" />'."\n";
	echo '</fieldset>'."\n";
	echo '</form>'."\n";
	echo '</div>'."\n";
	echo '</div>'."\n";
}