From 39132f9bcf8133174bca01a1801477a493ab3b7a Mon Sep 17 00:00:00 2001 From: pies Date: Sat, 11 Jun 2005 03:45:31 +0000 Subject: [PATCH] - I've rebuilt the startup a bit, more libraries are explicitly loaded at startup. They were loaded anyway (Object, Inflector), but implicitly thru uses() calls. I did it to untangle the relationships between files. - Link tag generator fixed for compatibility with XHTML (& => &) - prepare() and tables() methods renamed to prepareField() and tablesList() in database layers, prepare() and tables() meta-methods created in Model. The first one so that prepare() can accept both strings and arrays, the second one to fix Ticket #26 (case-sensitive table names didn't work for DB2). - Few minor changes of includes() to requires() and the other way, to prevent unnecessary program terminations, and potential crashes. - Time::toAtom() and Time::toRss() to format dates for XML feeds. - Some code cleanups (unnecessary __construct()'s), also, I'm changing the parentheses into: if (true) { } I hope that's ok with everybody? I find it easier to understand code with that formatting. Does anyone know a highly configurable tool that would format PHP code automatically? git-svn-id: https://svn.cakephp.org/repo/trunk/cake@241 3807eeeb-6ff5-0310-8944-8be069107fe0 --- libs/basics.php | 36 +++---- libs/controller.php | 8 +- libs/dbo.php | 28 ++++-- libs/dbo_adodb.php | 5 +- libs/dbo_mysql.php | 5 +- libs/dbo_pear.php | 12 ++- libs/dbo_postgres.php | 5 +- libs/dbo_sqlite.php | 2 +- libs/dispatcher.php | 11 ++- libs/error_messages.php | 18 +--- libs/flay.php | 21 ++-- libs/folder.php | 7 -- libs/inflector.php | 57 +++++++++-- libs/model.php | 205 +++++++++++++++++++++++++--------------- libs/object.php | 5 +- libs/router.php | 14 +-- libs/template.php | 23 ++--- libs/test.php | 7 -- libs/time.php | 113 +++++++++++----------- libs/validators.php | 3 - public/index.php | 10 +- 21 files changed, 327 insertions(+), 268 deletions(-) diff --git a/libs/basics.php b/libs/basics.php index 5dbba6605..21926ab8e 100644 --- a/libs/basics.php +++ b/libs/basics.php @@ -30,8 +30,6 @@ * */ -uses('neat_array'); - /** * Loads all models. * @@ -80,7 +78,7 @@ function loadController ($name) { if (file_exists($helper_fn)) require($helper_fn); - + return file_exists($controller_fn)? require($controller_fn): false; } @@ -90,7 +88,8 @@ function loadController ($name) { * @param string $path * @return array */ -function listClasses($path) { +function listClasses($path) +{ $modules = new Folder($path); return $modules->find('(.+)\.php'); } @@ -102,7 +101,7 @@ function config () { $args = func_get_args(); foreach ($args as $arg) { if (file_exists(CONFIGS.$arg.'.php')) { - require_once (CONFIGS.$arg.'.php'); + include (CONFIGS.$arg.'.php'); if (count($args) == 1) return true; } else { @@ -118,7 +117,7 @@ function config () { * * Example: * - * uses('inflector', 'object'); + * uses('flay', 'time'); * * * @uses LIBS @@ -147,8 +146,10 @@ function uses () * @param boolean $var * @param boolean $show_html */ -function debug($var = false, $show_html = false) { - if (DEBUG) { +function debug($var = false, $show_html = false) +{ + if (DEBUG) + { print "\n
\n";
 		if ($show_html) $var = str_replace('<', '<', str_replace('>', '>', $var));
 		print_r($var);
@@ -157,7 +158,8 @@ function debug($var = false, $show_html = false) {
 }
 
 
-if (!function_exists('getMicrotime')) {
+if (!function_exists('getMicrotime')) 
+{
 /**
  * Returns microtime for execution time checking.
  *
@@ -181,24 +183,24 @@ if (!function_exists('sortByKey')) {
  */
 	function sortByKey(&$array, $sortby, $order='asc', $type=SORT_NUMERIC) {
 
-		if( is_array($array) ) {
+		if (is_array($array)) {
 
-			foreach( $array AS $key => $val )
+			foreach ($array as $key => $val)
 			$sa[$key] = $val[$sortby];
 
-			if( $order == 'asc' )
-			asort($sa, $type);
+			if ($order == 'asc')
+				asort($sa, $type);
 			else
-			arsort($sa, $type);
+				arsort($sa, $type);
 
-			foreach( $sa as $key=>$val )
-			$out[] = $array[$key];
+			foreach ($sa as $key=>$val)
+				$out[] = $array[$key];
 
 			return $out;
 
 		}
 		else
-		return null;
+			return null;
 	}
 }
 
diff --git a/libs/controller.php b/libs/controller.php
index 7437beafe..3f3c182ab 100644
--- a/libs/controller.php
+++ b/libs/controller.php
@@ -112,7 +112,7 @@ class Controller extends Template {
 
 		$this->name = strtolower($r[1]);
 		$this->viewpath = Inflector::underscore($r[1]);
-		
+
 		$model_class = Inflector::singularize($this->name);
 		
 		if (class_exists($model_class) && $this->db && ($this->uses === false)) 
@@ -224,6 +224,7 @@ class Controller extends Template {
 
 /**
   * Returns an external HTML link to $url for given $title, optionally using $html_options.
+  * The ereg_replace is to replace the '&' in the URL into & for XHTML purity.
   *
   * @param string $title
   * @param string $url
@@ -232,7 +233,7 @@ class Controller extends Template {
   */
 	function linkOut ($title, $url=null, $html_options=null) {
 		$url = $url? $url: $title;
-		return sprintf(TAG_LINK, $url, $this->parseHtmlOptions($html_options), $title);
+		return sprintf(TAG_LINK, ereg_replace('&([^a])', '&\1', $url), $this->parseHtmlOptions($html_options), $title);
 	}
 
 /**
@@ -247,6 +248,7 @@ class Controller extends Template {
 		$html_options['action'] = $this->UrlFor($target);
 		$html_options['method'] = $type=='get'? 'get': 'post';
 		$type == 'file'? $html_options['enctype'] = 'multipart/form-data': null;
+
 		return sprintf(TAG_FORM, $this->parseHtmlOptions($html_options, ''));
 	}
 
@@ -631,8 +633,6 @@ class Controller extends Template {
 		return empty($this->validationErrors[$field])? 0: $this->validationErrors[$field];
 	}
 
-
-
 /**
   * Adds $name and $link to the breadcrumbs array.
   *
diff --git a/libs/dbo.php b/libs/dbo.php
index d8c6deed6..4c5971ee4 100644
--- a/libs/dbo.php
+++ b/libs/dbo.php
@@ -23,7 +23,7 @@
   * Example usage:
   *
   * 
-  * require('dbo_mysql.php'); // or 'dbo_postgres.php'
+  * require_once('dbo_mysql.php'); // or 'dbo_postgres.php'
   *
   * // create and connect the object
   * $db = new DBO_MySQL(array( // or 'DBO_Postgres'
@@ -186,7 +186,6 @@ class DBO extends Object {
   */
 	var $_queriesLogMax=200;
  
-
 	// specific for each database, implemented in db drivers
 	function connect ($config) {
 		die('Please implement DBO::connect() first.');
@@ -204,7 +203,7 @@ class DBO extends Object {
 		die('Please implement DBO::fetchRow() first.');
 	}
 
-	function tables() {
+	function tablesList() {
 		die('Please implement DBO::tables() first.');
 	}
 
@@ -212,6 +211,10 @@ class DBO extends Object {
 		die('Please implement DBO::fields() first.');
 	}
 
+	function prepareField ($data) {
+		die('Please implement DBO::prepareField() first.');
+	}
+
 	function lastError ($result) {
 		die('Please implement DBO::lastError() first.');
 	}
@@ -278,11 +281,7 @@ class DBO extends Object {
  */
 	function prepare ($data) 
 	{
-		if (is_string($data))
-		{
-			return $this->prepareValue($data);
-		}
-		else 
+		if (is_array($data))
 		{
 			$out = null;
 			foreach ($data as $key=>$item) 
@@ -291,8 +290,18 @@ class DBO extends Object {
 			}
 			return $out;
 		}
+		else 
+		{
+			return $this->prepareValue($data);
+		}
 	}
 
+	function tables()
+	{
+		return array_map('strtolower', $this->tablesList());
+	}
+	
+	
 /**
   * Executes given SQL statement.
   *
@@ -312,7 +321,8 @@ class DBO extends Object {
   * @param string $sql
   * @return unknown
   */
-	function query($sql) {
+	function query($sql) 
+	{
 		$t = getMicrotime();
 		$this->_result = $this->execute($sql);
 		$this->affected = $this->lastAffected();
diff --git a/libs/dbo_adodb.php b/libs/dbo_adodb.php
index 076b5bd15..c22c136a6 100644
--- a/libs/dbo_adodb.php
+++ b/libs/dbo_adodb.php
@@ -14,7 +14,6 @@
 //////////////////////////////////////////////////////////////////////////
 
 /**
-  * Purpose: DBO_AdoDB
   * AdoDB layer for DBO.
   * 
   * @filesource 
@@ -32,7 +31,6 @@
 
 /**
   * Include AdoDB files.
-  *
   */
 require_once(VENDORS.'adodb/adodb.inc.php');
 
@@ -42,7 +40,6 @@ require_once(VENDORS.'adodb/adodb.inc.php');
   * @package cake
   * @subpackage cake.libs
   * @since Cake v 0.2.9
-  *
   */
 class DBO_AdoDB extends DBO {
 
@@ -99,7 +96,7 @@ class DBO_AdoDB extends DBO {
   *
   * @return array Array of tablenames in the database
   */
-	function tables() {
+	function tablesList() {
 		$tables = $this->_adodb->MetaTables('TABLES');
 
 		if (!sizeof($tables)>0) {
diff --git a/libs/dbo_mysql.php b/libs/dbo_mysql.php
index f62291416..63f3be1fb 100644
--- a/libs/dbo_mysql.php
+++ b/libs/dbo_mysql.php
@@ -37,7 +37,6 @@
 
 /**
   * Include DBO.
-  *
   */
 
 uses('dbo');
@@ -47,7 +46,6 @@ uses('dbo');
   * @package cake
   * @subpackage cake.libs
   * @since Cake v 0.2.9
-  *
   */
 class DBO_MySQL extends DBO {
 	
@@ -104,7 +102,7 @@ class DBO_MySQL extends DBO {
   *
   * @return array Array of tablenames in the database
   */
-	function tables () {
+	function tablesList () {
 		$result = mysql_list_tables($this->config['database']);
 
 		if (!$result) {
@@ -177,7 +175,6 @@ class DBO_MySQL extends DBO {
 /**
   * Returns the ID generated from the previous INSERT operation.
   *
-  * @param string $table Name of the database table
   * @return int 
   */
 	function lastInsertId() {
diff --git a/libs/dbo_pear.php b/libs/dbo_pear.php
index b4f4cac8a..08add7a81 100644
--- a/libs/dbo_pear.php
+++ b/libs/dbo_pear.php
@@ -37,16 +37,15 @@
 
 /**
   * Include DBO.
-  *
   */
 uses('dbo');
+
 /**
   * Pear::DB layer for DBO.
   *
   * @package cake
   * @subpackage cake.libs
   * @since Cake v 0.2.9
-  *
   */
 class DBO_Pear extends DBO {
 
@@ -54,6 +53,7 @@ class DBO_Pear extends DBO {
   * Connects to the database using options in the given configuration array.
   *
   * @param array $config Configuration array for connecting
+  * @return unknown
   */
 	function connect ($config) {
 		die('Please implement DBO::connect() first.');
@@ -93,7 +93,7 @@ class DBO_Pear extends DBO {
   *
   * @return array Array of tablenames in the database
   */
-	function tables () {  // POSTGRESQL ONLY! PEAR:DB DOESN'T SUPPORT LISTING TABLES
+	function tablesList () {  // POSTGRESQL ONLY! PEAR:DB DOESN'T SUPPORT LISTING TABLES
 		$sql = "SELECT a.relname AS name
          FROM pg_class a, pg_user b
          WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
@@ -144,8 +144,10 @@ class DBO_Pear extends DBO {
   *
   * @return string Error message
   */
-	function lastError () {
-		return PEAR::isError($this->_result)? $this->_result->getMessage(): null;
+	function lastError ($result=null) {
+		if (!$result) $result = $this->_result;
+
+		return PEAR::isError($result)? $result->getMessage(): null;
 	}
 
 /**
diff --git a/libs/dbo_postgres.php b/libs/dbo_postgres.php
index 2648d841f..10481aa3e 100644
--- a/libs/dbo_postgres.php
+++ b/libs/dbo_postgres.php
@@ -31,7 +31,6 @@
 
 /**
   * Include DBO.
-  *
   */
 uses('dbo');
 
@@ -41,7 +40,6 @@ uses('dbo');
   * @package cake
   * @subpackage cake.libs
   * @since Cake v 1.0.0.114
-  *
   */
 class DBO_Postgres extends DBO {
 	
@@ -49,6 +47,7 @@ class DBO_Postgres extends DBO {
   * Connects to the database using options in the given configuration array.
   *
   * @param array $config Configuration array for connecting
+  * @return True if successfully connected.
   */
 	function connect ($config) {
 		if($config) {
@@ -98,7 +97,7 @@ class DBO_Postgres extends DBO {
   *
   * @return array Array of tablenames in the database
   */
-	function tables () {
+	function tablesList () {
 		$sql = "SELECT a.relname AS name
          FROM pg_class a, pg_user b
          WHERE ( relkind = 'r') and relname !~ '^pg_' AND relname !~ '^sql_'
diff --git a/libs/dbo_sqlite.php b/libs/dbo_sqlite.php
index 02c6bc1b5..2df7d643d 100644
--- a/libs/dbo_sqlite.php
+++ b/libs/dbo_sqlite.php
@@ -99,7 +99,7 @@ class DBO_SQLite extends DBO {
   *
   * @return array Array of tablenames in the database
   */
-	function tables () {
+	function tablesList () {
 		$result = sqlite_query($this->_conn, "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;");
 $this->_conn
 		if (!$result) {
diff --git a/libs/dispatcher.php b/libs/dispatcher.php
index c767a5934..ae11a70c9 100644
--- a/libs/dispatcher.php
+++ b/libs/dispatcher.php
@@ -40,13 +40,12 @@ uses('error_messages', 'object', 'router', 'controller');
 /**
   * Dispatches the request, creating appropriate models and controllers.
   *
-  *
   * @package cake
   * @subpackage cake.libs
   * @since Cake v 0.2.9
-  *
   */
 class Dispatcher extends Object {
+
 /**
   * Base URL
   *
@@ -75,7 +74,8 @@ class Dispatcher extends Object {
   * @param string $url
   * @return unknown
   */
-	function dispatch ($url) {
+	function dispatch ($url) 
+	{
 		global $_POST, $_GET, $_FILES, $_SESSION;
 
 		/* @var $params array */
@@ -141,12 +141,13 @@ class Dispatcher extends Object {
   * @param string $from_url
   * @return array Parameters found in POST and GET.
   */
-	function parseParams ($from_url) {
+	function parseParams ($from_url) 
+	{
 		global $_POST, $_FILES;
 
 		// load routes config
 		$Route = new Router();
-		require CONFIGS.'routes.php';
+		include CONFIGS.'routes.php';
 		$params = $Route->parse ($from_url);
 
 		// add submitted form data
diff --git a/libs/error_messages.php b/libs/error_messages.php
index 4d67482ce..0c83ef8a2 100644
--- a/libs/error_messages.php
+++ b/libs/error_messages.php
@@ -31,97 +31,81 @@
 
 /**
   * Error string for when the specified database driver can not be found.
-  *
   */
 define ('ERROR_UNKNOWN_DATABASE_DRIVER', '[DbFactory] Specified database driver (%s) not found');
 
 /**
   * Error string for when the dispatcher can not find a default controller.
-  *
   */
 define ('ERROR_NO_CONTROLLER_SET', '[Dispatcher] No default controller, can\'t continue, check routes config');
 
 /**
   * Error string for when the dispatcher can not find a default action.
-  *
   */
 define ('ERROR_NO_ACTION_SET', '[Dispatcher] No default action, can\'t continue, check routes config');
 
 /**
   * Error string for when the dispatcher can not find given controller.
-  *
   */
 define ('ERROR_UNKNOWN_CONTROLLER', '[Dispatcher] Specified controller "%s" doesn\'t exist, create it first');
 
 /**
   * Error string for when the dispatcher can not find expected action in controller.
-  *
   */
 define ('ERROR_NO_ACTION', '[Dispatcher] Action "%s" is not defined in the "%s" controller, create it first');
 
 /**
   * Error string for errors in view.
-  *
   */
 define ('ERROR_IN_VIEW', '[Controller] Error in view "%s", got: 
%s
'); /** * Error string for when the controller can not find expected view. - * */ define ('ERROR_NO_VIEW', '[Controller] No template file for view "%s" (expected "%s"), create it first'); /** * Error string for errors in layout. - * */ define ('ERROR_IN_LAYOUT', '[Controller] Error in layout "%s", got:
"%s"
'); /** * Error string for when the controller can not find expected layout. - * */ define ('ERROR_NO_LAYOUT', '[Controller] Couln\'t find layout "%s" (expected "%s"), create it first'); /** * Error string for database not being able to access the table list. - * */ define ('ERROR_NO_TABLE_LIST', '[Database] Couldn\'t get table list, check database config'); /** - * Error string for No corresponding database table found for model. - * + * Error string for no corresponding database table found for model. */ define ('ERROR_NO_MODEL_TABLE', '[Model] No DB table for model "%s" (expected "%s"), create it first'); /** * Error string for Field not present in table. - * */ define ('ERROR_NO_FIELD_IN_MODEL_DB', '[Model::set()] Field "%s" is not present in table "%s", check database schema'); /** * Error string short short error message. - * */ define ('SHORT_ERROR_MESSAGE', '
%s
'); /** * Error string for when original image can not be loaded. - * */ define ('ERROR_CANT_GET_ORIGINAL_IMAGE', '[Image] Couldn\'t load original image %s (tried from "%s")'); /** * Error string for error 404. - * */ define ('ERROR_404', "The requested address /%s was not found on this server."); // second %s contains short error message /** * Error string for error 500. - * */ define ('ERROR_500', "Application error, sorry."); diff --git a/libs/flay.php b/libs/flay.php index 32c911f6b..4943b6764 100644 --- a/libs/flay.php +++ b/libs/flay.php @@ -16,8 +16,6 @@ /** * Purpose: Flay * Text-to-html parser, similar to Textile or RedCloth, only with somehow different syntax. - * See Flay::test() for examples. - * Test with $flay = new Flay(); $flay->test(); * * @filesource * @author Cake Authors/Developers @@ -34,20 +32,19 @@ /** * Enter description here... - * */ uses('object'); /** * Text-to-html parser, similar to Textile or RedCloth, only with a little different syntax. * - * * @package cake * @subpackage cake.libs * @since Cake v 0.2.9 - * */ -class Flay extends Object { + +class Flay extends Object +{ /** * Enter description here... * @@ -146,13 +143,17 @@ class Flay extends Object { if (!$bare) { // guess links $urls = null; - if (preg_match_all("#((?:http|https|ftp|nntp)://[^ ]+)#", $line, $urls)) { - foreach ($urls[1] as $url) { + if (preg_match_all("#((?:http|https|ftp|nntp)://[^ ]+)#", $line, $urls)) + { + foreach ($urls[1] as $url) + { $line = str_replace($url, "{$url}", $line); } } - if (preg_match_all("#(www\.[^\n\%\ ]+[^\n\%\,\.\ ])#", $line, $urls)) { - foreach ($urls[1] as $url) { + if (preg_match_all("#(www\.[^\n\%\ ]+[^\n\%\,\.\ ])#", $line, $urls)) + { + foreach ($urls[1] as $url) + { $line = str_replace($url, "{$url}", $line); } } diff --git a/libs/folder.php b/libs/folder.php index 15778464f..9b0b1ee3d 100644 --- a/libs/folder.php +++ b/libs/folder.php @@ -30,16 +30,9 @@ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ -/** - * Enter description here... - * - */ -uses('object'); - /** * Folder structure browser, lists folders and files. * - * * @package cake * @subpackage cake.libs * @since Cake v 0.2.9 diff --git a/libs/inflector.php b/libs/inflector.php index 9133fc282..3af4d0ced 100644 --- a/libs/inflector.php +++ b/libs/inflector.php @@ -32,11 +32,6 @@ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ -/** - * Enter description here... - */ -uses('object'); - /** * This is a port of Ruby on Rails' Inflector class. * Inflector pluralizes and singularizes English nouns. @@ -46,7 +41,8 @@ uses('object'); * @subpackage cake.libs * @since Cake v 0.2.9 */ -class Inflector extends Object { +class Inflector extends Object +{ /** * Constructor. @@ -168,8 +164,9 @@ class Inflector extends Object { * @param string $table_name Name of database table to get class name for * @return string */ - function classify($table_name) { - return $this->camelize($this->singularize($table_name)); + function classify($table_name) + { + return Inflector::camelize(Inflector::singularize($table_name)); } /** @@ -179,9 +176,49 @@ class Inflector extends Object { * @param string $class_name * @return string */ - function foreignKey($class_name) { - return $this->underscore($class_name) . "_id"; + function foreignKey($class_name) + { + return Inflector::underscore($class_name) . "_id"; } + + function toControllerFilename($name) + { + return CONTROLLERS.Inflector::underscore($name).'.php'; + } + + function toHelperFilename($name) + { + return HELPERS.Inflector::underscore($name).'.php'; + } + + function toFullName($name, $correct) + { + if (strstr($name, '_') && (strtolower($name) == $name)) + { + return Inflector::camelize($name); + } + + if (preg_match("/^(.*)({$correct})$/i", $name, $reg)) + { + if ($reg[2] == $correct) + { + return $name; + } + else + { + return ucfirst($reg[1].$correct); + } + } + else + { + return ucfirst($name.$correct); + } + } + + function toLibraryFilename ($name) + { + return LIBS.Inflector::underscore($name).'.php'; + } } ?> diff --git a/libs/model.php b/libs/model.php index cfd19fd73..cc047a595 100644 --- a/libs/model.php +++ b/libs/model.php @@ -39,7 +39,6 @@ /** * Enter description here... - * */ uses('object', 'validators', 'inflector'); @@ -50,13 +49,13 @@ uses('object', 'validators', 'inflector'); * The table is required to have at least 'id auto_increment', 'created datetime', * and 'modified datetime' fields. * - * * @package cake * @subpackage cake.libs * @since Cake v 0.2.9 * */ -class Model extends Object { +class Model extends Object +{ /** * Enter description here... @@ -153,17 +152,11 @@ class Model extends Object { * @param string $table Database table to use. * @param unknown_type $db Database connection object. */ - function __construct ($id=false, $table=null, $db=null) { + function __construct ($id=false, $table=null, $db=null) + { global $DB; - if ($db) - { - $this->db = $db; - } - else - { - $this->db = &$DB; - } + $this->db = $db? $db: $DB; if ($id) $this->id = $id; @@ -178,13 +171,14 @@ class Model extends Object { * Creates has-many relationships, and then call relink. * * @see relink() - * */ - function createLinks () { + function createLinks () + { if (!empty($this->hasMany)) $this->_hasMany = explode(',', $this->hasMany); - foreach ($this->_hasMany as $model_name) { + foreach ($this->_hasMany as $model_name) + { // todo fix strip the model name $model_name = Inflector::singularize($model_name); $this->$model_name = new $model_name(); @@ -197,10 +191,11 @@ class Model extends Object { * Updates this model's many-to-one links, by emptying the links list, and then linkManyToOne again. * * @see linkManyToOne() - * */ - function relink () { - foreach ($this->_hasMany as $model) { + function relink () + { + foreach ($this->_hasMany as $model) + { $name = Inflector::singularize($model); $this->$name->clearLinks(); $this->$name->linkManyToOne(get_class($this), $this->id); @@ -215,7 +210,8 @@ class Model extends Object { * @param string $model_name Name of model to link to * @param unknown_type $value Defaults to NULL. */ - function linkManyToOne ($model_name, $value=null) { + function linkManyToOne ($model_name, $value=null) + { $table_name = Inflector::tableize($model_name); $field_name = Inflector::singularize($table_name).'_id'; $this->_one_to_many[] = array($table_name, $field_name, $value); @@ -225,7 +221,8 @@ class Model extends Object { * Removes all one-to-many links to other Models. * */ - function clearLinks () { + function clearLinks () + { $this->_one_to_many = array(); } @@ -234,12 +231,15 @@ class Model extends Object { * * @param string $table_name Name of the custom table */ - function useTable ($table_name) { - if (!in_array($table_name, $this->db->tables())) { + function useTable ($table_name) + { + if (!in_array(strtolower($table_name), $this->db->tables())) + { trigger_error (sprintf(ERROR_NO_MODEL_TABLE, get_class($this), $table_name), E_USER_ERROR); die(); } - else { + else + { $this->table = $table_name; $this->loadInfo(); } @@ -258,11 +258,13 @@ class Model extends Object { * @param string $two Value string for the alternative indata method * @return unknown */ - function set ($one, $two=null) { + function set ($one, $two=null) + { $this->validationErrors = null; $data = is_array($one)? $one: array($one=>$two); - foreach ($data as $n => $v) { + foreach ($data as $n => $v) + { /* if (!$this->hasField($n)) { DEBUG? @@ -281,7 +283,8 @@ class Model extends Object { * * @param int $id Id */ - function setId ($id) { + function setId ($id) + { $this->id = $id; $this->relink(); } @@ -291,7 +294,8 @@ class Model extends Object { * * @return array Array of table metadata */ - function loadInfo () { + function loadInfo () + { if (empty($this->_table_info)) $this->_table_info = new NeatArray($this->db->fields($this->table)); return $this->_table_info; @@ -304,7 +308,8 @@ class Model extends Object { * @param string $name Name of table to look in * @return boolean */ - function hasField ($name) { + function hasField ($name) + { if (empty($this->_table_info)) $this->loadInfo(); return $this->_table_info->findIn('name', $name); } @@ -315,7 +320,8 @@ class Model extends Object { * @param mixed $fields String of single fieldname, or an array of fieldnames. * @return array Array of database fields */ - function read ($fields=null) { + function read ($fields=null) + { $this->validationErrors = null; return $this->id? $this->find("id = '{$this->id}'", $fields): false; } @@ -327,18 +333,25 @@ class Model extends Object { * @param string $conditions SQL conditions (defaults to NULL) * @return field contents */ - function field ($name, $conditions=null) { - if ($conditions) { + function field ($name, $conditions=null) + { + if ($conditions) + { $data = $this->find($conditions); return $data[$name]; } - if (isset($this->data[$name])) + elseif (isset($this->data[$name])) + { return $this->data[$name]; - else { - if ($this->id && $data = $this->read($name)) { + } + else + { + if ($this->id && $data = $this->read($name)) + { return isset($data[$name])? $data[$name]: false; } - else { + else + { return false; } } @@ -351,7 +364,8 @@ class Model extends Object { * @param mixed $value Value of the field * @return boolean True on success save */ - function saveField($name, $value) { + function saveField($name, $value) + { return $this->save(array($name=>$value), false); } @@ -362,57 +376,75 @@ class Model extends Object { * @param boolean $validate * @return boolean success */ - function save ($data=null, $validate=true) { + function save ($data=null, $validate=true) + { if ($data) $this->set($data); if ($validate && !$this->validates()) return false; $fields = $values = array(); - foreach ($this->data as $n=>$v) { - if ($this->hasField($n)) { + foreach ($this->data as $n=>$v) + { + if ($this->hasField($n)) + { $fields[] = $n; $values[] = $this->db->prepare($v); } } - if (empty($this->id) && $this->hasField('created') && !in_array('created', $fields)) { + if (empty($this->id) && $this->hasField('created') && !in_array('created', $fields)) + { $fields[] = 'created'; $values[] = date("'Y-m-d H:i:s'"); } - if ($this->hasField('modified') && !in_array('modified', $fields)) { + if ($this->hasField('modified') && !in_array('modified', $fields)) + { $fields[] = 'modified'; $values[] = 'NOW()'; } - if(count($fields)){ + if(count($fields)) + { if($this->id){ $sql = array(); - foreach (array_combine($fields, $values) as $field=>$value) { + foreach (array_combine($fields, $values) as $field=>$value) + { $sql[] = $field.'='.$value; } - if($this->db->query("UPDATE {$this->table} SET ".join(',', $sql)." WHERE id = '{$this->id}'") && $this->db->lastAffected()){ + + $sql = "UPDATE {$this->table} SET ".join(',', $sql)." WHERE id = '{$this->id}'"; + + if ($this->db->query($sql) && $this->db->lastAffected()) + { $this->data = false; return true; } - else { + else + { return $this->db->hasAny($this->table, "id = '{$this->id}'"); } } - else { + else + { $fields = join(',', $fields); $values = join(',', $values); - if($this->db->query("INSERT INTO {$this->table} ({$fields}) VALUES ({$values})")) { + $sql = "INSERT INTO {$this->table} ({$fields}) VALUES ({$values})"; + + if($this->db->query($sql)) + { $this->id = $this->db->lastInsertId($this->table, 'id'); return true; } - else { + else + { return false; } } } - else { + else + { return false; } @@ -425,7 +457,8 @@ class Model extends Object { * @see function del * @return boolean True on success */ - function remove ($id=null) { + function remove ($id=null) + { return $this->del($id); } @@ -435,9 +468,11 @@ class Model extends Object { * @param mixed $id Id of database record to delete * @return boolean True on success */ - function del ($id=null) { + function del ($id=null) + { if ($id) $this->id = $id; - if ($this->id && $this->db->query("DELETE FROM {$this->table} WHERE id = '{$this->id}'")) { + if ($this->id && $this->db->query("DELETE FROM {$this->table} WHERE id = '{$this->id}'")) + { $this->id = false; return true; } @@ -450,7 +485,8 @@ class Model extends Object { * * @return boolean True if such a record exists */ - function exists () { + function exists () + { return $this->id? $this->db->hasAny($this->table, "id = '{$this->id}'"): false; } @@ -460,7 +496,8 @@ class Model extends Object { * * @return boolean True if such a record exists */ - function hasAny ($sql_conditions = null) { + function hasAny ($sql_conditions = null) + { return $this->db->hasAny($this->table, $sql_conditions); } @@ -472,7 +509,8 @@ class Model extends Object { * @param mixed $fields Either a single string of a field name, or an array of field names * @return array Array of records */ - function find ($conditions = null, $fields = null) { + function find ($conditions = null, $fields = null) + { $data = $this->findAll($conditions, $fields, null, 1); return empty($data[0])? false: $data[0]; } @@ -481,18 +519,23 @@ class Model extends Object { * @return string * */ - function parseConditions ($conditions) { - if (is_string($conditions)) { + function parseConditions ($conditions) + { + if (is_string($conditions)) + { return $conditions; } - elseif (is_array($conditions)) { + elseif (is_array($conditions)) + { $out = array(); - foreach ($conditions as $key=>$value) { + foreach ($conditions as $key=>$value) + { $out[] = "{$key}=".($value===null? 'null': $this->db->prepare($value)); } return join(' and ', $out); } - else { + else + { return null; } } @@ -507,7 +550,8 @@ class Model extends Object { * @param int $page Page number * @return array Array of records */ - function findAll ($conditions = null, $fields = null, $order = null, $limit=50, $page=1) { + function findAll ($conditions = null, $fields = null, $order = null, $limit=50, $page=1) + { $conditions = $this->parseConditions($conditions); @@ -520,7 +564,8 @@ class Model extends Object { $joins = $whers = array(); - foreach ($this->_oneToMany as $rule) { + foreach ($this->_oneToMany as $rule) + { list($table, $field, $value) = $rule; $joins[] = "LEFT JOIN {$table} ON {$this->table}.{$field} = {$table}.id"; $whers[] = "{$this->table}.{$field} = '{$value}'"; @@ -551,7 +596,8 @@ class Model extends Object { * @param string $sql SQL query * @return array */ - function findBySql ($sql) { + function findBySql ($sql) + { return $this->db->all($sql); } @@ -561,7 +607,8 @@ class Model extends Object { * @param string $conditions SQL conditions (WHERE clause conditions) * @return int Number of matching rows */ - function findCount ($conditions) { + function findCount ($conditions) + { list($data) = $this->findAll($conditions, 'COUNT(id) AS count'); return $data['count']; } @@ -573,7 +620,8 @@ class Model extends Object { * @param unknown_type $fields * @return unknown */ - function findAllThreaded ($conditions=null, $fields=null, $sort=null) { + function findAllThreaded ($conditions=null, $fields=null, $sort=null) + { return $this->_doThread($this->findAll($conditions, $fields, $sort), null); } @@ -584,11 +632,14 @@ class Model extends Object { * @param unknown_type $root NULL or id for root node of operation * @return array */ - function _doThread ($data, $root) { + function _doThread ($data, $root) + { $out = array(); - for ($ii=0; $ii_doThread($data, $data[$ii]['id']): null; $out[] = $tmp; @@ -607,7 +658,8 @@ class Model extends Object { * @param unknown_type $value * @return array Array with keys "prev" and "next" that holds the id's */ - function findNeighbours ($conditions, $field, $value) { + function findNeighbours ($conditions, $field, $value) + { list($prev) = $this->findAll($conditions." AND {$field} < '{$value}'", $field, "{$field} DESC", 1); list($next) = $this->findAll($conditions." AND {$field} > '{$value}'", $field, "{$field} ASC", 1); @@ -620,7 +672,8 @@ class Model extends Object { * @param string $sql SQL statement * @return array Resultset */ - function query ($sql) { + function query ($sql) + { return $this->db->query($sql); } @@ -630,7 +683,8 @@ class Model extends Object { * @param array $data POST data * @return boolean True if there are no errors */ - function validates ($data=null) { + function validates ($data=null) + { $errors = count($this->invalidFields($data? $data: $this->data)); return $errors == 0; @@ -642,7 +696,8 @@ class Model extends Object { * @param array $data Posted data * @return array Array of invalid fields */ - function invalidFields ($data=null) { + function invalidFields ($data=null) + { return $this->_invalidFields($data); } @@ -652,7 +707,8 @@ class Model extends Object { * @param array $data * @return array Array of invalid fields */ - function _invalidFields ($data=null) { + function _invalidFields ($data=null) + { if (!isset($this->validate)) return true; @@ -662,7 +718,8 @@ class Model extends Object { $data = ($data? $data: (isset($this->data)? $this->data: array())); $errors = array(); - foreach ($this->validate as $field_name=>$validator) { + foreach ($this->validate as $field_name=>$validator) + { if (!isset($data[$field_name]) || !preg_match($validator, $data[$field_name])) $errors[$field_name] = 1; } diff --git a/libs/object.php b/libs/object.php index 6d0f3bb36..c94006f61 100644 --- a/libs/object.php +++ b/libs/object.php @@ -30,8 +30,6 @@ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ -uses('log'); - /** * Enter description here... * @@ -39,7 +37,8 @@ uses('log'); * @subpackage cake.libs * @since Cake v 0.2.9 */ -class Object { +class Object +{ /** * A hack to support __construct() on PHP 4 diff --git a/libs/router.php b/libs/router.php index 091981278..a78bb8491 100644 --- a/libs/router.php +++ b/libs/router.php @@ -30,16 +30,11 @@ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ -/** - * Enter description here... - * - */ uses('object'); /** * Parses the request URL into controller, action, and parameters. * - * * @package cake * @subpackage cake.libs * @since Cake v 0.2.9 @@ -53,14 +48,6 @@ class Router extends Object { * @var array */ var $routes = array(); - -/** - * Constructor. - * - */ - function __construct () { - parent::__construct(); - } /** * TODO: Better description. Returns this object's routes array. Returns false if there are no routes available. @@ -178,6 +165,7 @@ class Router extends Object { break; } } + return $out; } } diff --git a/libs/template.php b/libs/template.php index 3653a951a..dcee559ed 100644 --- a/libs/template.php +++ b/libs/template.php @@ -38,8 +38,6 @@ uses('object'); /** * Templating for Controller class. Takes care of rendering views. - * - * * * @package cake * @subpackage cake.libs @@ -97,27 +95,19 @@ class Template extends Object { var $_page_title = false; /** - * Constructor. + * Choose the layout to be used when rendering. * - */ - function __construct () { - parent::__construct(); - } - -/** - * Enter description here... - * - * @param unknown_type $layout + * @param string $layout */ function setLayout ($layout) { $this->layout = $layout; } /** - * Enter description here... + * Saves a variable to use inside a template. * - * @param mixed $one An array of POST data. (Or: a string of a single POST datum.) - * @param string $two Value in case $one is a string (which then works as the key). + * @param mixed $one A string or an array of data. + * @param string $two Value in case $one is a string (which then works as the key), otherwise unused. * @return unknown */ function set($one, $two=null) { @@ -275,7 +265,8 @@ class Template extends Object { * @param boolean $___play_safe If set to false, the include() of the $__view_fn is done without suppressing output of errors * @return string Rendered output */ - function _render($___view_fn, $___data_for_view, $___play_safe = true) { + function _render($___view_fn, $___data_for_view, $___play_safe = true) + { extract($___data_for_view, EXTR_SKIP); # load all view variables $BASE = $this->base; $params = &$this->params; diff --git a/libs/test.php b/libs/test.php index fcb3e7276..9860a2ef6 100644 --- a/libs/test.php +++ b/libs/test.php @@ -76,7 +76,6 @@ if (phpversion() >= '4') { /** * Exception class for testing * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -128,7 +127,6 @@ class TestException { /** * Asserts for Unit Testing * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -589,7 +587,6 @@ class TestCase extends Assert /* implements Test */ { /** * Test Suite for Unit Testing. * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -724,7 +721,6 @@ class TestSuite /* implements Test */ { /** * Test Failure for Unit Testing * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -790,7 +786,6 @@ class TestFailure { /** * Test Result for Unit Testing * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -961,7 +956,6 @@ class TestResult { /** * Mines data from test results. Used for Unit Testing. * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 @@ -1038,7 +1032,6 @@ class ResultDataMiner extends TestResult { /** * Test Runner for Unit Testing. * - * * @package cake * @subpackage cake.libs * @since Cake v 1.0.0.0 diff --git a/libs/time.php b/libs/time.php index 43030c997..d229c0f86 100644 --- a/libs/time.php +++ b/libs/time.php @@ -30,16 +30,11 @@ * @license http://www.opensource.org/licenses/mit-license.php The MIT License */ -/** - * Enter description here... - * - */ uses ('object'); /** * Time related functions, formatting for dates etc. * - * * @package cake * @subpackage cake.libs * @since Cake v 0.2.9 @@ -112,7 +107,7 @@ class Time extends Object { } /** - * Returns a Unix timestamp for a datetime string. Wrapper for PHP function strtotime(). + * Returns a Unix timestamp from a textual datetime description. Wrapper for PHP function strtotime(). * * @param string $date_string Datetime string to be represented as a Unix timestamp * @return int Unix timestamp @@ -127,14 +122,24 @@ class Time extends Object { * @param string $date Datetime string * @return string Formatted date string */ - function toRss ($date) { - return date('Y-m-d', $date).'T'.date('H:i:s', $date).'Z'; + function toAtom ($date) { + return date('Y-m-d\TH:i:s\Z', $date); + } + +/** + * Formats date for RSS feeds + * + * @param datetime $date Datetime string + * @return string Formatted date string + */ + function toRSS ($date) { + return date('D, d M Y H:i:s O', $date); } /** - * Returns either a relative date or a formatted date depending - * on the difference between the current time and given datetime. - * $datetime should be in a strtotime-parsable format like MySQL datetime. + * Returns either a relative date or a formatted date depending + * on the difference between the current time and given datetime. + * $datetime should be in a strtotime-parsable format like MySQL datetime. * * Relative dates look something like this: * 3 weeks, 4 days ago @@ -142,56 +147,56 @@ class Time extends Object { * Formatted dates look like this: * on 02/18/2004 * - * The returned string includes 'ago' or 'on' and assumes you'll properly add a word + * The returned string includes 'ago' or 'on' and assumes you'll properly add a word * like 'Posted ' before the function output. * * @param $datetime Time in strtotime-parsable format * @return string Relative time string. */ - function timeAgoInWords ($datetime) { - - $in_seconds=strtotime($datetime); - $diff = time()-$in_seconds; - $months = floor($diff/2419200); - $diff -= $months*2419200; - $weeks = floor($diff/604800); - $diff -= $weeks*604800; - $days = floor($diff/86400); - $diff -= $days*86400; - $hours = floor($diff/3600); - $diff -= $hours*3600; - $minutes = floor($diff/60); - $diff -= $minutes*60; - $seconds = $diff; + function timeAgoInWords ($datetime) + { + $in_seconds=strtotime($datetime); + $diff = time()-$in_seconds; + $months = floor($diff/2419200); + $diff -= $months*2419200; + $weeks = floor($diff/604800); + $diff -= $weeks*604800; + $days = floor($diff/86400); + $diff -= $days*86400; + $hours = floor($diff/3600); + $diff -= $hours*3600; + $minutes = floor($diff/60); + $diff -= $minutes*60; + $seconds = $diff; - if ($months>0) { - // over a month old, just show date (mm/dd/yyyy format) - return 'on '.date("j/n/Y", $in_seconds); - } else { - $relative_date=''; - if ($weeks>0) { - // weeks and days - $relative_date .= ($relative_date?', ':'').$weeks.' week'.($weeks>1?'s':''); - $relative_date .= $days>0?($relative_date?', ':'').$days.' day'.($days>1?'s':''):''; - } elseif ($days>0) { - // days and hours - $relative_date .= ($relative_date?', ':'').$days.' day'.($days>1?'s':''); - $relative_date .= $hours>0?($relative_date?', ':'').$hours.' hour'.($hours>1?'s':''):''; - } elseif ($hours>0) { - // hours and minutes - $relative_date .= ($relative_date?', ':'').$hours.' hour'.($hours>1?'s':''); - $relative_date .= $minutes>0?($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':''):''; - } elseif ($minutes>0) { - // minutes only - $relative_date .= ($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':''); - } else { - // seconds only - $relative_date .= ($relative_date?', ':'').$seconds.' second'.($seconds>1?'s':''); - } - } - // show relative date and add proper verbiage - return $relative_date.' ago'; + if ($months>0) { + // over a month old, just show date (mm/dd/yyyy format) + return 'on '.date("j/n/Y", $in_seconds); + } else { + $relative_date=''; + if ($weeks>0) { + // weeks and days + $relative_date .= ($relative_date?', ':'').$weeks.' week'.($weeks>1?'s':''); + $relative_date .= $days>0?($relative_date?', ':'').$days.' day'.($days>1?'s':''):''; + } elseif ($days>0) { + // days and hours + $relative_date .= ($relative_date?', ':'').$days.' day'.($days>1?'s':''); + $relative_date .= $hours>0?($relative_date?', ':'').$hours.' hour'.($hours>1?'s':''):''; + } elseif ($hours>0) { + // hours and minutes + $relative_date .= ($relative_date?', ':'').$hours.' hour'.($hours>1?'s':''); + $relative_date .= $minutes>0?($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':''):''; + } elseif ($minutes>0) { + // minutes only + $relative_date .= ($relative_date?', ':'').$minutes.' minute'.($minutes>1?'s':''); + } else { + // seconds only + $relative_date .= ($relative_date?', ':'').$seconds.' second'.($seconds>1?'s':''); + } + } + // show relative date and add proper verbiage + return $relative_date.' ago'; } } diff --git a/libs/validators.php b/libs/validators.php index 8b3a9cf91..e17918f26 100644 --- a/libs/validators.php +++ b/libs/validators.php @@ -32,19 +32,16 @@ /** * Not empty. - * */ define('VALID_NOT_EMPTY', '/.+/'); /** * Numbers [0-9] only. - * */ define('VALID_NUMBER', '/^[0-9]+$/'); /** * A valid email address. - * */ define('VALID_EMAIL', '/^([a-z0-9][a-z0-9_\-\.\+]*)@([a-z0-9][a-z0-9\.\-]{0,63}\.[a-z]{2,3})$/i'); diff --git a/public/index.php b/public/index.php index 3c3d8fe13..c92b2dcbe 100644 --- a/public/index.php +++ b/public/index.php @@ -42,17 +42,23 @@ if (!defined('ROOT')) define ('ROOT', dirname(dirname(__FILE__)).DS); /** - * Directory layout and basic functions + * Configuration, directory layout and standard libraries */ require (ROOT.'config/core.php'); require (ROOT.'config/paths.php'); +require (ROOT.'libs/log.php'); +require (ROOT.'libs/object.php'); +require (ROOT.'libs/neat_array.php'); +require (ROOT.'libs/inflector.php'); require (ROOT.'libs/basics.php'); +require (ROOT.'libs/folder.php'); DEBUG? error_reporting(E_ALL): error_reporting(0); $TIME_START = getMicrotime(); -uses ('folder', 'dispatcher', 'dbo_factory'); +uses ('dispatcher', 'dbo_factory'); + config ('tags', 'database'); $DB = DboFactory::make('devel');