diff --git a/README.md b/README.md new file mode 100644 index 0000000..ce6d0cf --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +# Memex, a personal web memory + +## Overview + +This hopes one day to grow up to be an Open Source social bookmarking web application. + +## Installation + +* Get a copy or a link of the latest [Zend Framework][zf] into the `library/` directory. +* Try using `scripts/load.sqlite.php` to create the database. + +[zf]: http://framework.zend.com/download/latest + +## Contributors + +* l.m.orchard - + +## License + +Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 3.0 Unported License. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..7779ede --- /dev/null +++ b/TODO.md @@ -0,0 +1,13 @@ +# TODO + +* Make *-dist versions of config files, delete originals +* Implement an installer that can produce local configs +* v1 API +* AtomPub API +* {Atom,RSS,JSON} feeds +* AJAXify post save / edit / delete +* Implement network based on RSS/Atom aggregation +* [Message / work queues and deferred processing](queues) +* Make it scale + +[queues]: http://decafbad.com/blog/2008/07/04/queue-everything-and-delight-everyone diff --git a/application/bootstrap.php b/application/bootstrap.php new file mode 100644 index 0000000..72c86e1 --- /dev/null +++ b/application/bootstrap.php @@ -0,0 +1,26 @@ +registerPlugin($init); diff --git a/application/config/app.ini b/application/config/app.ini new file mode 100644 index 0000000..65e119d --- /dev/null +++ b/application/config/app.ini @@ -0,0 +1,26 @@ +[production] +database.adapter = "PDO_SQLITE" +database.params.dbname = APPLICATION_PATH "/../data/db/memex.db" +database.profile = false + +log.writer = "Stream" +log.priority = 2 +log.path = APPLICATION_PATH "/../logs/application.log" + +error.show_exceptions = false + +; TODO: Change this in install script? +form.salt = this is the form salt + +[development : production] +database.params.dbname = APPLICATION_PATH "/../data/db/memex-dev.db" +database.profile = true + +log.writer = "Firebug" +log.priority = 7 + +error.show_exceptions = true + +[testing : production] +database.params.dbname = APPLICATION_PATH "/../data/db/memex-test.db" +database.profile = true diff --git a/application/config/routes.ini b/application/config/routes.ini new file mode 100644 index 0000000..238d4d9 --- /dev/null +++ b/application/config/routes.ini @@ -0,0 +1,8 @@ +[production] +routes.foob.route = "foob/*" +routes.foob.defaults.controller = "index" +routes.foob.defaults.action = "index" +routes.foob.defaults.poof = "wang" + +[development : production] +[testing : production] diff --git a/application/config/routes.php b/application/config/routes.php new file mode 100644 index 0000000..a7d40ff --- /dev/null +++ b/application/config/routes.php @@ -0,0 +1,178 @@ + array( + + 'post_profile_tags' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => '(.*)/(.*)', + 'defaults' => array( + 'controller' => 'post', 'action' => 'profile' + ), + 'map' => array( + 1 => 'screen_name', + 2 => 'tags' + ), + 'reverse' => '%s/%s', + ), + 'post_profile' => array( + 'type' => 'Zend_Controller_Router_Route', + 'route' => ':screen_name', + 'defaults' => array( + 'controller' => 'post', 'action' => 'profile' + ) + ), + + 'doc_index' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'docs/(.*)', + 'defaults' => array( + 'controller' => 'doc', 'action' => 'index' + ), + 'map' => array( + 1 => 'path' + ), + 'reverse' => 'docs/%s', + ), + + + 'post_save' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'save', + 'defaults' => array( + 'controller' => 'post', 'action' => 'save' + ) + ), + 'post_view' => array( + 'type' => 'Zend_Controller_Router_Route', + 'route' => 'posts/:uuid', + 'defaults' => array( + 'controller' => 'post', 'action' => 'view' + ) + ), + 'post_save_edit' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'posts/(.*);edit', + 'defaults' => array( + 'controller' => 'post', 'action' => 'save', 'subaction' => 'edit' + ), + 'map' => array( + 1 => 'uuid' + ), + 'reverse' => 'posts/%s;edit', + ), + 'post_save_copy' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'posts/(.*);copy', + 'defaults' => array( + 'controller' => 'post', 'action' => 'save', 'subaction' => 'copy' + ), + 'map' => array( + 1 => 'uuid' + ), + 'reverse' => 'posts/%s;copy', + ), + 'post_delete' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'posts/(.*);delete', + 'defaults' => array( + 'controller' => 'post', 'action' => 'delete' + ), + 'map' => array( + 1 => 'uuid' + ), + 'reverse' => 'posts/%s;delete', + ), + 'post_tag_recent' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'recent', + 'defaults' => array( + 'controller' => 'post', 'action' => 'tag' + ) + ), + 'post_tag' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'tag/(.*)', + 'defaults' => array( + 'controller' => 'post', 'action' => 'tag' + ), + 'map' => array( + 1 => 'tags' + ), + 'reverse' => 'tag/%s', + ), + /* + 'post_profile_tags' => array( + 'type' => 'Zend_Controller_Router_Route_Regex', + 'route' => 'people/(.*)/(.*)', + 'defaults' => array( + 'controller' => 'post', 'action' => 'profile' + ), + 'map' => array( + 1 => 'screen_name', + 2 => 'tags' + ), + 'reverse' => 'people/%s/%s', + ), + 'post_profile' => array( + 'type' => 'Zend_Controller_Router_Route', + 'route' => 'people/:screen_name', + 'defaults' => array( + 'controller' => 'post', 'action' => 'profile' + ) + ), + */ + + 'profile_index' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'people', + 'defaults' => array( + 'controller' => 'profile', 'action' => 'index' + ) + ), + + 'auth_home' => array( + 'route' => 'home', + 'defaults' => array( + 'controller' => 'auth', 'action' => 'home' + ) + ), + + 'auth_register' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'register', + 'defaults' => array( + 'controller' => 'auth', 'action' => 'register' + ) + ), + 'auth_login' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'login', + 'defaults' => array( + 'controller' => 'auth', 'action' => 'login' + ) + ), + 'auth_logout' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => 'logout', + 'defaults' => array( + 'controller' => 'auth', 'action' => 'logout' + ) + ), + 'auth_openid' => array( + 'type' => "Zend_Controller_Router_Route_Static", + 'route' => 'openid', + 'defaults' => array( + 'controller' => 'auth', 'action' => 'openid' + ) + ), + + 'post_tag_recent' => array( + 'type' => 'Zend_Controller_Router_Route_Static', + 'route' => '', + 'defaults' => array( + 'controller' => 'post', 'action' => 'tag' + ) + ), + + ) +); diff --git a/application/controllers/AuthController.php b/application/controllers/AuthController.php new file mode 100644 index 0000000..f6f2ea5 --- /dev/null +++ b/application/controllers/AuthController.php @@ -0,0 +1,201 @@ +hasIdentity()) { + if (!in_array($this->getRequest()->getActionName(), array('logout', 'home'))) { + $this->_helper->redirector('home'); + } + } else { + if (!in_array($this->getRequest()->getActionName(), array('index', 'register', 'login'))) { + $this->_helper->redirector('index'); + } + } + + $this->view->login_form = $this->_helper->getForm( + 'login', + array( + 'action' => $this->view->url( + array( + 'controller' => 'auth', + 'action' => 'login', + ), + 'auth_login', + true + ), + ) + ); + $this->view->registration_form = $this->_helper->getForm( + 'registration', + array( + 'action' => $this->view->url( + array( + 'controller' => 'auth', + 'action' => 'register', + ), + 'auth_register', + true + ), + ) + ); + } + + /** + * Combination login / registration action. + */ + public function indexAction() + { + } + + /** + * Convenience action to redirect to logged in user's default profile. + */ + public function homeAction() + { + $logins = $this->_helper->getModel('Logins'); + $identity = Zend_Auth::getInstance()->getIdentity(); + $profile = $logins->fetchDefaultProfileForLogin($identity->id); + + return $this->_helper->redirector->gotoRoute( + array('screen_name' => $profile['screen_name']), + 'post_profile' + ); + } + + /** + * New user registration action. + */ + function registerAction() + { + $request = $this->getRequest(); + if (!$this->getRequest()->isPost()) { + return; + } + + $form = $this->view->registration_form; + if (!$form->isValid($request->getPost())) { + return; + } + + $logins = $this->_helper->getModel('Logins'); + //try { + $new_login_id = $logins->registerWithProfile($form->getValues()); + //} catch (Exception $e) { + // TODO: Better error message + // $form->setDescription('Registration failed, please try again.'); + // return; + //} + + $this->_helper->redirector('home'); + } + + /** + * User login action. + */ + public function loginAction() + { + $request = $this->getRequest(); + if (!$request->isPost()) { + return; + } + + $form = $this->view->login_form; + if (!$form->isValid($request->getPost())) { + return; + } + + // Get our authentication adapter and check credentials + $adapter = $this->getAuthAdapter($form->getValues()); + $auth = Zend_Auth::getInstance(); + $result = $auth->authenticate($adapter); + if (!$result->isValid()) { + $form->setDescription('Login name and password not valid'); + return; + } + + // Persist some identity details + $logins_model = $this->_helper->getModel('Logins'); + $identity = $adapter->getResultRowObject(array( + 'id', 'login_name', 'email', 'created' + )); + $identity->default_profile = + $logins_model->fetchDefaultProfileForLogin($identity->id); + $auth->getStorage()->write($identity); + + // We're authenticated! Redirect to the user page + $this->_helper->redirector('home'); + } + + /** + * User logout action. + */ + public function logoutAction() + { + // Clear the identity and remove it from the view. + Zend_Auth::getInstance()->clearIdentity(); + $this->view->assign(array( + 'auth_identity' => null, + 'auth_profile' => null + )); + } + + function openidAction() + { + $status = ""; + $auth = Zend_Auth::getInstance(); + if ((isset($_POST['openid_action']) && + $_POST['openid_action'] == "login" && + !empty($_POST['openid_identifier'])) || + isset($_GET['openid_mode']) || + isset($_POST['openid_mode'])) { + $result = $auth->authenticate( + new Zend_Auth_Adapter_OpenId(@$_POST['openid_identifier'])); + if ($result->isValid()) { + $status = "You are logged in as " + . $auth->getIdentity(); + } else { + $auth->clearIdentity(); + foreach ($result->getMessages() as $message) { + $status .= "$message\n"; + } + } + } else if ($auth->hasIdentity()) { + if (isset($_POST['openid_action']) && + $_POST['openid_action'] == "logout") { + $auth->clearIdentity(); + } else { + $status = "You are logged in as "; + // . $auth->getIdentity(); + } + } + $this->view->status = $status; + + } + + /** + * Build a Zend auth adapter given a username and password pair. + */ + public function getAuthAdapter($values) + { + if (null === $this->_authAdapter) { + $this->_authAdapter = new Zend_Auth_Adapter_DbTable( + Zend_Db_Table_Abstract::getDefaultAdapter(), + 'logins', + 'login_name', + 'password', + '?' // AND (date_banned IS NULL)' + ); + } + $this->_authAdapter->setIdentity($values['login_name']); + $this->_authAdapter->setCredential(md5($values['password'])); + return $this->_authAdapter; + } + +} diff --git a/application/controllers/DocController.php b/application/controllers/DocController.php new file mode 100644 index 0000000..85ac30d --- /dev/null +++ b/application/controllers/DocController.php @@ -0,0 +1,34 @@ +getRequest(); + + $doc_path = $request->getParam('path'); + if (!$doc_path) $doc_path = 'README'; + + $root_docs = array( 'README', 'TODO' ); + + if (in_array($doc_path, $root_docs)) { + $path = dirname(APPLICATION_PATH) . '/' . $doc_path . '.md'; + } else { + $path = dirname(APPLICATION_PATH) . '/docs/' . $doc_path . '.md'; + } + + if (!is_file($path)) + throw new Zend_Exception('Not Found', 404); + if (realpath($path) != $path) + throw new Zend_Exception('Forbidden ' . realpath($path) . ' != ' . $path, 403); + + $this->view->doc_path = + $doc_path; + $this->view->doc_content = + Markdown(file_get_contents($path)); + } +} diff --git a/application/controllers/ErrorController.php b/application/controllers/ErrorController.php new file mode 100644 index 0000000..6994501 --- /dev/null +++ b/application/controllers/ErrorController.php @@ -0,0 +1,55 @@ +_helper->viewRenderer->setViewSuffix('phtml'); + + // Grab the error object from the request + $errors = $this->_getParam('error_handler'); + + // $errors will be an object set as a parameter of the request object, + // type is a property + switch ($errors->type) { + case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: + case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: + + // 404 error -- controller or action not found + $this->getResponse()->setHttpResponseCode(404); + $this->view->message = 'Page not found'; + break; + default: + // application error + $this->getResponse()->setHttpResponseCode(500); + $this->view->message = 'Application error'; + break; + } + + // pass the environment to the view script so we can conditionally + // display more/less information + $this->view->env = $this->getInvokeArg('env'); + + // pass the actual exception object to the view + $this->view->exception = $errors->exception; + + // pass the request to the view + $this->view->request = $errors->request; + } +} diff --git a/application/controllers/IndexController.php b/application/controllers/IndexController.php new file mode 100644 index 0000000..6d5230f --- /dev/null +++ b/application/controllers/IndexController.php @@ -0,0 +1,32 @@ +view->account = Zend_Auth::getInstance()->getIdentity(); + } + +} diff --git a/application/controllers/PostController.php b/application/controllers/PostController.php new file mode 100644 index 0000000..cf18dfb --- /dev/null +++ b/application/controllers/PostController.php @@ -0,0 +1,322 @@ +hasIdentity()) { + } else { + if (in_array($this->getRequest()->getActionName(), array('save', 'delete'))) { + $this->_helper->redirector->gotoRoute(array(), 'auth_login'); + } + } + } + + /** + * Profile home page, listing posts and etc + */ + public function profileAction() + { + $request = $this->getRequest(); + + // Try to match the screen name to a profile, or bail with a 404. + $profiles_model = $this->_helper->getModel('Profiles'); + $screen_name = $request->getParam('screen_name'); + $profile = $profiles_model->fetchByScreenName($screen_name); + if (!$profile) { + throw new Zend_Exception("Profile '$screen_name' not found.", 404); + } + $this->view->profile = $profile; + $this->view->screen_name = $screen_name; + + // Parse out any tags specified in the URL route. + $tags_model = $this->_helper->getModel('Tags'); + $tags = $this->view->tags = + $tags_model->parseTags($request->getParam('tags')); + + // Set up the count, page size, and page number parameters + // for paginator. + $posts_model = $this->_helper->getModel('Posts'); + $posts_count = $this->view->posts_count = + $posts_model->countByProfileAndTags($profile['id'], $tags); + $page_size = 25; + $page_number = $request->getQuery('page'); + if (!$page_number) $page_number = 1; + + // Build the paginator for the view. + $paginator = new Zend_Paginator( + new Zend_Paginator_Adapter_Null($posts_count) + ); + $this->view->paginator = $paginator + ->setCurrentPageNumber($page_number) + ->setItemCountPerPage($page_size); + + // Fetch the posts using the route tags and pagination vars. + $posts_start = ($page_number - 1) * $page_size; + $posts = $posts_model->fetchByProfileAndTags( + $profile['id'], $tags, $posts_start, $page_size + ); + $this->view->posts = $posts; + } + + /** + * Tag view action + */ + function tagAction() + { + $request = $this->getRequest(); + + // Parse out any tags specified in the URL route. + $tags_model = $this->_helper->getModel('Tags'); + $tags = $this->view->tags = + $tags_model->parseTags($request->getParam('tags')); + + // Set up the count, page size, and page number parameters + // for paginator. + $posts_model = $this->_helper->getModel('Posts'); + $posts_count = $this->view->posts_count = + $posts_model->countByTags($tags); + $page_size = 25; + $page_number = $request->getQuery('page'); + if (!$page_number) $page_number = 1; + + // Build the paginator for the view. + $paginator = new Zend_Paginator( + new Zend_Paginator_Adapter_Null($posts_count) + ); + $this->view->paginator = $paginator + ->setCurrentPageNumber($page_number) + ->setItemCountPerPage($page_size); + + // Fetch the posts using the route tags and pagination vars. + $posts_start = ($page_number - 1) * $page_size; + $posts = $posts_model->fetchByTags( + $tags, $posts_start, $page_size + ); + $this->view->posts = $posts; + } + + /** + * Post view action. + */ + function viewAction() + { + $identity = Zend_Auth::getInstance()->getIdentity(); + $request = $this->getRequest(); + $get_data = $request->getQuery(); + $post_data = $request->getPost(); + + $uuid = $request->getParam('uuid'); + if (isset($get_data['uuid'])) { + $uuid = $get_data['uuid']; + } elseif (isset($post_data['uuid'])) { + $uuid = $post_data['uuid']; + } + + $posts_model = $this->_helper->getModel('Posts'); + + // If we have a URL, try looking up existing post data. + if ($uuid) { + $post = $posts_model->fetchOneByUUID($uuid); + } + $this->view->post = $post; + + // Make sure the post exists, and belongs to the current profile + $profile_id = (!$identity) ? null : $identity->default_profile['id']; + if (empty($post)) { + throw new Zend_Exception("Post '$uuid' not found.", 404); + } elseif ($post['profile_id'] != $profile_id && $post['visibility'] > 0) { + // TODO: Need more work on the visibility / privacy thing. + throw new Zend_Exception("View of '$uuid' forbidden.", 403); + } + + } + + /** + * Post delete action. + */ + function deleteAction() + { + $identity = Zend_Auth::getInstance()->getIdentity(); + $request = $this->getRequest(); + $get_data = $request->getQuery(); + $post_data = $request->getPost(); + + $uuid = $request->getParam('uuid'); + if (isset($get_data['uuid'])) { + $uuid = $get_data['uuid']; + } elseif (isset($post_data['uuid'])) { + $uuid = $post_data['uuid']; + } + + if (!isset($post_data['cancel'])) { + + $profile_id = $identity->default_profile['id']; + $posts_model = $this->_helper->getModel('Posts'); + + $form = $this->view->delete_form = $this->_helper->getForm( + 'postDelete', array('action' => $this->view->url()) + ); + + // If we have a URL, try looking up existing post data. + if ($uuid) { + $post = $posts_model->fetchOneByUUID($uuid); + } elseif ($url) { + $post = $posts_model->fetchOneByUrlAndProfile($url, $profile_id); + } + $this->view->post = $post; + + // Make sure the post exists, and belongs to the current profile + if (empty($post)) { + throw new Zend_Exception("Post '$uuid' not found.", 404); + } elseif ($post['profile_id'] != $profile_id) { + throw new Zend_Exception("Delete of '$uuid' forbidden.", 403); + } + + // Allow pre-population from query string + if (!$this->getRequest()->isPost()) { + $get_data['uuid'] = $uuid; + $form->isValid($get_data); + return; + } + + // Now, try validating the POST request. + $post_data['uuid'] = $uuid; + if (!$form->isValid($post_data)) { + return; + } + + // Finally, perform the deletion. + $posts_model->deleteByUUID($uuid); + } + + // Any other values for ?jump lead to the profile page. + return $this->_helper->redirector->gotoRoute( + array('screen_name' => $identity->default_profile['screen_name']), + 'post_profile' + ); + + } + + /** + * Handle saving a new bookmark, with a variety of post-save redirection + * options. + */ + function saveAction() + { + $identity = Zend_Auth::getInstance()->getIdentity(); + $request = $this->getRequest(); + $get_data = $request->getQuery(); + $post_data = $request->getPost(); + + $have_url = false; + + // Try getting the in-progress post's URL from query or form. + $url = null; + if (isset($get_data['url'])) { + $url = $get_data['url']; + } elseif (isset($post_data['url'])) { + $url = $post_data['url']; + } + if ($url) $have_url = true; + + $uuid = $request->getParam('uuid'); + if (isset($get_data['uuid'])) { + $uuid = $get_data['uuid']; + } elseif (isset($post_data['uuid'])) { + $uuid = $post_data['uuid']; + } + + if (!isset($post_data['cancel'])) { + + $profile_id = $identity->default_profile['id']; + $posts_model = $this->_helper->getModel('Posts'); + + // If we have a URL, try looking up existing post data. + $existing_post = null; + if ($uuid) { + $existing_post = $posts_model->fetchOneByUUID($uuid); + } elseif ($url) { + $existing_post = + $posts_model->fetchOneByUrlAndProfile($url, $profile_id); + } + + if (empty($existing_post)) { + $existing_post = array(); + } else { + $have_url = true; + if ($existing_post['profile_id'] != $profile_id) { + // If the logged in profile and the post profile ID don't + // match, then this is a cross-profile copy and the UUID + // should be nuked to force a copy instead of update. + unset($existing_post['uuid']); + } + } + + $form = $this->view->post_form = $this->_helper->getForm( + 'post', + array( + 'action' => $this->view->url(), + 'have_url' => $have_url + ) + ); + + // Allow pre-population from query string + if (!$this->getRequest()->isPost()) { + $new_post_data = array_merge($existing_post, $get_data); + $form->isValid($new_post_data); + return; + } + + // Now, try validating the POST request. + $new_post_data = array_merge($existing_post, $post_data); + if (!$form->isValid($new_post_data)) { + return; + } + + $new_post_data['profile_id'] = $profile_id; + + // Finally, try saving the combination of existing and new input. + $saved_post = $posts_model->save($new_post_data); + } + + // The ?jump parameter indicates one of several post-save redirect + // options. + $jump = $post_data['jump']; + if ($jump == 'doclose' || $jump == 'close') { + + // jump=doclose or jump=close should close the window after + // posting. + return $this->_helper->redirector->gotoRoute( + array('controller'=>'post', 'action'=>'doclose'), + 'post_doclose' + ); + + } elseif (strpos($jump, '/') === 0) { + + // jump=/... forwards the user to some path within the site + return $this->_helper->redirector->gotoUrl($jump, array( + 'prependBase' => true + )); + + } elseif ($jump == 'yes' && $url) { + + // If there's a URL and ?jump=yes, then hop on over to the original URL. + return $this->_helper->redirector->gotoUrl($url); + + } else { + + // Any other values for ?jump lead to the profile page. + return $this->_helper->redirector->gotoRoute( + array('screen_name' => $identity->default_profile['screen_name']), + 'post_profile' + ); + + } + + } + +} diff --git a/application/controllers/ProfileController.php b/application/controllers/ProfileController.php new file mode 100644 index 0000000..e29ef61 --- /dev/null +++ b/application/controllers/ProfileController.php @@ -0,0 +1,23 @@ +_loader = new Zend_Loader_PluginLoader(array( + 'Memex_Form' => APPLICATION_PATH . '/forms', + )); + } + + /** + * Load and return a form object + * + * @param string $form + * @param Zend_Config|array $config + * @return Zend_Form + */ + public function getForm($form, $config = null) + { + if (!array_key_exists($form, $this->_forms)) { + $class = $this->_loader->load($form); + $this->_forms[$form] = new $class($config); + } + return $this->_forms[$form]; + } + + /** + * Proxy to getForm() + * + * @param string $form + * @param array|Zend_Config|null $config + * @return Zend_Form + */ + public function direct($form, $config = null) + { + return $this->getForm($form, $config); + } +} diff --git a/application/controllers/helpers/GetModel.php b/application/controllers/helpers/GetModel.php new file mode 100644 index 0000000..2f1f122 --- /dev/null +++ b/application/controllers/helpers/GetModel.php @@ -0,0 +1,48 @@ +_loader = new Zend_Loader_PluginLoader(array( + 'Memex_Model' => APPLICATION_PATH . '/models', + )); + } + + /** + * Load a model class and return an object instance + * + * @param string $model + * @return object + */ + public function getModel($model) + { + $class = $this->_loader->load($model); + return new $class; + } + + /** + * Proxy to getModel() + * + * @param string $model + * @return object + */ + public function direct($model) + { + return $this->getModel($model); + } +} diff --git a/application/forms/Login.php b/application/forms/Login.php new file mode 100644 index 0000000..205968e --- /dev/null +++ b/application/forms/Login.php @@ -0,0 +1,44 @@ +addElement('text', 'login_name', array( + 'filters' => array('StringTrim', 'StringToLower'), + 'validators' => array( + array('Alnum', true, array(false)), + array('StringLength', false, array(3, 64)) + ), + 'required' => true, + 'label' => 'Login name:', + )); + + $password = $this->addElement('password', 'password', array( + 'filters' => array('StringTrim'), + 'validators' => array( + array('StringLength', false, array(3, 64)) + ), + 'required' => true, + 'label' => 'Password:', + )); + + $login = $this->addElement('submit', 'login', array( + 'required' => false, + 'ignore' => true, + 'label' => 'Login', + )); + + // We want to display a 'failed authentication' message if necessary; + // we'll do that with the form 'description', so we need to add that + // decorator. + $this->setDecorators(array( + 'FormElements', + array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')), + array('Description', array('placement' => 'prepend')), + 'Form' + )); + } +} diff --git a/application/forms/Post.php b/application/forms/Post.php new file mode 100644 index 0000000..d90f386 --- /dev/null +++ b/application/forms/Post.php @@ -0,0 +1,118 @@ +addElementPrefixPath( + 'Memex_Validate', APPLICATION_PATH . '/models/Validate/', + 'validate' + ) + ->addElementPrefixPath( + 'Memex_Filter', APPLICATION_PATH . '/models/Filter', + 'filter' + ) + + ->addElement('text', 'url', array( + 'label' => 'URL', + 'required' => true, + 'filters' => array('StringTrim', 'NormalizeUrl'), + 'validators' => array('Uri') + )); + + if (!$this->getAttrib('have_url')) { + + // If the form doesn't have a URL value yet, force into GET and + // omit the rest of the form. + $this->setMethod('get') + ->addElement('submit', 'save', array( + 'label' => 'Next' + )); + + } else { + + // Once a URL has been supplied, build the rest of the POST form. + $this->setMethod('post') + ->addElement('hash', 'csrf', array( + 'salt' => Zend_Registry::get('config')->form->salt, + 'decorators' => array( + array('ViewHelper') + ) + )) + ->addElement('text', 'title', array( + 'label' => 'Title', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('StringLength', true, array(0, 255)) + ) + )) + ->addElement('textarea', 'notes', array( + 'attribs' => array( + 'rows' => '5', + 'cols' => '50' + ), + 'label' => 'Notes', + 'required' => false, + 'validators' => array( + array('StringLength', true, array(0, 1024)) + ) + )) + ->addElement('text', 'tags', array( + 'label' => 'Tags', + 'required' => false, + 'filters' => array('StringTrim'), + 'validators' => array( + ) + )) + ->addElement('checkbox', 'private', array( + 'label' => 'Private' + )) + /* TODO: Variable visibility? + ->addElement('radio', 'visibility', array( + 'label' => 'Share', + 'required' => true, + 'attribs' => array( + 'value' => 1, + ), + 'multiOptions' => array( + '1' => 'public', + '2' => 'friends-only', + '0' => 'private', + ) + )); + */ + + ->addElement('submit', 'save', array( + 'label' => 'save' + )) + ->addElement('submit', 'cancel', array( + 'label' => 'cancel' + )); + + } + + $this + ->addElement('hidden', 'uuid', array( + 'decorators' => array('ViewHelper') + )) + ->addElement('hidden', 'v', array( + 'decorators' => array('ViewHelper') + )) + ->addElement('hidden', 'noui', array( + 'decorators' => array('ViewHelper') + )) + ->addElement('hidden', 'jump', array( + 'decorators' => array('ViewHelper') + )) + ->addElement('hidden', 'src', array( + 'decorators' => array('ViewHelper') + )); + + } +} diff --git a/application/forms/PostDelete.php b/application/forms/PostDelete.php new file mode 100644 index 0000000..bf53e69 --- /dev/null +++ b/application/forms/PostDelete.php @@ -0,0 +1,35 @@ +addElementPrefixPath( + 'Memex_Validate', APPLICATION_PATH . '/models/Validate/', + 'validate' + ) + ->addElementPrefixPath( + 'Memex_Filter', APPLICATION_PATH . '/models/Filter', + 'filter' + ) + ->setMethod('post') + ->addElement('hash', 'csrf', array( + 'salt' => Zend_Registry::get('config')->form->salt, + 'decorators' => array( + array('ViewHelper') + ) + )) + ->addElement('hidden', 'uuid', array( + 'decorators' => array('ViewHelper') + )) + ->addElement('submit', 'delete', array( + 'label' => 'delete' + )) + ->addElement('submit', 'cancel', array( + 'label' => 'cancel' + )); + } +} diff --git a/application/forms/Registration.php b/application/forms/Registration.php new file mode 100644 index 0000000..794e882 --- /dev/null +++ b/application/forms/Registration.php @@ -0,0 +1,152 @@ +setMethod('post') + ->addElementPrefixPath( + 'Memex_Validate', APPLICATION_PATH . '/models/Validate/', + 'validate' + ); + + $this + ->addElement('text', 'login_name', array( + 'label' => 'Login name', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('StringLength', false, array(3, 64)), + array('Alnum', true, array(false)), + array('LoginNameAvailable', false, array($helper->getModel('Logins'))) + ) + )) + ->addElement('text', 'email', array( + 'label' => 'Email address', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('EmailAddress') + ) + )) + ->addElement('password', 'password', array( + 'label' => 'Password', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('StringLength', false, array(3, 64)), + array('PasswordStrength') + ) + )) + ->addElement('password', 'password_confirm', array( + 'label' => 'Password (confirm)', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('MatchField', false, array('password')) + ) + )); + + $this->addDisplayGroup( + array('login_name', 'email', 'password', 'password_confirm'), + 'login', + array('legend' => 'Login details') + ); + + $this + ->addElement('text', 'screen_name', array( + 'label' => 'Screen name', + 'required' => true, + 'filters' => array('StringTrim', 'StringToLower'), + 'validators' => array( + array('Alnum', false, array(false)), + array('StringLength', true, array(3, 64)), + array('ScreenNameAvailable', false, array($helper->getModel('Profiles'))) + ) + )) + ->addElement('text', 'full_name', array( + 'label' => 'Full name', + 'required' => true, + 'filters' => array('StringTrim'), + 'validators' => array( + array('StringLength', false, array(3, 128)) + ) + )) + ->addElement('textarea', 'bio', array( + 'attribs' => array( + 'rows' => '5', + 'cols' => '50' + ), + 'label' => 'Bio / About you', + 'required' => false, + 'filters' => array('StringTrim', 'StripTags'), + 'validators' => array( + array('StringLength', false, array(0, 1024)) + ) + )); + + $this->addDisplayGroup( + array('screen_name', 'full_name', 'bio'), + 'account', + array('legend' => 'Profile details') + ); + + $this + ->addElement('captcha', 'captcha', array( + 'label' => 'Please enter the 5 letters displayed below:', + 'required' => true, + 'captcha' => array( + 'captcha' => 'Figlet', 'wordLen' => 5, 'timeout' => 300 + ) + )) + ->addElement('submit', 'submit', array( + 'label' => 'Register' + )); + + $this->addDisplayGroup( + array('captcha', 'submit'), + 'finish', + array('legend' => 'Register') + ); + + /* TODO: Work with this to make ul/li form, or give in and try styling dl/dt/dd + + $this->setElementDecorators(array( + 'ViewHelper', + 'Errors', + 'Description', + array(array('data'=>'HtmlTag'),array('tag'=>'span')), + array('Label',array()), + array(array('row'=>'HtmlTag'),array('tag'=>'li')) + )); + + $this->setDisplayGroupDecorators(array( + 'FormElements', + array(array('data'=>'HtmlTag'),array('tag'=>'ul')), + 'FieldSet', + array(array('row'=>'HtmlTag'),array('tag'=>'li')) + )); + + $this->setDecorators(array( + 'FormElements', + array(array('data'=>'HtmlTag'),array('tag'=>'ul')), + 'Form' + )); + + */ + + $this->setDecorators(array( + 'FormElements', + array('HtmlTag', array('tag' => 'dl', 'class' => 'zend_form')), + array('Description', array('placement' => 'prepend')), + 'Form' + )); + + parent::init(); + } + +} diff --git a/application/layouts/scripts/layout.phtml b/application/layouts/scripts/layout.phtml new file mode 100644 index 0000000..886e105 --- /dev/null +++ b/application/layouts/scripts/layout.phtml @@ -0,0 +1,89 @@ + +getRequest(); + $action_name = $request->getActionName(); + $controller_name = $request->getControllerName(); + + if (null === $this->auth_profile) { + } else { + $profile_home_url = $this->url( + array('screen_name' => $this->auth_profile['screen_name']), + 'post_profile' + ); + } +?> + + + + memex + + + + + + + + +
+ + + +
+ placeholder('infobar') ?> +
+ +
+ layout()->content ?> +
+ + + +
+ + + diff --git a/application/models/DbTable/Logins.php b/application/models/DbTable/Logins.php new file mode 100644 index 0000000..e1665b3 --- /dev/null +++ b/application/models/DbTable/Logins.php @@ -0,0 +1,37 @@ + array( + 'columns' => 'login_id', + 'refTableClass' => 'Memex_Db_Table_Logins', + 'refColumns' => 'id' + ), + 'Account' => array( + 'columns' => 'profile_id', + 'refTableClass' => 'Memex_Db_Table_Profiles', + 'refColumns' => 'id' + ) + ); +} diff --git a/application/models/DbTable/Posts.php b/application/models/DbTable/Posts.php new file mode 100644 index 0000000..2e90642 --- /dev/null +++ b/application/models/DbTable/Posts.php @@ -0,0 +1,43 @@ + array( + 'columns' => 'url_id', + 'refTableClass' => 'Urls', + 'refColumns' => 'id' + ) + ); + + /** + * Insert new row + * + * Ensure that a timestamp is set for the created field. + * + * @param array $data + * @return int + */ + public function insert(array $data) + { + $data['created'] = date('Y-m-d\TH:i:sP', time()); + if (empty($data['user_date'])) + $data['user_date'] = date('Y-m-d\TH:i:sP', time()); + return parent::insert($data); + } + +} + +/** + * Wrapper for login rows. + */ +class Memex_Db_Table_Row_Posts extends Zend_Db_Table_Row +{ + +} diff --git a/application/models/DbTable/Profiles.php b/application/models/DbTable/Profiles.php new file mode 100644 index 0000000..7fdfd21 --- /dev/null +++ b/application/models/DbTable/Profiles.php @@ -0,0 +1,35 @@ +fetchByLoginName($data['login_name'])) + throw new Exception('duplicate login name'); + + $table = $this->getDbTable(); + + $id = $table->insert(array( + 'login_name' => $data['login_name'], + 'email' => $data['email'], + 'password' => md5($data['password']), + 'created' => date('Y-m-d H:i:s', time()) + )); + + return $id; + } + + /** + * Delete a login. + * + * Note that this does not cascadingly delete profiles or anything else, + * since profiles are the primary resource here and multiple logins may be + * attached to a single profile. + * + * @param string Login ID + */ + public function delete($id) { + $this->getDbTable()->delete($id); + } + + /** + * Create a new login and associated profile. + */ + public function registerWithProfile($data) + { + $new_login_id = $this->create($data); + try { + $new_profile_id = $this->getModel('Profiles')->create($data); + $this->addProfileToLogin($new_login_id, $new_profile_id); + } catch (Exception $e) { + // If profile creation failed, delete the login. + $this->delete($new_login_id); + throw $e; + } + return $new_login_id; + } + + /** + * Link an profile with this login + */ + public function addProfileToLogin($login_id, $profile_id) + { + return $this->getDbTable()->getAdapter()->insert( + 'logins_profiles', array( + 'login_id' => $login_id, + 'profile_id' => $profile_id + ) + ); + } + + /** + * Look up by login name + * + * @param string Screen name + * @ + */ + public function fetchByLoginName($login_name) + { + $table = $this->getDbTable(); + $row = $table->fetchRow( + $table->select()->where('login_name=?', $login_name) + ); + if (null == $row) return null; + $data = $row->toArray(); + return $data; + } + + /** + * Fetch the default profile for a login. + */ + public function fetchDefaultProfileForLogin($login_id) + { + $profiles = $this->fetchProfilesForLogin($login_id); + return (!$profiles) ? null : $profiles[0]; + } + + /** + * Get all profiles for a login + */ + public function fetchProfilesForLogin($login_id) + { + $login_row = $this->getDbTable()->find($login_id)->current(); + if (null == $login_row) return null; + + $profile_rows = $login_row->findManyToManyRowset( + 'Memex_Db_Table_Profiles', + 'Memex_Db_Table_LoginsProfiles' + ); + $profiles = array(); + foreach ($profile_rows as $row) + $profiles[] = $row->toArray(); + + return $profiles; + } + + /** + * Delete all users from the system. Useful for tests, but dangerous + * otherwise. + */ + public function deleteAll() + { + if ('testing' != APPLICATION_ENVIRONMENT) + throw new Exception('Mass deletion only supported during testing'); + $this->getDbTable()->delete(''); + } + +} diff --git a/application/models/Model.php b/application/models/Model.php new file mode 100644 index 0000000..9d09316 --- /dev/null +++ b/application/models/Model.php @@ -0,0 +1,93 @@ + array(), + 'model' => array(), + 'form' => array() + ); + + /** + * Public constructor. + */ + public function __construct() + { + $this->init(); + } + + /** + * Conventional initializer method. + */ + public function init() + { + } + + /** + * Generate a UUID. + * + * @param string prefix for UUID + */ + public function uuid($prefix='') + { + $chars = md5(uniqid(mt_rand(), true)); + return $prefix . join('-', array( + substr($chars,0,8), + substr($chars,8,4), + substr($chars,12,4), + substr($chars,16,4), + substr($chars,20,12) + )); + } + + /** + * Instantiate a table by name + * + * @param string Table name + * @return Zend_Db_Table + */ + public function getDbTable($name=null) + { + if (null == $name) $name = $this->_table_name; + return $this->_loadResource($name, 'dbtable', 'models/DbTable', 'Memex_Db_Table'); + } + + /** + * Instantiate a model by name + * + * @param string Model name + * @return Decafbad_Model + */ + public function getModel($name) + { + return $this->_loadResource($name, 'model', 'models', 'Memex_Model'); + } + + /** + * Instantiate a form by name + * + * @param string Form name + * @return Zend_Form + public function getForm($name) + { + return $this->_loadResource($name, 'form', 'forms', 'Memex_Form'); + } + */ + + /** + * Utility function to load a resource. + */ + private function _loadResource($name, $type, $path, $class_prefix) + { + if (!isset($this->_objects[$type][$name])) { + require_once APPLICATION_PATH . '/' . $path . '/' . $name . '.php'; + $class = $class_prefix . '_' . $name; + $this->_objects[$type][$name] = new $class; + } + return $this->_objects[$type][$name]; + } + +} diff --git a/application/models/Posts.php b/application/models/Posts.php new file mode 100644 index 0000000..d9e657b --- /dev/null +++ b/application/models/Posts.php @@ -0,0 +1,416 @@ +normalize_url_filter = new Memex_Filter_NormalizeUrl(); + } + + /** + * Save a post with the given data for the given profile, creating a new + * one or overwriting an existing one if necessary. + * + * @param array Post data to save + * @param string Profile ID + * @return array Post data after save + */ + public function save($post_data) + { + if (empty($post_data['url'])) + throw new Exception('url required'); + if (empty($post_data['title'])) + throw new Exception('title required'); + if (empty($post_data['profile_id'])) + throw new Exception('profile_id required'); + + if (!empty($post_data['user_date'])) { + $date_in = strtotime($post_data['user_date'], time()); + if (!$date_in) + throw new Exception('valid optional date required'); + $post_data['date'] = date('Y-m-d\TH:i:sP', $date_in); + } + + $table = $this->getDbTable(); + + // Get an ID for the post's URL and set the ID in post data + $urls_model = $this->getModel('Urls'); + $url_data = $urls_model->fetchOrCreate( + $post_data['url'], $post_data['profile_id'] + ); + $post_data['url_id'] = $url_data['id']; + + // Try looking up an existing post for this URL and profile. + $row = null; + if (!empty($post_data['uuid'])) { + $row = $table->fetchRow($table->select() + ->where('uuid=?', $post_data['uuid']) + ); + } elseif (!empty($post_data['id'])) { + $row = $table->fetchRow($table->select() + ->where('id=?', $post_data['id']) + ); + } else { + $row = $table->fetchRow($table->select() + ->where('url_id=?', $url_data['id']) + ->where('profile_id=?', $post_data['profile_id']) + ); + } + + // If there's no existing post, create a new one. + if (null == $row) { + $row = $table->createRow()->setFromArray(array( + 'uuid' => $this->uuid(), + 'url_id' => $url_data['id'], + 'profile_id' => $post_data['profile_id'] + )); + } + + // Has the URL been changed in an existing post? + if ($row['url_id'] != $url_data['id']) { + // TODO: Delete URL record if last bookmark reference gone? + // Probably a good job for an offline queue. + } + + // Update the post's data and save it. Note that only a select set of + // fields are used, which prevents changes in UUID and others + $accepted_post_fields = array( + 'profile_id', 'url_id', 'title', 'notes', 'tags', + 'visibility', 'user_date' + ); + foreach ($accepted_post_fields as $key) { + if (isset($post_data[$key])) + $row->$key = $post_data[$key]; + } + $row->save(); + + // HACK: Re-fetch the just-saved post. Ensures consistent data, but + // probably needs some work to avoid cache issues later on. + $saved_post = $this->fetchOneById($row->id); + + // Update the tags for this post. + $tags_model = $this->getModel('Tags'); + $tags_model->updateTagsForPost($saved_post); + + // Return the results of the save. + return $saved_post; + } + + /** + * Fetch post by post ID + * + * @param string Post ID + * @return array A single post + */ + public function fetchOneById($id) { + return $this->fetchOneBy($id, null, null, null); + } + + /** + * Fetch post by post UUID + * + * @param string Post UUID + * @return array A single post + */ + public function fetchOneByUUID($uuid) { + return $this->fetchOneBy(null, null, $uuid, null); + } + + /** + * Attempt to fetch a post for the given URL and profile ID. + * + * @param string URL + * @param string Profile ID + * @return array Post data + */ + public function fetchOneByUrlAndProfile($url, $profile_id) + { + return $this->fetchOneBy(null, $url, null, $profile_id); + } + + /** + * Fetch one post by a variety of criteria + * + * @param string Post ID + * @param string Post URL + * @param string Post UUID + * @param string Profile ID + * @return array A single post + */ + public function fetchOneBy($id=null, $url=null, $uuid=null, $profile_id=null) + { + // Try looking up an existing post for this URL and profile. + $table = $this->getDbTable(); + $select = $this->_getPostsSelect(); + + if (null != $profile_id) + $select->where('profile_id=?', $profile_id); + if (null != $id) + $select->where('posts.id=?', $id); + if (null != $uuid) + $select->where('posts.uuid=?', $uuid); + if (null != $url) + $select->where('urls.url=?', + $this->normalize_url_filter->filter($url)); + + $data = $this->_postsRowSetToArray( + $table->fetchAll($select) + ); + return empty($data) ? null : $data[0]; + } + + /** + * Fetch posts by tags + * + * @param array List of tags for intersection + * @param integer Start index + * @param integer Count of results + * @param string Order ({field} {asc,desc}) + * @return array Posts + */ + public function fetchByTags($tags, $start=0, $count=10, $order='user_date desc') + { + return $this->fetchBy(null, null, null, $tags, $start, $count, $order); + } + + /** + * Fetch posts by profile and tags + * + * @param string Profile ID + * @param array List of tags for intersection + * @param integer Start index + * @param integer Count of results + * @param string Order ({field} {asc,desc}) + * @return array Posts + */ + public function fetchByProfileAndTags($profile_id, $tags, $start=0, $count=10, $order='user_date desc') + { + return $this->fetchBy(null, null, $profile_id, $tags, $start, $count, $order); + } + + /** + * Fetch posts for a variety of criteria + * + * @param string Profile ID + * @param array List of tags for intersection + * @param integer Start index + * @param integer Count of results + * @param string Order ({field} {asc,desc}) + * @return array Posts + */ + public function fetchBy($uuid=null, $id=null, $profile_id=null, $tags=null, $start=0, $count=10, $order='user_date desc') + { + $table = $this->getDbTable(); + $select = $this->_getPostsSelect(); + + if ($order == 'user_date desc') + $select->order('user_date DESC'); + if (null !== $uuid) + $select->where('posts.uuid=?', $uuid); + if (null !== $id) + $select->where('posts.id=?', $id); + if (null !== $profile_id) + $select->where('posts.profile_id=?', $profile_id); + if (null !== $tags) + $this->_addWhereForTags($select, $tags); + if (null !== $count && null !== $start) + $select->limit($count, $start); + + return $this->_postsRowSetToArray( + $table->fetchAll($select) + ); + } + + /** + * Get a count of posts by profile. + * + * @param string Profile ID + * @return integer Count of posts belonging to the profile. + */ + public function countByProfile($profile_id) + { + return $this->countBy($profile_id, null); + } + + /** + * Get a count of posts by tag intersection. + * + * @param array List of tags + * @return integer Count of posts belonging to the profile. + */ + public function countByTags($tags) + { + return $this->countBy(null, $tags); + } + + /** + * Get a count of posts by profile and tag intersection. + * + * @param string Profile ID + * @param array List of tags + * @return integer Count of posts belonging to the profile. + */ + public function countByProfileAndTags($profile_id, $tags) + { + return $this->countBy($profile_id, $tags); + } + + /** + * Get a count of posts for a variety of criteria + * + * @param string Profile ID + * @param array List of tags + * @return integer Count of posts belonging to the profile. + */ + public function countBy($profile_id=null, $tags=null) + { + $table = $this->getDbTable(); + $select = $table->select() + ->from($table, 'count(posts.id) as count'); + + if (null !== $profile_id) + $select->where('posts.profile_id=?', $profile_id); + if (null !== $tags) + $this->_addWhereForTags($select, $tags); + + $row = $table->fetchRow($select); + return $row['count']; + } + + /** + * Delete a post by ID + * + * @param string Post ID + */ + public function deleteById($post_id) + { + $table = $this->getDbTable(); + $rv = $table->delete( + $table->getAdapter()->quoteInto('id=?', $post_id) + ); + return $rv; + } + + /** + * Delete a post by UUID + * + * @param string Post UUID + */ + public function deleteByUUID($uuid) + { + $table = $this->getDbTable(); + $rv = $table->delete( + $table->getAdapter()->quoteInto('uuid=?', $uuid) + ); + return $rv; + } + + /** + * Delete a post by URL and profile_id + * + * @param string URL + * @param string Profile ID + */ + public function deleteByUrlAndProfile($url, $profile_id) + { + $data = $this->fetchOneByUrlAndProfile($url, $profile_id); + if (null == $data) return null; + return $this->deleteById($data['id']); + } + + /** + * Delete all. Useful for tests, but dangerous otherwise. + */ + public function deleteAll() + { + if ('testing' != APPLICATION_ENVIRONMENT) + throw new Exception('Mass deletion only supported during testing'); + $this->getDbTable()->delete(''); + } + + /** + * Convert a row set from the posts table into an array of post + * data arrays. + * + * @param Zend_Db_Table_Rowset posts rows + * @return array list of posts + */ + private function _postsRowSetToArray($posts) + { + $tags_model = $this->getModel('Tags'); + $posts_out = array(); + foreach ($posts as $row) { + $row_data = $row->toArray(); + $row_data['tags_parsed'] = + $tags_model->parseTags($row_data['tags']); + $posts_out[] = $row_data; + } + return $posts_out; + } + + /** + * Build the common select statement for all fetches. + */ + private function _getPostsSelect() + { + return $this->getDbTable()->select() + ->setIntegrityCheck(false) + ->from('posts') + ->join( + 'urls', + 'urls.id=posts.url_id', + array('urls.url', 'urls.hostname', 'urls.hash') + ) + ->join( + 'profiles', + 'profiles.id=posts.profile_id', + array('profiles.screen_name') + ); + } + + /** + * Add clauses to a select statement to implement a tag intersection for a + * list of tags. + * + * @param Zend_Db_Select Select + * @param array tags in intersection + */ + private function _addWhereForTags($select, $tags) + { + if (empty($tags)) + return; + if (!is_array($tags)) + $tags = array($tags); + + $select->setIntegrityCheck(false); + if (count($tags) == 1) { + $select + ->join('tags', 'tags.post_id=posts.id', array()) + ->where('tags.tag=?', $tags[0]); + + // TODO: Optimize for more common intersections of 2-3 + // } elseif (count($tags) == 2) { + // } elseif (count($tags) == 3) { + + } else { + foreach ($tags as $tag) { + $select->where( + 'posts.id IN ( SELECT post_id FROM tags WHERE tag=? )', + $tag + ); + } + } + + } + +} diff --git a/application/models/Profiles.php b/application/models/Profiles.php new file mode 100644 index 0000000..9ffa910 --- /dev/null +++ b/application/models/Profiles.php @@ -0,0 +1,67 @@ +fetchByScreenName($data['screen_name'])) + throw new Exception('duplicate screen name'); + + $table = $this->getDbTable(); + + $id = $table->insert(array( + 'uuid' => $this->uuid(), + 'screen_name' => $data['screen_name'], + 'full_name' => $data['full_name'], + 'bio' => empty($data['bio']) ? '' : $data['bio'], + 'created' => date('Y-m-d H:i:s', time()) + )); + + return $id; + } + + /** + * Look up by screen name + * + * @param string Screen name + * @ + */ + public function fetchByScreenName($screen_name) + { + $table = $this->getDbTable(); + $row = $table->fetchRow( + $table->select()->where('screen_name=?', $screen_name) + ); + if (null == $row) return false; + $data = $row->toArray(); + return $data; + } + + /** + * Delete all profiles from the system. Useful for tests, but dangerous + * otherwise. + */ + public function deleteAll() + { + if ('testing' != APPLICATION_ENVIRONMENT) + throw new Exception('Mass deletion only supported during testing'); + $this->getDbTable()->delete(''); + } + +} diff --git a/application/models/Tags.php b/application/models/Tags.php new file mode 100644 index 0000000..8744025 --- /dev/null +++ b/application/models/Tags.php @@ -0,0 +1,116 @@ +getDbTable(); + $row = $table->fetchRow($table->select() + ->where('tag=?', $tag_name) + ->where('profile_id=?', $profile_id) + ); + return (null == $row) ? null : $row->toArray(); + } + + /** + * For a given post, update the individual tag records to reflect updated + * in the post. + */ + public function updateTagsForPost($post_data) + { + $table = $this->getDbTable(); + $db = $table->getAdapter(); + $posts = $this->getModel('Posts'); + $new_tags = $this->parseTags($post_data['tags']); + + // Look up all existing tags for the post. + $tag_rows = $table->fetchAll( + $table->select()->where('post_id=?', $post_data['id']) + ); + $old_tags = array(); + foreach ($tag_rows as $row) { + $old_tags[] = $row['tag']; + } + + // The existing tags to delete are the difference between old and new + $delete_tags = array_diff($old_tags, $new_tags); + foreach ($delete_tags as $tag) { + $table->delete(array( + $db->quoteInto('post_id=?', $post_data['id']), + $db->quoteInto('tag=?', $tag) + )); + } + + // The new tags to add are the difference between new and old + $create_tags = array_diff($new_tags, $old_tags); + foreach ($create_tags as $tag) { + $table->insert(array( + 'tag' => $tag, + 'post_id' => $post_data['id'], + 'profile_id' => $post_data['profile_id'], + 'url_id' => $post_data['url_id'] + )); + } + + // Update the position index on all the updated tags. + foreach ($new_tags as $position=>$tag) { + $table->update( + array( + 'position' => $position + ), + array( + $db->quoteInto('post_id=?', $post_data['id']), + $db->quoteInto('tag=?', $tag) + ) + ); + } + + return $this; + } + + /** + * Delete all. Useful for tests, but dangerous otherwise. + */ + public function deleteAll() + { + if ('testing' != APPLICATION_ENVIRONMENT) + throw new Exception('Mass deletion only supported during testing'); + $this->getDbTable()->delete(''); + } + +} diff --git a/application/models/Urls.php b/application/models/Urls.php new file mode 100644 index 0000000..c8a1196 --- /dev/null +++ b/application/models/Urls.php @@ -0,0 +1,116 @@ +normalize_url_filter = new Memex_Filter_NormalizeUrl(); + } + + /** + * Fetch data for a URL by URL + * + * @param string URL for lookup + * @return array URL data + */ + public function fetchByUrl($url) + { + return $this->fetchBy($url, null); + } + + /** + * Fetch data for a URL by hash + * + * @param string URL for lookup + * @return array URL data + */ + public function fetchByHash($hash) + { + return $this->fetchBy(null, $hash); + } + + /** + * Fetch data for a URL by hash + * + * @param string URL for lookup + * @return array URL data + */ + public function fetchByUrlOrHash($url, $hash) + { + return $this->fetchBy($url, $hash); + } + + /** + * Fetch data using a variety of criteria. + * + * @param string URL for lookup + * @return array URL data + */ + public function fetchBy($url=null, $hash=null) + { + $table = $this->getDbTable(); + $select = $table->select(); + if (null != $url) { + $url = $this->normalize_url_filter->filter($url); + $select->where('url=?', $url); + } elseif (null != $hash) { + $select->where('hash=?', $hash); + } + $row = $table->fetchRow($select); + return (null == $row) ? null : $row->toArray(); + } + + /** + * Fetch an existing record by URL, or create a new one for this URL. + * + * @param string URL for lookup + * @param string Account ID for first URL save + * @return array URL data + */ + public function fetchOrCreate($url, $account_id) + { + $url = $this->normalize_url_filter->filter($url); + $table = $this->getDbTable(); + + // Try fetching an existing URL and return it if found. + $data = $this->fetchByUrl($url); + if (null != $data) { + return $data; + } + + // Parse the URL for indexable bits + $url_parts = parse_url($url); + + // Next, create a new URL record and return it. + $new_id = $table->insert(array( + 'url' => $url, + 'hash' => md5($url), + 'hostname' => empty($url_parts['host']) ? '' : $url_parts['host'], + 'first_profile_id' => $account_id, + 'created' => date('Y-m-d H:i:s', time()) + )); + $rows = $table->find($new_id); + return ($rows) ? $rows->current()->toArray() : null; + } + + /** + * Delete all. Useful for tests, but dangerous otherwise. + */ + public function deleteAll() + { + if ('testing' != APPLICATION_ENVIRONMENT) + throw new Exception('Mass deletion only supported during testing'); + $this->getDbTable()->delete(''); + } + +} diff --git a/application/models/Validate/LoginNameAvailable.php b/application/models/Validate/LoginNameAvailable.php new file mode 100644 index 0000000..16ee263 --- /dev/null +++ b/application/models/Validate/LoginNameAvailable.php @@ -0,0 +1,38 @@ + "'%value%' is not available as a unique login name" + ); + + protected $_model; + + public function __construct($model) + { + $this->_model = $model; + } + + public function isValid($value) + { + $this->_setValue($value); + + $is_valid = true; + + if ($this->_model->fetchByLoginName($value)) { + $this->_error(self::NOT_AVAILABLE); + $is_valid = false; + } + + return $is_valid; + } + +} diff --git a/application/models/Validate/MatchField.php b/application/models/Validate/MatchField.php new file mode 100644 index 0000000..17e8db9 --- /dev/null +++ b/application/models/Validate/MatchField.php @@ -0,0 +1,41 @@ + 'Fields do not match' + ); + + public function __construct($match_field) + { + $this->_match_field = $match_field; + } + + public function isValid($value, $context = null) + { + $value = (string) $value; + $this->_setValue($value); + + if (is_array($context)) { + if (isset($context[$this->_match_field]) + && ($value == $context[$this->_match_field])) + { + return true; + } + } elseif (is_string($context) && ($value == $context)) { + return true; + } + + $this->_error(self::NOT_MATCH); + return false; + } +} diff --git a/application/models/Validate/PasswordStrength.php b/application/models/Validate/PasswordStrength.php new file mode 100644 index 0000000..6fea81b --- /dev/null +++ b/application/models/Validate/PasswordStrength.php @@ -0,0 +1,49 @@ + "'%value%' must be at least 8 characters in length", + self::UPPER => "'%value%' must contain at least one uppercase letter", + self::LOWER => "'%value%' must contain at least one lowercase letter", + self::DIGIT => "'%value%' must contain at least one digit character" + ); + + public function isValid($value) + { + $this->_setValue($value); + + $isValid = true; + + if (strlen($value) < 8) { + $this->_error(self::LENGTH); + $isValid = false; + } + + if (!preg_match('/[A-Z]/', $value)) { + $this->_error(self::UPPER); + $isValid = false; + } + + if (!preg_match('/[a-z]/', $value)) { + $this->_error(self::LOWER); + $isValid = false; + } + + if (!preg_match('/\d/', $value)) { + $this->_error(self::DIGIT); + $isValid = false; + } + + return $isValid; + } +} diff --git a/application/models/Validate/ScreenNameAvailable.php b/application/models/Validate/ScreenNameAvailable.php new file mode 100644 index 0000000..b42adf1 --- /dev/null +++ b/application/models/Validate/ScreenNameAvailable.php @@ -0,0 +1,38 @@ + "'%value%' is not available as a unique screen name" + ); + + protected $_model; + + public function __construct($model) + { + $this->_model = $model; + } + + public function isValid($value) + { + $this->_setValue($value); + + $is_valid = true; + + if ($this->_model->fetchByScreenName($value)) { + $this->_error(self::NOT_AVAILABLE); + $is_valid = false; + } + + return $is_valid; + } + +} diff --git a/application/models/Validate/Uri.php b/application/models/Validate/Uri.php new file mode 100644 index 0000000..00d062d --- /dev/null +++ b/application/models/Validate/Uri.php @@ -0,0 +1,28 @@ + "Invalid URI", + ); + + public function isValid($value) + { + $this->_setValue($value); + + $valid = Zend_Uri::check($value); + + if ($valid) { + return true; + } else { + $this->_error(self::MSG_URI); + return false; + + } + } +} +?> diff --git a/application/plugins/Auth.php b/application/plugins/Auth.php new file mode 100644 index 0000000..61abf90 --- /dev/null +++ b/application/plugins/Auth.php @@ -0,0 +1,88 @@ +getModel('Profiles'); + $logins_model = $model_helper->getModel('Logins'); + + $view = Zend_Layout::getMvcInstance()->getView(); + $auth = Zend_Auth::getInstance(); + + if ($auth->hasIdentity()) { + + $identity = $auth->getIdentity(); + $profile = $logins_model->fetchDefaultProfileForLogin($identity->id); + $view->assign(array( + 'auth_identity' => $identity, + 'auth_profile' => $profile + )); + $role = empty($identity->role) ? 'user' : $identity->role; + + } else { + + $view->assign(array( + 'auth_identity' => null, + 'auth_profile' => null + )); + $role = 'guest'; + + } + + // Zend_Registry::set('acl', $this->getAcl()); + // Zend_Registry::set('role', $role); + } + + /** + * Get ACL lists + * + * @return Zend_Acl + public function getAcl() + { + if (null === $this->_acl) { + $acl = new Zend_Acl(); + $this->_loadAclClasses(); + $acl->add(new Bugapp_Acl_Resource_Bug) + ->addRole(new Bugapp_Acl_Role_Guest) + ->addRole(new Bugapp_Acl_Role_User, 'guest') + ->addRole(new Bugapp_Acl_Role_Developer, 'user') + ->addRole(new Bugapp_Acl_Role_Manager, 'developer') + ->deny() + ->allow('guest', 'bug', array('view', 'list', 'index')) + ->allow('user', 'bug', array('comment', 'add', 'process-add')) + ->allow('developer', 'bug', array('resolve')) + ->allow('developer', 'bug', array('close', 'delete')); + $this->_acl = $acl; + } + return $this->_acl; + } + */ + + /** + * Load ACL classes from module models directory + * + * @return void + protected function _loadAclClasses() + { + $loader = new Zend_Loader_PluginLoader(array( + 'Bugapp_Acl_Role' => APPLICATION_PATH . '/models/Acl/Role/', + 'Bugapp_Acl_Resource' => APPLICATION_PATH . '/models/Acl/Resource/', + )); + foreach (array('Guest', 'User', 'Developer', 'Manager') as $role) { + $loader->load($role); + } + foreach (array('Bug') as $resource) { + $loader->load($resource); + } + } + */ +} diff --git a/application/plugins/Initialize.php b/application/plugins/Initialize.php new file mode 100644 index 0000000..7bcc497 --- /dev/null +++ b/application/plugins/Initialize.php @@ -0,0 +1,294 @@ +_setEnv($env); + if (null === $appPath) { + $appPath = realpath(dirname(__FILE__) . '/../'); + } + $this->_appPath = $appPath; + $this->_front = Zend_Controller_Front::getInstance(); + $this->_registry = Zend_Registry::getInstance(); + + Zend_Locale::$compatibilityMode = false; + } + + /** + * Route startup + * + * @param Zend_Controller_Request_Abstract $request + * @return void + */ + public function routeStartup(Zend_Controller_Request_Abstract $request) + { + $this->init(); + } + + /** + * Perform app initialization. + */ + public function init() + { + // $this->initPathCache() + $this->initLogger() + ->initDb() + ->initHelpers() + ->initView() + ->initPlugins() + ->initRoutes() + ->initControllers(); + return $this; + } + + /** + * Get config object (static) + * + * @return Zend_Config + */ + public static function getConfig() + { + return self::$_config; + } + + /** + * Initialize the file map cache for Zend_Loader + * + * @return Memex_Plugin_Initialize + */ + public function initPathCache() + { + $pluginIncFile = $this->_appPath . '/../data/cache/plugins.inc.php'; + if (file_exists($pluginIncFile)) { + include_once $pluginIncFile; + } + Zend_Loader::setIncludeFileCache($pluginIncFile); + Zend_Loader_PluginLoader::setIncludeFileCache($pluginIncFile); + return $this; + } + + /** + * Initialize logger + * + * @return Memex_Plugin_Initialize + */ + public function initLogger() + { + $config = $this->_getConfig(); + + // Set up logging from configuration. + switch ($config->log->writer) { + case 'Firebug': + $writer = new Zend_Log_Writer_Firebug(); + break; + default: + $writer = new Zend_Log_Writer_Stream( + $config->log->path + ); + break; + } + $logger = new Zend_Log($writer); + $filter = new Zend_Log_Filter_Priority( + (int)$config->log->priority + ); + $logger->addFilter($filter); + + Zend_Registry::set('logger', $logger); + return $this; + } + + /** + * Initialize DB + * + * @return Memex_Plugin_Initialize + */ + public function initDb() + { + $config = $this->_getConfig(); + + $db = Zend_Db::factory($config->database); + if ($config->database->profile) { + $db->getProfiler()->setEnabled(TRUE); + } + + Zend_Db_Table_Abstract::setDefaultAdapter($db); + Zend_Registry::set('db', $db); + return $this; + } + + /** + * Initialize action helpers + * + * @return Memex_Plugin_Initialize + */ + public function initHelpers() + { + Zend_Controller_Action_HelperBroker::addPath( + $this->_appPath . '/controllers/helpers', 'Memex_Helper' + ); + return $this; + } + + /** + * Initialize view and layout + * + * @return Memex_Plugin_Initialize + */ + public function initView() + { + // Setup View + $view = new Zend_View(); + $view->doctype('XHTML1_TRANSITIONAL'); + $view->addHelperPath( + $this->_appPath . '/views/helpers', 'Memex_View_Helper' + ); + $view->placeholder('nav')->setPrefix(''); + + // Set view in ViewRenderer + $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer'); + $viewRenderer->setView($view); + + // Initialize layouts + Zend_Layout::startMvc($this->_appPath . '/layouts/scripts'); + + return $this; + } + + /** + * Initialize plugins + * + * @return Memex_Plugin_Initialize + */ + public function initPlugins() + { + $loader = new Zend_Loader_PluginLoader(array( + 'Memex_Plugin' => $this->_appPath . '/plugins/', + )); + $class = $loader->load('Auth'); + $this->_front->registerPlugin(new $class()); + return $this; + } + + /** + * Initialize routes + * + * @return Memex_Plugin_Initialize + */ + public function initRoutes() + { + $config = $this->_getConfig(); + $router = $this->_front->getRouter(); + + $router->addConfig($config, 'routes'); + + return $this; + } + + /** + * Initialize controller directories + * + * @return Memex_Plugin_Initialize + */ + public function initControllers() + { + $this->_front->addControllerDirectory($this->_appPath . '/controllers/'); + return $this; + } + + /** + * Get configuration object + * + * @return Zend_Config + */ + protected function _getConfig() + { + if (null === self::$_config) { + + $php_files = array( + 'routes.php' + ); + $ini_files = array( + 'app.ini' + ); + + self::$_config = new Zend_Config(array( + 'root' => $this->_appPath, + 'environment' => $this->_env + ), true); + + foreach ($php_files as $fn) { + self::$_config->merge(new Zend_Config( + require $this->_appPath . '/config/' . $fn + )); + } + + foreach ($ini_files as $fn) { + self::$_config->merge(new Zend_Config_Ini( + $this->_appPath . '/config/' . $fn, + $this->_env, + true + )); + } + + $this->_registry->config = self::$_config; + } + return self::$_config; + } + + /** + * Set environment + * + * @param string $env + * @return void + */ + protected function _setEnv($env) + { + if (!in_array($env, array('development', 'testing', 'production'))) { + $env = 'development'; + } + $this->_env = $env; + } +} diff --git a/application/vendor/markdown.php b/application/vendor/markdown.php new file mode 100755 index 0000000..8179b56 --- /dev/null +++ b/application/vendor/markdown.php @@ -0,0 +1,1710 @@ + +# +# Original Markdown +# Copyright (c) 2004-2006 John Gruber +# +# + + +define( 'MARKDOWN_VERSION', "1.0.1m" ); # Sat 21 Jun 2008 + + +# +# Global default settings: +# + +# Change to ">" for HTML output +@define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />"); + +# Define the width of a tab for code blocks. +@define( 'MARKDOWN_TAB_WIDTH', 4 ); + + +# +# WordPress settings: +# + +# Change to false to remove Markdown from posts and/or comments. +@define( 'MARKDOWN_WP_POSTS', true ); +@define( 'MARKDOWN_WP_COMMENTS', true ); + + + +### Standard Function Interface ### + +@define( 'MARKDOWN_PARSER_CLASS', 'Markdown_Parser' ); + +function Markdown($text) { +# +# Initialize the parser and return the result of its transform method. +# + # Setup static parser variable. + static $parser; + if (!isset($parser)) { + $parser_class = MARKDOWN_PARSER_CLASS; + $parser = new $parser_class; + } + + # Transform text using parser. + return $parser->transform($text); +} + + +### WordPress Plugin Interface ### + +/* +Plugin Name: Markdown +Plugin URI: http://www.michelf.com/projects/php-markdown/ +Description: Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More... +Version: 1.0.1m +Author: Michel Fortin +Author URI: http://www.michelf.com/ +*/ + +if (isset($wp_version)) { + # More details about how it works here: + # + + # Post content and excerpts + # - Remove WordPress paragraph generator. + # - Run Markdown on excerpt, then remove all tags. + # - Add paragraph tag around the excerpt, but remove it for the excerpt rss. + if (MARKDOWN_WP_POSTS) { + remove_filter('the_content', 'wpautop'); + remove_filter('the_content_rss', 'wpautop'); + remove_filter('the_excerpt', 'wpautop'); + add_filter('the_content', 'Markdown', 6); + add_filter('the_content_rss', 'Markdown', 6); + add_filter('get_the_excerpt', 'Markdown', 6); + add_filter('get_the_excerpt', 'trim', 7); + add_filter('the_excerpt', 'mdwp_add_p'); + add_filter('the_excerpt_rss', 'mdwp_strip_p'); + + remove_filter('content_save_pre', 'balanceTags', 50); + remove_filter('excerpt_save_pre', 'balanceTags', 50); + add_filter('the_content', 'balanceTags', 50); + add_filter('get_the_excerpt', 'balanceTags', 9); + } + + # Comments + # - Remove WordPress paragraph generator. + # - Remove WordPress auto-link generator. + # - Scramble important tags before passing them to the kses filter. + # - Run Markdown on excerpt then remove paragraph tags. + if (MARKDOWN_WP_COMMENTS) { + remove_filter('comment_text', 'wpautop', 30); + remove_filter('comment_text', 'make_clickable'); + add_filter('pre_comment_content', 'Markdown', 6); + add_filter('pre_comment_content', 'mdwp_hide_tags', 8); + add_filter('pre_comment_content', 'mdwp_show_tags', 12); + add_filter('get_comment_text', 'Markdown', 6); + add_filter('get_comment_excerpt', 'Markdown', 6); + add_filter('get_comment_excerpt', 'mdwp_strip_p', 7); + + global $mdwp_hidden_tags, $mdwp_placeholders; + $mdwp_hidden_tags = explode(' ', + '

 
  • '); + $mdwp_placeholders = explode(' ', str_rot13( + 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '. + 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli')); + } + + function mdwp_add_p($text) { + if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) { + $text = '

    '.$text.'

    '; + $text = preg_replace('{\n{2,}}', "

    \n\n

    ", $text); + } + return $text; + } + + function mdwp_strip_p($t) { return preg_replace('{}i', '', $t); } + + function mdwp_hide_tags($text) { + global $mdwp_hidden_tags, $mdwp_placeholders; + return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text); + } + function mdwp_show_tags($text) { + global $mdwp_hidden_tags, $mdwp_placeholders; + return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text); + } +} + + +### bBlog Plugin Info ### + +function identify_modifier_markdown() { + return array( + 'name' => 'markdown', + 'type' => 'modifier', + 'nicename' => 'Markdown', + 'description' => 'A text-to-HTML conversion tool for web writers', + 'authors' => 'Michel Fortin and John Gruber', + 'licence' => 'BSD-like', + 'version' => MARKDOWN_VERSION, + 'help' => 'Markdown syntax allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by John Gruber. More...' + ); +} + + +### Smarty Modifier Interface ### + +function smarty_modifier_markdown($text) { + return Markdown($text); +} + + +### Textile Compatibility Mode ### + +# Rename this file to "classTextile.php" and it can replace Textile everywhere. + +if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) { + # Try to include PHP SmartyPants. Should be in the same directory. + @include_once 'smartypants.php'; + # Fake Textile class. It calls Markdown instead. + class Textile { + function TextileThis($text, $lite='', $encode='') { + if ($lite == '' && $encode == '') $text = Markdown($text); + if (function_exists('SmartyPants')) $text = SmartyPants($text); + return $text; + } + # Fake restricted version: restrictions are not supported for now. + function TextileRestricted($text, $lite='', $noimage='') { + return $this->TextileThis($text, $lite); + } + # Workaround to ensure compatibility with TextPattern 4.0.3. + function blockLite($text) { return $text; } + } +} + + + +# +# Markdown Parser Class +# + +class Markdown_Parser { + + # Regex to match balanced [brackets]. + # Needed to insert a maximum bracked depth while converting to PHP. + var $nested_brackets_depth = 6; + var $nested_brackets_re; + + var $nested_url_parenthesis_depth = 4; + var $nested_url_parenthesis_re; + + # Table of hash values for escaped characters: + var $escape_chars = '\`*_{}[]()>#+-.!'; + var $escape_chars_re; + + # Change to ">" for HTML output. + var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX; + var $tab_width = MARKDOWN_TAB_WIDTH; + + # Change to `true` to disallow markup or entities. + var $no_markup = false; + var $no_entities = false; + + # Predefined urls and titles for reference links and images. + var $predef_urls = array(); + var $predef_titles = array(); + + + function Markdown_Parser() { + # + # Constructor function. Initialize appropriate member variables. + # + $this->_initDetab(); + $this->prepareItalicsAndBold(); + + $this->nested_brackets_re = + str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth). + str_repeat('\])*', $this->nested_brackets_depth); + + $this->nested_url_parenthesis_re = + str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth). + str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth); + + $this->escape_chars_re = '['.preg_quote($this->escape_chars).']'; + + # Sort document, block, and span gamut in ascendent priority order. + asort($this->document_gamut); + asort($this->block_gamut); + asort($this->span_gamut); + } + + + # Internal hashes used during transformation. + var $urls = array(); + var $titles = array(); + var $html_hashes = array(); + + # Status flag to avoid invalid nesting. + var $in_anchor = false; + + + function setup() { + # + # Called before the transformation process starts to setup parser + # states. + # + # Clear global hashes. + $this->urls = $this->predef_urls; + $this->titles = $this->predef_titles; + $this->html_hashes = array(); + + $in_anchor = false; + } + + function teardown() { + # + # Called after the transformation process to clear any variable + # which may be taking up memory unnecessarly. + # + $this->urls = array(); + $this->titles = array(); + $this->html_hashes = array(); + } + + + function transform($text) { + # + # Main function. Performs some preprocessing on the input text + # and pass it through the document gamut. + # + $this->setup(); + + # Remove UTF-8 BOM and marker character in input, if present. + $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text); + + # Standardize line endings: + # DOS to Unix and Mac to Unix + $text = preg_replace('{\r\n?}', "\n", $text); + + # Make sure $text ends with a couple of newlines: + $text .= "\n\n"; + + # Convert all tabs to spaces. + $text = $this->detab($text); + + # Turn block-level HTML blocks into hash entries + $text = $this->hashHTMLBlocks($text); + + # Strip any lines consisting only of spaces and tabs. + # This makes subsequent regexen easier to write, because we can + # match consecutive blank lines with /\n+/ instead of something + # contorted like /[ ]*\n+/ . + $text = preg_replace('/^[ ]+$/m', '', $text); + + # Run document gamut methods. + foreach ($this->document_gamut as $method => $priority) { + $text = $this->$method($text); + } + + $this->teardown(); + + return $text . "\n"; + } + + var $document_gamut = array( + # Strip link definitions, store in hashes. + "stripLinkDefinitions" => 20, + + "runBasicBlockGamut" => 30, + ); + + + function stripLinkDefinitions($text) { + # + # Strips link definitions from text, stores the URLs and titles in + # hash references. + # + $less_than_tab = $this->tab_width - 1; + + # Link defs are in the form: ^[id]: url "optional title" + $text = preg_replace_callback('{ + ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1 + [ ]* + \n? # maybe *one* newline + [ ]* + ? # url = $2 + [ ]* + \n? # maybe one newline + [ ]* + (?: + (?<=\s) # lookbehind for whitespace + ["(] + (.*?) # title = $3 + [")] + [ ]* + )? # title is optional + (?:\n+|\Z) + }xm', + array(&$this, '_stripLinkDefinitions_callback'), + $text); + return $text; + } + function _stripLinkDefinitions_callback($matches) { + $link_id = strtolower($matches[1]); + $this->urls[$link_id] = $matches[2]; + $this->titles[$link_id] =& $matches[3]; + return ''; # String that will replace the block + } + + + function hashHTMLBlocks($text) { + if ($this->no_markup) return $text; + + $less_than_tab = $this->tab_width - 1; + + # Hashify HTML blocks: + # We only want to do this for block-level HTML tags, such as headers, + # lists, and tables. That's because we still want to wrap

    s around + # "paragraphs" that are wrapped in non-block-level tags, such as anchors, + # phrase emphasis, and spans. The list of tags we're looking for is + # hard-coded: + # + # * List "a" is made of tags which can be both inline or block-level. + # These will be treated block-level when the start tag is alone on + # its line, otherwise they're not matched here and will be taken as + # inline later. + # * List "b" is made of tags which are always block-level; + # + $block_tags_a_re = 'ins|del'; + $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'. + 'script|noscript|form|fieldset|iframe|math'; + + # Regular expression for the content of a block tag. + $nested_tags_level = 4; + $attr = ' + (?> # optional tag attributes + \s # starts with whitespace + (?> + [^>"/]+ # text outside quotes + | + /+(?!>) # slash not followed by ">" + | + "[^"]*" # text inside double quotes (tolerate ">") + | + \'[^\']*\' # text inside single quotes (tolerate ">") + )* + )? + '; + $content = + str_repeat(' + (?> + [^<]+ # content without tag + | + <\2 # nested opening tag + '.$attr.' # attributes + (?> + /> + | + >', $nested_tags_level). # end of opening tag + '.*?'. # last level nested tag content + str_repeat(' + # closing nested tag + ) + | + <(?!/\2\s*> # other tags with a different name + ) + )*', + $nested_tags_level); + $content2 = str_replace('\2', '\3', $content); + + # First, look for nested blocks, e.g.: + #

    + #
    + # tags for inner block must be indented. + #
    + #
    + # + # The outermost tags must start at the left margin for this to match, and + # the inner nested divs must be indented. + # We need to do this before the next, more liberal match, because the next + # match will start at the first `
    ` and stop at the first `
    `. + $text = preg_replace_callback('{(?> + (?> + (?<=\n\n) # Starting after a blank line + | # or + \A\n? # the beginning of the doc + ) + ( # save in $1 + + # Match from `\n` to `\n`, handling nested tags + # in between. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_b_re.')# start tag = $2 + '.$attr.'> # attributes followed by > and \n + '.$content.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special version for tags of group a. + + [ ]{0,'.$less_than_tab.'} + <('.$block_tags_a_re.')# start tag = $3 + '.$attr.'>[ ]*\n # attributes followed by > + '.$content2.' # content, support nesting + # the matching end tag + [ ]* # trailing spaces/tabs + (?=\n+|\Z) # followed by a newline or end of document + + | # Special case just for
    . It was easier to make a special + # case than to make the other regex more complicated. + + [ ]{0,'.$less_than_tab.'} + <(hr) # start tag = $2 + '.$attr.' # attributes + /?> # the matching end tag + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # Special case for standalone HTML comments: + + [ ]{0,'.$less_than_tab.'} + (?s: + + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + | # PHP and ASP-style processor instructions ( + ) + [ ]* + (?=\n{2,}|\Z) # followed by a blank line or end of document + + ) + )}Sxmi', + array(&$this, '_hashHTMLBlocks_callback'), + $text); + + return $text; + } + function _hashHTMLBlocks_callback($matches) { + $text = $matches[1]; + $key = $this->hashBlock($text); + return "\n\n$key\n\n"; + } + + + function hashPart($text, $boundary = 'X') { + # + # Called whenever a tag must be hashed when a function insert an atomic + # element in the text stream. Passing $text to through this function gives + # a unique text-token which will be reverted back when calling unhash. + # + # The $boundary argument specify what character should be used to surround + # the token. By convension, "B" is used for block elements that needs not + # to be wrapped into paragraph tags at the end, ":" is used for elements + # that are word separators and "X" is used in the general case. + # + # Swap back any tag hash found in $text so we do not have to `unhash` + # multiple times at the end. + $text = $this->unhash($text); + + # Then hash the block. + static $i = 0; + $key = "$boundary\x1A" . ++$i . $boundary; + $this->html_hashes[$key] = $text; + return $key; # String that will replace the tag. + } + + + function hashBlock($text) { + # + # Shortcut function for hashPart with block-level boundaries. + # + return $this->hashPart($text, 'B'); + } + + + var $block_gamut = array( + # + # These are all the transformations that form block-level + # tags like paragraphs, headers, and list items. + # + "doHeaders" => 10, + "doHorizontalRules" => 20, + + "doLists" => 40, + "doCodeBlocks" => 50, + "doBlockQuotes" => 60, + ); + + function runBlockGamut($text) { + # + # Run block gamut tranformations. + # + # We need to escape raw HTML in Markdown source before doing anything + # else. This need to be done for each block, and not only at the + # begining in the Markdown function since hashed blocks can be part of + # list items and could have been indented. Indented blocks would have + # been seen as a code block in a previous pass of hashHTMLBlocks. + $text = $this->hashHTMLBlocks($text); + + return $this->runBasicBlockGamut($text); + } + + function runBasicBlockGamut($text) { + # + # Run block gamut tranformations, without hashing HTML blocks. This is + # useful when HTML blocks are known to be already hashed, like in the first + # whole-document pass. + # + foreach ($this->block_gamut as $method => $priority) { + $text = $this->$method($text); + } + + # Finally form paragraph and restore hashed blocks. + $text = $this->formParagraphs($text); + + return $text; + } + + + function doHorizontalRules($text) { + # Do Horizontal Rules: + return preg_replace( + '{ + ^[ ]{0,3} # Leading space + ([-*_]) # $1: First marker + (?> # Repeated marker group + [ ]{0,2} # Zero, one, or two spaces. + \1 # Marker character + ){2,} # Group repeated at least twice + [ ]* # Tailing spaces + $ # End of line. + }mx', + "\n".$this->hashBlock("empty_element_suffix")."\n", + $text); + } + + + var $span_gamut = array( + # + # These are all the transformations that occur *within* block-level + # tags like paragraphs, headers, and list items. + # + # Process character escapes, code spans, and inline HTML + # in one shot. + "parseSpan" => -30, + + # Process anchor and image tags. Images must come first, + # because ![foo][f] looks like an anchor. + "doImages" => 10, + "doAnchors" => 20, + + # Make links out of things like `` + # Must come after doAnchors, because you can use < and > + # delimiters in inline links like [this](). + "doAutoLinks" => 30, + "encodeAmpsAndAngles" => 40, + + "doItalicsAndBold" => 50, + "doHardBreaks" => 60, + ); + + function runSpanGamut($text) { + # + # Run span gamut tranformations. + # + foreach ($this->span_gamut as $method => $priority) { + $text = $this->$method($text); + } + + return $text; + } + + + function doHardBreaks($text) { + # Do hard breaks: + return preg_replace_callback('/ {2,}\n/', + array(&$this, '_doHardBreaks_callback'), $text); + } + function _doHardBreaks_callback($matches) { + return $this->hashPart("empty_element_suffix\n"); + } + + + function doAnchors($text) { + # + # Turn Markdown link shortcuts into XHTML tags. + # + if ($this->in_anchor) return $text; + $this->in_anchor = true; + + # + # First, handle reference-style links: [link text] [id] + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + ) + }xs', + array(&$this, '_doAnchors_reference_callback'), $text); + + # + # Next, inline-style links: [link text](url "optional title") + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + \[ + ('.$this->nested_brackets_re.') # link text = $2 + \] + \( # literal paren + [ ]* + (?: + <(\S*)> # href = $3 + | + ('.$this->nested_url_parenthesis_re.') # href = $4 + ) + [ ]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # Title = $7 + \6 # matching quote + [ ]* # ignore any spaces/tabs between closing quote and ) + )? # title is optional + \) + ) + }xs', + array(&$this, '_DoAnchors_inline_callback'), $text); + + # + # Last, handle reference-style shortcuts: [link text] + # These must come last in case you've also got [link test][1] + # or [link test](/foo) + # +// $text = preg_replace_callback('{ +// ( # wrap whole match in $1 +// \[ +// ([^\[\]]+) # link text = $2; can\'t contain [ or ] +// \] +// ) +// }xs', +// array(&$this, '_doAnchors_reference_callback'), $text); + + $this->in_anchor = false; + return $text; + } + function _doAnchors_reference_callback($matches) { + $whole_match = $matches[1]; + $link_text = $matches[2]; + $link_id =& $matches[3]; + + if ($link_id == "") { + # for shortcut links like [this][] or [this]. + $link_id = $link_text; + } + + # lower-case and turn embedded newlines into spaces + $link_id = strtolower($link_id); + $link_id = preg_replace('{[ ]?\n}', ' ', $link_id); + + if (isset($this->urls[$link_id])) { + $url = $this->urls[$link_id]; + $url = $this->encodeAttribute($url); + + $result = "titles[$link_id] ) ) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + $result = $this->hashPart($result); + } + else { + $result = $whole_match; + } + return $result; + } + function _doAnchors_inline_callback($matches) { + $whole_match = $matches[1]; + $link_text = $this->runSpanGamut($matches[2]); + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + $url = $this->encodeAttribute($url); + + $result = "encodeAttribute($title); + $result .= " title=\"$title\""; + } + + $link_text = $this->runSpanGamut($link_text); + $result .= ">$link_text"; + + return $this->hashPart($result); + } + + + function doImages($text) { + # + # Turn Markdown image shortcuts into tags. + # + # + # First, handle reference-style labeled images: ![alt text][id] + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + + [ ]? # one optional space + (?:\n[ ]*)? # one optional newline followed by spaces + + \[ + (.*?) # id = $3 + \] + + ) + }xs', + array(&$this, '_doImages_reference_callback'), $text); + + # + # Next, handle inline images: ![alt text](url "optional title") + # Don't forget: encode * and _ + # + $text = preg_replace_callback('{ + ( # wrap whole match in $1 + !\[ + ('.$this->nested_brackets_re.') # alt text = $2 + \] + \s? # One optional whitespace character + \( # literal paren + [ ]* + (?: + <(\S*)> # src url = $3 + | + ('.$this->nested_url_parenthesis_re.') # src url = $4 + ) + [ ]* + ( # $5 + ([\'"]) # quote char = $6 + (.*?) # title = $7 + \6 # matching quote + [ ]* + )? # title is optional + \) + ) + }xs', + array(&$this, '_doImages_inline_callback'), $text); + + return $text; + } + function _doImages_reference_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $link_id = strtolower($matches[3]); + + if ($link_id == "") { + $link_id = strtolower($alt_text); # for shortcut links like ![this][]. + } + + $alt_text = $this->encodeAttribute($alt_text); + if (isset($this->urls[$link_id])) { + $url = $this->encodeAttribute($this->urls[$link_id]); + $result = "\"$alt_text\"";titles[$link_id])) { + $title = $this->titles[$link_id]; + $title = $this->encodeAttribute($title); + $result .= " title=\"$title\""; + } + $result .= $this->empty_element_suffix; + $result = $this->hashPart($result); + } + else { + # If there's no such link ID, leave intact: + $result = $whole_match; + } + + return $result; + } + function _doImages_inline_callback($matches) { + $whole_match = $matches[1]; + $alt_text = $matches[2]; + $url = $matches[3] == '' ? $matches[4] : $matches[3]; + $title =& $matches[7]; + + $alt_text = $this->encodeAttribute($alt_text); + $url = $this->encodeAttribute($url); + $result = "\"$alt_text\"";encodeAttribute($title); + $result .= " title=\"$title\""; # $title already quoted + } + $result .= $this->empty_element_suffix; + + return $this->hashPart($result); + } + + + function doHeaders($text) { + # Setext-style headers: + # Header 1 + # ======== + # + # Header 2 + # -------- + # + $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx', + array(&$this, '_doHeaders_callback_setext'), $text); + + # atx-style headers: + # # Header 1 + # ## Header 2 + # ## Header 2 with closing hashes ## + # ... + # ###### Header 6 + # + $text = preg_replace_callback('{ + ^(\#{1,6}) # $1 = string of #\'s + [ ]* + (.+?) # $2 = Header text + [ ]* + \#* # optional closing #\'s (not counted) + \n+ + }xm', + array(&$this, '_doHeaders_callback_atx'), $text); + + return $text; + } + function _doHeaders_callback_setext($matches) { + # Terrible hack to check we haven't found an empty list item. + if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) + return $matches[0]; + + $level = $matches[2]{0} == '=' ? 1 : 2; + $block = "".$this->runSpanGamut($matches[1]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + function _doHeaders_callback_atx($matches) { + $level = strlen($matches[1]); + $block = "".$this->runSpanGamut($matches[2]).""; + return "\n" . $this->hashBlock($block) . "\n\n"; + } + + + function doLists($text) { + # + # Form HTML ordered (numbered) and unordered (bulleted) lists. + # + $less_than_tab = $this->tab_width - 1; + + # Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[.]'; + $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; + + $markers_relist = array($marker_ul_re, $marker_ol_re); + + foreach ($markers_relist as $marker_re) { + # Re-usable pattern to match any entirel ul or ol list: + $whole_list_re = ' + ( # $1 = whole list + ( # $2 + [ ]{0,'.$less_than_tab.'} + ('.$marker_re.') # $3 = first list item marker + [ ]+ + ) + (?s:.+?) + ( # $4 + \z + | + \n{2,} + (?=\S) + (?! # Negative lookahead for another list item marker + [ ]* + '.$marker_re.'[ ]+ + ) + ) + ) + '; // mx + + # We use a different prefix before nested lists than top-level lists. + # See extended comment in _ProcessListItems(). + + if ($this->list_level) { + $text = preg_replace_callback('{ + ^ + '.$whole_list_re.' + }mx', + array(&$this, '_doLists_callback'), $text); + } + else { + $text = preg_replace_callback('{ + (?:(?<=\n)\n|\A\n?) # Must eat the newline + '.$whole_list_re.' + }mx', + array(&$this, '_doLists_callback'), $text); + } + } + + return $text; + } + function _doLists_callback($matches) { + # Re-usable patterns to match list item bullets and number markers: + $marker_ul_re = '[*+-]'; + $marker_ol_re = '\d+[.]'; + $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)"; + + $list = $matches[1]; + $list_type = preg_match("/$marker_ul_re/", $matches[3]) ? "ul" : "ol"; + + $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re ); + + $list .= "\n"; + $result = $this->processListItems($list, $marker_any_re); + + $result = $this->hashBlock("<$list_type>\n" . $result . ""); + return "\n". $result ."\n\n"; + } + + var $list_level = 0; + + function processListItems($list_str, $marker_any_re) { + # + # Process the contents of a single ordered or unordered list, splitting it + # into individual list items. + # + # The $this->list_level global keeps track of when we're inside a list. + # Each time we enter a list, we increment it; when we leave a list, + # we decrement. If it's zero, we're not in a list anymore. + # + # We do this because when we're not inside a list, we want to treat + # something like this: + # + # I recommend upgrading to version + # 8. Oops, now this line is treated + # as a sub-list. + # + # As a single paragraph, despite the fact that the second line starts + # with a digit-period-space sequence. + # + # Whereas when we're inside a list (or sub-list), that line will be + # treated as the start of a sub-list. What a kludge, huh? This is + # an aspect of Markdown's syntax that's hard to parse perfectly + # without resorting to mind-reading. Perhaps the solution is to + # change the syntax rules such that sub-lists must start with a + # starting cardinal number; e.g. "1." or "a.". + + $this->list_level++; + + # trim trailing blank lines: + $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str); + + $list_str = preg_replace_callback('{ + (\n)? # leading line = $1 + (^[ ]*) # leading whitespace = $2 + ('.$marker_any_re.' # list marker and space = $3 + (?:[ ]+|(?=\n)) # space only required if item is not empty + ) + ((?s:.*?)) # list item text = $4 + (?:(\n+(?=\n))|\n) # tailing blank line = $5 + (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n)))) + }xm', + array(&$this, '_processListItems_callback'), $list_str); + + $this->list_level--; + return $list_str; + } + function _processListItems_callback($matches) { + $item = $matches[4]; + $leading_line =& $matches[1]; + $leading_space =& $matches[2]; + $marker_space = $matches[3]; + $tailing_blank_line =& $matches[5]; + + if ($leading_line || $tailing_blank_line || + preg_match('/\n{2,}/', $item)) + { + # Replace marker with the appropriate whitespace indentation + $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item; + $item = $this->runBlockGamut($this->outdent($item)."\n"); + } + else { + # Recursion for sub-lists: + $item = $this->doLists($this->outdent($item)); + $item = preg_replace('/\n+$/', '', $item); + $item = $this->runSpanGamut($item); + } + + return "
  • " . $item . "
  • \n"; + } + + + function doCodeBlocks($text) { + # + # Process Markdown `
    ` blocks.
    +	#
    +		$text = preg_replace_callback('{
    +				(?:\n\n|\A\n?)
    +				(	            # $1 = the code block -- one or more lines, starting with a space/tab
    +				  (?>
    +					[ ]{'.$this->tab_width.'}  # Lines must start with a tab or a tab-width of spaces
    +					.*\n+
    +				  )+
    +				)
    +				((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z)	# Lookahead for non-space at line-start, or end of doc
    +			}xm',
    +			array(&$this, '_doCodeBlocks_callback'), $text);
    +
    +		return $text;
    +	}
    +	function _doCodeBlocks_callback($matches) {
    +		$codeblock = $matches[1];
    +
    +		$codeblock = $this->outdent($codeblock);
    +		$codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
    +
    +		# trim leading newlines and trailing newlines
    +		$codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
    +
    +		$codeblock = "
    $codeblock\n
    "; + return "\n\n".$this->hashBlock($codeblock)."\n\n"; + } + + + function makeCodeSpan($code) { + # + # Create a code span markup for $code. Called from handleSpanToken. + # + $code = htmlspecialchars(trim($code), ENT_NOQUOTES); + return $this->hashPart("$code"); + } + + + var $em_relist = array( + '' => '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(? '(?:(? '(?<=\S)(? '(?<=\S)(?em_relist as $em => $em_re) { + foreach ($this->strong_relist as $strong => $strong_re) { + # Construct list of allowed token expressions. + $token_relist = array(); + if (isset($this->em_strong_relist["$em$strong"])) { + $token_relist[] = $this->em_strong_relist["$em$strong"]; + } + $token_relist[] = $em_re; + $token_relist[] = $strong_re; + + # Construct master expression from list. + $token_re = '{('. implode('|', $token_relist) .')}'; + $this->em_strong_prepared_relist["$em$strong"] = $token_re; + } + } + } + + function doItalicsAndBold($text) { + $token_stack = array(''); + $text_stack = array(''); + $em = ''; + $strong = ''; + $tree_char_em = false; + + while (1) { + # + # Get prepared regular expression for seraching emphasis tokens + # in current context. + # + $token_re = $this->em_strong_prepared_relist["$em$strong"]; + + # + # Each loop iteration seach for the next emphasis token. + # Each token is then passed to handleSpanToken. + # + $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE); + $text_stack[0] .= $parts[0]; + $token =& $parts[1]; + $text =& $parts[2]; + + if (empty($token)) { + # Reached end of text span: empty stack without emitting. + # any more emphasis. + while ($token_stack[0]) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + break; + } + + $token_len = strlen($token); + if ($tree_char_em) { + # Reached closing marker while inside a three-char emphasis. + if ($token_len == 3) { + # Three-char closing marker, close em and strong. + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + $strong = ''; + } else { + # Other closing marker: close one em or strong and + # change current token state to match the other + $token_stack[0] = str_repeat($token{0}, 3-$token_len); + $tag = $token_len == 2 ? "strong" : "em"; + $span = $text_stack[0]; + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] = $this->hashPart($span); + $$tag = ''; # $$tag stands for $em or $strong + } + $tree_char_em = false; + } else if ($token_len == 3) { + if ($em) { + # Reached closing marker for both em and strong. + # Closing strong marker: + for ($i = 0; $i < 2; ++$i) { + $shifted_token = array_shift($token_stack); + $tag = strlen($shifted_token) == 2 ? "strong" : "em"; + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "<$tag>$span"; + $text_stack[0] .= $this->hashPart($span); + $$tag = ''; # $$tag stands for $em or $strong + } + } else { + # Reached opening three-char emphasis marker. Push on token + # stack; will be handled by the special condition above. + $em = $token{0}; + $strong = "$em$em"; + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $tree_char_em = true; + } + } else if ($token_len == 2) { + if ($strong) { + # Unwind any dangling emphasis marker: + if (strlen($token_stack[0]) == 1) { + $text_stack[1] .= array_shift($token_stack); + $text_stack[0] .= array_shift($text_stack); + } + # Closing strong marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $strong = ''; + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $strong = $token; + } + } else { + # Here $token_len == 1 + if ($em) { + if (strlen($token_stack[0]) == 1) { + # Closing emphasis marker: + array_shift($token_stack); + $span = array_shift($text_stack); + $span = $this->runSpanGamut($span); + $span = "$span"; + $text_stack[0] .= $this->hashPart($span); + $em = ''; + } else { + $text_stack[0] .= $token; + } + } else { + array_unshift($token_stack, $token); + array_unshift($text_stack, ''); + $em = $token; + } + } + } + return $text_stack[0]; + } + + + function doBlockQuotes($text) { + $text = preg_replace_callback('/ + ( # Wrap whole match in $1 + (?> + ^[ ]*>[ ]? # ">" at the start of a line + .+\n # rest of the first line + (.+\n)* # subsequent consecutive lines + \n* # blanks + )+ + ) + /xm', + array(&$this, '_doBlockQuotes_callback'), $text); + + return $text; + } + function _doBlockQuotes_callback($matches) { + $bq = $matches[1]; + # trim one level of quoting - trim whitespace-only lines + $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq); + $bq = $this->runBlockGamut($bq); # recurse + + $bq = preg_replace('/^/m', " ", $bq); + # These leading spaces cause problem with
     content, 
    +		# so we need to fix that:
    +		$bq = preg_replace_callback('{(\s*
    .+?
    )}sx', + array(&$this, '_DoBlockQuotes_callback2'), $bq); + + return "\n". $this->hashBlock("
    \n$bq\n
    ")."\n\n"; + } + function _doBlockQuotes_callback2($matches) { + $pre = $matches[1]; + $pre = preg_replace('/^ /m', '', $pre); + return $pre; + } + + + function formParagraphs($text) { + # + # Params: + # $text - string to process with html

    tags + # + # Strip leading and trailing lines: + $text = preg_replace('/\A\n+|\n+\z/', '', $text); + + $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY); + + # + # Wrap

    tags and unhashify HTML blocks + # + foreach ($grafs as $key => $value) { + if (!preg_match('/^B\x1A[0-9]+B$/', $value)) { + # Is a paragraph. + $value = $this->runSpanGamut($value); + $value = preg_replace('/^([ ]*)/', "

    ", $value); + $value .= "

    "; + $grafs[$key] = $this->unhash($value); + } + else { + # Is a block. + # Modify elements of @grafs in-place... + $graf = $value; + $block = $this->html_hashes[$graf]; + $graf = $block; +// if (preg_match('{ +// \A +// ( # $1 =
    tag +//
    ]* +// \b +// markdown\s*=\s* ([\'"]) # $2 = attr quote char +// 1 +// \2 +// [^>]* +// > +// ) +// ( # $3 = contents +// .* +// ) +// (
    ) # $4 = closing tag +// \z +// }xs', $block, $matches)) +// { +// list(, $div_open, , $div_content, $div_close) = $matches; +// +// # We can't call Markdown(), because that resets the hash; +// # that initialization code should be pulled into its own sub, though. +// $div_content = $this->hashHTMLBlocks($div_content); +// +// # Run document gamut methods on the content. +// foreach ($this->document_gamut as $method => $priority) { +// $div_content = $this->$method($div_content); +// } +// +// $div_open = preg_replace( +// '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open); +// +// $graf = $div_open . "\n" . $div_content . "\n" . $div_close; +// } + $grafs[$key] = $graf; + } + } + + return implode("\n\n", $grafs); + } + + + function encodeAttribute($text) { + # + # Encode text for a double-quoted HTML attribute. This function + # is *not* suitable for attributes enclosed in single quotes. + # + $text = $this->encodeAmpsAndAngles($text); + $text = str_replace('"', '"', $text); + return $text; + } + + + function encodeAmpsAndAngles($text) { + # + # Smart processing for ampersands and angle brackets that need to + # be encoded. Valid character entities are left alone unless the + # no-entities mode is set. + # + if ($this->no_entities) { + $text = str_replace('&', '&', $text); + } else { + # Ampersand-encoding based entirely on Nat Irons's Amputator + # MT plugin: + $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/', + '&', $text);; + } + # Encode remaining <'s + $text = str_replace('<', '<', $text); + + return $text; + } + + + function doAutoLinks($text) { + $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i', + array(&$this, '_doAutoLinks_url_callback'), $text); + + # Email addresses: + $text = preg_replace_callback('{ + < + (?:mailto:)? + ( + [-.\w\x80-\xFF]+ + \@ + [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+ + ) + > + }xi', + array(&$this, '_doAutoLinks_email_callback'), $text); + + return $text; + } + function _doAutoLinks_url_callback($matches) { + $url = $this->encodeAttribute($matches[1]); + $link = "$url"; + return $this->hashPart($link); + } + function _doAutoLinks_email_callback($matches) { + $address = $matches[1]; + $link = $this->encodeEmailAddress($address); + return $this->hashPart($link); + } + + + function encodeEmailAddress($addr) { + # + # Input: an email address, e.g. "foo@example.com" + # + # Output: the email address as a mailto link, with each character + # of the address encoded as either a decimal or hex entity, in + # the hopes of foiling most address harvesting spam bots. E.g.: + # + #

    foo@exampl + # e.com

    + # + # Based by a filter by Matthew Wickline, posted to BBEdit-Talk. + # With some optimizations by Milian Wolff. + # + $addr = "mailto:" . $addr; + $chars = preg_split('/(? $char) { + $ord = ord($char); + # Ignore non-ascii chars. + if ($ord < 128) { + $r = ($seed * (1 + $key)) % 100; # Pseudo-random function. + # roughly 10% raw, 45% hex, 45% dec + # '@' *must* be encoded. I insist. + if ($r > 90 && $char != '@') /* do nothing */; + else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';'; + else $chars[$key] = '&#'.$ord.';'; + } + } + + $addr = implode('', $chars); + $text = implode('', array_slice($chars, 7)); # text without `mailto:` + $addr = "$text"; + + return $addr; + } + + + function parseSpan($str) { + # + # Take the string $str and parse it into tokens, hashing embeded HTML, + # escaped characters and handling code spans. + # + $output = ''; + + $span_re = '{ + ( + \\\\'.$this->escape_chars_re.' + | + (?no_markup ? '' : ' + | + # comment + | + <\?.*?\?> | <%.*?%> # processing instruction + | + <[/!$]?[-a-zA-Z0-9:]+ # regular tags + (?> + \s + (?>[^"\'>]+|"[^"]*"|\'[^\']*\')* + )? + > + ').' + ) + }xs'; + + while (1) { + # + # Each loop iteration seach for either the next tag, the next + # openning code span marker, or the next escaped character. + # Each token is then passed to handleSpanToken. + # + $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE); + + # Create token from text preceding tag. + if ($parts[0] != "") { + $output .= $parts[0]; + } + + # Check if we reach the end. + if (isset($parts[1])) { + $output .= $this->handleSpanToken($parts[1], $parts[2]); + $str = $parts[2]; + } + else { + break; + } + } + + return $output; + } + + + function handleSpanToken($token, &$str) { + # + # Handle $token provided by parseSpan by determining its nature and + # returning the corresponding value that should replace it. + # + switch ($token{0}) { + case "\\": + return $this->hashPart("&#". ord($token{1}). ";"); + case "`": + # Search for end marker in remaining text. + if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm', + $str, $matches)) + { + $str = $matches[2]; + $codespan = $this->makeCodeSpan($matches[1]); + return $this->hashPart($codespan); + } + return $token; // return as text since no ending marker found. + default: + return $this->hashPart($token); + } + } + + + function outdent($text) { + # + # Remove one level of line-leading tabs or spaces + # + return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text); + } + + + # String length function for detab. `_initDetab` will create a function to + # hanlde UTF-8 if the default function does not exist. + var $utf8_strlen = 'mb_strlen'; + + function detab($text) { + # + # Replace tabs with the appropriate amount of space. + # + # For each line we separate the line in blocks delemited by + # tab characters. Then we reconstruct every line by adding the + # appropriate number of space between each blocks. + + $text = preg_replace_callback('/^.*\t.*$/m', + array(&$this, '_detab_callback'), $text); + + return $text; + } + function _detab_callback($matches) { + $line = $matches[0]; + $strlen = $this->utf8_strlen; # strlen function for UTF-8. + + # Split in blocks. + $blocks = explode("\t", $line); + # Add each blocks to the line. + $line = $blocks[0]; + unset($blocks[0]); # Do not add first block twice. + foreach ($blocks as $block) { + # Calculate amount of space, insert spaces, insert block. + $amount = $this->tab_width - + $strlen($line, 'UTF-8') % $this->tab_width; + $line .= str_repeat(" ", $amount) . $block; + } + return $line; + } + function _initDetab() { + # + # Check for the availability of the function in the `utf8_strlen` property + # (initially `mb_strlen`). If the function is not available, create a + # function that will loosely count the number of UTF-8 characters with a + # regular expression. + # + if (function_exists($this->utf8_strlen)) return; + $this->utf8_strlen = create_function('$text', 'return preg_match_all( + "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/", + $text, $m);'); + } + + + function unhash($text) { + # + # Swap back in all the tags hashed by _HashHTMLBlocks. + # + return preg_replace_callback('/(.)\x1A[0-9]+\1/', + array(&$this, '_unhash_callback'), $text); + } + function _unhash_callback($matches) { + return $this->html_hashes[$matches[0]]; + } + +} + +/* + +PHP Markdown +============ + +Description +----------- + +This is a PHP translation of the original Markdown formatter written in +Perl by John Gruber. + +Markdown is a text-to-HTML filter; it translates an easy-to-read / +easy-to-write structured text format into HTML. Markdown's text format +is most similar to that of plain text email, and supports features such +as headers, *emphasis*, code blocks, blockquotes, and links. + +Markdown's syntax is designed not as a generic markup language, but +specifically to serve as a front-end to (X)HTML. You can use span-level +HTML tags anywhere in a Markdown document, and you can use block level +HTML tags (like
    and as well). + +For more information about Markdown's syntax, see: + + + + +Bugs +---- + +To file bug reports please send email to: + + + +Please include with your report: (1) the example input; (2) the output you +expected; (3) the output Markdown actually produced. + + +Version History +--------------- + +See the readme file for detailed release notes for this version. + + +Copyright and License +--------------------- + +PHP Markdown +Copyright (c) 2004-2008 Michel Fortin + +All rights reserved. + +Based on Markdown +Copyright (c) 2003-2006 John Gruber + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +* Neither the name "Markdown" nor the names of its contributors may + be used to endorse or promote products derived from this software + without specific prior written permission. + +This software is provided by the copyright holders and contributors "as +is" and any express or implied warranties, including, but not limited +to, the implied warranties of merchantability and fitness for a +particular purpose are disclaimed. In no event shall the copyright owner +or contributors be liable for any direct, indirect, incidental, special, +exemplary, or consequential damages (including, but not limited to, +procurement of substitute goods or services; loss of use, data, or +profits; or business interruption) however caused and on any theory of +liability, whether in contract, strict liability, or tort (including +negligence or otherwise) arising in any way out of the use of this +software, even if advised of the possibility of such damage. + +*/ +?> \ No newline at end of file diff --git a/application/views/helpers/BaseUrl.php b/application/views/helpers/BaseUrl.php new file mode 100644 index 0000000..4f5509f --- /dev/null +++ b/application/views/helpers/BaseUrl.php @@ -0,0 +1,21 @@ +getBaseUrl(); + + // Remove trailing slashes + $file = ($file !== null) ? ltrim($file, '/\\') : null; + + // Build return + $return = rtrim($baseUrl, '/\\') . (($file !== null) ? ('/' . $file) : ''); + + return $return; + } +} diff --git a/application/views/helpers/QueryUrl.php b/application/views/helpers/QueryUrl.php new file mode 100644 index 0000000..e7f623d --- /dev/null +++ b/application/views/helpers/QueryUrl.php @@ -0,0 +1,24 @@ +getRouter(); + return $router->assemble($urlOptions, $name, $reset, $encode) . + '?' . http_build_query(array_merge($_GET, $params)); + } +} diff --git a/application/views/scripts/auth/index.phtml b/application/views/scripts/auth/index.phtml new file mode 100644 index 0000000..f923c07 --- /dev/null +++ b/application/views/scripts/auth/index.phtml @@ -0,0 +1,5 @@ +

    Login

    +login_form ?> + +

    New User? Please register!

    +registration_form ?> diff --git a/application/views/scripts/auth/login.phtml b/application/views/scripts/auth/login.phtml new file mode 100644 index 0000000..125920c --- /dev/null +++ b/application/views/scripts/auth/login.phtml @@ -0,0 +1,5 @@ +placeholder('crumbs')->captureStart() ?> + / login +placeholder('crumbs')->captureEnd() ?> + +login_form ?> diff --git a/application/views/scripts/auth/logout.phtml b/application/views/scripts/auth/logout.phtml new file mode 100644 index 0000000..6e66716 --- /dev/null +++ b/application/views/scripts/auth/logout.phtml @@ -0,0 +1,5 @@ +

    Logged out

    + +Log in again? + +login_form ?> diff --git a/application/views/scripts/auth/openid.phtml b/application/views/scripts/auth/openid.phtml new file mode 100644 index 0000000..1272441 --- /dev/null +++ b/application/views/scripts/auth/openid.phtml @@ -0,0 +1,7 @@ +status);?> +
    +OpenID Login + + + +
    diff --git a/application/views/scripts/auth/register.phtml b/application/views/scripts/auth/register.phtml new file mode 100644 index 0000000..67e9416 --- /dev/null +++ b/application/views/scripts/auth/register.phtml @@ -0,0 +1,5 @@ +placeholder('crumbs')->captureStart() ?> + / register +placeholder('crumbs')->captureEnd() ?> + +registration_form ?> diff --git a/application/views/scripts/doc/index.phtml b/application/views/scripts/doc/index.phtml new file mode 100644 index 0000000..cffd24e --- /dev/null +++ b/application/views/scripts/doc/index.phtml @@ -0,0 +1,5 @@ +placeholder('crumbs')->captureStart() ?> + / docs / doc_path ?> +placeholder('crumbs')->captureEnd() ?> + +
    doc_content ?>
    diff --git a/application/views/scripts/error/error.phtml b/application/views/scripts/error/error.phtml new file mode 100644 index 0000000..c742c28 --- /dev/null +++ b/application/views/scripts/error/error.phtml @@ -0,0 +1,15 @@ +

    An error occurred

    +

    message ?>

    + +error->show_exceptions): ?> +

    Exception information:

    +

    + Message: exception->getMessage() ?> +

    + +

    Stack trace:

    +
    exception->getTraceAsString() ?>
    + +

    Request Parameters:

    +
    request->getParams()) ?>
    + diff --git a/application/views/scripts/index/index.phtml b/application/views/scripts/index/index.phtml new file mode 100644 index 0000000..a360aff --- /dev/null +++ b/application/views/scripts/index/index.phtml @@ -0,0 +1,14 @@ +

    + Hello, from the Zend Framework MVC!
    + I am the index controllers's view script. +

    + +

    validated ?>

    + +form ?> + +login_id) : ?> +

    Logged in as escape($this->login_name);?>. +Logout

    + diff --git a/application/views/scripts/pagination_control.phtml b/application/views/scripts/pagination_control.phtml new file mode 100644 index 0000000..6f40064 --- /dev/null +++ b/application/views/scripts/pagination_control.phtml @@ -0,0 +1,44 @@ +queryUrl(array('page' => $this->first)); + $url_previous = $this->queryUrl(array('page' => $this->previous)); + $url_next = $this->queryUrl(array('page' => $this->next)); + $url_last = $this->queryUrl(array('page' => $this->last)); +?> + diff --git a/application/views/scripts/pagination_mini_control.phtml b/application/views/scripts/pagination_mini_control.phtml new file mode 100644 index 0000000..6072569 --- /dev/null +++ b/application/views/scripts/pagination_mini_control.phtml @@ -0,0 +1,29 @@ +queryUrl(array('page' => $this->first)); + $url_previous = $this->queryUrl(array('page' => $this->previous)); + $url_next = $this->queryUrl(array('page' => $this->next)); + $url_last = $this->queryUrl(array('page' => $this->last)); +?> +
      + + + + + +
    • + page current ?> of last ?> +
    • + +
    diff --git a/application/views/scripts/post.phtml b/application/views/scripts/post.phtml new file mode 100644 index 0000000..6001320 --- /dev/null +++ b/application/views/scripts/post.phtml @@ -0,0 +1,39 @@ +auth_profile && + $this->post['profile_id'] == $this->auth_profile['id']); + + $profile_home_url = $this->url( + array('screen_name' => $this->post['screen_name']), + 'post_profile' + ); +?> +
  • +

    + escape($this->post['title']) ?> +

    + post['notes'])): ?> +

    escape($this->post['notes']) ?>

    + +
    + + escape($this->post['screen_name']) ?> + escape($this->post['user_date']) ?> + +
    + + +
    post->toArray()) ?>
    + + +
  • diff --git a/application/views/scripts/post/delete.phtml b/application/views/scripts/post/delete.phtml new file mode 100644 index 0000000..ffdb13e --- /dev/null +++ b/application/views/scripts/post/delete.phtml @@ -0,0 +1,10 @@ +

    Delete this?

    + +
      + partial('post.phtml', array( + 'auth_profile' => $this->auth_profile, + 'post' => $this->post + )); ?> +
    + +delete_form ?> diff --git a/application/views/scripts/post/index.phtml b/application/views/scripts/post/index.phtml new file mode 100644 index 0000000..5372dcb --- /dev/null +++ b/application/views/scripts/post/index.phtml @@ -0,0 +1,2 @@ + +post_form ?> diff --git a/application/views/scripts/post/profile.phtml b/application/views/scripts/post/profile.phtml new file mode 100644 index 0000000..7307403 --- /dev/null +++ b/application/views/scripts/post/profile.phtml @@ -0,0 +1,66 @@ +url( + array('screen_name' => $this->screen_name), + 'post_profile' + ); +?> + +placeholder('crumbs')->captureStart() ?> + / people / escape($this->screen_name) ?> + tags): ?> + / escape(join(' + ', $this->tags)) ?> + +placeholder('crumbs')->captureEnd() ?> + +placeholder('infobar')->captureStart() ?> + auth_profile && $this->screen_name == $this->auth_profile['screen_name']) ? + 'your items' : $this->screen_name . "'s items"; + ?> + tags): ?> + All (posts_count ?>) + + tagged tags as $tag): ?> + escape($tag) ?> + (posts_count ?>) + +placeholder('infobar')->captureEnd() ?> + +posts)): ?> + +
    + auth_profile || $this->screen_name != $this->auth_profile['screen_name']): ?> +

    No items found.

    + + tags): ?> +

    You have no bookmarks, yet.

    +

    + Why not start by saving a new bookmark? +

    + +

    You have no bookmarks tagged tags as $tag): ?>escape($tag) ?>.

    + + +
    + + + + paginationControl( + $this->paginator, 'Sliding', 'pagination_mini_control.phtml' + ); ?> + +
      + posts as $post): ?> + partial('post.phtml', array( + 'profile' => $this->profile, + 'auth_profile' => $this->auth_profile, + 'post' => $post + )); ?> + +
    + + paginationControl( + $this->paginator, 'Sliding', 'pagination_control.phtml' + ); ?> + + diff --git a/application/views/scripts/post/save.phtml b/application/views/scripts/post/save.phtml new file mode 100644 index 0000000..4906fe3 --- /dev/null +++ b/application/views/scripts/post/save.phtml @@ -0,0 +1,12 @@ +url( + array('screen_name' => $this->auth_profile['screen_name']), + 'post_profile' + ); +?> + +placeholder('crumbs')->captureStart() ?> + / escape($this->auth_profile['screen_name']) ?> +placeholder('crumbs')->captureEnd() ?> + +post_form ?> diff --git a/application/views/scripts/post/tag.phtml b/application/views/scripts/post/tag.phtml new file mode 100644 index 0000000..b0abc3a --- /dev/null +++ b/application/views/scripts/post/tag.phtml @@ -0,0 +1,56 @@ +placeholder('crumbs')->captureStart() ?> + tags)): ?> + / recent + + / tag / tags) ?> + +placeholder('crumbs')->captureEnd() ?> + +placeholder('infobar')->captureStart() ?> + tags)): ?> + Recent items (posts_count ?>) + + Recent items tagged tags as $tag): ?> + escape($tag) ?> + (posts_count ?>) + +placeholder('infobar')->captureEnd() ?> + +posts)): ?> + +
    + auth_profile || $this->screen_name != $this->auth_profile['screen_name']): ?> +

    No items found.

    + + tags): ?> +

    You have no bookmarks, yet.

    +

    + Why not start by saving a new bookmark? +

    + +

    You have no bookmarks tagged tags as $tag): ?>escape($tag) ?>.

    + + +
    + + + + paginationControl( + $this->paginator, 'Sliding', 'pagination_mini_control.phtml' + ); ?> + +
      + posts as $post): ?> + partial('post.phtml', array( + 'profile' => $this->profile, + 'auth_profile' => $this->auth_profile, + 'post' => $post + )); ?> + +
    + + paginationControl( + $this->paginator, 'Sliding', 'pagination_control.phtml' + ); ?> + + diff --git a/application/views/scripts/post/view.phtml b/application/views/scripts/post/view.phtml new file mode 100644 index 0000000..c85d568 --- /dev/null +++ b/application/views/scripts/post/view.phtml @@ -0,0 +1,6 @@ +
      + partial('post.phtml', array( + 'auth_profile' => $this->auth_profile, + 'post' => $this->post + )); ?> +
    diff --git a/application/views/scripts/profile/index.phtml b/application/views/scripts/profile/index.phtml new file mode 100644 index 0000000..4a670ab --- /dev/null +++ b/application/views/scripts/profile/index.phtml @@ -0,0 +1 @@ +

    People home

    diff --git a/data/.exists b/data/.exists new file mode 100644 index 0000000..e69de29 diff --git a/docs/.exists b/docs/.exists new file mode 100644 index 0000000..e69de29 diff --git a/library/.exists b/library/.exists new file mode 100644 index 0000000..e69de29 diff --git a/logs/.exists b/logs/.exists new file mode 100644 index 0000000..e69de29 diff --git a/public/.htaccess b/public/.htaccess new file mode 100644 index 0000000..e31220e --- /dev/null +++ b/public/.htaccess @@ -0,0 +1,47 @@ +# Let's make sure that we have setup the timezone for this application, +# In some php.ini files, this value is not set. This will ensure it exists +# for every reqeust of this application. +php_value date.timezone "UTC" + +# Let's also make sure that we can use the php short tag, " php -r "echo E_ALL|E_STRICT;" +# 8191 +php_value error_reporting "8191" + +# The following display_*error directives instruct PHP how to display +# errors that might come up. In a production environment, it might +# be good to set these values inside the actual VHOST definiation. +# NOTE: these display error ini's should most likely be OFF +# in your production environment +php_value display_startup_errors "1" +php_value display_errors "1" + +# NOTE: by setting the above php ini values, we are ensuring that +# regardless of the servers php.ini values, we can be assured that +# our application will have these set values set on every request. + + + + +# The rules below basically say that if the file exists in the tree, just +# serve it; otherwise, go to index.php. This is more future-proof for your +# site, because if you start adding more and more content types, you don't +# need to alter the .htaccess to accomodate them. +# This is an important concept for the Front Controller Pattern which the +# ZF MVC makes use of. +RewriteEngine On +RewriteCond %{REQUEST_FILENAME} -s [OR] +RewriteCond %{REQUEST_FILENAME} -l [OR] +RewriteCond %{REQUEST_FILENAME} -d +RewriteRule ^.*$ - [NC,L] +RewriteRule ^.*$ /index.php [NC,L] + diff --git a/public/css/main.css b/public/css/main.css new file mode 100644 index 0000000..e9e4a4e --- /dev/null +++ b/public/css/main.css @@ -0,0 +1,317 @@ +/** + * + */ +html, body, form { + margin: 0; padding: 0; +} +body { + font-family: arial, sans-serif; + background-color: #fff; +} + +a:link { + text-decoration: none; + color: #00f; +} +a:visited { + text-decoration: none; + color: #639; +} +a:hover { + text-decoration: underline; +} +a:active { + text-decoration: underline; +} + +#header { + font-size: 75%; + margin: 0.5em 1.5em 0.5em 1.5em; + padding: 0 0 0 0; + height: 80px; + position: relative; +} +#header .logo { + float: left; +} +#header .logo span:before { + font-size: 75px; + content: '\2756'; +} +#header .logo span { + padding: 0 15px 0 10px; +} +#header .crumbs { + font-size: 200%; + padding: 0.25em 0 0 0; +} +#header .crumbs .title { + display: inline; + font-weight: bold; +} +#header .main { + margin: 0 0 0 0; + padding: 0.75em 0 0 0; + position: absolute; + left: 85px; + bottom: 1.25em; +} +#header .main .nav { + margin: 0 0 0 0; + padding: 0 0 0 0; + list-style: none; +} +#header .main .nav li { + display: inline; + border-left: 1px solid #000; + margin-left: 0.25em; + padding-left: 0.5em; +} +#header .main .nav li.first { + font-weight: bold; + border: none; + padding: 0; + margin: 0; +} +#header .main .title { + margin: 0 0 0.5em 0; + padding: 0 0 0 0; +} +#header .sub { + position: absolute; + right: 0; + bottom: 1.25em; + margin: 1.25em 0 0 0; + padding: 0 0 0 0; +} +#header .sub .nav { + margin: 0 0 0 0; + padding: 0 0 0 0; +} +#header .sub .nav li { + display: inline; + border-left: 1px solid #000; + margin-left: 0.25em; + padding-left: 0.5em; +} +#header .sub .nav li.first { + border: none; + padding: 0; + margin: 0; +} +#infobar { + font-size: 75%; + margin: 0.5em 1.5em 1.5em 1.5em; + padding: 0.5em 0.8em; + background-color: #eee; + border: 1px solid #ccc; + border-left: none; + border-right: none; +} +#content { + font-size: 75%; + margin: 0em 1.5em 0em 1.5em; +} +#footer { + position: relative; + font-size: 75%; + margin: 0em 1.5em 1.5em 1.5em; + padding: 0.5em 0 0 0; + background-color: #eee; +} +#footer .nav { + background-color: #fff; + margin: 0 0 0 0; + padding: 0.5em 0 0 0; + border-top: 1px solid #ccc; + list-style: none; +} +#footer .nav:before { + content: "\2756"; +} +#footer .nav li { + display: inline; + border-left: 1px solid #000; + margin-left: 0.25em; + padding-left: 0.5em; +} +#footer .nav li.first { + font-weight: bold; + border: none; + padding: 0; + margin: 0; +} +#footer .license { + position: absolute; + top: 1em; + right: 0; +} +#footer .license img { + border: 0; +} + +.posts { + clear: both; + margin: 0em 0em 1.5em 0em; + padding: 0 0 0 0; + list-style: none; +} +.posts .post { + clear: both; + padding: 0.25em 0 0.75em 0; +} +.posts .post .title { + margin: 0; padding: 0; + font-weight: normal; + font-size: 132%; +} +.posts .post .notes { + margin: 0.125em 0.0em 0.125em 0.0em; + padding: 0 0 0 0; +} +.posts .post .meta { + color: #999; +} +.posts .post .meta a { + color: #99F; +} +.posts .post .tags:before { + content: ' to '; +} +.posts .post .tags { + display: inline; + margin: 0; padding: 0; +} +.posts .post .tags .tag { + display: inline; + list-style: none; + padding: 0 0 0 0; + margin: 0 0.25ex 0 0.25ex; + margin: 0 0 0 0; +} +.posts .post .author:before { + content: ' by '; +} +.posts .post .author { +} +.posts .post .date:before { + content: ' ... on '; +} +.posts .post .date { +} +.posts .post .commands:before { + content: ' ... '; +} +.posts .post .commands { + margin: 0 0 0 0; + padding: 0 0 0 0; + list-style: none; + display: inline; +} +.posts .post .commands li { + display: inline; + /* + border-left: 1px solid #000; + */ + margin-left: 0; + padding-left: 0; +} +.posts .post .commands li:before { + content: ' / '; +} +.posts .post .commands li.first { + border: none; + padding: 0; + margin: 0; +} +.posts .post .commands li.first:before { + content: ''; +} + +.pagination { + clear: both; + margin: 0.5em 0em 0em 0em; + padding: 0.5em 0 0.5em 0; + color: #666; + text-align: center; + background-color: #eee; + border-top: 1px solid #ccc; +} +.pagination .pages { + /* background-color: #fff; */ + margin: 0 0 0em 0; + padding: 1.0em 0 0.75em 0; + list-style: none; +} +.pagination .pages li { + display: inline; +} +.pagination .pages li.page { + display: inline; + margin: 0 0.125em 0 0.125em; +} +.pagination .pages li.page a, .pagination .pages li.page span.current { + border: 1px solid #ccc; + padding: 0 0.5em 0 0.5em; +} +.pagination .pages li.page span.current { + background: #ccc; + font-weight: bold; + color: #333; +} +.pagination .pages li:after.page { + content: ' | '; +} +.pagination .pages li.previous { + padding-right: 0.5em; +} +.pagination .pages li.previous:before { + content: '\00AB'; +} +.pagination .pages li.next { + padding-left: 0.5em; +} +.pagination .pages li.next:after { + content: '\00BB'; +} +.pagination .page_position { + /* background: #fff; */ +} +.pagination_mini { + margin: 0 0em 1.5em 0em; + padding: 0 0 0 0; + list-style: none; + color: #999; +} +.pagination_mini li { + display: inline; +} +.pagination_mini .next:before { +} +.pagination_mini .next:after { + content: '\00BB'; +} +.pagination_mini .next { +} +.pagination_mini .next .disabled { +} +.pagination_mini .previous:before { + content: '\00AB'; +} +.pagination_mini .previous:after { + content: ' | '; +} +.pagination_mini .previous { +} +.pagination_mini .previous .disabled { +} +.pagination_mini .page { + padding-left: 1.5em; +} + +.ctrl_doc .doc_content { + font-size: 120%; + padding: 0 85px 0 85px; + line-height: 1.75em; +} + diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..1b079ce --- /dev/null +++ b/public/index.php @@ -0,0 +1,18 @@ +
    ' + . 'An exception occured while bootstrapping the application.'; + if (defined('APPLICATION_ENVIRONMENT') && APPLICATION_ENVIRONMENT != 'production') { + echo '

    ' . $exception->getMessage() . '
    ' + . '
    Stack Trace:' + . '
    ' . $exception->getTraceAsString() . '
    '; + } + echo '
    '; + exit(1); +} + +Zend_Controller_Front::getInstance()->dispatch(); diff --git a/public/js/main.js b/public/js/main.js new file mode 100644 index 0000000..e69de29 diff --git a/scripts/data.sqlite.sql b/scripts/data.sqlite.sql new file mode 100644 index 0000000..569d70a --- /dev/null +++ b/scripts/data.sqlite.sql @@ -0,0 +1,7 @@ +INSERT INTO logins (id, login_name, email, password) + VALUES (1, 'admin', 'l.m.orchard@pobox.com', 'admin'); +INSERT INTO profiles (id, screen_name, full_name) + VALUES (1, 'admin', 'Admin User'); +INSERT INTO logins_profiles (id, login_id, profile_id) + VALUES (1, 1, 1); + diff --git a/scripts/load.sqlite.php b/scripts/load.sqlite.php new file mode 100644 index 0000000..e910754 --- /dev/null +++ b/scripts/load.sqlite.php @@ -0,0 +1,93 @@ +init(); + +// if any parameter is passed after the script name (like 1 or --withdata) +// load the data file after the schema has loaded. +$withData = isset($_SERVER['argv'][1]); + +// pull the adapter out of the application registry +$dbAdapter = Zend_Registry::get('db'); + +// let the user know whats going on (we are actually creating a +// database here) +echo 'Writing Database Guestbook in (control-c to cancel): ' . PHP_EOL; + +// this block executes the actual statements that were loaded from +// the schema file. +try { + $schemaSql = file_get_contents('./schema.sqlite.sql'); + // use the connection directly to load sql in batches + $dbAdapter->getConnection()->exec($schemaSql); + echo PHP_EOL; + echo 'Database Created'; + echo PHP_EOL; + + if ($withData) { + require_once APPLICATION_PATH . '/models/Logins.php'; + $logins_model = new Memex_Model_Logins(); + + require_once APPLICATION_PATH . '/models/Profiles.php'; + $profiles_model = new Memex_Model_Profiles(); + + require_once APPLICATION_PATH . '/models/Posts.php'; + $posts_model = new Memex_Model_Posts(); + + $login_id = $logins_model->registerWithProfile(array( + 'login_name' => 'deusx', + 'email' => 'l.m.orchard@pobox.com', + 'password' => 'Fey23Bork!', + 'screen_name' => 'deusx', + 'full_name' => 'l.m.orchard', + 'bio' => 'deusx from delicious.com' + )); + $profile = $logins_model->fetchDefaultProfileForLogin($login_id); + $profile_id = $profile['id']; + + $data_xml = file_get_contents('./deusx.xml'); + $posts = simplexml_load_string($data_xml); + $cnt = 0; + foreach ($posts as $post) { + $post_data = array( + 'profile_id' => $profile_id, + 'url' => $post['href'], + 'title' => $post['description'], + 'notes' => $post['extended'], + 'tags' => $post['tag'], + 'user_date' => $post['time'] + ); + $posts_model->save($post_data); + + $cnt++; + if ( ($cnt % 100) == 0) + echo "$cnt..."; + else + echo '.'; + + // if ($cnt > 200) break; + } + echo "\n"; + /* + $dataSql = file_get_contents('./data.sqlite.sql'); + // use the connection directly to load sql in batches + $dbAdapter->getConnection()->exec($dataSql); + echo 'Data Loaded.'; + echo PHP_EOL; + */ + } + +} catch (Exception $e) { + echo 'AN ERROR HAS OCCURED:' . PHP_EOL; + echo $e->getMessage() . PHP_EOL; + return false; +} + +// generally speaking, this script will be run from the command line +return true; diff --git a/scripts/schema.sqlite.sql b/scripts/schema.sqlite.sql new file mode 100644 index 0000000..e803b68 --- /dev/null +++ b/scripts/schema.sqlite.sql @@ -0,0 +1,73 @@ +DROP TABLE IF EXISTS logins; +CREATE TABLE logins ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + login_name VARCHAR(64) NOT NULL UNIQUE, + email VARCHAR(255) NOT NULL, + password VARCHAR(32) NOT NULL, + created DATETIME, + last_login DATETIME +); + +DROP TABLE IF EXISTS profiles; +CREATE TABLE profiles ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + uuid VARCHAR(40) NOT NULL, + screen_name VARCHAR(64) NOT NULL, + full_name VARCHAR(128) NOT NULL, + bio TEXT, + created DATETIME, + last_login DATETIME +); + +DROP TABLE IF EXISTS logins_profiles; +CREATE TABLE logins_profiles ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + login_id INTEGER NOT NULL, + profile_id INTEGER NOT NULL +); + +DROP TABLE IF EXISTS posts; +CREATE TABLE posts ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + uuid VARCHAR(40) NOT NULL, + profile_id INTEGER NOT NULL, + url_id INTEGER NOT NULL, + title VARCHAR(255) default NULL, + notes TEXT, + tags TEXT, + visibility INTEGER, + user_date DATETIME, + created DATESTAMP, + modified DATESTAMP +); + +DROP TABLE IF EXISTS tags; +CREATE TABLE tags ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + post_id INTEGER NOT NULL, + profile_id INTEGER NOT NULL, + url_id INTEGER NOT NULL, + tag VARCHAR(128), + position INTEGER, + created DATESTAMP, + modified DATESTAMP +); + +DROP TABLE IF EXISTS urls; +CREATE TABLE urls ( + id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, + url TEXT, + hostname VARCHAR(255), + hash VARCHAR(32) default NULL, + content TEXT, + first_profile_id INT default NULL, + latest_profile_id INT default NULL, + created DATESTAMP, + modified DATESTAMP +); + +DROP TABLE IF EXISTS updates; +CREATE TABLE updates ( + hash char(32) NOT NULL default '', + updated DATETIME default NULL +); diff --git a/tests/Model/LoginsTest.php b/tests/Model/LoginsTest.php new file mode 100644 index 0000000..5b44424 --- /dev/null +++ b/tests/Model/LoginsTest.php @@ -0,0 +1,187 @@ +model = new Memex_Model_Logins(); + $this->model->deleteAll(); + + $this->profiles_model = new Memex_Model_Profiles(); + $this->profiles_model->deleteAll(); + } + + /** + * This method is called after a test is executed. + * + * @return void + */ + public function tearDown() + { + } + + /** + * Ensure that required fields for a login are enforced. + */ + public function testCreateRequiredFields() + { + try { + $test_id = $this->model->create(array()); + $this->fail('Logins with missing fields should not be allowed'); + } catch (Exception $e1) { + $this->assertContains('required', $e1->getMessage()); + } + try { + $test_id = $this->model->create(array( + 'login_name' => 'tester1' + )); + $this->fail('Logins with missing fields should not be allowed'); + } catch (Exception $e2) { + $this->assertContains('required', $e2->getMessage()); + } + try { + $test_id = $this->model->create(array( + 'login_name' => 'tester1', + 'password' => 'tester_password' + )); + $this->fail('Logins with missing fields should not be allowed'); + } catch (Exception $e3) { + $this->assertContains('required', $e3->getMessage()); + } + try { + $test_id = $this->model->create(array( + 'login_name' => 'tester1', + 'password' => 'tester_password', + 'email' => 'tester1@example.com' + )); + } catch (Exception $e) { + $this->fail('Users with duplicate login names should raise exceptions'); + } + } + + /** + * Ensure a login can be created and fetched by login name. + */ + public function testCreateAndFetchLogin() + { + $login_id = $this->model->create(array( + 'login_name' => 'tester1', + 'email' => 'tester1@example.com', + 'password' => 'tester_password', + )); + + $login = $this->model->fetchByLoginName('tester1'); + + $this->assertEquals($login['login_name'], 'tester1'); + $this->assertEquals($login['email'], 'tester1@example.com'); + $this->assertEquals($login['password'], md5('tester_password')); + } + + /** + * Ensure that logins with the same login names cannot be created. + */ + public function testShouldNotAllowDuplicateLoginName() + { + $login_id = $this->model->create(array( + 'login_name' => 'tester1', + 'email' => 'tester1@example.com', + 'password' => 'tester_password', + )); + + try { + $login_id2 = $this->model->create(array( + 'login_name' => 'tester1', + 'email' => 'tester1@example.com', + 'password' => 'tester_password', + )); + $this->fail('Users with duplicate login names should raise exceptions'); + } catch (Exception $e) { + $this->assertContains('duplicate', $e->getMessage()); + } + } + + /** + * Since login and profile creation during registration are two steps, + * ensure that a failed profile creation doesn't result in a deadend login. + */ + public function testRegistrationShouldCreateProfile() + { + $login_id = $this->model->registerWithProfile(array( + 'login_name' => 'tester1', + 'email' => 'tester1@example.com', + 'password' => 'tester_password', + 'screen_name' => 'tester1_screenname', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + $this->assertTrue(null !== $login_id); + + $profile = $this->profiles_model->fetchByScreenName('tester1_screenname'); + + $this->assertTrue(null !== $profile); + $this->assertEquals($profile['screen_name'], 'tester1_screenname'); + $this->assertEquals($profile['full_name'], 'Tess T. Erone'); + $this->assertEquals($profile['bio'], 'I live!'); + + $default_profile = + $this->model->fetchDefaultProfileForLogin($login_id); + $this->assertEquals($profile['id'], $default_profile['id']); + } + + /** + * Since login and profile creation during registration are two steps, + * ensure that a failed profile creation doesn't result in a deadend login. + */ + public function testFailedRegistrationShouldNotCreateLogin() + { + try { + $login_id = $this->model->registerWithProfile(array( + 'login_name' => 'tester1', + 'email' => 'tester1@example.com', + 'password' => 'tester_password', + )); + $this->fail('Missing profile details should cause registration to fail'); + } catch (Exception $e) { + $this->assertContains('required', $e->getMessage()); + $login = $this->model->fetchByLoginName('tester1'); + $this->assertNull($login); + } + } + +} + +// Call Memex_Model_LoginsTest::main() if this source file is executed directly. +if (PHPUnit_MAIN_METHOD == "Memex_Model_LoginsTest::main") { + Memex_Model_LoginsTest::main(); +} diff --git a/tests/Model/PostsTest.php b/tests/Model/PostsTest.php new file mode 100644 index 0000000..5ddf557 --- /dev/null +++ b/tests/Model/PostsTest.php @@ -0,0 +1,589 @@ +model = new Memex_Model_Posts(); + $this->model->deleteAll(); + + $this->profiles_model = new Memex_Model_Profiles(); + $this->profiles_model->deleteAll(); + + $this->urls_model = new Memex_Model_Urls(); + $this->urls_model->deleteAll(); + + $this->tags_model = new Memex_Model_Tags(); + $this->tags_model->deleteAll(); + + $this->profile_id = $this->profiles_model->create(array( + 'screen_name' => 'tester1_screenname', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + + $this->profile_id_2 = $this->profiles_model->create(array( + 'screen_name' => 'tester2_screenname', + 'full_name' => 'Joe Tester', + 'bio' => 'I exist!' + )); + + } + + /** + * This method is called after a test is executed. + * + * @return void + */ + public function tearDown() + { + } + + /** + * Ensure that required fields for a login are enforced. + */ + public function testSaveRequiredFields() + { + try { + $test_post = $this->model->save(array()); + $this->fail('missing required fields should not be allowed'); + } catch (Exception $e1) { + $this->assertContains('required', $e1->getMessage()); + } + try { + $test_post = $this->model->save(array( + 'url' => 'http://example.com' + )); + $this->fail('missing required fields should not be allowed'); + } catch (Exception $e2) { + $this->assertContains('required', $e2->getMessage()); + } + try { + $test_post = $this->model->save(array( + 'url' => 'http://example.com', + 'title' => 'Example bookmark' + )); + } catch (Exception $e3) { + $this->assertContains('required', $e3->getMessage()); + } + try { + $test_post = $this->model->save(array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com', + 'title' => 'Example bookmark' + )); + } catch (Exception $e4) { + $this->fail('all required fields supplied, but failed anyway ' . + $e4->getMessage()); + } + } + + /** + * Ensure that valid dates are required and used in posts. + */ + public function testPostUserDates() + { + try { + $test_post = $this->model->save(array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com', + 'title' => 'Example bookmark', + 'user_date' => 'THIS IS A BOGUS DATE' + )); + $this->fail('only a valid date should be accepted'); + } catch (Exception $e) { + $this->assertContains('required', $e->getMessage()); + } + try { + $test_post = $this->model->save(array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com', + 'title' => 'Example bookmark', + 'user_date' => '2007-10-24T10:10:24-0500' + )); + } catch (Exception $e) { + $this->fail('a valid ISO8601 date should be accepted'); + } + $this->assertEquals($test_post['user_date'], + '2007-10-24T10:10:24-0500'); + } + + /** + * Save a post and check what gets saved in the models. + */ + public function testPostSave() + { + $post_data = array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com', + 'title' => 'Test bookmark #1', + 'notes' => 'These are test notes', + 'tags' => 'foo bar baz quux xyzzy' + ); + + $normalized_url = 'http://example.com/'; + + // There shouldn't yet be a URL entry for this bookmark. + $url = $this->urls_model->fetchByUrl($post_data['url']); + $this->assertNull($url); + + // Saving the bookmark should result in data returned. + $saved_post = $this->model->save($post_data); + $this->assertTrue(null != $saved_post); + + // The URL in the saved bookmark should reflect normalization. + $this->assertEquals($normalized_url, $saved_post['url']); + + // Assert equality between input and saved post data, except URL. + foreach (array('profile_id', 'title', 'notes', 'tags') as $name) + $this->assertEquals($post_data[$name], $saved_post[$name]); + + // Ensure that a new URL record has been created for this bookmark. + $url = $this->urls_model->fetchByUrl($post_data['url']); + $this->assertTrue(null != $url); + $this->assertEquals($normalized_url, $url['url']); + + // Fetch the bookmark. + $fetched_post = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertTrue(null != $fetched_post); + + // Assert that the input and fetched post contents match. + $this->assertEquals($normalized_url, $fetched_post['url']); + foreach (array('profile_id', 'title', 'notes', 'tags') as $name) + $this->assertEquals($post_data[$name], $fetched_post[$name]); + + $this->assertEquals($fetched_post['screen_name'], 'tester1_screenname'); + + // Assert that the saved and fetched post contents match. + foreach (array('url','title','notes','tags','profile_id') as $name) { + $this->assertEquals( + $name.'='.$fetched_post[$name], + $name.'='.$saved_post[$name] + ); + } + } + + /** + * Ensure that post deletion by ID works. + */ + public function testDeleteById() + { + // Do this a bunch of times to make sure IDs aren't colliding. + for ($i=0; $i<10; $i++) { + + $post_data = array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com/foobar.html', + 'title' => 'Example bookmark', + 'user_date' => '2007-10-24T10:10:24-0500' + ); + $test_post = $this->model->save($post_data); + + $fetched_post = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertEquals($post_data['url'], $fetched_post['url']); + + $this->model->deleteById($test_post['id']); + + $fetched_post2 = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertNull($fetched_post2); + + } + } + + /** + * Ensure that post deletion by UUID works. + */ + public function testDeleteByUUID() + { + // Do this a bunch of times to make sure IDs aren't colliding. + for ($i=0; $i<10; $i++) { + + $post_data = array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com/foobar.html', + 'title' => 'Example bookmark', + 'user_date' => '2007-10-24T10:10:24-0500' + ); + $test_post = $this->model->save($post_data); + + $fetched_post = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertEquals($post_data['url'], $fetched_post['url']); + $this->assertEquals($test_post['uuid'], $fetched_post['uuid']); + + $rv = $this->model->deleteByUUID($fetched_post['uuid']); + + $fetched_post2 = $this->model->fetchOneByUUID( + $fetched_post['uuid'] + ); + $this->assertNull($fetched_post2); + + $fetched_post3 = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertNull($fetched_post3); + + } + } + + /** + * Ensure that post deletion by url and profile works. + */ + public function testDeleteByUrlAndProfile() + { + // Do this a bunch of times to make sure IDs aren't colliding. + for ($i=0; $i<10; $i++) { + + $post_data = array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com/foobar.html', + 'title' => 'Example bookmark', + 'user_date' => '2007-10-24T10:10:24-0500' + ); + $test_post = $this->model->save($post_data); + + $fetched_post = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + $this->assertEquals($post_data['url'], $fetched_post['url']); + + $rv = $this->model->deleteByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + + $fetched_post2 = $this->model->fetchOneByUrlAndProfile( + $post_data['url'], $this->profile_id + ); + + $this->assertNull($fetched_post2); + + } + } + + /** + * Ensure that changing the URL of a post doesn't result in duplicate + * posts. + */ + public function testChangeUrl() + { + $post_data = array( + 'profile_id' => $this->profile_id, + 'url' => 'http://example.com/foobar.html', + 'title' => 'Example bookmark', + 'notes' => 'Notes for the example bookmark', + 'tags' => 'alpha beta gamma woo', + 'user_date' => '2007-10-24T10:10:24-0500' + ); + + $url_1 = $post_data['url']; + $url_2 = 'http://example.com/barfoo/yayhooray.html'; + + $saved_post_1 = $this->model->save($post_data); + $uuid = $saved_post_1['uuid']; + + $changed_post = $saved_post_1; + $changed_post['url'] = $url_2; + + $saved_post_2 = $this->model->save($changed_post); + $this->assertEquals($uuid, $saved_post_2['uuid']); + + $should_be_null_post = + $this->model->fetchOneByUrlAndProfile($url_1, $this->profile_id); + $this->assertNull($should_be_null_post); + } + + /** + * Ensure that an accurate count can be gotten. + */ + public function testCountByProfileAndTags() + { + $test_count = rand(4, 12); + + for ($i=0; $i<$test_count; $i++) { + $this->model->save(array( + 'profile_id' => $this->profile_id, + 'url' => "http://example.com/page$i", + 'title' => "Example bookmark #$i", + 'notes' => "Notes for example bookmark #$i", + 'tags' => "tag-a-$i tag-b-$i tag-c-$i" + )); + } + + $result_count = $this->model->countByProfile($this->profile_id); + $this->assertEquals($test_count, $result_count); + } + + /** + * Exercise fetch and counts indexed by tags. + */ + public function testFetchAndCountByProfileAndTags() + { + $posts_keys = array('url', 'title', 'notes', 'tags'); + $posts_data = array( + array('http://example.com/1','Example 1','These are notes for example 1','foo bar baz quux'), + array('http://example.com/2','Example 2','These are notes for example 2',' bar baz quux'), + array('http://example.com/3','Example 3','These are notes for example 3','foo baz quux'), + array('http://example.com/4','Example 4','These are notes for example 4',' bar quux'), + array('http://example.com/5','Example 5','These are notes for example 5','foo bar baz '), + array('http://example.com/6','Example 6','These are notes for example 6',' baz quux'), + array('http://example.com/7','Example 7','These are notes for example 7','foo bar baz quux'), + array('http://example.com/8','Example 8','These are notes for example 8',' bar quux'), + array('http://example.com/9','Example 9','These are notes for example 9','foo baz quux'), + array('http://example.com/a','Example a','These are notes for example a',' quux'), + array('http://example.com/b','Example b','These are notes for example b','foo baz ') + ); + + $tag_intersections = array( + '', + 'foo', + ' bar', + ' baz', + ' quux', + 'foo bar', + 'foo baz', + 'foo quux', + ' bar baz quux', + 'foo bar baz quux', + 'quux baz bar foo' + ); + + $tags_counts = array(); + $tags_posts = array(); + $url_posts = array(); + + // Process all the test posts. + foreach ($posts_data as $post_data) { + $post_data = array_combine($posts_keys, $post_data); + + // Index this post by URL. + $url = $post_data['url']; + $url_posts[$url] = $post_data; + + // Compare tags against intersections. + $tags = $this->tags_model->parseTags($post_data['tags']); + foreach ($tag_intersections as $i) { + $i_tags = $this->tags_model->parseTags($i); + if (count(array_intersect($tags, $i_tags)) == count($i_tags)) { + + // Count this post by tag intersection. + if (!isset($tags_counts[$i])) { + $tags_counts[$i] = 1; + } else { + $tags_counts[$i]++; + } + + // Index this post by tag intersection. + if (!isset($tags_posts[$i])) { + $tags_posts[$i] = array( $url => $post_data ); + } else { + $tags_posts[$i][$url] = $post_data; + } + + } + } + + // Save this test post. + $this->model->save(array_merge( + $post_data, array('profile_id' => $this->profile_id) + )); + } + + // Run through all the defined test intersections and test model data. + foreach ($tags_counts as $tags_str=>$test_count) { + $tags = $this->tags_model->parseTags($tags_str); + + // Ensure the count for this intersection is correct. + $result_count = + $this->model->countByProfileAndTags($this->profile_id, $tags); + $this->assertEquals($test_count, $result_count); + + // Ensure the count for this intersection is correct, by fetching + // actual data. + $result_posts = $this->model->fetchByProfileAndTags( + $this->profile_id, $tags, null, null + ); + $this->assertEquals($test_count, count($result_posts)); + + // Ensure the content for each of the fetched posts is correct. + foreach ($result_posts as $result_post) { + + // Double check that the profile screen name is present. + $this->assertEquals( + $result_post['screen_name'], + 'tester1_screenname' + ); + + // Ensure the post content for each field of the fetched post. + $url = $result_post['url']; + foreach (array('url','title','notes','tags') as $name) { + $this->assertEquals( + $name.'='.$result_post[$name], + $name.'='.$tags_posts[$tags_str][$url][$name] + ); + } + + } + } + + } + + /** + * Exercise fetch and counts indexed by tags. + * + * HACK: This is basically a copy of the previous test, just with varying + * profile IDs. Maybe refactor some day? + */ + public function testFetchAndCountByTags() + { + $posts_keys = array('profile_id', 'url', 'title', 'notes', 'tags'); + $posts_data = array( + array($this->profile_id, 'http://example.com/1','Example 1','These are notes for example 1','foo bar baz quux'), + array($this->profile_id_2, 'http://example.com/2','Example 2','These are notes for example 2',' bar baz quux'), + array($this->profile_id, 'http://example.com/3','Example 3','These are notes for example 3','foo baz quux'), + array($this->profile_id_2, 'http://example.com/4','Example 4','These are notes for example 4',' bar quux'), + array($this->profile_id, 'http://example.com/5','Example 5','These are notes for example 5','foo bar baz '), + array($this->profile_id_2, 'http://example.com/6','Example 6','These are notes for example 6',' baz quux'), + array($this->profile_id, 'http://example.com/7','Example 7','These are notes for example 7','foo bar baz quux'), + array($this->profile_id_2, 'http://example.com/8','Example 8','These are notes for example 8',' bar quux'), + array($this->profile_id, 'http://example.com/9','Example 9','These are notes for example 9','foo baz quux'), + array($this->profile_id_2, 'http://example.com/a','Example a','These are notes for example a',' quux'), + array($this->profile_id, 'http://example.com/b','Example b','These are notes for example b','foo baz ') + ); + + $screen_names = array( + $this->profile_id => 'tester1_screenname', + $this->profile_id_2 => 'tester2_screenname' + ); + + $tag_intersections = array( + 'foo', + ' bar', + ' baz', + ' quux', + 'foo bar', + 'foo baz', + 'foo quux', + ' bar baz quux', + 'foo bar baz quux', + 'quux baz bar foo' + ); + + $tags_counts = array(); + $tags_posts = array(); + $url_posts = array(); + + // Process all the test posts. + foreach ($posts_data as $post_data) { + $post_data = array_combine($posts_keys, $post_data); + + // Index this post by URL. + $url = $post_data['url']; + $url_posts[$url] = $post_data; + + // Compare tags against intersections. + $tags = $this->tags_model->parseTags($post_data['tags']); + foreach ($tag_intersections as $i) { + $i_tags = $this->tags_model->parseTags($i); + if (count(array_intersect($tags, $i_tags)) == count($i_tags)) { + + // Count this post by tag intersection. + if (!isset($tags_counts[$i])) { + $tags_counts[$i] = 1; + } else { + $tags_counts[$i]++; + } + + // Index this post by tag intersection. + if (!isset($tags_posts[$i])) { + $tags_posts[$i] = array( $url => $post_data ); + } else { + $tags_posts[$i][$url] = $post_data; + } + + } + } + + // Save this test post. + $this->model->save($post_data); + } + + // Run through all the defined test intersections and test model data. + foreach ($tags_counts as $tags_str=>$test_count) { + $tags = $this->tags_model->parseTags($tags_str); + + // Ensure the count for this intersection is correct. + $result_count = + $this->model->countByTags($tags); + $this->assertEquals($test_count, $result_count); + + // Ensure the count for this intersection is correct, by fetching + // actual data. + $result_posts = $this->model->fetchByTags($tags, null, null); + $this->assertEquals($test_count, count($result_posts)); + + // Ensure the content for each of the fetched posts is correct. + foreach ($result_posts as $result_post) { + + // Double check that the profile screen name is present. + $this->assertEquals( + $result_post['screen_name'], + $screen_names[$result_post['profile_id']] + ); + + // Ensure the post content for each field of the fetched post. + $url = $result_post['url']; + foreach (array('profile_id','url','title','notes','tags') as $name) { + $this->assertEquals( + $name.'='.$result_post[$name], + $name.'='.$tags_posts[$tags_str][$url][$name] + ); + } + + } + } + + } + +} + +// Call Memex_Model_PostsTest::main() if this source file is executed directly. +if (PHPUnit_MAIN_METHOD == "Memex_Model_PostsTest::main") { + Memex_Model_PostsTest::main(); +} diff --git a/tests/Model/ProfilesTest.php b/tests/Model/ProfilesTest.php new file mode 100644 index 0000000..75cf2ed --- /dev/null +++ b/tests/Model/ProfilesTest.php @@ -0,0 +1,127 @@ +model = new Memex_Model_Profiles(); + $this->model->deleteAll(); + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + * + * @return void + */ + public function tearDown() + { + } + + /** + * Ensure that required fields for a login are enforced. + */ + public function testCreateRequiredFields() + { + try { + $test_id = $this->model->create(array()); + $this->fail('missing fields should not be allowed'); + } catch (Exception $e) { + $this->assertContains('required', $e->getMessage()); + } + try { + $test_id = $this->model->create(array( + 'screen_name' => 'tester1' + )); + $this->fail('missing fields should not be allowed'); + } catch (Exception $e) { + $this->assertContains('required', $e->getMessage()); + } + try { + $test_id = $this->model->create(array( + 'screen_name' => 'tester1', + 'full_name' => 'Tess T. Erone' + )); + } catch (Exception $e) { + $this->fail('Logins with missing fields should not be allowed'); + } + } + + /** + * Ensure a login can be created and fetched by login name. + */ + public function testCreateAndFetch() + { + $profile_id = $this->model->create(array( + 'screen_name' => 'tester1_screenname', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + + $profile = $this->model->fetchByScreenName('tester1_screenname'); + + $this->assertEquals($profile['screen_name'], 'tester1_screenname'); + $this->assertEquals($profile['full_name'], 'Tess T. Erone'); + $this->assertEquals($profile['bio'], 'I live!'); + } + + /** + * Ensure that logins with the same login names cannot be created. + */ + public function testShouldNotAllowDuplicateName() + { + $profile_id = $this->model->create(array( + 'screen_name' => 'tester1', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + + try { + $profile_id2 = $this->model->create(array( + 'screen_name' => 'tester1', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + $this->fail('duplicate screen names should raise exceptions'); + } catch (Exception $e) { + $this->assertContains('duplicate', $e->getMessage()); + } + } + +} + +// Call Memex_Model_ProfilesTest::main() if this source file is executed directly. +if (PHPUnit_MAIN_METHOD == "Memex_Model_ProfilesTest::main") { + Memex_Model_ProfilesTest::main(); +} diff --git a/tests/Model/TagsTest.php b/tests/Model/TagsTest.php new file mode 100644 index 0000000..3768e7b --- /dev/null +++ b/tests/Model/TagsTest.php @@ -0,0 +1,123 @@ +model = new Memex_Model_Tags(); + $this->model->deleteAll(); + + $this->posts_model = new Memex_Model_Posts(); + $this->posts_model->deleteAll(); + + $this->profiles_model = new Memex_Model_Profiles(); + $this->profiles_model->deleteAll(); + + $this->urls_model = new Memex_Model_Urls(); + $this->urls_model->deleteAll(); + + $this->profile_id = $this->profiles_model->create(array( + 'screen_name' => 'tester1_screenname', + 'full_name' => 'Tess T. Erone', + 'bio' => 'I live!' + )); + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + * + * @return void + */ + public function tearDown() + { + } + + public function testFetchByTagAndProfile() + { + $posts_keys = array('url', 'title', 'notes', 'tags'); + $posts_data = array( + array('http://example.com/1','Example 1','These are notes for example 1','foo bar baz quux'), + array('http://example.com/2','Example 2','These are notes for example 2',' bar baz quux'), + array('http://example.com/3','Example 3','These are notes for example 3','foo baz quux'), + array('http://example.com/4','Example 4','These are notes for example 4',' bar quux'), + array('http://example.com/5','Example 5','These are notes for example 5','foo bar baz '), + array('http://example.com/6','Example 6','These are notes for example 6',' baz quux'), + array('http://example.com/7','Example 7','These are notes for example 7','foo bar baz quux'), + array('http://example.com/8','Example 8','These are notes for example 8',' bar quux'), + array('http://example.com/9','Example 9','These are notes for example 9','foo baz quux') + ); + $tags_counts = array(); + $tags_posts = array(); + + foreach ($posts_data as $post_data) { + $post_data = array_combine($posts_keys, $post_data); + + // Count and index posts by tag. + $tags = $this->model->parseTags($post_data['tags']); + foreach ($tags as $tag) { + if (!isset($tags_counts[$tag])) { + $tags_counts[$tag] = 1; + } else { + $tags_counts[$tag]++; + } + if (!isset($tags_posts[$tag])) { + $tags_posts[$tag] = array( $post_data ); + } else { + $tags_posts[$tag][] = array( $post_data ); + } + } + + // Save this test post. + $this->posts_model->save(array_merge( + $post_data, + array('profile_id' => $this->profile_id) + )); + } + + foreach ($tags_counts as $tag=>$test_count) { + $tag_data = $this->model->fetchByTagAndProfile($tag, $this->profile_id); + $this->assertEquals($tag, $tag_data['tag']); + $this->assertEquals($this->profile_id, $tag_data['profile_id']); + $this->assertTrue(null != $tag_data['id']); + } + + } + +} + +// Call Memex_Model_TagsTest::main() if this source file is executed directly. +if (PHPUnit_MAIN_METHOD == "Memex_Model_TagsTest::main") { + Memex_Model_TagsTest::main(); +} diff --git a/tests/Model/UrlsTest.php b/tests/Model/UrlsTest.php new file mode 100644 index 0000000..d693e5b --- /dev/null +++ b/tests/Model/UrlsTest.php @@ -0,0 +1,154 @@ +model = new Memex_Model_Urls(); + $this->model->deleteAll(); + + $this->posts_model = new Memex_Model_Posts(); + $this->posts_model->deleteAll(); + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + * + * @return void + */ + public function tearDown() + { + } + + /* + public function truncateTable() + { + $this->model->getTable('user')->getAdapter()->getConnection()->exec('DELETE FROM user'); + } + + public function testShouldNotAllowAddingUsersWithExistingUsername() + { + $id = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + + try { + $test = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo2@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + $this->fail('Users with duplicate names should raise exceptions'); + } catch (Exception $e) { + $this->assertContains('duplicate', $e->getMessage()); + } + } + + public function testShouldNotAllowAddingUsersWithExistingEmail() + { + $id = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + + try { + $test = $this->model->save(array( + 'username' => 'foo2', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + $this->fail('Users with duplicate names should raise exceptions'); + } catch (Exception $e) { + $this->assertContains('duplicate', $e->getMessage()); + } + } + + public function testFetchUserShouldAllowFetchingByUsername() + { + $id = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + + $user = $this->model->fetchUser('foo'); + $this->assertEquals($id, $user->id); + } + + public function testFetchUserShouldAllowFetchingByEmail() + { + $id = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + + $user = $this->model->fetchUser('foo@email.com'); + $this->assertEquals($id, $user->id); + } + + public function testShouldAllowBanningUsers() + { + $id = $this->model->save(array( + 'username' => 'foo', + 'email' => 'foo@email.com', + 'fullname' => 'Foo Bar', + 'password' => md5('foobar'), + )); + + $user = $this->model->fetchUser('foo@email.com'); + + $this->model->ban($id); + + $test = $this->model->fetchUser('foo@email.com'); + $this->assertNotSame($user, $test); + $this->assertNull($test); + } + */ +} + +// Call Memex_Model_UrlsTest::main() if this source file is executed directly. +if (PHPUnit_MAIN_METHOD == "Memex_Model_UrlsTest::main") { + Memex_Model_UrlsTest::main(); +} diff --git a/tests/README b/tests/README new file mode 100644 index 0000000..fc1d265 --- /dev/null +++ b/tests/README @@ -0,0 +1,14 @@ +To run the unit tests, use the following: + + phpunit --configuration phpunit.xml + +You can also run tests for just the controllers: + + phpunit --configuration phpunit.xml --group Controllers + +or just the models: + + phpunit --configuration phpunit.xml --group Models + +By default, coverage reports and TestDox are generated in the logs/ +subdirectory. diff --git a/tests/TestHelper.php b/tests/TestHelper.php new file mode 100644 index 0000000..526d5a2 --- /dev/null +++ b/tests/TestHelper.php @@ -0,0 +1,59 @@ +init(); + +/* + * Prepend the library/, tests/, and models/ directories to the + * include_path. This allows the tests to run out of the box. + */ +$path = array( + $models, + $library, + $tests, + get_include_path() +); +set_include_path(implode(PATH_SEPARATOR, $path)); + +/* + * Add library/ and models/ directory to the PHPUnit code coverage + * whitelist. This has the effect that only production code source files appear + * in the code coverage report and that all production code source files, even + * those that are not covered by a test yet, are processed. + */ +if (defined('TESTS_GENERATE_REPORT') && TESTS_GENERATE_REPORT === true && + version_compare(PHPUnit_Runner_Version::id(), '3.1.6', '>=')) { + PHPUnit_Util_Filter::addDirectoryToWhitelist($library); + PHPUnit_Util_Filter::addDirectoryToWhitelist($models); + PHPUnit_Util_Filter::addDirectoryToWhitelist($controllers); +} + +/* + * Setup default DB adapter + */ +$db = Zend_Db_Table_Abstract::getDefaultAdapter(); +$schema_sql = file_get_contents($root.'/scripts/schema.sqlite.sql'); +$db->getConnection()->exec($schema_sql); + +/* + * Unset global variables that are no longer needed. + */ +unset($init, $root, $library, $models, $controllers, $tests, $path, $db); diff --git a/tests/phpunit.xml b/tests/phpunit.xml new file mode 100644 index 0000000..9d7ed4d --- /dev/null +++ b/tests/phpunit.xml @@ -0,0 +1,27 @@ + + + ./ + + + + + + + + + ../library/ + ../application/ + + ../application/ + + + + + + + + + +