Esempio n. 1
0
function escape_nickname($t)
{
    $t = preg_replace("/[^a-zA-Z0-9-\\[\\]\\*\\ \\+=\\._\\|]/", "", $t);
    $t = substr($t, 0, 15);
    $t = escape($t, 'string');
    return $t;
}
Esempio n. 2
0
function login($dirty_email, $dirty_password)
{
    $email = escape($dirty_email);
    $password = escape($dirty_password);
    if (!validate_email($email)) {
        echo "login-invalid-email";
        return;
    }
    if (!validate_password($password)) {
        echo "login-invalid-password";
        return;
    }
    $account_id = account_id_from_email($email);
    if ($account_id == -1) {
        echo "DEBUG: email or password invalid";
        return;
    }
    if (correct_password($account_id, $password) == false) {
        echo "DEBUG: email or password invalid";
        return;
    }
    session_regenerate_id();
    fresh_logon($account_id);
    $username = username_from_account_id($account_id);
    setcookie('LOGGED_IN', $username, time() + 3600);
    echo "login-success";
}
Esempio n. 3
0
function pingWeblogs($name, $url, $server)
{
    global $Paths;
    if (strpos($server, "http://") === false) {
        $server = "http://" . $server;
    }
    $server = parse_url($server);
    if ($server['path'] == "") {
        $server['path'] = "/";
    }
    if ($server['port'] == "") {
        $server['port'] = "80";
    }
    printf("<p><b>%s:%s%s</b>:<br />", $server['host'], $server['port'], $server['path']);
    flush();
    $client = new xmlrpc_client($server['path'], $server['host'], $server['port']);
    $message = new xmlrpcmsg("weblogUpdates.ping", array(new xmlrpcval($name), new xmlrpcval($url)));
    $result = $client->send($message);
    if (!$result || $result->faultCode()) {
        echo "<br />Pivot says: could not send ping. Check if you set the server address correctly, or else the server may be temporarily down. This happens sometimes, and if this error occurs out of the blue, it's likely that it will go away in a few hours or days. <br /></p>";
        echo "<!-- \n";
        print_r($result);
        echo "\n -->\n\n\n";
        return false;
    }
    $msg = $result->serialize();
    $msg = preg_replace('#.*<name>message</name>[^<]*<value>(.*?)</value>.*#si', '$1', $msg);
    // Stripping off any tags in the message value - typically the string element
    $msg = strip_tags($msg);
    $msg = escape($msg);
    echo "Server said: <i>'{$msg}'</i><br /></p>";
    return true;
}
Esempio n. 4
0
 public function login()
 {
     if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
         if (strtolower($_SESSION['validCode']) != strtolower(trim($_POST['validCode']))) {
             //记录日志
             $logInfo['success'] = 0;
             $logInfo['password'] = '';
             $user_loginlog_db->insert($logInfo);
             //echo SITE_NAME.':验证码输入错误,<a href="login.php?user='******'email'].'">返回重新登录</a>';
             echo '<script>window.location.href=\'?user='******'email'] . '&error=errorcode\';</script>';
             exit;
         } else {
             $userObj = bpBase::loadAppCLass('userObj', 'user');
             $rt = $userObj->adminLoginWithEmail($_POST['email'], $_POST['password']);
             if ($rt > 0) {
                 //记录日志
                 $logInfo['success'] = 1;
                 $logInfo['password'] = '';
                 $user_loginlog_db->insert($logInfo);
                 //
                 if (!isah()) {
                     $thisUser = $userObj->getUserByUID($rt);
                     setcookie('jsusername', escape($thisUser->username), SYS_TIME + 2592000, '/', DOMAIN_ROOT);
                     $r = setcookie('autousername', $thisUser->username, SYS_TIME + 2592000, '/', DOMAIN_ROOT);
                 } else {
                     if (isset($_COOKIE['jsusername'])) {
                         setcookie('jsusername', '', 0);
                         setcookie('jsusername', '', 0, '/', DOMAIN_ROOT);
                         setcookie('jsusername', '', 0, '/', $_SERVER['HTTP_HOST']);
                     }
                 }
                 delCache('rigthsOf' . $rt);
                 delCache('citysOf' . $rt);
                 $_SESSION['autoAdminUid'] = $rt;
                 //session_regenerate_id();
                 $_SESSION['cmsuid'] = $rt;
                 //session_regenerate_id();
                 //echo '<span style="font-size:12px;">登录成功,正在转向...如果您的浏览器不能自动跳转,<a href="index.php" style="font-size:12px;">请点击</a>';
                 echo '<script>window.location.href=\'index.php\';</script></span>';
                 exit;
             } else {
                 //记录日志
                 $logInfo['success'] = 0;
                 $user_loginlog_db->insert($logInfo);
                 //
                 $_SESSION['autoAdminUid'] = null;
                 unset($_SESSION['autoAdminUid']);
                 //echo SITE_NAME.':登录失败,<a href="login.php?user='******'email'].'">返回重新登录</a>';
                 echo '<script>window.location.href=\'?user='******'email'] . '&error=notmatch\';</script>';
                 exit;
             }
         }
     } else {
         $m = empty($m) ? ROUTE_MODEL : $m;
         if (empty($m)) {
             return false;
         }
         include ABS_PATH . MANAGE_DIR . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $m . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'login.tpl.php';
     }
 }
/**
 * Removes HTML tags & encodes HTML entities.
 *
 * @param string $string_
 * @param string $ignoreTags_
 * @param string $charset_
 * @param bool $escape_
 * @param integer $type_
 *
 * @return string
 */
function strip($string_, $ignoreTags_ = null, $charset_ = null, $escape_ = true, $type_ = ENT_XHTML, $flags_ = ENT_QUOTES)
{
    if ($escape_) {
        return escape(strip_tags($string_, $ignoreTags_), $charset_, $type_, $flags_);
    }
    return strip_tags($string_, $ignoreTags_);
}
Esempio n. 6
0
function submitPurchase($purchase_id, $purchase)
{
    $purchase_id = escape($purchase_id);
    //make sure not already submitted
    $result = mysql_query("SELECT status, club_id, instance_id FROM purchase_order WHERE id = '{$purchase_id}'");
    if ($row = mysql_fetch_array($result)) {
        if ($row[0] != 0) {
            return -1;
        } else {
            $purchase_name = $row[1];
            $instance_id = $row[2];
        }
    } else {
        return -2;
    }
    $error = customSave($instance_id, $purchase);
    if ($error !== TRUE) {
        return -2;
    }
    //create the PDF
    $filename = customSubmit($instance_id, "Puchase Order", $purchase_name);
    if ($filename === -1) {
        //if error during PDF generation
        return -2;
    } else {
        if ($filename === -2) {
            //if incomplete
            return -3;
        }
    }
    mysql_query("UPDATE purchase_order SET status='1', filename='{$filename}' WHERE id = '{$purchase_id}'");
    return 0;
}
Esempio n. 7
0
function statusDue($overdue = false)
{
    global $db;
    $result = $db->query("SELECT service_id, v FROM service_params WHERE k = 'due'");
    $dueArray = array();
    while ($row = $result->fetch_array()) {
        if (empty($row[1]) || $row[1] == "N/A") {
            continue;
        }
        $service_id = escape($row[0]);
        $due = strtotime($row[1]);
        if ($overdue && time() > $due || !$overdue && time() <= $due && time() > $due - 3600 * 24 * 12) {
            $inner_result = $db->query("SELECT services.account_id, services.name, accounts.email, accounts.name FROM services LEFT JOIN accounts ON accounts.id = services.account_id WHERE services.id = '{$service_id}'");
            if ($inner_row = $inner_result->fetch_array()) {
                $price = getServiceParam($service_id, 'price');
                if ($price === false) {
                    $price = "Unknown";
                }
                $dueArray[] = array('due' => $due, 'service_id' => $service_id, 'account_id' => $inner_row[0], 'service' => $inner_row[1], 'email' => $inner_row[2], 'name' => $inner_row[3], 'price' => $price);
            }
            $inner_result->close();
        }
    }
    $result->close();
    usort($dueArray, "statusDueCompare");
    return $dueArray;
}
Esempio n. 8
0
function do_entry($file, $yearmonth, $day)
{
    global $months;
    global $absoluteurl;
    global $topdir;
    global $firstdate;
    $s = "";
    $monthnum = substr($yearmonth, 4, 2);
    $year = substr($yearmonth, 0, 4);
    // $title = "$months[$monthnum] $day, $year";
    if (!tags_match($file)) {
        return "";
    }
    $title = sprintf("%04d-%02d-%02d", $year, $monthnum, $day);
    $intitle = get_entrytitle($yearmonth, $day);
    $mtime = filemtime($file);
    if ($intitle) {
        $title = $intitle;
    }
    $s .= "    <item>\n" . "      <title>{$title}</title>\n" . "      <pubDate>" . date("r", $mtime) . "</pubDate>\n" . "      <link>{$absoluteurl}/{$topdir}/?m={$yearmonth}#{$day}</link>\n" . "      <guid isPermaLink=\"true\">{$absoluteurl}/{$topdir}/?m={$yearmonth}#{$day}</guid>\n" . "      <description>";
    $entrylines = do_entrycontent($yearmonth, $day);
    if (preg_match('@^\\s*<b>.*</b>\\s*$@', $entrylines[0])) {
        $entrylines[0] = "";
    }
    foreach ($entrylines as $eline) {
        $s .= escape($eline);
    }
    $s .= "      </description>\n" . "    </item>\n";
    return $s;
}
Esempio n. 9
0
 public function __construct(ApiList $list)
 {
     //Loop through each product name
     foreach ($list->getProdName() as $prodName) {
         $getInfoData = ConfigURL::getURL(ApiInfo::$name, $prodName);
         //Check for any errors and store them in $_errors array
         if (isset($getInfoData['error'])) {
             $this->_errors[$prodName] = $getInfoData['error'];
             continue;
         }
         //Initialize $data array
         $data = array();
         //Loop through the product info and store it in the data array.
         //In the case of suppliers, call the sanitize escape function.
         foreach ($getInfoData as $prodKey) {
             foreach ($prodKey as $name => $value) {
                 switch ($name) {
                     case 'suppliers':
                         $data[$name] = escape(implode(', ', $value));
                         break;
                     default:
                         $data[$name] = $value;
                         break;
                 }
             }
         }
         //Store all the data in $_productInfo
         $this->_productInfo[$prodName] = $data;
     }
 }
Esempio n. 10
0
 /**
  * @param string $label
  * @param array $attributes
  */
 public function __construct($label, array $attributes = [])
 {
     if (is_string($label)) {
         $label = escape(t($label, [], ['scope' => 'button']));
     }
     parent::__construct('div', $attributes + [self::INNER_HTML => $label]);
 }
Esempio n. 11
0
 /**
  * The element is created with the type "button" and an union of the provided attributes and
  * the following values:
  *
  * - `type`: "button"
  * - {@link INNER_HTML}: The translated and escaped label. The label is translated with
  * the "button" scope. If an {@link HTMLString} instance is provided, it is used as is.
  *
  * @param string $label Label of the button (inner text).
  * @param array $attributes Optional attributes used to create the element.
  */
 public function __construct($label, array $attributes = [])
 {
     if (!$label instanceof HTMLString) {
         $label = escape(t($label, [], ['scope' => 'button']));
     }
     parent::__construct('button', $attributes + ['type' => 'button', self::INNER_HTML => $label]);
 }
Esempio n. 12
0
function CreateGroup($user)
{
    if (isset($_POST["group_title"])) {
        $title = escape($_POST["group_title"]);
        $body = escape($_POST["group_body"]);
        if (isset($_POST["group_private"])) {
            $is_private = 1;
        } else {
            $is_private = 0;
        }
        $time = time();
        $query = "INSERT INTO groups (group_name,description,owner_id,time,is_private)";
        $query .= " VALUES ('{$title}','{$body}',{$user},{$time},{$is_private})";
        query($query);
        //tag processor
        $tags = escape($_POST["group_tags"]);
        if (!empty($tags)) {
            $query = "SELECT group_id FROM groups WHERE time= {$time}";
            //getting id of last added post
            $result = query($query);
            $row = mysqli_fetch_array($result);
            AddTag($tags, $row["group_id"], "group");
        }
        ?>
    <div class="alert alert-success alert-dismissible fade in">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <span class="glyphicon glyphicon-ok glyphicon-pad"></span> Group successfully created!
    </div>
<?php 
    }
}
Esempio n. 13
0
function getSettings($set, $account)
{
    global $dz, $apiMode;
    // The built setting string:
    $settingString = '';
    // For each one:
    foreach ($set as $setting) {
        if ($settingString != '') {
            $settingString .= ',';
        }
        $settingString .= '"' . escape($setting) . '"';
    }
    // Run the query now, selecting the values from the account settings:
    $list = $dz->get_list('select `Setting`,`Value` from `' . $apiMode . '.Account.Settings` where `Account`=' . $account . ' and `Setting` in (' . $settingString . ')');
    $result = array();
    // Make it associative:
    foreach ($list as $setting) {
        $result[$setting['Setting']] = $setting['Value'];
    }
    // Any settings that were not present are set to null:
    foreach ($set as $setting) {
        // Was it added?
        if (!isset($result[$setting])) {
            // No - Add it but as a null:
            $result[$setting] = null;
        }
    }
    return $result;
}
 /**
  * Send an email with Swift library engine.
  *
  * @param array $aInfo
  * @param string $sContents
  * @param boolean $bHtmlFormat Default TRUE
  * @return integer Number of recipients who were accepted for delivery.
  */
 public function send(array $aInfo, $sContents, $bHtmlFormat = true)
 {
     // Default values
     $sFromMail = empty($aInfo['from']) ? DbConfig::getSetting('returnEmail') : $aInfo['from'];
     // Email noreply (generally noreply@yoursite.com)
     $sFromName = empty($aInfo['form_name']) ? DbConfig::getSetting('emailName') : $aInfo['form_name'];
     $sToMail = empty($aInfo['to']) ? DbConfig::getSetting('adminEmail') : $aInfo['to'];
     $sToName = empty($aInfo['to_name']) ? $sToMail : $aInfo['to_name'];
     $sSubject = $aInfo['subject'];
     // Setup the mailer
     $oTransport = \Swift_MailTransport::newInstance();
     $oMailer = \Swift_Mailer::newInstance($oTransport);
     $oMessage = \Swift_Message::newInstance()->setSubject(escape($sSubject, true))->setFrom(array(escape($sFromMail, true) => escape($sFromName, true)))->setTo(array(escape($sToMail, true) => escape($sToName, true)));
     $bHtmlFormat ? $oMessage->addPart($sContents, 'text/html') : $oMessage->setBody($sContents);
     $iResult = $oMailer->send($oMessage);
     unset($oTransport, $oMailer, $oMessage);
     /*
      * Check if Swift is able to send message, otherwise we use the traditional native PHP mail() function
      * as on some hosts config, Swift Mail doesn't work.
      */
     if (!$iResult) {
         $aData = ['from' => $sFromMail, 'to' => $sToMail, 'subject' => $sSubject, 'body' => $sContents];
         $iResult = (int) $this->phpMail($aData);
     }
     return $iResult;
 }
Esempio n. 15
0
function readFileDirectory($path)
{
    global $mysql, $getID3, $albumSongs;
    foreach (scandir($path) as $currentFile) {
        if ($currentFile == "." || $currentFile == "..") {
            continue;
        }
        $fullPath = $path . "/" . $currentFile;
        if (is_dir($fullPath)) {
            readFileDirectory($fullPath);
        } else {
            $fileExtension = pathinfo($currentFile, PATHINFO_EXTENSION);
            if ($fileExtension == "mp3" || $fileExtension == "wav" || $fileExtension == "ogg") {
                $songInfo = $getID3->analyze($fullPath);
                getid3_lib::CopyTagsToComments($songInfo);
                if (!$songInfo['comments_html']['title'][0]) {
                    $songInfo['comments_html']['title'][0] = basename($currentFile);
                }
                if ($songInfo['tags']['id3v2']['album'][0]) {
                    $albumSongs[escape($songInfo['tags']['id3v2']['album'][0])] = true;
                } else {
                    $albumSongs[escape($songInfo['comments_html']['artist'][0])] = true;
                }
                $mysql->query("INSERT INTO `songs` (`path`, `title`, `artist`, `album`, `length`) VALUES ('{$fullPath}', '" . escape($songInfo['comments_html']['title'][0]) . "', '" . escape($songInfo['comments_html']['artist'][0]) . "', '" . escape($songInfo['tags']['id3v2']['album'][0]) . "', '" . escape($songInfo['playtime_string']) . "')");
            }
        }
    }
}
Esempio n. 16
0
 public function updateCar($car)
 {
     $Id = $car->getId();
     $SiteId = toNull($car->getSiteId(), false);
     $CarBrandId = toNull($car->getCarBrandId(), false);
     $Type = toNull(escape($car->getType()), true);
     $TypeShort = toNull(escape($car->getTypeShort()), true);
     $PreviewLink = toNull(escape($car->getPreviewLink()), true);
     $DateAdded = toNull(toYYYYMMDD($car->getDateAdded()), true);
     $State = toNull(escape($car->getState()), true);
     $DateApproved = toNull(toYYYYMMDD($car->getDateApproved()), true);
     $FolderName = toNull(escape($car->getFolderName()), true);
     $PressContactId = toNull($car->getPressContactId(), false);
     $UserIdAdded = toNull($car->getUserIdAdded(), false);
     $UserIdApproved = toNull($car->getUserIdApproved(), false);
     $DetailTypeId = toNull($car->getDetailTypeId(), false);
     $DefaultPictureId = toNull($car->getDefaultPictureId(), false);
     $LRClicks = toNull($car->getLRClicks(), false);
     $HRClicks = toNull($car->getHRClicks(), false);
     $Views = toNull($car->getViews(), false);
     $ReleaseDate = toNull(escape($car->getReleaseDate()), true);
     $MovieFolder = toNull(escape($car->getMovieFolder()), true);
     $sql = "UPDATE car\n\t\t\tSET SiteId = {$SiteId},\n\t\t\tCarBrandId = {$CarBrandId},\n\t\t\tType = {$Type},\n\t\t\tTypeShort = {$TypeShort},\n\t\t\tPreviewLink = {$PreviewLink},\n\t\t\tDateAdded = {$DateAdded},\n\t\t\tState = {$State},\n\t\t\tDateApproved = {$DateApproved},\n\t\t\tFolderName = {$FolderName},\n\t\t\tPressContactId = {$PressContactId},\n\t\t\tUserIdAdded = {$UserIdAdded},\n\t\t\tUserIdApproved = {$UserIdApproved},\n\t\t\tDetailTypeId = {$DetailTypeId},\n\t\t\tDefaultPictureId = {$DefaultPictureId},\n\t\t\tLRClicks = {$LRClicks},\n\t\t\tHRClicks = {$HRClicks},\n\t\t\tViews = {$Views},\n\t\t\tReleaseDate = {$ReleaseDate},\n                        MovieFolder = {$MovieFolder}\n\t\t\tWHERE Id = {$Id}";
     if (!mysql_query($sql, $this->connectie)) {
         die('Error: ' . mysql_error());
     }
 }
Esempio n. 17
0
function UpdateCourse()
{
    if (isset($_POST['update_course'])) {
        $CID = $_GET['id'];
        //course id
        $code = escape($_POST['code']);
        $credit = $_POST['credit'];
        $semester = $_POST['semester'];
        $point = $_POST['grade'];
        global $USERID;
        if (isset($_POST['retake'])) {
            $is_retake = true;
        } else {
            $is_retake = 'NULL';
        }
        $query = "UPDATE GRADES SET course='{$code}', grade={$point}, credit={$credit}, semester={$semester}, is_retake={$is_retake}";
        $query .= " WHERE user_id= {$USERID} AND grade_id={$CID}";
        query($query);
        ?>
    <div class="alert alert-success alert-dismissible fade in">
      <button type="button" class="close" data-dismiss="alert">×</button>
      <span class="glyphicon glyphicon-thumbs-up glyphicon-pad"></span> Course successfully updated!
    </div>
  <?php 
    }
}
Esempio n. 18
0
/**
 * Formats a string for HTML display by replacing variable placeholders.
 *
 * This function replaces variable placeholders in a string with the requested values and escapes
 * the values so they can be safely displayed as HTML. It should be used on any unknown text that
 * is intended to be printed to an HTML page (especially text that may have come from untrusted
 * users, since in that case it prevents cross-site scripting and other security problems).
 *
 * @param string   $string A string containing placeholders.
 * @param string[] $args   An associative array of replacements to make. Occurrences in $string of
 *                         any key in $args are replaced with the corresponding value, after optional
 *                         sanitization and formatting. The type of sanitization and formatting
 *                         depends on the first character of the key:
 *                         - @variable: Escaped to HTML.
 *                         - *variable: Escaped to HTML and formatted as <strong>emphasized</strong> text.
 *                         - %variable: Escaped to HTML and formatted as <em>emphasized</em> text.
 *                         - !variable: Inserted as is, with no sanitization or formatting.
 *
 * @return string
 */
function format($string, array $args)
{
    // Transform arguments before inserting them.
    foreach ($args as $key => $value) {
        switch ($key[0]) {
            case '@':
                // Escaped only.
                $args[$key] = escape($value);
                break;
            case '%':
                // Escaped and emphasised.
                $value = escape($value);
                $args[$key] = '<em>' . $value . '</em>';
                break;
            case '*':
                // Escaped and strong.
                $value = escape($value);
                $args[$key] = '<strong>' . $value . '</strong>';
                break;
            case '!':
                // Pass-through.
                break;
            default:
                throw new \RuntimeException('String format type not provided.');
        }
    }
    return strtr($string, $args);
}
Esempio n. 19
0
function pageController()
{
    $data = [];
    //$data['counter'] = isset($_GET["counter"]) ? $_GET["counter"] : 0;
    $data['counter'] = inputHas('counter') ? escape(inputGet('counter')) : 0;
    return $data;
}
 public function step1()
 {
     $db_name = $this->db->real_escape_string(escape(Input::get('db-name')));
     $query = "CREATE DATABASE IF NOT EXISTS `" . $db_name . "`";
     $result = $this->db->query($query);
     if ($this->db->error != '') {
         echo $this->db->error;
         return;
     }
     $this->db->select_db($db_name);
     $table_name = $this->db->real_escape_string(escape(Input::get('db-table')));
     $query = "CREATE TABLE IF NOT EXISTS `" . $table_name . "` (id bigint(20) NOT NULL auto_increment,\n                                                                uid bigint(20),\n                                                                email varchar(100) NOT NULL,\n                                                                first_name varchar(50) NOT NULL,\n                                                                last_name varchar(50) NOT NULL,\n                                                                name varchar(100) NOT NULL,\n                                                                gender varchar(10) NOT NULL,\n                                                                dob date,\n                                                                dos date NOT NULL,\n                                                                profile_pic_link varchar(255),\n                                                                PRIMARY KEY(id),\n                                                                UNIQUE KEY(email))";
     $result = $this->db->query($query);
     if ($this->db->error != '') {
         echo $this->db->error;
         echo "<br/>Something Went Wrong!";
         return;
     }
     Session::put('db-server', Input::get('db-server'));
     Session::put('db-username', Input::get('db-username'));
     Session::put('db-password', Input::get('db-password'));
     Session::put('db-name', Input::get('db-name'));
     Session::put('db-table', Input::get('db-table'));
     Session::put('proxy-rule', Input::get('proxy-rule'));
     return 1;
 }
Esempio n. 21
0
 /**
  * @param string|Element $label Defines the content of the element. If `$label` is not
  * a {@link Element} instance it is escaped.
  * @param string $href URI for linked resource.
  * @param array $attributes Optional attributes.
  */
 public function __construct($label, $href = '#', array $attributes = [])
 {
     if (!$label instanceof HTMLStringInterface) {
         $label = escape(t($label));
     }
     parent::__construct('a', $attributes + ['href' => $href, self::INNER_HTML => $label]);
 }
Esempio n. 22
0
 protected function render_inner_html()
 {
     $html = '';
     $options = $this[self::OPTIONS];
     $value = $this['value'];
     if ($value === null) {
         $value = $this[self::DEFAULT_VALUE];
     }
     foreach ($options as $key => $option) {
         if ($option === false) {
             $html .= '<li class="divider"></li>';
             continue;
         } else {
             if ($option === null) {
                 continue;
             }
         }
         $html .= '<li' . ((string) $key === (string) $value ? ' class="active"' : '') . '>';
         if ($option instanceof Element) {
             $html .= $option;
         } else {
             $html .= '<a href="' . escape($key) . '" data-key="' . escape($key) . '">' . (is_string($option) ? escape($option) : $option) . '</a>';
         }
         $html .= '</li>';
     }
     return $html;
 }
Esempio n. 23
0
function outputCommodity($tag)
{
    global $firstCommodity, $dz;
    // Get the commodity info. Might not exist; in that case, we just respond with the parent:
    $row = $dz->get_row('select `Tag`,`Description_en`,`Name_en`,`Divisor`,`Policy`,`Root.Entities`.`Endpoint` as `Issuer`,`Root.Entities`.`Name` as `IssuerName` from `Root.Commodities` left join `Root.Entities` on `Root.Entities`.`ID` = `Root.Commodities`.`Issuer` where `Root.Commodities`.`Tag`="' . $tag . '"');
    if (!$row) {
        return false;
    }
    if ($firstCommodity) {
        $firstCommodity = false;
    } else {
        echo ',';
    }
    // Output the header:
    echo '"' . $row['Tag'] . '":{';
    $firstColumn = true;
    // For each column in the row..
    foreach ($row as $field => $value) {
        // Add commas between the columns:
        if ($firstColumn) {
            $firstColumn = false;
        } else {
            echo ',';
        }
        echo '"' . $field . '":"' . escape($value) . '"';
    }
    echo '}';
    return true;
}
Esempio n. 24
0
 public function getUserByUserNameExcludeId($account, $id)
 {
     $account = toNull(escape($account), true);
     $sql = "SELECT * FROM user WHERE account={$account} && id != {$id}";
     $resultaat = mysql_query($sql, $this->connectie);
     return mysql_num_rows($resultaat);
 }
Esempio n. 25
0
 public function authenticate(\fpoirotte\Pssht\Messages\USERAUTH\REQUEST\Base $message, \fpoirotte\Pssht\Transport $transport, array &$context)
 {
     if (!$message instanceof \fpoirotte\Pssht\Messages\USERAUTH\REQUEST\PublicKey) {
         throw new \InvalidArgumentException();
     }
     if ($message->getSignature() === null) {
         return self::AUTH_REJECT;
     }
     $logging = \Plop\Plop::getInstance();
     $reverse = gethostbyaddr($transport->getAddress());
     $algos = \fpoirotte\Pssht\Algorithms::factory();
     $cls = $algos->getClass('PublicKey', $message->getAlgorithm());
     if ($cls === null || !$this->store->exists($message->getUserName(), $message->getKey())) {
         $logging->info('Rejected public key connection from remote host "%(reverse)s" ' . 'to "%(luser)s" (unsupported key)', array('luser' => escape($message->getUserName()), 'reverse' => $reverse));
         return self::AUTH_REJECT;
     }
     $key = $cls::loadPublic(base64_encode($message->getKey()));
     $encoder = new \fpoirotte\Pssht\Wire\Encoder();
     $encoder->encodeString($context['DH']->getExchangeHash());
     $encoder->encodeBytes(chr(\fpoirotte\Pssht\Messages\USERAUTH\REQUEST\Base::getMessageId()));
     $encoder->encodeString($message->getUserName());
     $encoder->encodeString($message->getServiceName());
     $encoder->encodeString(static::getName());
     $encoder->encodeBoolean(true);
     $encoder->encodeString($message->getAlgorithm());
     $encoder->encodeString($message->getKey());
     if ($key->check($encoder->getBuffer()->get(0), $message->getSignature())) {
         $logging->info('Accepted public key connection from remote host "%(reverse)s" ' . 'to "%(luser)s" (using "%(algorithm)s" algorithm)', array('luser' => escape($message->getUserName()), 'reverse' => $reverse, 'algorithm' => escape($message->getAlgorithm())));
         return self::AUTH_ACCEPT;
     }
     $logging->info('Rejected public key connection from remote host "%(reverse)s" ' . 'to "%(luser)s" (invalid signature)', array('luser' => escape($message->getUserName()), 'reverse' => $reverse));
     return self::AUTH_REJECT;
 }
Esempio n. 26
0
function save_blog($projectUrlName, $curBlogUrlName, $newBlogName, $imgLink, $firstSnippet, $blogContents)
{
    //TODO: escape all other variables
    $eBlogContents = str_replace("\"", "'", $blogContents);
    $eBlogContents = escape($eBlogContents);
    //TODO: makes sure the escape function is doing what it is supposed to do... the \ are not showing up in the db
    $currentUser = current_account();
    if ($currentUser < 0) {
        echo '{"result": "user-not-signed-in"}';
        return;
    }
    // 1 - Get the blog num of the blog to save
    $blogNum = _getBlogNumFromNothing($projectUrlName, $curBlogUrlName, $currentUser);
    if ($blogNum == false) {
        return;
    }
    // 2 - Update the tables related to the blog the user is editing
    $updateBlogResult = _updateBlogInfo($blogNum, $imgLink, $firstSnippet);
    if ($updateBlogResult == false) {
        //probably also need to do database cleanup
        return;
    }
    $newUrlName = name_to_url_name(trim($newBlogName));
    _updateBlogHead($blogNum, $newBlogName, $newUrlName);
    //TODO: error handling
    _updateBlogContents($blogNum, $eBlogContents);
    //TODO: error handling
    echo '{"result": "blog-save-success", "new_url_name": "' . $newUrlName . '"}';
}
Esempio n. 27
0
function authenticate($force = 0)
{
    global $template;
    global $controller;
    global $action;
    $loggedin = 0;
    if (!empty($_SESSION['email']) && !empty($_SESSION['password'])) {
        $sql = "select id,name,points from users where email = '" . escape($_SESSION['email']) . "' and password = '******'password']) . "'";
        $query = mysql_query($sql);
        $user = mysql_fetch_array($query);
        if ($user['id'] > 0) {
            $_SESSION['points'] = $user['points'];
            $_SESSION['name'] = $user['name'];
            $loggedin = 1;
        }
    }
    if (($force == 1 || ALLOW_VISITORS == 0) && $loggedin == 0 && ($controller != 'users' && ($action != 'validate' || $action != 'create' || $action != 'register'))) {
        $template->overrideController('users');
        $template->overrideAction('login');
        $template->set('link', getLink());
        $controller = "users";
        $action = "login";
    }
    if ($loggedin == 0) {
        $_SESSION['userid'] = '';
    }
}
function run()
{
    $consumer = getConsumer();
    // Complete the authentication process using the server's
    // response.
    $return_to = getReturnTo();
    $response = $consumer->complete($return_to);
    // Check the response status.
    if ($response->status == Auth_OpenID_CANCEL) {
        // This means the authentication was cancelled.
        $msg = 'Verification cancelled.';
        if (isset($_COOKIE[session_name()])) {
            setcookie(session_name(), '', time() - 42000, '/');
        }
        session_destroy();
    } else {
        if ($response->status == Auth_OpenID_FAILURE) {
            // Authentication failed; display the error message.
            $msg = "OpenID authentication failed: " . $response->message;
            if (isset($_COOKIE[session_name()])) {
                setcookie(session_name(), '', time() - 42000, '/');
            }
            session_destroy();
        } else {
            if ($response->status == Auth_OpenID_SUCCESS) {
                // This means the authentication succeeded; extract the
                // identity URL and Simple Registration data (if it was
                // returned).
                $openid = $response->getDisplayIdentifier();
                $esc_identity = escape($openid);
                $_SESSION = array();
                $_SESSION['openid'] = $esc_identity;
                if ($response->endpoint->canonicalID) {
                    $escaped_canonicalID = escape($response->endpoint->canonicalID);
                    $success .= '  (XRI CanonicalID: ' . $escaped_canonicalID . ') ';
                    $_SESSION['openid'] = $escaped_canonicalID;
                }
                // AX Process
                $ax_resp = Auth_OpenID_AX_FetchResponse::fromSuccessResponse($response);
                if ($ax_resp) {
                    global $ax_data;
                    foreach ($ax_data as $ax_key => $ax_data_ns) {
                        if ($ax_resp->data[$ax_data_ns][0]) {
                            $_SESSION['ax_' . $ax_key] = $ax_resp->data[$ax_data_ns][0];
                        }
                    }
                }
            }
        }
    }
    if ($_GET["popup"] == "true") {
        include 'close.php';
    } else {
        if ($_GET["callback"] == "ax") {
            header("Location: ./ax_example.php");
        } else {
            header("Location: ./index.php");
        }
    }
}
 public function check($source, $items = array())
 {
     foreach ($items as $item => $rules) {
         foreach ($rules as $rule => $rule_value) {
             if (isset($source[$item])) {
                 $value = trim($source[$item]);
                 $item = escape($item);
             }
             if ($rule === 'required' && empty($value)) {
                 $this->addError("{$item} is required");
                 break;
             } else {
                 switch ($rule) {
                     case 'min':
                         if (strlen($value) < $rule_value) {
                             $this->addError("{$item} must be a minimum of {$rule_value}");
                         }
                         break;
                     case 'max':
                         if (strlen($value) > $rule_value) {
                             $this->addError("{$item} must be a maximum of {$rule_value}");
                         }
                         break;
                     case 'matches':
                         if ($value != $source[$rule_value]) {
                             $this->addError("{$rule_value} must be match {$item}");
                         }
                         break;
                     case 'unique':
                         $check = $this->_db->get($rule_value, array($item, '=', $value));
                         if ($check->count()) {
                             $this->addError("{$item} has already registered");
                         }
                         break;
                     case 'numbered':
                         if (!ctype_digit($value)) {
                             $this->addError("{$item} must only have numbers");
                         }
                         break;
                     case 'email form':
                         if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                             $this->addError("{$item} must contain a valid email address");
                         }
                         break;
                     case 'valid date':
                         $d = DateTime::createFromFormat('Y-m-d', $value);
                         if (!$d && $d->format('Y-m-d') == $date) {
                             $this->addError("{$item} must contain a valid date");
                         }
                         break;
                 }
             }
         }
     }
     if (empty($this->_errors)) {
         $this->_passed = true;
     }
     return $this;
 }
Esempio n. 30
0
 function defaultAction()
 {
     $item = Core::$sql->row('*', DB . 'content', 'id=' . Core::$sql->s($this->id));
     translateFields(array('title', 'description'), $item);
     $page = new PageCommon($item['title']);
     $html = '<div class="row"><div class="col-md-offset-1 col-md-7">' . '<h1>' . escape($item['title']) . '</h1>' . $item['description'] . '</div></div>';
     return $page->start() . $html . $page->stop();
 }