<?php
class news
{
/**
* @var mysqliConnection
*/
private $db;
private $tableName;
public function __construct(&$db)
{
$this->db = &$db;
$this->tableName = config::get('news', 'tableName');
$db->checkTable($this->tableName, "
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`body` text COLLATE utf8_unicode_ci NOT NULL,
`is_visible` int(1) unsigned NOT NULL,
`posted` datetime NOT NULL,
PRIMARY KEY (`id`)
");
}
public function create($title)
{
$this->db->insert($this->tableName,
array('title' => $title,
'body' => '',
'is_visible' => 0,
'posted' => 'FROM_UNIXTIME(' . time() . ')'));
return $this->db->lastInsertedId();
}
public function get($id)
{
return $this->db->getRow($this->tableName, '*', 'id', $id);
}
public function getAll($cols = '*', $onlyVisible=false, $limit=0)
{
$tableName = $this->tableName;
$whereArray = array();
if ($onlyVisible) {
$whereArray[] = 'is_visible = 1';
}
$where = !empty($whereArray) ? 'WHERE' : '';
$limit = !empty($limit) ? "LIMIT $limit" : '';
$sqlQuery = "SELECT $cols,UNIX_TIMESTAMP(posted) AS posted_unix FROM $tableName $where " . implode(' AND ', $whereArray) . " ORDER BY posted DESC $limit";
$newsItems = $this->db->getRows($sqlQuery);
setlocale(LC_ALL, config::get('system', 'localeLong'), config::get('system', 'localeShort'));
foreach ($newsItems as &$newsItem) {
$newsItem['posted_str'] = strftime('%H:%M, %A %d %B %Y', $newsItem['posted_unix']);
}
return $newsItems;
}
public function edit($id, $title, $body, $visible)
{
if (empty($title)) {
$title = trim(substr(strip_tags($body), 0, 10)) . '...';
}
$this->db->update($this->tableName,
array('title' => $title,
'body' => $body,
'is_visible' => $visible),
'id = '.$this->db->quote($id));
}
public function remove($id)
{
$this->db->delete($this->tableName, 'id = '.$this->db->quote($id));
}
}