Example #1
0
 /**
  * Connect to the database or return connection instance.
  *
  * @return PDO Instance of PDO connection
  */
 private static function _connect()
 {
     // do we have an instance already?
     if (!self::$instance instanceof PDO) {
         try {
             // which driver are we using?
             switch (strtolower(DB_DRIVER)) {
                 // MySQL
                 case 'mysql':
                     self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';unix_socket=/var/run/mysqld/mysqld.sock', DB_USER, DB_PASS);
                     break;
                     // PostgreSQL (untested)
                 // PostgreSQL (untested)
                 case 'pgsql':
                     self::$instance = new PDO('pgsql:dbname=' . DB_NAME . ';host=' . DB_HOST, DB_USER, DB_PASS);
                     break;
                     // SQLite 3 that can only be under BASEPATH
                 // SQLite 3 that can only be under BASEPATH
                 case 'sqlite':
                     self::$instance = new PDO('sqlite:' . BASEPATH . '/' . DB_NAME);
                     break;
             }
             // error mode on, throw exceptions
             self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         } catch (PDOException $exception) {
             try {
                 throw new Fari_Exception('Cannot connect to DB: ' . $exception->getMessage() . '.');
             } catch (Fari_Exception $exception) {
                 $exception->fire();
             }
         }
     }
     return self::$instance;
 }
Example #2
0
 public function index($param)
 {
     // fetch categories & sources
     $this->view->categories = Fari_Db::select('hierarchy', 'value, slug', array('type' => 'category'), 'slug ASC');
     $this->view->sources = Fari_Db::select('hierarchy', 'value, slug', array('type' => 'source'), 'slug ASC');
     $this->view->display('search');
 }
Example #3
0
 function __construct()
 {
     // create SQLite database
     parent::__construct();
     // files
     $this->createTable('files', array('id' => 'INTEGER PRIMARY KEY', 'mime' => 'TEXT', 'data' => 'DATA', 'code' => 'TEXT', 'date' => 'TEXT', 'room' => 'NUMERIC', 'transcript' => 'NUMERIC', 'filename' => 'TEXT', 'type' => 'TEXT'));
     // image thumbnails
     $this->createTable('thumbs', array('data' => 'DATA', 'code' => 'TEXT'));
     // messages
     $this->createTable('messages', array('id' => 'INTEGER PRIMARY KEY', 'date' => 'TEXT', 'room' => 'NUMERIC', 'userId' => 'NUMERIC', 'text' => 'TEXT', 'type' => 'TEXT', 'user' => 'NUMERIC', 'transcript' => 'NUMERIC', 'highlight' => 'NUMERIC', 'locked' => 'NUMERIC'));
     // room transcripts
     $this->createTable('room_transcripts', array('key' => 'INTEGER PRIMARY KEY', 'deleted' => 'NUMERIC', 'niceDate' => 'TEXT', 'date' => 'TEXT', 'room' => 'NUMERIC'));
     // room users
     $this->createTable('room_users', array('timestamp' => 'NUMERIC', 'room' => 'NUMERIC', 'user' => 'NUMERIC'));
     // rooms
     $this->createTable('rooms', array('id' => 'INTEGER PRIMARY KEY', 'deleted' => 'TEXT', 'activity' => 'NUMERIC', 'timestamp' => 'NUMERIC', 'description' => 'TEXT', 'guest' => 'TEXT', 'locked' => 'TEXT', 'name' => 'TEXT'));
     // transcript users
     $this->createTable('transcript_users', array('date' => 'TEXT', 'room' => 'NUMERIC', 'user' => 'NUMERIC'));
     // user permissions
     $this->createTable('user_permissions', array('room' => 'NUMERIC', 'user' => 'NUMERIC'));
     // users
     $this->createTable('users', array('id' => 'INTEGER PRIMARY KEY', 'role' => 'TEXT', 'long' => 'TEXT', 'short' => 'TEXT', 'email' => 'TEXT', 'invitation' => 'TEXT', 'name' => 'TEXT', 'password' => 'TEXT', 'surname' => 'TEXT', 'username' => 'TEXT'));
     $db = Fari_Db::getConnection();
     $db->insert('users', array('role' => 'admin', 'name' => 'Radek', 'surname' => 'Stepan', 'long' => 'Radek Stepan', 'short' => 'Radek S.', 'password' => 'd033e22ae348aeb5660fc2140aec35850c4da997', 'username' => 'admin'));
 }
Example #4
0
 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();
     }
 }
Example #5
0
 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');
 }
Example #6
0
 public function _init()
 {
     // a listing of articles in the footer
     $this->view->list = !Fari_User::isAuthenticated('realname') ? Fari_Db::select('articles', 'name, published, slug', array('status' => 1), 'published DESC', BLOG_LIST) : Fari_Db::select('articles', 'name, published, slug', NULL, 'published DESC', BLOG_LIST);
     // articles archive (no limit on number of articles)
     $this->view->archive = !Fari_User::isAuthenticated('realname') ? Fari_Db::select('articles', 'name, published, slug', array('status' => 1), 'published DESC') : Fari_Db::select('articles', 'name, published, slug', NULL, 'published DESC');
 }
Example #7
0
 /**
  * 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();
 }
Example #8
0
 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;
 }
Example #9
0
 public function source($slug, $page)
 {
     $slug = Fari_Escape::text($slug);
     $paginator = new Fari_Paginator(5, 3);
     $this->view->paginator = $paginator->select($page, 'kb', '*', array('sourceSlug' => $slug), 'date DESC');
     $this->view->title = Fari_Db::selectRow('hierarchy', 'value, slug', array('slug' => $slug, 'type' => 'source'));
     $this->view->browse = 'source';
     $this->view->display('browse');
 }
Example #10
0
 /**
  * A select statement using Fari_Db::select() on itself.
  * 
  * @param string $columns Columns to return
  * @param array $where Where clause in a form array('column' => 'value')
  * @param string $order Order by clause
  * @param string $limit Limit by clause
  * @return array Table
  */
 public static function select($columns = '*', $where = NULL, $id = NULL, $order = NULL, $limit = NULL)
 {
     try {
         // get table name
         $tableName = strtolower(self::_getChildClassName());
         return Fari_Db::select($tableName, $columns, $where, $order, $limit);
     } catch (Fari_Exception $exception) {
         $exception->fire();
     }
 }
Example #11
0
 /**
  * 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();
 }
Example #12
0
 /**
  * Constructor, creating a timestamp type message (whenever any action happens)
  *
  * Make sure that activity column has a number in it!
  *
  * @param integer $roomId Id of the room (optional)
  * @param integer $time UNIX timestamp (optional)
  * @param integer $hide Set to one if you don't want a message to appear in transcript but room is not locked yet
  * @return void
  */
 function __construct($roomId = null, $time = null, $hide = 0)
 {
     // call parent constructor to set db connection
     $this->db = Fari_Db::getConnection();
     parent::__construct($this->db);
     // we don't want to timestamp a room as active if a user is leaving for example...
     if (isset($roomId)) {
         $this->roomId = $roomId;
         $this->timestampRoom($time, $hide);
     }
 }
 function __construct($roomPermissionsString)
 {
     // setup db connection
     $this->db = Fari_Db::getConnection();
     // fetch the count of all the transcripts, calculate in PHP
     $this->all = $this->db->select('room_transcripts' . ' JOIN rooms' . ' ON room_transcripts.room=rooms.id', 'room_transcripts.key, rooms.id, rooms.name, room_transcripts.niceDate, room_transcripts.date', "room_transcripts.deleted=0 AND rooms.id IN ({$roomPermissionsString})", 'room_transcripts.key DESC');
     // count of all items
     if (($this->count = count($this->all)) == 0) {
         throw new TranscriptEmptyException();
     }
 }
Example #14
0
 public static function query($query)
 {
     // explode the query by space forming an array of searched for words
     $query = explode(' ', strtolower($query));
     // form an SQL LIKE
     $like = '';
     foreach ($query as $word) {
         $like .= "stems LIKE '%{$word}%' OR titleStems LIKE '%{$word}%' OR tags LIKE '%{$word}%' OR source LIKE '%{$word}%'\n                OR category LIKE '%{$word}%' OR type LIKE '%{$word}%' OR comments LIKE '%{$word}%' OR text LIKE '%{$word}%'\n                OR ";
     }
     $like = substr($like, 0, -4);
     // leave out the trailing ' OR '
     // fetch the text
     $result = Fari_Db::select('kb', '*', "({$like})");
     return self::relevance($query, $result);
 }
Example #15
0
 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;
 }
Example #16
0
 /**
  * Connect to the database or return connection instance.
  * @return PDO Instance of PDO connection
  */
 public static function getConnection()
 {
     // do we have an instance already?
     if (!self::$dbConnection instanceof Fari_DbConnection) {
         try {
             // which driver are we using?
             switch (strtolower(DB_DRIVER)) {
                 // MySQL
                 case 'mysql':
                     $pdoInstance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';unix_socket=/var/run/mysqld/mysqld.sock', DB_USER, DB_PASS);
                     break;
                     // PostgreSQL (untested)
                 // PostgreSQL (untested)
                 case 'pgsql':
                     $pdoInstance = new PDO('pgsql:dbname=' . DB_NAME . ';host=' . DB_HOST, DB_USER, DB_PASS);
                     break;
                     // SQLite 3
                 // SQLite 3
                 case 'sqlite3':
                 case 'sqlite':
                     $pdoInstance = new PDO('sqlite:' . BASEPATH . '/' . DB_NAME);
                     break;
                     // SQLite 2
                 // SQLite 2
                 case 'sqlite2':
                     $pdoInstance = new PDO('sqlite2:' . BASEPATH . '/' . DB_NAME);
                     break;
             }
             // error mode on, throw exceptions
             $pdoInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             // create Fari_DbConnection using the PDO instance
             self::$dbConnection = new Fari_DbConnection($pdoInstance);
         } catch (PDOException $exception) {
             try {
                 throw new Fari_Exception('Cannot connect to DB: ' . $exception->getMessage() . '.');
             } catch (Fari_Exception $exception) {
                 $exception->fire();
             }
         }
     }
     // return Fari_DbConnection
     return self::$dbConnection;
 }
Example #17
0
 function __construct($date, $roomId)
 {
     // setup db connection
     $this->db = Fari_Db::getConnection();
     $this->details = $this->db->selectRow('room_transcripts JOIN rooms ON rooms.id=room_transcripts.room', 'room_transcripts.key, niceDate, name, room, date', array('date' => $date, 'room_transcripts.deleted' => 0, 'room' => $roomId));
     // nothing found, throw an exception
     if (!is_array($this->details)) {
         throw new TranscriptNotFoundException();
     }
     // get users
     $this->users = $this->getUsers($date, $roomId);
     // get messages
     $this->messages = $this->getMessages($date, $roomId);
     // get files
     $this->files = $this->getFiles($date, $roomId);
     // next transcript
     $this->next = $this->next($roomId);
     // previous transcript
     $this->previous = $this->previous($roomId);
 }
Example #18
0
 function __construct($time = NULL)
 {
     if (!isset($time)) {
         $time = mktime();
     }
     $this->db = Fari_Db::getConnection();
     parent::__construct($this->db);
     $cutoff = $time - 60 * 10;
     // check if user has a timestamp older than 5 minutes in a room
     $leave = $this->db->select('room_users JOIN users ON room_users.user=users.id', 'user, room, short', "timestamp < {$cutoff}");
     if (!empty($leave)) {
         $message = new MessageSpeak();
         foreach ($leave as $user) {
             // leaving message
             $message->leave($user['room'], $time, $user['short']);
         }
         // clear them out from the room
         $this->db->delete('room_users', "timestamp < {$cutoff}");
     }
 }
Example #19
0
 /**
  * Create object for authenticated user
  */
 function __construct($roles = NULL)
 {
     $this->db = Fari_Db::getConnection();
     parent::__construct();
     // no entry, we are not logged in, fail the constructor
     if (!$this->isAuthenticated()) {
         throw new UserNotAuthenticatedException();
     }
     // fetch the database entry for us
     $dbUser = $this->db->selectRow('users', 'id, role, name, surname, short, long, invitation', array('username' => $this->getCredentials()));
     // user has been inactivated, throw them away
     if ($dbUser['role'] == 'inactive') {
         throw new UserNotAuthenticatedException();
     }
     // ORM much? effectively map db entry into an identity Fari_Bag object
     $this->identity = new Fari_Bag();
     foreach ($dbUser as $key => $value) {
         $this->identity->{$key} = $value;
     }
     // get an array of room permissions for us
     $q = $this->db->select('user_permissions', 'room', array('user' => $dbUser['id']), 'room ASC');
     foreach ($q as $room) {
         array_push($this->permissions, $room['room']);
     }
     // which rooms are we in?
     $q = $this->db->select('room_users JOIN rooms ON room_users.room=rooms.id', 'rooms.id, name', array('user' => $dbUser['id']), 'room ASC');
     foreach ($q as $room) {
         $this->inRoom[$room['name']] = $room['id'];
     }
     // optionally check the roles
     if (isset($roles)) {
         if (!$this->isAuthorized(&$roles, $dbUser['role'])) {
             throw new UserNotAuthorizedException();
         }
     }
 }
Example #20
0
 /**
  * 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;
 }
Example #21
0
 public function _init()
 {
     $this->view->settings = Fari_Db::toKeyValues(Fari_Db::select('settings', 'name, value'), 'name');
 }
Example #22
0
 /**
  * Builds and returns an XML sitemap.
  * @uses date in standard db form, W3C Datetime (YYYY-MM-DD)
  *
  * @param string/array $items Database table we work with or array of data already
  * @param string $linksURL URL to append slug links to (e.g., http://.$_SERVER['HTTP_HOST'].WWW_DIR.Controller)
  * @return XML sitemap
  */
 public function create($items, $linksURL = NULL)
 {
     // try determining this server's address if URL is not provided
     if (!isset($linksURL)) {
         $linksURL = 'http://' . $_SERVER['SERVER_NAME'] . WWW_DIR;
     }
     // add a trailing slash to URL
     $linksURL = Fari_File::addTrailingSlash($linksURL);
     // start dom string
     $DOMDocument = new DOMDocument('1.0', 'UTF-8');
     // <urlset> root
     $rootNode = $DOMDocument->appendChild($DOMDocument->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset'));
     // get items from the database if we are not passing a formed array already
     if (!is_array($items)) {
         // last modification date and page priority won't be provided
         if (!isset($this->lastModificationDate) && !isset($this->pagePriority)) {
             $columns = $this->linkSlug;
             // last modification date won't be provided
         } elseif (!isset($this->lastModificationDate)) {
             $columns = $this->linkSlug . ', ' . $this->pagePriority;
             // page priority won't be provided
         } elseif (!isset($this->pagePriority)) {
             $columns = $this->linkSlug . ', ' . $this->lastModificationDate;
             // we will be provided with all params
         } else {
             $columns = $this->linkSlug . ',' . $this->lastModificationDate . ',' . $this->pagePriority;
         }
         // the actual call to the db
         $items = Fari_Db::select($items, $columns);
     }
     // set default element text, page priority
     $pagePriorityText = self::LINK_PRIORITY;
     // set default element text, generate last modification date as now
     $lastModificationText = date('Y-m-d');
     // traverse through all records
     foreach ($items as $item) {
         // <urlset><url>
         $URLNode = $rootNode->appendChild($DOMDocument->createElement('url'));
         // <urlset><url><loc> link address
         $URLNode->appendChild($DOMDocument->createElement('loc', $linksURL . $item[$this->linkSlug]));
         // <urlset><url><lastmod> last modification date of the page
         if (isset($this->lastModificationDate)) {
             $lastModificationText = $item[$this->lastModificationDate];
             // convert UNIX timestamp to well formed date if present
             if (strlen($lastModificationText) == 10 && $lastModificationText > 1000000000) {
                 $lastModificationText = date('Y-m-d', $lastModificationText);
             }
         }
         $URLNode->appendChild($DOMDocument->createElement('lastmod', $lastModificationText));
         // <urlset><url><priority> page priority
         if (isset($this->pagePriority)) {
             $pagePriorityText = $item[$this->pagePriority];
         }
         $URLNode->appendChild($DOMDocument->createElement('priority', $pagePriorityText));
     }
     // generate XML and return
     $DOMDocument->formatOutput = TRUE;
     return $DOMDocument->saveXML();
 }
Example #23
0
 public function star($slug)
 {
     $result = Fari_Db::selectRow('kb', '*', array('slug' => $slug));
     if (empty($result)) {
         // text not found
         $this->redirect('/error404');
         die;
     }
     // switch the star for the text we have already fetched & update in the db
     if ($result['starred'] == 'full') {
         $result['starred'] = 'empty';
         // switch in the current set
         Fari_Db::update('kb', array('starred' => 'empty'), array('id' => $result['id']));
     } else {
         $result['starred'] = 'full';
         // switch in the current set
         Fari_Db::update('kb', array('starred' => 'full'), array('id' => $result['id']));
     }
     // return back
     header('Location: ' . $_SERVER['HTTP_REFERER']);
 }
Example #24
0
 public function sitemap()
 {
     $sitemap = new Fari_Sitemap('slug', 'published');
     $articles = Fari_Db::select('articles', 'slug, published', array('status' => 1));
     echo $sitemap->create($articles, '/blog/article/');
 }
 /**
  * Get instance of database connection.
  */
 public function __construct()
 {
     $this->db = Fari_Db::getConnection();
 }
Example #26
0
 /**
  * Calculate the total number of items in a query.
  *
  * @param string $table Database table we work with
  * @param string/array $where WHERE $where = $id
  * @return int Items total count
  */
 private function getItemsTotal($table, $where = NULL)
 {
     // count total
     $array = Fari_Db::select($table, "COUNT(*) AS total", $where);
     // why this way? to reuse select() easily
     return $array[0]['total'];
 }
Example #27
0
 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');
 }
Example #28
0
 /**
  * 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);
 }