/** * Factory method. * * @static * @access public * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function factory() { self::$defaultLifeTime = Config::get('cache.lifetime', 3600); $driverName = ucfirst(Config::get('cache.driver')); $driver = '\\Plethora\\Cache\\Drivers\\' . $driverName . 'CacheDriver'; static::$driver = new $driver(); Log::insert('Cache type "' . Config::get('cache.driver') . '" initialized!'); }
static function conditional_insert($type, $ref_id, $user_id = 0, $seconds = 0, $annotation = false) { global $db, $globals; if (!Log::get_date($type, $ref_id, $user_id, $seconds)) { return Log::insert($type, $ref_id, $user_id, $annotation); } return false; }
function register($accion, $parametro = '') { $log = new Log(); $log->id_accion = $accion; $log->fecha = date("Y/m/d"); $log->hora = date("H:i:s"); $log->parametro = $parametro ? $parametro : NULL; $log->id_usuario = RegistryHelper::getIdUsuario(); return $log->insert(); }
function do_login() { global $current_user, $globals; $form_ip_check = check_form_auth_ip(); $previous_login_failed = Log::get_date('login_failed', $globals['form_user_ip_int'], 0, 300); echo '<form action="' . get_auth_link() . 'login.php" id="xxxthisform" method="post">' . "\n"; if ($_POST["processlogin"] == 1) { // Check the IP, otherwise redirect if (!$form_ip_check) { header('HTTP/1.1 303 Load'); header("Location: http://" . $_COOKIE['return_site'] . $globals['base_url'] . "login.php"); die; } $username = clean_input_string(trim($_POST['username'])); $password = trim($_POST['password']); // Check form if (($previous_login_failed > 2 || $globals['captcha_first_login'] == true && !UserAuth::user_cookie_data()) && !ts_is_human()) { Log::insert('login_failed', $globals['form_user_ip_int'], 0); recover_error(_('el código de seguridad no es correcto')); } elseif (strlen($password) > 0 && $current_user->Authenticate($username, $password, $_POST['persistent']) == false) { Log::insert('login_failed', $globals['form_user_ip_int'], 0); recover_error(_('usuario o email inexistente, sin validar, o clave incorrecta')); $previous_login_failed++; } else { UserAuth::check_clon_from_cookies(); header('HTTP/1.1 303 Load'); if (!empty($_REQUEST['return'])) { header('Location: http://' . $_COOKIE['return_site'] . $_REQUEST['return']); } else { header('Location: http://' . $_COOKIE['return_site'] . $globals['base_url']); } die; } } echo '<p><label for="name">' . _('usuario o email') . ':</label><br />' . "\n"; echo '<input type="text" name="username" size="25" tabindex="1" id="name" value="' . htmlentities($username) . '" /></p>' . "\n"; echo '<p><label for="password">' . _('clave') . ':</label><br />' . "\n"; echo '<input type="password" name="password" id="password" size="25" tabindex="2"/></p>' . "\n"; echo '<p><label for="remember">' . _('recuérdame') . ': </label><input type="checkbox" name="persistent" id="remember" tabindex="3"/></p>' . "\n"; // Print captcha if ($previous_login_failed > 2 || $globals['captcha_first_login'] == true && !UserAuth::user_cookie_data()) { ts_print_form(); } get_form_auth_ip(); echo '<p><input type="submit" value="login" tabindex="4" />' . "\n"; echo '<input type="hidden" name="processlogin" value="1"/></p>' . "\n"; echo '<input type="hidden" name="return" value="' . htmlspecialchars($_REQUEST['return']) . '"/>' . "\n"; echo '</form>' . "\n"; echo '<div><strong><a href="login.php?op=recover">' . _('¿has olvidado la contraseña?') . '</a></strong></div>' . "\n"; echo '<div style="margin-top: 30px">'; print_oauth_icons($_REQUEST['return']); echo '</div>' . "\n"; }
public function loginAction() { $request = $this->getRequest(); $config = Zend_Registry::get('config'); // Check if we have a POST request if (!$request->isPost()) { $this->_helper->redirector('index', 'index'); } $lang = $this->getRequest()->getPost('lang'); if (isset($lang) && $lang != null) { $langNamespace = new Zend_Session_Namespace('Lang'); $langNamespace->lang = $lang; } // Get our form and validate it $form = new LoginForm(); if (!$form->isValid($request->getPost())) { // Invalid entries $this->_flashMessenger->addMessage('Email or Password is required and its length should between 6 and 20'); $this->view->form = $form; $this->_helper->redirector('loginfailed', 'index'); } // Get our authentication adapter and check credentials $adapter = new LoginAuthAdapter($form->getValue('email'), $form->getValue('password')); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); if ($result->isValid()) { // We're authenticated! Redirect to the home page $db = Zend_Registry::get('db'); $consumer_id = $db->fetchOne("SELECT id FROM consumer WHERE email = :temp or login_phone = :temp and state='ACTIVE'", array('temp' => $form->getValue('email'))); $consumerModel = new Consumer(); $consumer = $consumerModel->find($consumer_id)->current(); $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = $consumer; $authNamespace->role = 'consumer'; //log $logModel = new Log(); $logId = $logModel->insert(array('consumer_id' => $consumer->id, 'date' => date("Y-m-d H:i:s"), 'event' => 'LOGIN')); $url = $form->getValue('url'); if (isset($url) && !empty($url)) { $this->_redirector = $this->_helper->getHelper('Redirector'); $this->_redirector->gotoUrl($url); } else { $this->_helper->redirector('index', 'home'); } } else { // Invalid credentials $this->_flashMessenger->addMessage('Invalid credentials provided'); $this->view->form = $form; $this->_helper->redirector('loginfailed', 'index'); } }
public function Login() { try { if (!empty($_POST['usuario']) and !empty($_POST['password']) and !empty($_POST['session'])) { $db = new Conexion(); $this->usuario = $db->real_escape_string($_POST['usuario']); $this->password = $db->real_escape_string($_POST['password']); //$this->password = $this->Encript($_POST['password']); $sql = $db->query("SELECT * FROM claves WHERE Nombre='{$this->usuario}' AND Clave='{$this->password}';"); if ($db->rows($sql) > 0) { $datos = $db->recorrer($sql); $id = $datos['Id']; $_SESSION['id'] = $id; $_SESSION['usuario'] = $datos['Nombre']; $_SESSION['nivel'] = $datos['Nivel']; $_SESSION['controlfases'] = $datos['ControlFases']; $_SESSION['cuentaverexpedientes'] = $datos['CuentaVerExpedientes']; $_SESSION['indemnizacion'] = $datos['Indemnizacion']; $_SESSION['modificaraseguradora'] = $datos['Modaseguradora']; $_SESSION['verfacturas'] = $datos['VerFacturas']; $_SESSION['beneficio'] = $datos['beneficio']; $_SESSION['facturas'] = $datos['facturas']; $_SESSION['modificarsiniestro'] = $datos['modsiniestro']; $_SESSION['tramitadores'] = $datos['tramitadores']; $log = new Log("log", "./logs/"); $log->insert('Acceso al programa por el usuario ' . $_SESSION['usuario'], false, false, false); if ($_POST['session'] == true) { ini_set('session.cookie_lifetime', time() + 60 * 60 * 24 * 2); } echo 1; } else { $log = new Log("log", "./logs/"); $log->insert('Acceso no autorizado', false, false, false); throw new Exception(2); } $db->liberar($sql); $db->close(); } else { throw new exception('Error: Datos vacios'); } } catch (exception $login) { echo $login->getMessage(); } }
function save_profile() { global $db, $user, $current_user, $globals, $admin_mode, $site_key, $bio_max; $errors = 0; // benjami: control added (2005-12-22) $new_pass = false; $messages = array(); $form_hash = md5($site_key . $user->id . $current_user->user_id); if (isset($_POST['disabledme']) && intval($_POST['disable']) == 1 && $_POST['form_hash'] == $form_hash && $_POST['user_id'] == $current_user->user_id) { $old_user_login = $user->username; $old_user_id = $user->id; $user->disable(true); Log::insert('user_delete', $old_user_id, $old_user_id); syslog(LOG_NOTICE, "Meneame, disabling {$old_user_id} ({$old_user_login}) by {$current_user->user_login} -> {$user->username} "); $current_user->Logout(get_user_uri($user->username)); die; } if (!isset($_POST['save_profile']) || !isset($_POST['process']) || $_POST['user_id'] != $current_user->user_id && !$admin_mode) { return; } if (empty($_POST['form_hash']) || $_POST['form_hash'] != $form_hash) { array_push($messages, _('Falta la clave de control')); $errors++; } if (!empty($_POST['username']) && trim($_POST['username']) != $user->username) { $newname = trim($_POST['username']); if (strlen($newname) < 3) { array_push($messages, _('nombre demasiado corto')); $errors++; } if (!check_username($newname)) { array_push($messages, _('nombre de usuario erróneo, caracteres no admitidos')); $errors++; } elseif (user_exists($newname, $user->id)) { array_push($messages, _('el usuario ya existe')); $errors++; } else { $user->username = $newname; } } if (!empty($_POST['bio']) || $user->bio) { $bio = clean_text($_POST['bio'], 0, false, $bio_max); if ($bio != $user->bio) { $user->bio = $bio; } } if ($user->email != trim($_POST['email']) && !check_email(trim($_POST['email']))) { array_push($messages, _('el correo electrónico no es correcto')); $errors++; } elseif (!$admin_mode && trim($_POST['email']) != $current_user->user_email && email_exists(trim($_POST['email']), false)) { array_push($messages, _('ya existe otro usuario con esa dirección de correo')); $errors++; } else { $user->email = trim($_POST['email']); } $user->url = htmlspecialchars(clean_input_url($_POST['url'])); // Check IM address if (!empty($_POST['public_info'])) { $_POST['public_info'] = htmlspecialchars(clean_input_url($_POST['public_info'])); $public = $db->escape($_POST['public_info']); $im_count = intval($db->get_var("select count(*) from users where user_id != {$user->id} and user_level != 'disabled' and user_level != 'autodisabled' and user_public_info='{$public}'")); if ($im_count > 0) { array_push($messages, _('ya hay otro usuario con la misma dirección de MI, no se ha grabado')); $_POST['public_info'] = ''; $errors++; } } $user->phone = $_POST['phone']; $user->public_info = htmlspecialchars(clean_input_url($_POST['public_info'])); // End check IM address if ($user->id == $current_user->user_id) { // Check phone number if (!empty($_POST['phone'])) { if (!preg_match('/^\\+[0-9]{9,16}$/', $_POST['phone'])) { array_push($messages, _('número telefónico erróneo, no se ha grabado')); $_POST['phone'] = ''; $errors++; } else { $phone = $db->escape($_POST['phone']); $phone_count = intval($db->get_var("select count(*) from users where user_id != {$user->id} and user_level != 'disabled' and user_level != 'autodisabled' and user_phone='{$phone}'")); if ($phone_count > 0) { array_push($messages, _('ya hay otro usuario con el mismo número, no se ha grabado')); $_POST['phone'] = ''; $errors++; } } } $user->phone = $_POST['phone']; // End check phone number } // Verifies adsense code if ($globals['external_user_ads']) { $_POST['adcode'] = trim($_POST['adcode']); $_POST['adchannel'] = trim($_POST['adchannel']); if (!empty($_POST['adcode']) && $user->adcode != $_POST['adcode']) { if (!preg_match('/pub-[0-9]{16}$/', $_POST['adcode'])) { array_push($messages, _('código AdSense incorrecto, no se ha grabado')); $_POST['adcode'] = ''; $errors++; } else { $adcode_count = intval($db->get_var("select count(*) from users where user_id != {$user->id} and user_level != 'disabled' and user_level != 'autodisabled' and user_adcode='" . $_POST['adcode'] . "'")); if ($adcode_count > 0) { array_push($messages, _('ya hay otro usuario con la misma cuenta, no se ha grabado')); $_POST['adcode'] = ''; $errors++; } } } if (!empty($_POST['adcode']) && !empty($_POST['adchannel']) && $user->adchannel != $_POST['adchannel']) { if (!preg_match('/^[0-9]{10,12}$/', $_POST['adchannel'])) { array_push($messages, _('canal AdSense incorrecto, no se ha grabado')); $_POST['adchannel'] = ''; $errors++; } } $user->adcode = $_POST['adcode']; $user->adchannel = $_POST['adchannel']; } $user->names = clean_text($_POST['names']); if (!empty($_POST['password']) || !empty($_POST['password2'])) { if (!check_password($_POST["password"])) { array_push($messages, _('Clave demasiado corta, debe ser de 6 o más caracteres e incluir mayúsculas, minúsculas y números')); $errors = 1; } else { if (trim($_POST['password']) !== trim($_POST['password2'])) { array_push($messages, _('las claves no son iguales, no se ha modificado')); $errors = 1; } else { $new_pass = trim($_POST['password']); $user->pass = UserAuth::hash($new_pass); array_push($messages, _('La clave se ha cambiado')); $pass_changed = true; } } } if ($admin_mode && !empty($_POST['user_level'])) { $user->level = $db->escape($_POST['user_level']); } if ($admin_mode && !empty($_POST['karma']) && is_numeric($_POST['karma']) && $_POST['karma'] > 4 && $_POST['karma'] <= 20) { $user->karma = $_POST['karma']; } $user->comment_pref = intval($_POST['comment_pref']) + (intval($_POST['show_friends']) & 1) * 2 + (intval($_POST['show_2cols']) & 1) * 4; // Manage avatars upload if (!empty($_FILES['image']['tmp_name'])) { if (avatars_check_upload_size('image')) { $avatar_mtime = avatars_manage_upload($user->id, 'image'); if (!$avatar_mtime) { array_push($messages, _('error guardando la imagen')); $errors = 1; $user->avatar = 0; } else { $user->avatar = $avatar_mtime; } } else { array_push($messages, _('el tamaño de la imagen excede el límite')); $errors = 1; $user->avatar = 0; } } elseif ($_POST['avatar_delete']) { $user->avatar = 0; avatars_remove($user->id); } // Reset avatar for the logged user if ($current_user->user_id == $user->id) { $current_user->user_avatar = $user->avatar; } if (!$errors) { if (empty($user->ip)) { $user->ip = $globals['user_ip']; } $user->store(); $user->read(); if (!$admin_mode && ($current_user->user_login != $user->username || $current_user->user_email != $user->email || $new_pass)) { $current_user->Authenticate($user->username, $new_pass); } array_push($messages, _('datos actualizados')); } return $messages; }
function store_user() { global $db, $globals; // syslog(LOG_INFO, "store_user: "******" COOKIE: ".$_COOKIE['return']); $user = $this->user; if (!$this->secret) { $this->secret = $this->service . "-" . $globals['now']; } if (user_exists($this->username)) { $i = 1; while (user_exists($this->username . "_{$i}")) { $i++; } $user->username = $this->username . "_{$i}"; } else { $user->username = $this->username; } if (!$user->pass || preg_match('/$\\$/', $user->pass)) { $user->pass = "******"; } if (!$user->names && $this->names) { $user->names = $this->names; } if (!$user->url && $this->url) { $user->url = $this->url; } if ($user->id == 0) { $user->date = $globals['now']; $user->ip = $globals['user_ip']; $user->email = $this->username . '@' . $this->service; $user->email_register = $this->username . '@' . $this->service; $user->username_register = $user->username; } syslog(LOG_NOTICE, "Meneame new user from {$this->service}: {$user->username}, {$user->names}"); $user->store(); Log::insert('user_new', $user->id, $user->id); $db->query("update users set user_validated_date = now() where user_id = {$user->id} and user_validated_date is null"); if ($this->avatar) { require_once mnminclude . 'avatars.php'; avatars_get_from_url($user->id, $this->avatar); } }
function first() { $db = Zend_Registry::get('db'); $str = $_COOKIE; $uid = substr($str["weibojs_1864117054"], -10); if (isset($uid)) { $adapter = new WeiboLoginAuthAdapter($uid); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); $consumerModel = new Consumer(); $consumer_id = $db->fetchOne("SELECT id FROM consumer WHERE weiboid = :temp and state='ACTIVE'", array('temp' => $uid)); $consumer = $consumerModel->find($consumer_id)->current(); if ($result->isValid()) { $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = $consumer; $authNamespace->role = 'consumer'; $logModel = new Log(); $logId = $logModel->insert(array('consumer_id' => $consumer->id, 'date' => date("Y-m-d H:i:s"), 'event' => 'LOGIN')); $this->_helper->redirector('index', 'tag'); } } }
function callbackAction() { // if($this->_request->getParam('state')== $_SESSION['state']) //csrf // { $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&" . "client_id=" . $_SESSION["appid"] . "&redirect_uri=" . urlencode($_SESSION["callback"]) . "&client_secret=" . $_SESSION["appkey"] . "&code=" . $_REQUEST["code"]; $response = get_url_contents($token_url); if (strpos($response, "callback") !== false) { $lpos = strpos($response, "("); $rpos = strrpos($response, ")"); $response = substr($response, $lpos + 1, $rpos - $lpos - 1); $msg = json_decode($response); if (isset($msg->error)) { echo "<h3>error:</h3>" . $msg->error; echo "<h3>msg :</h3>" . $msg->error_description; exit; } } $params = array(); parse_str($response, $params); //debug //print_r($params); //set access token to session $_SESSION["access_token"] = $params["access_token"]; include_once "user/get_user_info.php"; $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $_SESSION['access_token']; $str = get_url_contents($graph_url); if (strpos($str, "callback") !== false) { $lpos = strpos($str, "("); $rpos = strrpos($str, ")"); $str = substr($str, $lpos + 1, $rpos - $lpos - 1); } $me = json_decode($str); if (isset($me->error)) { echo "<h3>error:</h3>" . $me->error; echo "<h3>msg :</h3>" . $me->error_description; exit; } //debug //echo("Hello " . $user->openid); //set openid to session $_SESSION["openid"] = $me->openid; $user = get_user_info(); $uid = $me->openid; $adapter = new QQLoginAuthAdapter($uid); $auth = Zend_Auth::getInstance(); $result = $auth->authenticate($adapter); $consumerModel = new Consumer(); $db = Zend_Registry::get('db'); $consumer_id = $db->fetchOne("SELECT id FROM consumer WHERE qqid = :temp and state='ACTIVE'", array('temp' => $uid)); $consumer = $consumerModel->find($consumer_id)->current(); if ($result->isValid()) { $authNamespace = new Zend_Session_Namespace('Zend_Auth'); $authNamespace->user = $consumer; $authNamespace->role = 'consumer'; $logModel = new Log(); $logId = $logModel->insert(array('consumer_id' => $consumer->id, 'date' => date("Y-m-d H:i:s"), 'event' => 'LOGIN')); $this->_helper->redirector('index', 'home'); } else { $this->_helper->redirector('register', 'register'); } // } // else // { // echo("The state does not match. You may be a victim of CSRF."); // } }
function do_save($link) { global $dblang, $globals, $current_user, $db; $link->status = $link->sub_status; $site_properties = SitesMgr::get_extended_properties(); // Store previous value for the log $link_old = new stdClass(); $link_old->url = $link->url; $link_old->title = $link->title; $link_old->content = $link->content; $link_old->tags = $link->tags; $link_old->status = $link->status; $link_old->sub_id = $link->sub_id; $link->read_content_type_buttons($_POST['type']); $link->sub_id = intval($_POST['sub_id']); if ($link->sub_id != $link_old->sub_id) { $link->sub_changed = true; // To force to delete old statuses with another origin } if ($current_user->admin || $current_user->user_level == 'blogger' || SitesMgr::is_owner()) { if (!empty($_POST['url'])) { $link->url = clean_input_url($_POST['url']); } if ($_POST['thumb_delete']) { $link->delete_thumb(); } if ($_POST['uri_update']) { $link->get_uri(); } if ($_POST['thumb_get']) { $link->get_thumb(); } elseif (!empty($_POST['thumb_url'])) { $url = clean_input_url($_POST['thumb_url']); $link->get_thumb(false, $url); } } $link->title = $_POST['title']; $link->content = $_POST['bodytext']; $link->tags = tags_normalize_string($_POST['tags']); $errors = link_edit_errors($link); // change the status if ($_POST['status'] != $link->status && ($_POST['status'] == 'autodiscard' || $current_user->admin || SitesMgr::is_owner()) && preg_match('/^[a-z]{4,}$/', $_POST['status']) && (!$link->is_discarded() || $current_user->admin || SitesMgr::is_owner())) { if (preg_match('/discard|abuse|duplicated|autodiscard/', $_POST['status'])) { // Insert a log entry if the link has been manually discarded $insert_discard_log = true; } $link->status = $_POST['status']; } if (!$errors) { if (empty($link->uri)) { $link->get_uri(); } // Check the blog_id $blog_id = Blog::find_blog($link->url, $link->id); if ($blog_id > 0 && $blog_id != $link->blog) { $link->blog = $blog_id; } $db->transaction(); $link->store(); // Disabled table tags // tags_insert_string($link->id, $dblang, $link->tags, $link->date); // Insert edit log/event if the link it's newer than 15 days if ($globals['now'] - $link->date < 86400 * 15) { if ($insert_discard_log) { // Insert always a link and discard event if the status has been changed to discard Log::insert('link_discard', $link->id, $current_user->user_id); if ($link->author == $current_user->user_id) { // Don't save edit log if it's discarded by an admin Log::insert('link_edit', $link->id, $current_user->user_id); } } elseif ($link->votes > 0) { Log::conditional_insert('link_edit', $link->id, $current_user->user_id, 60, serialize($link_old)); } } // Check this one is a draft, allows the user to save and send it to the queue if ($link->votes == 0 && $link->status != 'queued' && $link->author == $current_user->user_id) { $link->enqueue(); } $db->commit(); } $link->read(); $link->permalink = $link->get_permalink(); Haanga::Load('link/edit_result.html', compact('link', 'errors')); }
/** * Set a value in current user session * * @static * @access public * @param string $name new session variable name * @param mixed $value new session variable value * @throws Exception * @since 1.0.0-alpha * @version 1.0.0-alpha */ public static function set($name, $value) { if ($name == 'perm') { $msg = __('Name "perm" is reserved and cannot be used!'); Log::insert($msg, 'ERROR'); throw new Exception($msg); } static::$vars[$name] = $value; static::update(); }
/** * Audit model. */ public function audit(array $log) { $logAuditing = ['old_value' => json_encode($log['old_value']), 'new_value' => json_encode($log['new_value']), 'owner_type' => get_class($this), 'owner_id' => $this->getKey(), 'user_id' => $this->getUserId(), 'type' => $log['type'], 'created_at' => new \DateTime(), 'updated_at' => new \DateTime()]; return Log::insert($logAuditing); }
function publish($link) { global $globals, $db; //return; if (DEBUG) { return; } // Calculate votes average // it's used to calculate and check future averages $votes_avg = (double) $db->get_var("select SQL_NO_CACHE avg(vote_value) from votes, users where vote_type='links' AND vote_link_id={$link->id} and vote_user_id > 0 and vote_value > 0 and vote_user_id = user_id and user_level !='disabled'"); if ($votes_avg < $globals['users_karma_avg']) { $link->votes_avg = max($votes_avg, $globals['users_karma_avg'] * 0.97); } else { $link->votes_avg = $votes_avg; } $link->status = 'published'; $link->date = $link->published_date = time(); $db->query("update links set link_status='published', link_date=now(), link_votes_avg={$link->votes_avg} where link_id={$link->id}"); SitesMgr::deploy($link); // Increase user's karma $user = new User($link->author); if ($user->read) { $user->add_karma($globals['instant_karma_per_published'], _('noticia publicada')); } // Add the publish event/log Log::insert('link_publish', $link->id, $link->author); $link->annotation .= _('publicación') . "<br/>"; $link->save_annotation('link-karma'); // Publish to all sub sites: this and children who import the link category $my_id = SitesMgr::my_id(); // Get all sites that are "children" and try to post links // And that "import" the link->category $sites = array_intersect(SitesMgr::get_children($my_id), SitesMgr::get_receivers($link->category)); // Add my own $sites[] = $my_id; foreach ($sites as $s) { $server_name = SitesMgr::get_info($s)->server_name; syslog(LOG_INFO, "Meneame, calling: " . dirname(__FILE__) . "/post_link.php {$server_name} {$link->id}"); passthru(dirname(__FILE__) . "/post_link.php {$server_name} {$link->id}"); } }
function store($full = true) { global $db, $current_user, $globals; if (!$this->date) { $this->date = $globals['now']; } $comment_content = $db->escape($this->normalize_content()); if ($this->type == 'admin') { $comment_type = 'admin'; } else { $comment_type = 'normal'; } $db->transaction(); if ($this->id === 0) { $this->ip = $db->escape($globals['user_ip']); $this->ip_int = $db->escape($globals['user_ip_int']); $previous = $db->get_var("select count(*) from comments where comment_link_id={$this->link} FOR UPDATE"); if (!$previous > 0 && $previous !== '0') { syslog(LOG_INFO, "Failed to assign order to comment {$this->id} in insert"); $this->order = 0; } else { $this->order = intval($previous) + 1; } $r = $db->query("INSERT INTO comments (comment_user_id, comment_link_id, comment_type, comment_karma, comment_ip_int, comment_ip, comment_date, comment_randkey, comment_content, comment_order) VALUES ({$this->author}, {$this->link}, '{$comment_type}', {$this->karma}, {$this->ip_int}, '{$this->ip}', FROM_UNIXTIME({$this->date}), {$this->randkey}, '{$comment_content}', {$this->order})"); $new_id = $db->insert_id; if ($r) { $this->id = $new_id; // Insert comment_new event into logs if ($full) { Log::insert('comment_new', $this->id, $current_user->user_id); } } } else { $r = $db->query("UPDATE comments set comment_user_id={$this->author}, comment_link_id={$this->link}, comment_type='{$comment_type}', comment_karma={$this->karma}, comment_date=FROM_UNIXTIME({$this->date}), comment_modified=now(), comment_randkey={$this->randkey}, comment_content='{$comment_content}' WHERE comment_id={$this->id}"); if ($r) { // Insert comment_new event into logs if ($full) { if ($globals['now'] - $this->date < 86400) { Log::conditional_insert('comment_edit', $this->id, $current_user->user_id, 60); } $this->update_order(); } } } if (!$r) { syslog(LOG_INFO, "Error storing comment {$this->id}"); $db->rollback(); return false; } if ($full) { $this->update_conversation(); } // Check we got a good order value if (!$this->order) { syslog(LOG_INFO, "Trying to assign order to comment {$this->id} after commit"); $this->update_order(); } $db->commit(); return true; }
function do_register2() { global $db, $current_user, $globals; if (!ts_is_human()) { register_error(_('el código de seguridad no es correcto')); return; } if (!check_user_fields()) { return; } $username = clean_input_string(trim($_POST['username'])); // sanity check $dbusername = $db->escape($username); // sanity check $password = UserAuth::hash(trim($_POST['password'])); $email = clean_input_string(trim($_POST['email'])); // sanity check $dbemail = $db->escape($email); // sanity check $user_ip = $globals['form_user_ip']; if (!user_exists($username)) { if ($db->query("INSERT INTO users (user_login, user_login_register, user_email, user_email_register, user_pass, user_date, user_ip) VALUES ('{$dbusername}', '{$dbusername}', '{$dbemail}', '{$dbemail}', '{$password}', now(), '{$user_ip}')")) { echo '<fieldset>' . "\n"; echo '<legend><span class="sign">' . _("registro de usuario") . '</span></legend>' . "\n"; $user = new User(); $user->username = $username; if (!$user->read()) { register_error(_('error insertando usuario en la base de datos')); } else { require_once mnminclude . 'mail.php'; $sent = send_recover_mail($user); $globals['user_ip'] = $user_ip; //we force to insert de log with the same IP as the form Log::insert('user_new', $user->id, $user->id); } echo '</fieldset>' . "\n"; } else { register_error(_("error insertando usuario en la base de datos")); } } else { register_error(_("el usuario ya existe")); } }
/** * @access public * @param string $message * @param integer $code * @param \Exception $previous * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function __construct($message = '', $code = 0, \Exception $previous = NULL) { Log::insert($message, Log::ERROR); parent::__construct($message, $code, $previous); }
/** * Constructor. * * @access public * @since 1.0.0-alpha * @version 1.0.0-alpha */ public function __construct() { Log::insert('Response object initialized!'); }
/** * Checks if particular action for current controller exist. * * @static * @param string $sActionName * @return boolean * @throws Exception\Router * @since 1.0.0-alpha * @version 1.0.0-alpha */ private static function checkActionExistance($sActionName) { $sFullActionName = 'action' . $sActionName; if (method_exists(static::$controllerName, $sFullActionName)) { static::$action = $sFullActionName; return TRUE; } $sMsg = 'Action "' . $sFullActionName . '" in "' . static::$controllerName . '" controller does not exist.'; Log::insert($sMsg, 'ERROR'); if (Config::get('base.mode') == 'development') { throw new Exception\Router($sMsg); } else { return FALSE; } }
function myJobReviewed($jobid, $msg = '') { if ($jobid <= 0) { return; } Zend_Loader::loadClass('Job'); Zend_Loader::loadClass('Log'); if (empty($msg)) { $msg = $this->view->translate->_("Bacula Job Reviewed. See Webacula LOGBOOK_ID=" . $this->id_insert) . '.'; } // read Comment from Job table $table = new Job(); $where = $table->getAdapter()->quoteInto('JobId = ?', $jobid); $row = $table->fetchRow($where); if ($row) { $msg_job = $msg . "\n" . $row->comment; } else { $msg_job = $msg; } // change Job table $data = array('Reviewed' => 1, 'Comment' => $msg_job); $where = $table->getAdapter()->quoteInto('JobId = ?', $jobid); $res = $table->update($data, $where); if ($res) { $email = new MyClass_SendEmail(); // $from_email, $from_name, $to_email, $to_name, $subj, $body $email->mySendEmail($this->view->config->webacula->email->from, $this->view->translate->_('Webacula Logbook'), $this->view->config->webacula->email->to_admin, $this->view->translate->_('Webacula admin'), $this->view->translate->_('Bacula Job Reviewed'), $this->view->translate->_('Job Id') . " " . $jobid . "\n" . $msg_job); } unset($table); // add record in Log table $table = new Log(); $data = array('JobId' => $jobid, 'Time' => date("Y-m-d H:i:s", time()), 'LogText' => $msg); $table->insert($data); }
function store($full = true) { global $db, $current_user, $globals; if (!$this->date) { $this->date = time(); } $post_author = $this->author; $post_src = $this->src; $post_karma = $this->karma; $post_date = $this->date; $post_randkey = $this->randkey; $post_content = $db->escape($this->normalize_content()); if ($this->id === 0) { $this->ip = $globals['user_ip_int']; $r = $db->query("INSERT INTO posts (post_user_id, post_karma, post_ip_int, post_date, post_randkey, post_src, post_content) VALUES ({$post_author}, {$post_karma}, {$this->ip}, FROM_UNIXTIME({$post_date}), {$post_randkey}, '{$post_src}', '{$post_content}')"); $this->id = $db->insert_id; if ($this->id > 0) { $this->insert_vote($post_author); // Insert post_new event into logs if ($full) { Log::insert('post_new', $this->id, $post_author); } } } else { $r = $db->query("UPDATE posts set post_user_id={$post_author}, post_karma={$post_karma}, post_date=FROM_UNIXTIME({$post_date}), post_randkey={$post_randkey}, post_content='{$post_content}' WHERE post_id={$this->id}"); // Insert post_new event into logs if ($r && $full) { Log::conditional_insert('post_edit', $this->id, $post_author, 30); } } if ($r && $full) { $this->update_conversation(); } }
function do_login() { global $current_user, $globals; $form_ip_check = check_form_auth_ip(); $previous_login_failed = Log::get_date('login_failed', $globals['form_user_ip_int'], 0, 300); // Show menéame intro only if first try and the there were not previous logins if (!$globals['mobile'] && $previous_login_failed < 3 && empty($_POST["processlogin"]) && empty($_COOKIE['u'])) { echo '<div class="faq wideonly" style="float:right; width:55%; margin-top: 10px;">' . "\n"; // Only prints if the user was redirected from submit.php if (!empty($_REQUEST['return']) && preg_match('/submit\\.php/', $_REQUEST['return'])) { echo '<p style="border:1px solid #FF9400; font-size:1.3em; background:#FEFBEA; font-weight:bold; padding:0.5em 1em;">Para enviar una historia debes ser un usuario registrado</p>' . "\n"; } echo '<h3>' . _('¿Qué es menéame?') . '</h3>' . "\n"; echo '<p>' . _('Es un sitio que te permite enviar una historia que será revisada por todos y será promovida, o no, a la página principal. Cuando un usuario envía una historia ésta queda en la <a href="shakeit.php">cola de pendientes</a> hasta que reúne los votos suficientes para ser promovida a la página principal') . '.</p>' . "\n"; echo '<h3>' . _('¿Todavía no eres usuario de menéame?') . '</h3>' . "\n"; echo '<p>' . _('Como usuario registrado podrás, entre otras cosas') . ':</p>' . "\n"; echo '<ul style="margin-left: 1.5em">' . "\n"; echo '<li>' . "\n"; echo '<strong>' . _('Enviar historias') . '</strong><br />' . "\n"; echo '<p>' . _('Una vez registrado puedes enviar las historias que consideres interesantes para la comunidad. Si tienes algún tipo de duda sobre que tipo de historias puedes enviar revisa nuestras <a href="faq-es.php">preguntas frecuentes sobre menéame</a>') . '.</p>' . "\n"; echo '</li>' . "\n"; echo '<li>' . "\n"; echo '<strong>' . _('Escribir comentarios') . '</strong><br />' . "\n"; echo '<p>' . _('Puedes escribir tu opinión sobre las historias enviadas a menéame mediante comentarios de texto. También puedes votar positivamente aquellos comentarios ingeniosos, divertidos o interesantes y negativamente aquellos que consideres inoportunos') . '.</p>' . "\n"; echo '</li>' . "\n"; echo '<li>' . "\n"; echo '<strong>' . _('Perfil de usuario') . '</strong><br />' . "\n"; echo '<p>' . _('Toda tu información como usuario está disponible desde la página de tu perfil. También puedes subir una imagen que representará a tu usuario en menéame. Incluso es posible compartir los ingresos publicitarios de Menéame, solo tienes que introducir el código de tu cuenta Google Adsense desde tu perfil') . '.</p>' . "\n"; echo '</li>' . "\n"; echo '<li>' . "\n"; echo '<strong>' . _('Chatear en tiempo real desde la fisgona') . '</strong><br />' . "\n"; echo '<p>' . _('Gracias a la <a href="sneak.php">fisgona</a> puedes ver en tiempo real toda la actividad de menéame. Además como usuario registrado podrás chatear con mucha más gente de la comunidad menéame') . '</p>' . "\n"; echo '</li>' . "\n"; echo '</ul>' . "\n"; echo '<h3><a href="register.php" style="color:#FF6400; text-decoration:underline; display:block; width:8em; text-align:center; margin:0 auto; padding:0.5em 1em; border:3px double #FFE2C5; background:#FFF3E8;">Regístrate ahora</a></h3>' . "\n"; echo '</div>' . "\n"; echo '<div class="genericform" style="float:left; width:40%; margin: 0">' . "\n"; } else { echo '<div class="genericform" style="float:auto;">' . "\n"; } echo '<form action="' . get_auth_link() . 'login.php" id="thisform" method="post">' . "\n"; if ($_POST["processlogin"] == 1) { // Check the IP, otherwise redirect if (!$form_ip_check) { header('HTTP/1.1 303 Load'); header("Location: http://" . $_COOKIE['return_site'] . $globals['base_url'] . "login.php"); die; } $username = clean_input_string(trim($_POST['username'])); $password = trim($_POST['password']); // Check form if (($previous_login_failed > 2 || $globals['captcha_first_login'] == true && !UserAuth::user_cookie_data()) && !ts_is_human()) { Log::insert('login_failed', $globals['form_user_ip_int'], 0); recover_error(_('el código de seguridad no es correcto') . " ({$previous_login_failed})"); } elseif (strlen($password) > 0 && $current_user->Authenticate($username, $password, $_POST['persistent']) == false) { Log::insert('login_failed', $globals['form_user_ip_int'], 0); $previous_login_failed++; recover_error(_('usuario o email inexistente, sin validar, o clave incorrecta') . " ({$previous_login_failed})"); } else { UserAuth::check_clon_from_cookies(); // If the user is authenticating from a mobile device, keep her in the standard version if ($globals['mobile']) { setcookie('nomobile', '1', 0, $globals['base_url'], UserAuth::domain()); } header('HTTP/1.1 303 Load'); if (!empty($_REQUEST['return'])) { header('Location: http://' . $_COOKIE['return_site'] . $_REQUEST['return']); } else { header('Location: http://' . $_COOKIE['return_site'] . $globals['base_url']); } die; } } echo '<fieldset>' . "\n"; echo '<legend><span class="sign">' . _('usuario y contraseña') . '</span></legend>' . "\n"; echo '<p><label for="name">' . _('usuario o email') . ':</label><br />' . "\n"; echo '<input type="text" name="username" size="25" tabindex="1" id="name" value="' . htmlentities($username) . '" /></p>' . "\n"; echo '<p><label for="password">' . _('clave') . ':</label><br />' . "\n"; echo '<input type="password" name="password" id="password" size="25" tabindex="2"/></p>' . "\n"; echo '<p><label for="remember">' . _('recuérdame') . ': </label><input type="checkbox" name="persistent" id="remember" tabindex="3"/></p>' . "\n"; // Print captcha if ($previous_login_failed > 2 || $globals['captcha_first_login'] == true && !UserAuth::user_cookie_data()) { ts_print_form(); } get_form_auth_ip(); echo '<p><input type="submit" value="login" class="button" tabindex="4" /></p>' . "\n"; print_oauth_icons($_REQUEST['return']); echo '<input type="hidden" name="processlogin" value="1"/>' . "\n"; echo '<input type="hidden" name="return" value="' . htmlspecialchars($_REQUEST['return']) . '"/>' . "\n"; echo '</fieldset>' . "\n"; echo '</form>' . "\n"; echo '<div class="recoverpass" style="text-align:center"><h4><a href="login.php?op=recover">' . _('¿has olvidado la contraseña?') . '</a></h4></div>' . "\n"; echo '</div>' . "\n"; echo '<br/> '; }
function depublish($site_id) { // send back to queue links with too many negatives global $db, $globals; $days = 4; echo "STARTING depublish for {$site_id}\n"; $site_info = SitesMgr::get_info($site_id); $links = $db->get_col("select SQL_NO_CACHE link_id as id from links, sub_statuses where id = {$site_id} and status = 'published' and date > date_sub(now(), interval {$days} day) and date < date_sub(now(), interval 14 minute) and link = link_id and link_negatives > link_votes / 5"); if ($links) { $votes_clicks = $db->get_col("select SQL_NO_CACHE link_votes/counter from links, sub_statuses, link_clicks where sub_statuses.id = {$site_id} and status = 'published' and date > date_sub(now(), interval {$days} day) and link = link_id and link_clicks.id = link"); sort($votes_clicks); foreach ($links as $link) { $l = Link::from_db($link); $vc = $l->votes / $l->clicks; $prob = cdf($votes_clicks, $vc); // Count only those votes with karma > 6 to avoid abuses with new accounts with new accounts $negatives = (int) $db->get_var("select SQL_NO_CACHE sum(user_karma) from votes, users where vote_type='links' and vote_link_id={$l->id} and vote_date > from_unixtime({$l->date}) and vote_date > date_sub(now(), interval 24 hour) and vote_value < 0 and vote_user_id > 0 and user_id = vote_user_id and user_karma > " . $globals['depublish_negative_karma']); $positives = (int) $db->get_var("select SQL_NO_CACHE sum(user_karma) from votes, users where vote_type='links' and vote_link_id={$l->id} and vote_date > from_unixtime({$l->date}) and vote_value > 0 and vote_date > date_sub(now(), interval 24 hour) and vote_user_id > 0 and user_id = vote_user_id and user_karma > " . $globals['depublish_positive_karma']); echo "Candidate {$l->uri}\n karma: {$l->sub_karma} ({$l->karma}) negative karma: {$negatives} positive karma: {$positives}\n"; // Adjust positives to the probability of votes/clicks $c = 1 + (1 - $prob) * 0.5; $positives = $positives * $c; echo " probability: {$prob} New positives: {$positives} ({$c})\n"; if ($negatives > 10 && $negatives > $c * $l->sub_karma / 6 && $l->negatives > $c * $l->votes / 6 && $l->negatives > 5 && ($negatives > $positives || $negatives > $c * $l->sub_karma / 2 && $negatives > $positives / 2)) { echo "Queued again: {$l->id} negative karma: {$negatives} positive karma: {$positives}\n"; $karma_old = $l->sub_karma; $karma_new = intval($l->sub_karma / $globals['depublish_karma_divisor']); $l->status = 'queued'; $l->sub_karma = $l->karma = $karma_new; $db->query("update links set link_status='queued', link_date = link_sent_date, link_karma={$karma_new} where link_id = {$l->id}"); SitesMgr::deploy($l); // Add an annotation to show it in the logs $l->karma_old = $karma_old; $l->karma = $karma_new; $l->annotation = _('Retirada de portada'); $l->save_annotation('link-karma'); Log::insert('link_depublished', $l->id, $l->author); if (!$site_info->sub) { // Add the discard to log/event $user = new User($l->author); if ($user->read) { echo "{$user->username}: {$user->karma}\n"; $user->add_karma(-$globals['instant_karma_per_depublished'], _('Retirada de portada')); } // Increase karma to users that voted negative $ids = $db->get_col("select vote_user_id from votes where vote_type = 'links' and vote_link_id = {$l->id} and vote_user_id > 0 and vote_value < 0"); foreach ($ids as $id) { $u = new User($id); if ($u->read) { // Avoid abuse of users voting negative just to get more karma $voted = $db->get_var("select count(*) from logs where log_type = 'user_depublished_vote' and log_user_id = {$id} and log_date > date_sub(now(), interval 48 hour)"); if ($voted < 5) { $u->add_karma(0.2, _('Negativo a retirada de portada')); Log::insert('user_depublished_vote', $l->id, $id); } } } } /*********** * TODO: call for every site (as in promote) if ($globals['twitter_token'] || $globals['jaiku_user']) { if ($globals['url_shortener']) { $short_url = $l->get_short_permalink(); } else { $short_url = fon_gs($l->get_permalink()); } $text = _('Retirada de portada') . ': ' . $l->title; if ($globals['twitter_user'] && $globals['twitter_token']) { twitter_post($text, $short_url); } if ($globals['jaiku_user'] && $globals['jaiku_key']) { jaiku_post($text, $short_url); } } *******/ } } } }
function publish($site, $link) { global $globals, $db; $site_info = SitesMgr::get_info($site); if (DEBUG) { return; } // Calculate votes average // it's used to calculate and check future averages $votes_avg = (double) $db->get_var("select SQL_NO_CACHE avg(vote_value) from votes, users where vote_type='links' AND vote_link_id={$link->id} and vote_user_id > 0 and vote_value > 0 and vote_user_id = user_id and user_level !='disabled'"); if ($votes_avg < $globals['users_karma_avg']) { $link->votes_avg = max($votes_avg, $globals['users_karma_avg'] * 0.97); } else { $link->votes_avg = $votes_avg; } $link->status = 'published'; $link->date = $link->published_date = time(); $db->transaction(); $db->query("update links set link_status='published', link_date=now(), link_votes_avg={$link->votes_avg} where link_id={$link->id}"); SitesMgr::deploy($link); $db->commit(); // Increase user's karma $user = new User($link->author); if ($site_info->sub) { $karma_bonus = $globals['instant_karma_per_published'] / 10; // currently these published don't receive extra karma $log = false; } else { $karma_bonus = $globals['instant_karma_per_published']; $log = _('noticia publicada'); } if ($user->read) { $user->add_karma($karma_bonus, $log); } // Add the publish event/log Log::insert('link_publish', $link->id, $link->author); $link->annotation .= _('publicación') . "<br/>"; $link->save_annotation('link-karma'); // read twitter and facebok configuration from subs' extended info if (!$site_info->sub || $site_info->visible) { // Only post if it's not a sub or it's visible (dmnm in mnm, f.e.) syslog(LOG_INFO, "Meneame, calling: " . dirname(__FILE__) . "/post_link.php {$site_info->name} {$link->id}"); passthru(dirname(__FILE__) . "/post_link.php {$site_info->name} {$link->id} published"); } // Publish the links of the source subs if ($site_info->meta && ($senders = SitesMgr::get_senders($site))) { if (in_array($link->sub_id, $senders) && $link->sub_status_origen == 'queued') { syslog(LOG_INFO, "Meneame, publishing for sender {$link->sub_name} ({$link->sub_id})"); // "Simulate" the other site, needed for deploy SitesMgr::__init($link->sub_id); publish($link->sub_id, $link); SitesMgr::__init($site); // Back to the original site } } return; }