/** * Check that a captcha answer is valid. * * @param string $unsafeAnswer Unsafe answer from the user to check * @param string $name Name of the captcha answer in the session * @return boolean TRUE if answer is correct, FALSE otherwise */ public static function isValid($unsafeAnswer, $name = 'Default') { // escape unsafe token input $unsafeAnswer = Fari_Escape::text($unsafeAnswer); // check if token is valid return sha1($unsafeAnswer) == $_SESSION[self::SESSION_STORAGE . $name] ? TRUE : FALSE; }
public function __construct($file, $roomId) { // get file $this->name = Fari_Escape::file($file['name'], TRUE); $this->mime = $file['type']; // db instance $db = Fari_Db::getConnection(); $type = explode('/', $this->mime); $type = count($type) > 1 ? $type[1] : $type[0]; // set generic filetype for files we don't have icons for :) if (!in_array($type, $this->fileTypes)) { $type = 'generic'; } $stream = fopen($file['tmp_name'], 'rb'); $code = $this->randomCode($db); $date = SystemTime::timestampToDate(); // let's associate the file with a transcript (there better be a transcript...) $transcript = $db->selectRow('room_transcripts', 'key', array('date' => $date, 'room' => $roomId)); // insert the file $db->query("INSERT INTO files (mime, data, code, room, filename, type, date, transcript)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?)", array($this->mime, $stream, $this->code = $code, $roomId, $this->name, $this->type = $type, $date, $transcript['key'])); fclose($stream); // create a thumbnail if required $thumbnail = new UploadThumbnail($file); if ($thumbnail->isCreated()) { // yes we do have one $this->thumbnail = TRUE; $thumb = fopen($thumbnail->getPath(), 'rb'); // insert the thumbnail $db->query("INSERT INTO thumbs (data, code) VALUES (?, ?)", array($thumb, $this->code)); fclose($thumb); //$thumbnail->destroy(); } }
/** * Builds and returns an XML version of a table. * * @param string/array $items Database table we work with or array of data already * @param string $columns Columns to export * @param array $where Where clause in a form array('column' => 'value') * @param string $order Order by clause * @param string $limit Limit by clause * @return string XML backup of the table, headers not set */ public static function toXML($items, $columns = '*', array $where = NULL, $order = NULL, $limit = NULL) { // dom string $DOMDocument = new DOMDocument('1.0', 'UTF-8'); // get items from the database if we are not passing a formed array already if (!is_array($items)) { $items = Fari_Db::select($items, $columns, $where, $order, $limit); } // <table> root $table = $DOMDocument->appendChild($DOMDocument->createElement('table')); // traverse through all records foreach ($items as $item) { // get array keys of the item // we could explode $columns as well if they are passed $keys = array_keys($item); // <table><row> elemenent we will always have $row = $table->appendChild($DOMDocument->createElement('row')); // traverse through keys/columns foreach ($keys as $column) { // <table><row><column> value, escaped $row->appendChild($DOMDocument->createElement($column, Fari_Escape::XML($item[$column]))); } } // generate xml and return $DOMDocument->formatOutput = TRUE; return $DOMDocument->saveXML(); }
private function filterLinkify($text) { $urls = explode(' ', $text); $containsLink = FALSE; foreach ($urls as &$link) { if (Fari_Filter::isURL($link)) { $containsLink = TRUE; // do we have a YouTube video? // source: http://www.youtube.com/watch?v=nBBMnY7mANg&feature=popular // target: <img src="http://img.youtube.com/vi/nBBMnY7mANg/0.jpg" alt="0"> if (stripos(strtolower($link), 'youtube') !== FALSE) { $url = parse_url($link); parse_str($url[query], $query); // replace link with an image 'boosted' link :) $link = '<a class="youtube" target="_blank" href="' . $link . '"><img src="http://img.youtube.com/vi/' . $query['v'] . '/0.jpg" alt="YouTube"></a>'; } else { // plain old link $link = '<a target="_blank" href="' . $link . '">' . $link . '</a>'; } // convert so we can insert into DB $link = Fari_Escape::html($link); } } if ($containsLink) { return implode(' ', $urls); } else { return $text; } }
public static function add($username, $password, $realname) { // escape input $username = Fari_Escape::html($username); $password = Fari_Escape::html($password); $realname = Fari_Escape::html(Fari_Decode::javascript($realname)); // verify that credentials are provided in a valid form if (!empty($username) && ctype_alnum($username) && strlen($username) <= 10) { if (!empty($password) && ctype_alnum($password) && strlen($password) <= 10) { if (!empty($realname) && strlen($realname) <= 100) { // all OK, db insert Fari_Db::insert('users', array('username' => $username, 'password' => sha1($password), 'realname' => $realname)); Fari_Message::success("Welcome {$realname}!"); return TRUE; } else { Fari_Message::fail("Please provide a valid real name."); } } else { Fari_Message::fail("Please provide a valid password."); } } else { Fari_Message::fail("Please provide a valid username."); } return FALSE; }
/** * Check for uniqueness of the username * * @param string $username URL encoded username */ public function actionCheckUsername($username) { // is this Ajax? if ($this->request->isAjax()) { // URL decode & filter out username $username = Fari_Escape::text(Fari_Decode::url($username)); if (empty($username)) { $this->renderJson("The username can't be empty."); } else { // alphanumeric only? if (!Fari_Filter::isAlpha($username)) { $this->renderJson("Only alphanumeric characters are allowed."); } else { // do we have a match? if (!$this->accounts->isUsernameUnique($username)) { $this->renderJson("The username \"{$username}\" is unavailable, sorry."); } else { $this->renderJson(''); } } } } else { $this->renderTemplate('error404/javascript'); } }
public function index($param) { // get installed CSS themes $files = Fari_File::listing('/public'); $themes = array(); foreach ($files as $file) { $css = end(explode('/', $file['path'])); // its cheap if ($file['type'] == 'file' && substr($css, -4) == '.css') { $themes[] = substr($css, 0, -4); } } natsort(&$themes); $this->view->themes = $themes; // are we saving changes? if ($_POST) { $css = Fari_Escape::text($_POST['css']); $title = Fari_Escape::text($_POST['title']); Fari_Db::update('settings', array('value' => $css), array('name' => 'theme')); Fari_Db::update('settings', array('value' => $title), array('name' => 'title')); Fari_Message::success('Settings change successful.'); } $this->view->messages = Fari_Message::get(); $this->view->settings = Fari_Db::toKeyValues(Fari_Db::select('settings', 'name, value'), 'name'); $this->view->display('settings'); }
/** * Template for converting an array of db data into XML. * @return XML */ public function dbToXML($parameters) { // dom string $DOMDocument = new DOMDocument('1.0', 'UTF-8'); // fetch the data array $items = $this->items($parameters); // check we actually have an array try { if (!is_array($items)) { throw new Fari_Exception('Fari_Backup expects an array of items.'); } } catch (Fari_Exception $exception) { $exception->fire(); } // <table> root element $table = $DOMDocument->appendChild($DOMDocument->createElement('table')); // traverse through all records foreach ($items as $item) { // get array keys of the item // we could explode $columns as well if they are passed $keys = array_keys($item); // <table><row> elemenent we will always have $row = $table->appendChild($DOMDocument->createElement('row')); // traverse through keys/columns foreach ($keys as $column) { // <table><row><column> value, escaped $row->appendChild($DOMDocument->createElement($column, Fari_Escape::xml($item[$column]))); } } // generate XML and return $DOMDocument->formatOutput = TRUE; return $DOMDocument->saveXML(); }
public function tag($tag) { $tag = Fari_Escape::text($tag); $paginator = new Fari_Paginator(100, 3); switch ($tag) { case 'star': $this->view->paginator = $paginator->select(1, 'kb', '*', array('starred' => 'full'), 'date DESC'); $this->view->title = array('value' => 'Starred'); break; default: $this->redirect('/error404'); } $this->view->browse = 'both'; $this->view->display('browse'); }
public static function getArchive($month, $isAuthenticated) { // escape $month = Fari_Escape::text($month); // parse month and year passed list($month, $year) = explode('-', $month); $months = array('january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'); $monthPosition = array_search($month, $months) + 1; if (!empty($monthPosition)) { // we have ourselves the month number $low = mktime(1, 1, 1, $monthPosition, 1, $year); $high = mktime(23, 59, 59, $monthPosition, date('t', $low), $year); return !$isAuthenticated ? Fari_Db::select('articles', '*', "published >= '{$low}' AND published <= '{$high}' AND status = 1", 'published DESC') : Fari_Db::select('articles', '*', "published >= '{$low}' AND published <= '{$high}' AND status != 2", 'published DESC'); } return; }
/** * Send a message from a room * * @uses Ajax */ public function actionSpeak($roomId) { $text = Fari_Escape::text(Fari_Decode::javascript($this->request->getRawPost('text'))); if (!empty($text)) { $time = mktime(); // a text message $message = new MessageSpeak($roomId, $time); $message->text($roomId, $time, $this->user->getShortName(), $this->user->getId(), $text); // the message might be saved under wrong room id, but activity updater will kick us... try { $this->room->updateUserActivity($roomId, $time, $this->user->getId()); } catch (UserNotFoundException $e) { $this->renderJson('bye'); } } }
/** * Make a directory on the server. * * @param string $directoryPath Path where to create the directory * @param string $directoryName Name of the directory to create * @param int $permissions Permissions to apply to the directory * @return array Status and a message */ public static function mkdir($directoryPath, $directoryName, $permissions = 0755) { // only allow uploads in 'our' directory $directoryPath = BASEPATH . self::addTrailingSlash($directoryPath); // check that path is valid if (!is_dir($directoryPath) || !is_writable($directoryPath)) { return array('status' => 'fail', 'message' => 'The path is not writable.'); } // escape dirname $directoryName = Fari_Escape::directory($directoryName, TRUE); // does directory already exist? if (is_dir($directoryPath . $directoryName)) { return array('status' => 'fail', 'message' => 'Directory \'' . $directoryName . '\' already exists.'); } // make a directory if (!@mkdir($directoryPath . $directoryName, $permissions, TRUE)) { return array('status' => 'fail', 'message' => 'Failed to create a folder.'); } return array('status' => 'success', 'message' => 'Directory \'' . $directoryName . '\' created succesfully.'); }
public function results($query) { if (!empty($query)) { // cleanup, convert, replace, strip... $query = Fari_Decode::url($query); $query = preg_replace('~\\s{2,}~', ' ', implode(' ', explode('-', strtolower($query)))); $query = substr($query, -1) == ' ' ? substr($query, 0, -1) : $query; // trailing space $query = substr($query, 0, 1) == ' ' ? substr($query, 1) : $query; // leading space $this->view->query = $query = Fari_Escape::alpha($query); $this->view->keywords = implode('-', explode(' ', $query)); // implode back to have clean keywords } else { $this->redirect('/'); die; } // fetch the result and add relevance to it $this->view->result = Search::query($query); $this->view->display('results'); }
/** * Get code and name from the form and create a new user for us (generate username) */ public function actionCreate() { $name = Fari_Decode::accents($this->request->getPost('name')); $code = $this->request->getPost('code'); if (!empty($name)) { $name = explode(' ', $name); // do we have a 'long' name? if (count($name) > 1) { $short = $name[0] . ' ' . substr(end($name), 0, 1) . '.'; $long = implode(' ', $name); $surname = end($name); $name = $name[0]; } else { $short = $long = $name = $name[0]; $surname = ''; } // generate a username $username = Fari_Escape::slug($long) . Fari_Tools::randomCode(10); $db = Fari_Db::getConnection(); // insert the user in a guest role $userId = $db->insert('users', array('short' => $short, 'long' => $long, 'name' => $name, 'surname' => $surname, 'role' => 'guest', 'username' => $username)); // log them in automatically Fari_AuthenticatorSimple::forceAuthenticate($username); // give them permissions to enter this room $room = $db->selectRow('rooms', 'id', array('guest' => $code)); if (!empty($room)) { $db->insert('user_permissions', array('room' => $room['id'], 'user' => $userId)); } } // redirect to the room, if we've ailed will be asked for guest's name again $this->redirectTo('/g/' . $code); }
public function edit($slug) { $slug = Fari_Escape::text($slug); // are we saving? if ($_POST) { $success = TRUE; // save categories, sources & types $category = Fari_Escape::text($_POST['category']); $categorySlug = Fari_Escape::slug($category); $source = Fari_Escape::text($_POST['source']); $sourceSlug = Fari_Escape::slug($source); $type = Fari_Escape::text($_POST['type']); $typeSlug = Fari_Escape::slug($type); if (empty($category)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $category, 'type' => 'category')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $category, 'slug' => $categorySlug, 'type' => 'category')); } } if (empty($source)) { Fari_Message::fail('The source can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $source, 'type' => 'source')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $source, 'slug' => $sourceSlug, 'type' => 'source')); } } if (empty($type)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $type, 'type' => 'type')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $type, 'type' => 'type')); } } if ($success) { $text = Fari_Escape::quotes($_POST['textarea']); // convert main text to stems & add the lowercase original to it (better matches) $stems = Knowledge::stems($text) . ' ' . strtolower($text); $tags = Fari_Escape::text($_POST['tags']); $category = Fari_Escape::text($_POST['category']); $source = Fari_Escape::text($_POST['source']); $type = Fari_Escape::text($_POST['type']); $comments = Fari_Escape::text($_POST['comments']); $date = Fari_Escape::text($_POST['date']); // date if (!Fari_Filter::isDate($date)) { Fari_Message::fail('The date is not in the correct format.'); } else { // INSERT Fari_Db::update('kb', array('text' => $text, 'comments' => $comments, 'date' => $date, 'tags' => $tags, 'category' => $category, 'categorySlug' => $categorySlug, 'source' => $source, 'sourceSlug' => $sourceSlug, 'type' => $type, 'stems' => $stems), array('slug' => $slug)); Fari_Message::success('Saved successfully.'); } } } // fetch categories, sources & types $this->view->categories = $categories = Fari_Db::select('hierarchy', 'key, value', array('type' => 'category'), 'slug ASC'); $this->view->sources = $sources = Fari_Db::select('hierarchy', 'key, value', array('type' => 'source'), 'slug ASC'); $this->view->types = $types = Fari_Db::select('hierarchy', 'key, value', array('type' => 'type'), 'value ASC'); // form $saved = Fari_Db::selectRow('kb', '*', array('slug' => $slug)); $saved['textarea'] = $saved['text']; // for reuse... $this->view->saved = $saved; // get all messages $this->view->messages = Fari_Message::get(); $this->view->display('edit'); }
<h3><a href="<?php $this->url('/blog/article/' . $article['slug']); ?> " title="Permanent Link to <?php echo $article['name']; ?> "> <?php echo $article['name']; ?> </a></h3> <!-- text --> <p><?php $article['text'] = Fari_Escape::text(Fari_Textile::toHTML($article['text'])); echo strlen($article['text']) <= BLOG_PREVIEW ? $article['text'] : substr($article['text'], 0, BLOG_PREVIEW) . ' [...]'; ?> </p> <!-- details --> <div class="details"> Posted at <?php echo date("F j, Y, G:i", $article['published']); ?> | <span class="read-on"> <a href="<?php $this->url('/blog/article/' . $article['slug']); ?> ">read more</a>
/** * Check if user is in a specified role. * Method is_authenticated() should have been called at this point. * @uses 'role' in 'users' table * * @param string $userRole (e.g., admin) * @param string $credentials Optionally specify which column to use for credentials * @return boolean TRUE if user is in a role */ public static function isInRole($userRole, $credentialsColumn = 'username') { @($unsafe = self::getCredentials()); // get credentials string if (isset($unsafe)) { //escape input $credentials = Fari_Escape::text($unsafe); // select a matching row from a table $whereClause = array($credentialsColumn => $credentials); $user = Fari_Db::selectRow('users', 'role', $whereClause); // check that user satisfies a role if ($user['role'] === $userRole) { unset($user); return TRUE; } } return FALSE; }
<?php } $count = 1; $month = $articleMonth; ?> <?php } else { $count++; ?> <?php } } if ($count > 0) { ?> <li><a href="<?php $this->url('/blog/archive/' . Fari_Escape::slug($month)); ?> "> <?php echo $month; ?> </a> (<?php echo $count; ?> ) </li> <?php } else { ?> <li>No archive</li> <?php
" href="<?php $this->url('/text/star/' . $row['slug']); ?> "> </a> <a href="<?php $this->url('/text/view/' . $row['slug']); ?> "> <?php echo $row['title']; ?> </a></h3> <p class="preview"> <?php echo substr(Fari_Escape::text(Fari_Textile::toHTML($row['text'])), 0, 300); ?> …</p> <div class="description"> <?php if ($browse == 'category') { ?> <a href="<?php $this->url('/browse/source/' . $row['sourceSlug']); ?> "> <?php echo $row['source']; ?> <?php } elseif ($browse == 'source') {
public function create() { if (!Fari_User::isAuthenticated('realname')) { Fari_Message::fail('You need to authenticate first'); $this->redirect('/blog/login/'); } else { // are we saving updates? if (!empty($_POST['name'])) { $name = Fari_Escape::text($_POST['name']); $text = Fari_Escape::quotes($_POST['text']); $slug = Fari_Escape::slug($_POST['name']); // check article title uniqueness $result = Fari_Db::selectRow('articles', 'id', array('slug' => $slug)); if (empty($result)) { Fari_Db::insert('articles', array('text' => $text, 'slug' => $slug, 'name' => $name, 'status' => $_POST['status'], 'published' => time())); Fari_Message::success('Article \'' . $name . '\' saved.'); $this->redirect('/blog/edit/' . $slug); } else { Fari_Message::fail('Article name \'' . $name . '\' is not unique'); } } // pickup messages for us $this->view->messages = Fari_Message::get(); // fill back on fail $this->view->article = array('name' => $_POST['name'], 'text' => $_POST['text']); $this->view->display('/themes/' . BLOG_THEME . '/new'); } }
public function renderFile($fileCode, $type) { $system = new System(); switch ($type) { case 'file': $file = $system->getFile(Fari_Escape::text($fileCode)); break; case 'thumb': $file = $system->getThumbnail(Fari_Escape::text($fileCode)); break; } if (!empty($file)) { // respond with a file download $this->sendFile($file); } else { $this->renderTemplate('Error404/error404'); } }
<?php if (!defined('FARI')) { die; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title><?php echo Fari_Escape::text($text['title']); ?> </title> <link rel="shortcut icon" type="image/x-icon" href="<?php $this->url('/public/favicon.ico'); ?> "> <link rel="stylesheet" href="<?php $this->url('/public/grid/screen.css'); ?> " type="text/css" media="screen, projection"/> <link rel="stylesheet" href="<?php $this->url('/public/grid/print.css'); ?> " type="text/css" media="print"/> <!--[if lt IE 8]> <link rel="stylesheet" href="<?php $this->url('/public/grid/ie.css'); ?>
/** * Builds and returns an RSS feed (check data on db insert!). * * @param string $feedTitle Title of the feed * @param string $feedURL Link to the feed * @param string $feedDescription Description of this feed * @param string $items Database table * @param boolean $isDateInRSS Set to TRUE if dates in tn the $items table are already in RSS format * @return string RSS Feed */ public function create($feedTitle, $feedURL, $feedDescription, $items, $isDateInRSS = FALSE) { // escape input $feedTitle = Fari_Escape::XML($feedTitle); $feedURL = Fari_Escape::XML($feedURL); $feedDescription = Fari_Escape::XML($feedDescription); // set publishing date in RSS format $feedPublished = date(DATE_RSS); // start dom string $DOMDocument = new DOMDocument('1.0', 'UTF-8'); // form columns, we will use the info when traversing articles (and on the line below) $columns = $this->articleTitle . ', ' . $this->articleLink . ', ' . $this->articleDescription . ', ' . $this->articleDate; // get items from the database if we are not passing a formed array already if (!is_array($items)) { $items = Fari_Db::select($items, $columns); } // <rss> $rootNode = $DOMDocument->createElement('rss'); // use RSS version 2.0 attribute $rootNode->setAttribute('version', '2.0'); $DOMDocument->appendChild($rootNode); // <rss><channel> $channel = $rootNode->appendChild($DOMDocument->createElement('channel')); // create the header // <rss><channel><title> $channel->appendChild($DOMDocument->createElement('title', $feedTitle)); // <rss><channel><link> $channel->appendChild($DOMDocument->createElement('link', $feedURL)); // <rss><channel><description> $channel->appendChild($DOMDocument->createElement('description', $feedDescription)); // <rss><channel><pubDate> $channel->appendChild($DOMDocument->createElement('pubDate', $feedPublished)); // column to RSS form 'conversion', elements have to follow that order... $articleColumns = explode(', ', $columns); $RSSColumns = array('title', 'link', 'description', 'pubDate'); // traverse items now foreach ($items as $article) { // <rss><channel><item> $articleNode = $channel->appendChild($DOMDocument->createElement('item')); // traverse the items array consisting of 4 elements for ($i = 0; $i < 4; $i++) { // <rss><channel><item><$column> // <$column> value, escaped $columnText = Fari_Escape::XML($article[$articleColumns[$i]]); // do we need to fix RSS pubDate? if ($RSSColumns[$i] == 'pubDate' && !$isDateInRSS) { $columnText = Fari_Format::date($columnText, 'RSS'); } $articleNode->appendChild($DOMDocument->createElement($RSSColumns[$i], $columnText)); } } // generate XML and return $DOMDocument->formatOutput = TRUE; return $DOMDocument->saveXML(); }
/** * Format mixed variables for output * @param <type> $mixed * @return <type> */ public static function formatVars($mixed) { // we are working in HTML context //$mixed = Fari_Escape::html($mixed); if ($mixed === NULL) { $mixed = '<em>NULL</em>'; } else { if (empty($mixed)) { $mixed = '<em>empty</em>'; } else { if (is_string($mixed)) { $mixed = Fari_Escape::html($mixed); } else { ob_start(); var_dump($mixed); $mixed = ob_get_contents(); ob_clean(); $mixed = explode("\n", $mixed); foreach ($mixed as &$line) { // how big is the whitespace on the left? $padding = strlen($line) - strlen(ltrim($line)); // add extra padding for better readability for ($i = 0; $i < $padding; $i++) { $line = " " . $line; } // if our line contains a value give it extra pad if (strpos($trimmed = ltrim($line), "[") !== FALSE) { // highlight array key $line = str_replace("[", "<strong>[", $line); $line = str_replace("]", "]</strong>", $line); } else { if (substr(trim($line), 0) != "}") { $line = " " . $line; } } $line = substr($line, 3); } $mixed = implode("\n", $mixed); } } } return $mixed; }
/** * Set body of the messsage * @param string $subject Text * @param boolean $text escape text if set to true * @return Fari_Mail subclass */ public function setBody($body, $text = FALSE) { $this->body = $text ? Fari_Escape::text($body) : $body; return $this; }
/** * Escape SESSION data. * @param string */ public function prepareSession($sessionString) { return Fari_Escape::text($sessionString); }
public function index($param) { // are we saving? if ($_POST) { $success = TRUE; // save categories, sources & types $category = Fari_Escape::text($_POST['category']); $categorySlug = Fari_Escape::slug($category); $source = Fari_Escape::text($_POST['source']); $sourceSlug = Fari_Escape::slug($source); $type = Fari_Escape::text($_POST['type']); $typeSlug = Fari_Escape::slug($type); if (empty($category)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $category, 'type' => 'category')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $category, 'slug' => $categorySlug, 'type' => 'category')); } } if (empty($source)) { Fari_Message::fail('The source can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $source, 'type' => 'source')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $source, 'slug' => $sourceSlug, 'type' => 'source')); } } if (empty($type)) { Fari_Message::fail('The category can\'t be empty.'); $success = FALSE; } else { $result = Fari_Db::selectRow('hierarchy', 'key', array('value' => $type, 'type' => 'type')); if (empty($result)) { Fari_Db::insert('hierarchy', array('value' => $type, 'type' => 'type')); } } if ($success) { $title = Fari_Escape::text($_POST['title']); if (empty($title)) { Fari_Message::fail('The title can\'t be empty.'); } else { $slug = Fari_Escape::slug($_POST['title']); // unique slug/title $result = Fari_Db::selectRow('kb', 'id', array('slug' => $slug)); if (!empty($result)) { Fari_Message::fail('The title is not unique.'); } else { $text = Fari_Escape::quotes($_POST['textarea']); // convert title & main text to its stems and add lowercase originals better matches) $titleStems = Knowledge::stems($title) . ' ' . strtolower($title); $stems = Knowledge::stems($text) . ' ' . strtolower($text); $tags = Fari_Escape::text($_POST['tags']); $category = Fari_Escape::text($_POST['category']); $source = Fari_Escape::text($_POST['source']); $type = Fari_Escape::text($_POST['type']); $comments = Fari_Escape::text($_POST['comments']); $date = Fari_Escape::text($_POST['date']); // date if (!Fari_Filter::isDate($date)) { Fari_Message::fail('The date is not in the correct format.'); } else { // INSERT Fari_Db::insert('kb', array('title' => $title, 'slug' => $slug, 'text' => $text, 'tags' => $tags, 'category' => $category, 'categorySlug' => $categorySlug, 'source' => $source, 'sourceSlug' => $sourceSlug, 'type' => $type, 'stems' => $stems, 'comments' => $comments, 'date' => $date, 'titleStems' => $titleStems, 'starred' => 'empty')); Fari_Message::success('Saved successfully.'); $this->redirect('/text/edit/' . $slug); die; } } } } } // fetch categories, sources & types $this->view->categories = $categories = Fari_Db::select('hierarchy', 'key, value', array('type' => 'category'), 'slug ASC'); $this->view->sources = $sources = Fari_Db::select('hierarchy', 'key, value', array('type' => 'source'), 'slug ASC'); $this->view->types = $types = Fari_Db::select('hierarchy', 'key, value', array('type' => 'type'), 'value ASC'); // form if save failed... $this->view->saved = $_POST; // get all messages $this->view->messages = Fari_Message::get(); $this->view->display('new'); }