Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fari updated while developing Fireside

  • Loading branch information...
commit 12c0f246df8617f469739fe45c19afc381383af6 1 parent 82666bc
@radekstepan radekstepan authored
View
59 fari/Application/ApplicationDiagnostics.php
@@ -36,9 +36,7 @@ function shutdown() {
case E_COMPILE_ERROR:
case E_USER_ERROR:
// show diagnostics display
- if (REPORT_ERROR) Fari_ApplicationDiagnostics::display('PHP Error', $file, $line, $message.'.');
- // show message on a production server
- else Fari_ApplicationDiagnostics::productionMessage($message);
+ Fari_ApplicationDiagnostics::display('PHP Error', $file, $line, $message.'.');
break;
}
}
@@ -58,8 +56,8 @@ function shutdown() {
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework
*/
-class Fari_Exception extends Exception {
-
+final class Fari_Exception extends Exception {
+
/**
* Fire up a display with error message, sourcecode and some trace.
* @return void
@@ -74,10 +72,10 @@ public function fire() {
$message = $this->getMessage();
// trace of error
$trace = $this->getTrace();
-
+
Fari_ApplicationDiagnostics::display('Fari Exception', $file, $line, $message, $trace);
}
-
+
}
@@ -92,7 +90,7 @@ public function fire() {
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework
*/
-class Fari_ApplicationDiagnostics {
+final class Fari_ApplicationDiagnostics {
/**
* Dumps variables into the view.
@@ -113,6 +111,7 @@ public static function formatVars($mixed) {
//$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);
@@ -150,7 +149,7 @@ public static function formatVars($mixed) {
private static function recursiveDump($varname, $varval, $depth) {
// padding
for ($i=0; $i<$depth; $i++) echo "&nbsp;&nbsp;&nbsp;&nbsp;";
-
+
if (!is_array($varval)) {
echo $varname . ' = ' . var_export($varval, true) . ";<br>\n";
} else {
@@ -172,7 +171,7 @@ private static function recursiveDump($varname, $varval, $depth) {
public static function display($type, $file, $line, $message, $trace=NULL) {
// clean output
ob_end_clean();
-
+
// are we on a production server?
if (Fari_ApplicationEnvironment::isProduction()) self::productionMessage($message);
@@ -181,28 +180,28 @@ public static function display($type, $file, $line, $message, $trace=NULL) {
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
die("Fari Exception on line $line in \"$file\": $message");
}
-
+
// 'build' the header
self::showHeader();
-
+
// output the message to the user
echo '<div id="message"><h1>' . $type . '</h1><br />' . $message . '</div>';
-
+
// output information about the file
echo '<div id="file">File: <b>' . $file . '</b> Line: <b>' . $line . '</b></div>';
-
+
// show the source
self::showErrorSource($file, $line);
-
+
// show trace if present
if (!empty($trace)) self::showErrorTrace($trace);
-
+
// show declared classes
self::showDeclaredClasses();
-
+
// close the whole page properly
echo '</body></html>';
-
+
// end the misery...
die();
}
@@ -249,16 +248,16 @@ static function showErrorSource($errorFile, $errorLine, $displayRange=6, $divId=
$sourceCode = highlight_file($errorFile, TRUE);
// split into an array so that we can extract lines
$sourceCode = explode('<br />', $sourceCode);
-
+
// where (which line) to start showing source code? (start at line 1 ;)
$beginLine = max(1, $errorLine - $displayRange);
// where to stop?
$endLine = min($errorLine + $displayRange, count($sourceCode));
-
+
// open div with the error message
if ($divId != '0') echo '<div id="' . $divId . '" class="code" style="display:none;">';
else echo '<div id="' . $divId . '" class="code">';
-
+
// highlighting might have started before we 'cut' it
// set pointer to the beginning of our output
$pointer = $beginLine;
@@ -274,7 +273,7 @@ static function showErrorSource($errorFile, $errorLine, $displayRange=6, $divId=
break;
}
}
-
+
// paint the code
// set pointer to the beginning of our output
$pointer = $beginLine-1;
@@ -291,11 +290,11 @@ static function showErrorSource($errorFile, $errorLine, $displayRange=6, $divId=
// and output sourcecode line with delimiter
} else echo '<span class="num">' . $pointer . ':</span> &nbsp;&nbsp;&nbsp; ' . $line . "<br />\n";
}
-
+
// close div
echo '</div>';
}
-
+
/**
* Build a trace display with sourcecodes and all.
* @param array $errorTrace Contains an array with the trace as thrown
@@ -312,7 +311,7 @@ private static function showErrorTrace(array $errorTrace) {
if (isset($file)) echo '<b>' . $counter . '.</b>&nbsp;&nbsp;' . $file;
if (isset($line)) echo '&nbsp;&nbsp;(' . $line . ')';
if (isset($function)) echo '&nbsp;&nbsp;' . $function . '()&nbsp;&nbsp;';
-
+
// link to a javascript function that shows/hides the code listing
echo '<a href="" onclick="toggle(\'' . $counter . '\');return false;" >source</a>';
// add sourcecode listing
@@ -321,7 +320,7 @@ private static function showErrorTrace(array $errorTrace) {
}
echo "\n</div>"; // close her up
}
-
+
/**
* Shows declared classes and their descriptions.
* @return void
@@ -332,7 +331,7 @@ private static function showDeclaredClasses() {
// show only application related classes, Fari_Exception is implemented if we can see this :)
// a pointer to start from
$pointer = array_search('Fari_Exception', $declaredClasses) - 1;
-
+
// header
echo '<div id="box"><b>Declared Classes:</b><table>';
// go through the array...
@@ -342,18 +341,18 @@ private static function showDeclaredClasses() {
$class = @$declaredClasses[$pointer];
// output it
echo "\n<tr><td>" . $class . '</td><td><i>';
-
+
// get description if is implemented
@eval('if (method_exists($class, "_desc")) echo $class::_desc();');
// if (method_exists($class, '_desc')) echo $class::_desc(); // use from PHP 5.3.0
-
+
// close description
echo '</i></td</tr>';
}
// close her up
echo '</table></div>';
}
-
+
/**
* Is called when we are on a production server and don't want to show the source code.
* @param string $errorMessage Message Thrown
View
2  fari/Application/ApplicationEnvironment.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationEnvironment {
+final class Fari_ApplicationEnvironment {
/**
* Detect environment type.
View
9 fari/Application/ApplicationFunctions.php
@@ -70,5 +70,12 @@ function splitCamelCase($string) {
* @param string $title Title of the output
*/
function dump($mixed, $title='Variables Dump') {
- Fari_ApplicationDiagnostics::dump($mixed, $title);
+ if (is_string($mixed) && substr($mixed, 0, 5) == '<?xml') {
+ // an XML dump
+ if (!headers_sent()) header('Content-Type:text/xml');
+ echo $mixed;
+ } else {
+ // standard dump
+ Fari_ApplicationDiagnostics::dump($mixed, $title);
+ }
}
View
2  fari/Application/ApplicationI18n.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationI18n extends Fari_File {
+final class Fari_ApplicationI18n extends Fari_File {
/**#@+ directory with language locale */
const LOCALE_DIR = 'config/locales';
View
23 fari/Application/ApplicationLogger.php
@@ -18,7 +18,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationLogger {
+final class Fari_ApplicationLogger {
/**#@+ directory where to save logs */
const LOG_DIRECTORY = '/log';
@@ -64,7 +64,7 @@ public function update(Fari_ApplicationLoggerSubject $subject) {
*/
private function updateCounters($type) {
assert('!empty($type) && is_string($type); // log file type better be set!');
-
+
if (array_key_exists($type, $this->counters)) {
// increase count
$this->counters[$type]++;
@@ -92,11 +92,16 @@ private function writeLog($type, $content) {
$color = ($this->counters[$type] % 2 == 0) ? 'green' : 'blue';
// open file for writing
- $logFile = fopen(BASEPATH . self::LOG_DIRECTORY . '/' . "{$type}.log", 'a');
- // append to file...
- fwrite($logFile, $this->formatTime($color) . "\n {$this->rLogHighlight($content)}\n\n");
- // close file
- fclose($logFile);
+ try {
+ if ((!$logFile = fopen(BASEPATH . self::LOG_DIRECTORY . '/' . "{$type}.log", 'a'))) {
+ throw new Fari_Exception('Failed to open log file for writing '
+ . BASEPATH . self::LOG_DIRECTORY . '/' . "{$type}.log");
+ }
+ // append to file...
+ fwrite($logFile, $this->formatTime($color) . "\n {$this->rLogHighlight($content)}\n\n");
+ // close file
+ fclose($logFile);
+ } catch (Fari_Exception $exception) { $exception->fire(); }
}
/**
@@ -119,7 +124,7 @@ private function formatTime($color) {
private function rLogHighlight($string, $color='black', $underline=FALSE) {
// apply underline?
$underline = ($underline) ? '4' : '1';
-
+
// color switcher
switch ($color) {
case "magenta":
@@ -141,5 +146,5 @@ private function rLogHighlight($string, $color='black', $underline=FALSE) {
return "[{$underline};29;1m{$string}";
}
}
-
+
}
View
2  fari/Application/ApplicationReflection.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationReflection {
+final class Fari_ApplicationReflection {
/** @var ReflectionMethod */
private $method;
View
2  fari/Application/ApplicationRequest.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationRequest {
+final class Fari_ApplicationRequest {
/** @var Fari_ApplicationRoute */
private $route;
View
6 fari/Application/ApplicationResponse.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationResponse {
+final class Fari_ApplicationResponse {
/** @var default response code */
private $responseCode = '200';
@@ -169,7 +169,7 @@ function setContentType($type) {
*/
function redirectTo($url) {
// add forward slash if not specified
- if ($url[0] !== '/') $url .= '/';
+ if ($url[0] !== '/') $url = "/{$url}";
// is this an AJAX call?
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
@@ -182,5 +182,5 @@ function redirectTo($url) {
// die to 'protect' the presenter calling us
die();
}
-
+
}
View
2  fari/Application/ApplicationRoute.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationRoute extends Fari_Bag {
+final class Fari_ApplicationRoute extends Fari_Bag {
/**#@+ $_GET variable containing route (coming from .htaccess) */
const ROUTE = 'route';
View
2  fari/Application/ApplicationRouter.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationRouter {
+final class Fari_ApplicationRouter {
/** @var string with Fari_ApplicationPresenters */
private static $presenterDir = '';
View
2  fari/Application/ApplicationViewCache.php
@@ -17,7 +17,7 @@
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
-class Fari_ApplicationViewCache {
+final class Fari_ApplicationViewCache {
/**#@+ cache files directory & extension */
const CACHE_DIR = '/tmp/';
View
42 fari/Application/ApplicationViewHelpers.php
@@ -13,7 +13,7 @@
/**
* Helper class containing values etc.
- *
+ *
* @copyright Copyright (c) 2008, 2010 Radek Stepan
* @package Fari Framework\Application
*/
@@ -88,7 +88,7 @@ function renderPartial($name) {
$partial = BASEPATH . '/' . APP_DIR . '/views/' . Fari_ApplicationViewHelper::getPresenter()
. '/_' . $name . '.phtml';
}
-
+
// is it valid?
try {
// check if file path exists
@@ -145,8 +145,11 @@ function stylesheetLinkTag($css) {
// prepend slash?
if (substr($css, 0, 1) !== '/') $css = "/{$css}";
+ // append timestamp only in dev environment
+ $mktime = Fari_ApplicationEnvironment::isDevelopment() ? '?' . mktime() : '';
+
// echo with trailing timestamp
- echo '<link href="' . WWW_DIR . "/public{$css}" . '?' . mktime() .
+ echo '<link href="' . WWW_DIR . "/public{$css}" . $mktime .
'" media="screen" rel="stylesheet" type="text/css" />' . "\n";
}
@@ -159,7 +162,7 @@ function javascriptIncludeTag($js) {
// preconditions
assert('!empty($js); // javascript file not defined');
assert('is_string($js); // pass filename as a string');
-
+
// trim whitespace
$js = trim($js);
@@ -169,12 +172,26 @@ function javascriptIncludeTag($js) {
// prepend slash?
if (substr($js, 0, 1) !== '/') $js = "/{$js}";
+ // append timestamp only in dev environment
+ $mktime = Fari_ApplicationEnvironment::isDevelopment() ? '?' . mktime() : '';
+
// echo with trailing timestamp
- echo '<script src="' . WWW_DIR . "/public{$js}" . '?' . mktime() .
+ echo '<script src="' . WWW_DIR . "/public{$js}" . $mktime .
'" type="text/javascript"></script>' . "\n";
}
/**
+ * Form an atom RSS feed
+ * @param string $link
+ * @param boolean $echo echo output immediatelly?
+ */
+function atomTag($link, $echo=TRUE) {
+ $url = url($link, FALSE);
+ $tag = '<link href="'.$url.'" rel="alternate" title="ATOM" type="application/atom+xml" />';
+ if ($echo) echo $tag; else return $tag;
+}
+
+/**
* Generates a link to an image with alt in /public.
* @example <img alt="Bg" src="/images/bg.jpg?1213337144" />
* @param string $img path
@@ -193,8 +210,11 @@ function imageTag($img) {
// determine file so we can generate alt tag
$file = ucfirst(str_replace("-", " ", current(explode('.', end(explode('/', $img))))));
+ // append timestamp only in dev environment
+ $mktime = Fari_ApplicationEnvironment::isDevelopment() ? '?' . mktime() : '';
+
// echo with trailing timestamp
- echo "<img alt=\"{$file}\" src=\"" . WWW_DIR . "/public{$img}" . '?' . mktime() . '" />';
+ echo "<img alt=\"{$file}\" src=\"" . WWW_DIR . "/public{$img}" . $mktime . '" />';
}
/**
@@ -289,12 +309,18 @@ function url($link, $echo=TRUE, $domain=FALSE) {
* Will apply a highlight class to text.
* @param string $string input text
* @param string $highlight regex used in preg_replace
+ * @param boolean $echo echo output immediatelly?
*/
-function highlight($string, $highlight) {
+function highlight($string, $highlight, $echo=TRUE) {
// preconditions
assert('!empty($highlight); // you need to define what to highlight');
// apply highlight
- echo preg_replace("/($highlight)/", "<strong class='highlight'>$1</strong>", $string);
+ $string = preg_replace("/($highlight)/i", "<strong class='highlight'>$1</strong>", $string);
+ if ($echo) {
+ echo $string;
+ } else {
+ return $string;
+ }
}
/**
View
14 fari/Authenticator/AuthenticatorSimple.php
@@ -30,10 +30,16 @@ class Fari_AuthenticatorSimple extends Fari_AuthenticatorTemplate {
/**
* Setup database connection.
- * @param string $tableName
+ * @param mixed $table
*/
- public function __construct($tableName='users') {
- $this->table = new Table($tableName);
+ public function __construct($table='users') {
+ // are we passing a Table instance already?
+ if ($table instanceof Table) {
+ $this->table = $table;
+ // create new...
+ } else {
+ $this->table = new Table($table);
+ }
}
@@ -139,5 +145,5 @@ public function authenticateSuccess() {
public function authenticateFail() {
return FALSE;
}
-
+
}
View
70 fari/Db/DbTable.php
@@ -140,13 +140,6 @@ public function __call($method, $params) {
* @param mixed $value to save
*/
public function __set($column, $value) {
- // extract set prefix
- try {
- if (substr($column, 0, 3) !== 'set') {
- throw new Fari_Exception("Prepend 'set' before the column name.");
- } else $column = substr($column, 3);
- } catch (Fari_Exception $exception) { $exception->fire(); }
-
// save
$this->data[$column] = $value;
}
@@ -158,8 +151,6 @@ public function __set($column, $value) {
*/
public function set(array $values) {
foreach ($values as $key => $value) {
- // prepend set prefix
- $key = 'set' . $key;
// set
$this->$key = $value;
}
@@ -293,6 +284,8 @@ public function find() {
*/
public function findFirst() {
$this->limit = 1;
+ assert('isset($this->primaryKey); // primary key needs to be set');
+ $this->orderBy("{$this->primaryKey} ASC");
$this->method = '_find';
return $this;
}
@@ -303,6 +296,8 @@ public function findFirst() {
*/
public function findLast() {
$this->limit = 1;
+ assert('isset($this->primaryKey); // primary key needs to be set');
+ $this->orderBy("{$this->primaryKey} DESC");
$this->method = '_find';
return $this;
}
@@ -317,7 +312,7 @@ public function findAll() {
- /********************* destroy/remove queries *********************/
+ /********************* delete queries *********************/
@@ -325,8 +320,8 @@ public function findAll() {
* Remove item(s) from a table.
* @return Table, need to define a where clause
*/
- public function destroy() {
- $this->method = '_destroy';
+ public function delete() {
+ $this->method = '_delete';
return $this;
}
@@ -335,8 +330,8 @@ public function destroy() {
* Remove all items from a table.
* @return integer number of rows affected
*/
- public function destroyAll() {
- return $this->_destroy();
+ public function deleteAll() {
+ return $this->_delete();
}
@@ -399,7 +394,7 @@ public function countAll() {
* @return id of the inserted row
*/
public function save(array $values=NULL) {
- $this->add($values);
+ return $this->add($values);
}
/**
@@ -475,7 +470,7 @@ private function _find() {
$sql = "SELECT {$this->getSelectedColumns()} FROM {$this->getTableQuery()} {$this->getWhereQuery()}";
if (isset($this->order)) $sql .= " ORDER BY {$this->order}";
if (isset($this->limit)) $sql .= " LIMIT {$this->limit}";
-
+
// prepare SQL
$statement = $this->db->prepare($sql);
// bind where clause
@@ -484,20 +479,23 @@ private function _find() {
// notify
$this->logger->notify($this->toString($sql));
+ // we are going to clear the limit so...
+ $limit = $this->limit;
+
// reset data
$this->clearData();
// execute query and return an array result
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
- return ($this->limit == 1) ? (empty($result)) ? array() : end($result) : $result;
+ return ($limit == 1) ? (empty($result)) ? array() : current($result) : $result;
}
/**
* Remove items from a table.
* @return integer number of rows affected
*/
- private function _destroy() {
+ private function _delete() {
// SQL query
$sql = "DELETE FROM {$this->getTableQuery()} {$this->getWhereQuery()}";
@@ -705,8 +703,8 @@ private function prepareWhere() {
$result = '';
$i = 0;
foreach ($this->where as $column => $value) {
- // WHERE IN ()
- if (($operator = $this->findOperator($value)) == 'IN') {
+ // WHERE (NOT) IN ()
+ if (strpos($operator = $this->findOperator($value), 'IN') !== FALSE) {
// no binding occurs...
$result .= "{$column} {$value} AND ";
// the rest...
@@ -726,9 +724,12 @@ private function prepareWhere() {
*/
private function bindWhere($statement) {
$i = 0;
- foreach ($this->where as $column => $value) {
- // LIKE statement?
- if (strpos($value, '*') !== FALSE) $value = str_replace('*', '%', $value);
+ foreach ($this->where as $column => &$value) {
+ // (NOT)LIKE statements?
+ if (substr($value, 0, 1) == '!') $value = substr($value, 1);
+ if (substr($value, 0, 1) == '*') $value = str_replace('*', '%', $value);
+ // skip WHERE (NOT) IN
+ else if (substr($value, 0, 2) == 'IN' || substr($value, 0, 6) == 'NOT IN') continue;
// strip any operators and whitespace from the value
$value = preg_replace('/[>|<|=|\s\s+]/', '', $value);
@@ -746,19 +747,23 @@ private function bindWhere($statement) {
*/
private function findOperator($value) {
// LIKE
- if (strpos($value, '*') !== FALSE) { return 'LIKE';
+ if (substr($value, 0, 1) == '*') { return 'LIKE';
+ // NOT LIKE
+ } elseif (substr($value, 0, 2) == '!*') { return 'NOT LIKE';
// >=
- } elseif (strpos($value, '>=') !== FALSE) { return '>=';
+ } elseif (substr($value, 0, 2) == '>=') { return '>=';
// <=
- } elseif (strpos($value, '<=') !== FALSE) { return '<=';
+ } elseif (substr($value, 0, 2) == '<=') { return '<=';
// >
- } elseif (strpos($value, '>') !== FALSE) { return '>';
+ } elseif (substr($value, 0, 1) == '>') { return '>';
// <
- } elseif (strpos($value, '<') !== FALSE) { return '<';
+ } elseif (substr($value, 0, 1) == '<') { return '<';
// !=
- } elseif (strpos($value, '!=') !== FALSE) { return '!=';
+ } elseif (substr($value, 0, 2) == '!=') { return '!=';
+ // NOT IN
+ } elseif (substr($value, 0, 6) == 'NOT IN') { return 'NOT IN';
// IN
- } elseif (strpos($value, 'IN') !== FALSE) { return 'IN';
+ } elseif (substr($value, 0, 2) == 'IN') { return 'IN';
// =
} else return '=';
}
@@ -783,6 +788,11 @@ private function valueType($value) {
*/
private function clearData() {
$this->data = array();
+ $this->join = NULL;
+ $this->limit = NULL;
+ $this->order = NULL;
+ $this->select = NULL;
+ $this->where = NULL;
}
/**
View
70 fari/Feed/FeedAtom.php
@@ -0,0 +1,70 @@
+<?php if (!defined('FARI')) die();
+
+/**
+ * Fari Framework
+ *
+ * @copyright Copyright (c) 2008, 2010 Radek Stepan
+ * @license http://www.opensource.org/licenses/mit-license.php The MIT License
+ * @link http://radekstepan.com
+ * @category Fari Framework
+ */
+
+
+
+/**
+ * Create an Atom feed.
+ *
+ * @copyright Copyright (c) 2008, 2010 Radek Stepan
+ * @package Fari Framework\Feed
+ */
+class Fari_FeedAtom {
+
+ /** @var XML feed */
+ private $feed;
+ private $dom;
+
+ /**
+ * Construct an atom feed.
+ * @param string $title of the feed
+ */
+ public function __construct($title) {
+ $feed = simplexml_load_string('<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
+ <link rel="self"/><title type="html"/></feed>');
+
+ $feed->title = $title;
+ $feed->link['href'] = $feed->id = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
+ $feed->updated = date(DATE_ATOM);
+
+ $this->feed = dom_import_simplexml($feed);
+
+ $this->dom = $this->feed->ownerDocument;
+ }
+
+ /**
+ * Append items to the feed.
+ * @param array $items nees to contain content and title keys
+ */
+ public function atomise(array $items) {
+ foreach ($items as $id => $item) {
+ $entry = simplexml_load_string('<entry><link rel="alternate" type="text/html"/><title type="html"/>
+ <content type="html"/></entry>');
+
+ $entry->link['href'] = $entry->id = $id;
+ assert('array_key_exists("title", $item); // each item needs to have a \'title\' key');
+ $entry->title = $item['title'];
+ assert('array_key_exists("content", $item); // each item needs to have a \'content\' key');
+ $entry->content = $item['content'];
+
+ $this->feed->appendChild($this->dom->importNode(dom_import_simplexml($entry), true));
+ }
+ }
+
+ /**
+ * Echo the feed with appropriate header.
+ */
+ public function generate() {
+ header('Content-Type: application/atom+xml; charset=utf-8');
+ echo $this->dom->saveXML();
+ }
+
+}
View
15 fari/Mail/Mail.php
@@ -54,12 +54,19 @@ public function addFrom($email, $name=NULL) {
/**
* Add to field.
- * @param string $email Email address
+ * @param mixed $email Email address
* @param string $name Optional name
* @return Fari_Mail subclass
*/
public function addTo($email, $name=NULL) {
- $this->setHeader('To', $this->formatEmail($email, $name));
+ // if passing an array will form multiple recipients
+ if (is_array($email)) {
+ foreach ($email as &$e) $e = $this->formatEmail($e);
+ $this->setHeader('To', implode(',', $email));
+ } else {
+ // form a single recipient
+ $this->setHeader('To', $this->formatEmail($email, $name));
+ }
return $this;
}
@@ -109,7 +116,7 @@ private function setHeader($type, $value) {
public function getHeader($type) {
return $this->headers[$type];
}
-
+
/**
* Setup host, port, login and password.
* @param string $host
@@ -186,5 +193,5 @@ private function formatEmail($email, $name) {
* Sender.
*/
abstract function send();
-
+
}
View
2  fari/Test/TestUnit.php
@@ -128,7 +128,7 @@ public function report() {
color:#fff;font-size:100%;margin:0;padding:1px 0;}#message{border-top:1px solid <?php echo $line; ?>;
padding:5px 30px 10px;}h1{margin-bottom:0;font-weight:400;font-size:175%;}#box{background-color:#EEE;
border:1px solid #ADAEAF;margin:10px 30px 0;padding:5px;}#test{margin:10px 30px 0;padding:5px;background:#F5F5F5;
- color:#33393C;border:1px solid #CCCDCF;}#test .failed{color:#C52F24;}#test .passed{color:#26BF26;}
+ color:#33393C;border:1px solid #CCCDCF;}#test .failed{color:#C52F24;}#test .passed{color:#008800;}
i{color:#999;}.num{color:#9E9E7E;font-style:normal;font-weight:400;}a{color:#980905;}td{padding-right:20px;}
table{font:16px/1.5 "Trebuchet MS", "Geneva CE", lucida, sans-serif;font-size:100%;}#title b,span.err{color:#FFF;}
.code{background-color:#FFF9D8;border:1px solid #FECA51;margin:10px 30px;padding:5px;}.error{background-color:#C52F24;
View
78 fari/Tools/ToolsBenchmark.php
@@ -0,0 +1,78 @@
+<?php if (!defined('FARI')) die();
+
+/**
+ * Fari Framework
+ *
+ * @copyright Copyright (c) 2008, 2010 Radek Stepan
+ * @license http://www.opensource.org/licenses/mit-license.php The MIT License
+ * @link http://radekstepan.com
+ * @category Fari Framework
+ */
+
+
+
+/**
+ * Benchmark execution time.
+ *
+ * @copyright Copyright (c) 2008, 2010 Radek Stepan
+ * @package Fari Framework\Benchmark
+ */
+class Fari_ToolsBenchmark {
+
+ /** @var array of running benchmarks or results */
+ private $data;
+
+ /**
+ * Start benchmark.
+ * @param string $activity to save under
+ */
+ public function start($activity) {
+ $this->data[$activity] = microtime();
+ }
+
+ /**
+ * Stop benchmark and save time into activity.
+ * @param string $activity
+ * @return FALSE if activity not found
+ */
+ public function stop($activity) {
+ if (isset($this->data[$activity])) {
+ $stop = $this->fixMicrotime(microtime());
+ $start = $this->fixMicrotime($this->data[$activity]);
+ $this->data[$activity] = round($stop - $start, 4) . ' s';
+ } else {
+ return FALSE;
+ }
+ }
+
+ /**
+ * Return an array of benchmark results.
+ * @param boolean $nice set to TRUE if you want to echo the results into a table
+ * @return array
+ */
+ public function report($nice=FALSE) {
+ if ($nice) {
+ echo '<table class="benchmark">';
+ foreach ($this->data as $activity => $time) {
+ // print only results
+ if (strpos($time, 's') !== FALSE) {
+ echo "<tr><td>{$activity}</td><td>{$time}</td></tr>";
+ }
+ }
+ echo '</table>';
+ } else {
+ return $this->data;
+ }
+ }
+
+ /**
+ * Fix microtime.
+ * @param string $time
+ * @return string
+ */
+ private function fixMicrotime($time) {
+ $time = explode(' ', $time);
+ return doubleval($time[0]) + $time[1];
+ }
+
+}
View
2  index.php
@@ -18,7 +18,7 @@
// Step 1a: Define absolute environment values
// set so that we can check if PHP pages have been accessed directly
-if (!defined('FARI')) define('FARI', 'Fari Framework 2.3.12.0 (May 18, 2010)');
+if (!defined('FARI')) define('FARI', 'Fari Framework 2.3.14.1 (May 27, 2010)');
// get absolute pathname and define it as a constant (server install path)
if (!defined('BASEPATH')) define('BASEPATH', dirname(__FILE__));
View
54 script/generate.php
@@ -150,7 +150,7 @@ public function actionEdit() { }
public function actionUpdate() { }
/** Deletes the specified object from the database. */
- public function actionDestroy() { }
+ public function actionDelete() { }
}
CODE;
@@ -216,11 +216,11 @@ public function actionEdit() { }
/** Receives the form submission from the edit action and updates the specific object. */
public function actionUpdate(\$id) {
\$this->{$modelLowercase}->update()->set(\$this->request->getPost())->where(\$id);
- \$this->redirectTo('{$lowercase}/show/\$id');
+ \$this->redirectTo("{$lowercase}/show/{\$id}");
}
/** Deletes the specified object from the database. */
- public function actionDestroy(\$id) {
+ public function actionDelete(\$id) {
\$this->{$modelLowercase}->destroy()->where(\$id);
\$this->redirectTo('{$lowercase}/index');
}
@@ -402,9 +402,6 @@ function newAuth($name) {
const ADMIN = 'admin';
/**#@-*/
- /** @var authenticated user */
- private \$user;
-
public function actionIndex(\$p) {
\$this->actionLogin();
}
@@ -419,7 +416,7 @@ public function actionLogin() {
\$password = Fari_Decode::accents(\$this->request->getPost('password'));
try {
- \$this->user = new {$name}Auth(\$username, \$password, \$this->request->getPost('token'));
+ \$user = new {$name}Auth(\$username, \$password, \$this->request->getPost('token'));
\$this->redirectTo('/' . self::ADMIN);
} catch ({$prefix}UserNotAuthenticatedException \$e) {
@@ -436,11 +433,11 @@ public function actionLogin() {
* Destroy user session.
*/
public function actionLogout() {
- // do we have an instance?
- if (\$this->user instanceof {$prefix}User) {
- \$this->flashSuccess = 'You have been logged out';
- \$this->user->signOut();
- } else {
+ try {
+ \$user = new {$name}User();
+ \$user->signOut();
+ \$this->flashSuccess = "You have been logged out";
+ } catch (AuthUserNotAuthenticatedException \$e) {
\$this->flashSuccess = 'You are already logged out';
}
@@ -490,16 +487,33 @@ function __construct(\$username, \$password, \$token=NULL) {
* Authenticated user.
*
* @example This object will throw an exception if user is not authenticated, use in admin
- * @package Application\Models\\$prefix
+ * @package Application\Models\{$prefix}
*/
class {$prefix}User extends Fari_AuthenticatorSimple {
- public function __construct() {
- parent::__construct('{$lowercase}');
+ private \$table;
- // no entry, we are not logged in, fail the constructor
- if (!\$this->isAuthenticated()) throw new {$prefix}UserNotAuthenticatedException();
- }
+ /**
+ * Check that user is authenticated.
+ * @throws {$prefix}UserNotAuthenticatedException
+ */
+ public function __construct() {
+ // construct the db table
+ \$this->table = new Table('{$lowercase}');
+ // call the authenticator
+ parent::__construct(\$this->table);
+
+ // no entry, we are not logged in, fail the constructor
+ if (!\$this->isAuthenticated()) throw new {$prefix}UserNotAuthenticatedException();
+ }
+
+ /**
+ * Fetch row from '{$lowercase}' table.
+ * @return array
+ */
+ public function getUser() {
+ return \$this->table->findFirst()->where(array('username' => \$this->getCredentials()));
+ }
}
@@ -582,7 +596,7 @@ class {$prefix}UserNotAuthenticatedException extends Exception {}
createDirectory("{$viewsPath}/{$name}/");
// default index file
- createFile("{$viewsPath}/{$name}/login.tpl.php", $viewCode);
+ createFile("{$viewsPath}/{$name}/login.phtml", $viewCode);
// models are in prefix subdirectory
createDirectory("{$modelsPath}/{$prefix}/");
@@ -604,7 +618,7 @@ class {$prefix}UserNotAuthenticatedException extends Exception {}
* Create a new directory/check it exists.
* @param string $path to the directory
*/
-function createDirectory($path) {
+function createDirectory($path) {
// does the dir exist? I can haz file? Dir! File? Cheese!
if (file_exists(BASEPATH . "/{$path}")) {
message(" exists {$path}", 'gray');
Please sign in to comment.
Something went wrong with that request. Please try again.