repo
string | commit
string | message
string | diff
string |
---|---|---|---|
hiddentao/patterns2
|
0213e4bf53dadfaeba3baaa27008a1830760e79a
|
Fix a bug where the list of modules to be enabled gets structured incorrectly if including multiple sub-patterns with each sub-pattern providing its own list of modules to enable.
|
diff --git a/patterns.module b/patterns.module
index 4e96d2e..06e8e27 100644
--- a/patterns.module
+++ b/patterns.module
@@ -653,1024 +653,1036 @@ function patterns_list() {
patterns_load_components();
$patterns = patterns_get_patterns();
if (empty($patterns)) return t('No patterns available.');
// $header = array(t('Title'), t('Status'), t('Version'), t('Public'), t('Actions'));
$header = array(t('Title'), t('Status'), t('Version'), t('Actions'));
// List all patterns
$rows = array();
foreach($patterns as $pid => $pattern) {
$actions = array();
if (!$pattern->status) {
$actions[] = l(t('Run'), 'admin/build/patterns/enable/'. $pid);
}
else if ($pattern->enabled >= $pattern->updated) {
$actions[] = l(t('Re-Run'), 'admin/build/patterns/enable/'. $pid);
}
else {
$actions[] = l(t('Run Update'), 'admin/build/patterns/enable/'. $pid);
}
$actions[] = l(t('Edit'), 'admin/build/patterns/edit/'. $pid);
if (variable_get('patterns_allow_publish', FALSE)) {
$actions[] = $pattern->public ? l(t('Unpublish'), 'admin/build/patterns/unpublish/'. $pid) : l(t('Publish'), 'admin/build/patterns/publish/'. $pid);
}
$actions = implode(' ', $actions);
$cells = array();
// $title = l($pattern->title, 'admin/build/patterns/info/'. $pid, array('attributes' => array('class' => 'pattern-title', 'id' => 'pid-'. $pid)));
$title = '<span id="pid-'. $pid .'" class="pattern-title">'. $pattern->title .'</span>';
// $view_more = '<div>'. t('Clik on pattern title to see more details.') .'</div>';
$info = array();
$info[] = t('Author: ') . $pattern->info['author'];
$info[] = t('Email: ') . $pattern->info['author_email'];
$info[] = t('Web: ') . $pattern->info['author_website'];
$author = theme('item_list', $info);
$title .= '<div id="pid-'. $pid .'-info" class="pattern-info">'. $author . $pattern->description . $view_more .'</div>';
$cells[] = array('data' => $title, 'class' => 'title');
$cells[] = array('data' => $pattern->status ? t('Enabled') : t('Disabled'), 'class' => 'status');
$cells[] = array('data' => $pattern->info['version'], 'class' => 'version');
// $cells[] = $pattern->public ? t('Yes') : t('No');
$cells[] = array('data' => $actions, 'class' => 'actions');
$category = $pattern->info['category'] ? $pattern->info['category'] : t('Other');
$rows[$category][] = $cells;
}
ksort($rows);
foreach ($rows as $title => $category) {
$fieldset = array(
'#title' => t($title),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#value' => theme('table', $header, $category, array('class' => 'patterns-list')),
);
$output .= theme('fieldset', $fieldset);
}
return $output;
}
/**
* Menu callback to undo a patterns update changes
*/
// function patterns_revert($pid) {
// if ($name = db_result(db_query('SELECT name FROM {patterns} WHERE pid = "%d"', $pid))) {
// $path = file_create_path(variable_get('patterns_save_xml', 'patterns') .'/enabled/'. $name .'.xml');
// $new = db_result(db_query('SELECT file FROM {patterns} WHERE pid = "%d"'));
// }
// else {
// drupal_set_message(t('The pattern you specified does not exist.'), 'error');
// drupal_goto('admin/build/patterns');
// }
//
// if (file_exists($path)) {
// if (file_move($path, $new, FILE_EXISTS_REPLACE)) {
// drupal_set_message(t('This pattern was reverted to the state it was at when it was enabled.'));
// drupal_goto();
// }
// }
// else {
// drupal_set_message(t('The patterns enabled-state was not saved properly, therefore it cannot be reverted.'), 'error');
// }
//
// drupal_goto('admin/build/patterns');
// }
/**
* Menu callback to display patterns details page
*/
// function patterns_info($pid = null) {
// if (!is_numeric($pid)) {
// drupal_set_message(t('You must specify a pattern.'));
// return;
// }
//
// $pattern = patterns_get_pattern($pid);
//
// $output = '';
// return $output;
// }
/**
* Menu callback to edit a patterns data
*/
function patterns_edit(&$form_state, $pid = null) {
if (!is_numeric($pid)) {
drupal_set_message(t('You must specify a pattern to edit.'));
return;
}
$pattern = patterns_get_pattern($pid);
// TODO: Turn php into xml here.
// For now just allow modifying the original xml, which
// means the modification cannot be further modified
if (!$pattern->file) {
drupal_set_message(t('This pattern does not seem to have an XML source file to base the modifications off of.'), 'error');
return;
}
$xml = file_get_contents($pattern->file);
$form['name'] = array(
'#type' => 'value',
'#value' => $pattern->name
);
$form['pid'] = array(
'#type' => 'value',
'#value' => $pattern->pid
);
// if ($pattern->enabled <= $pattern->updated) {
// $form['revert'] = array(
// '#type' => 'markup',
// '#value' => l(t('Undo update changes to the state when you enabled the pattern.'), 'admin/build/patterns/revert/'. $pid, array(), drupal_get_destination())
// );
// }
$form['format'] = array(
'#type' => 'select',
'#title' => t('Pattern syntax'),
'#options' => array_combine(patterns_file_types(), patterns_file_types()),
'#default_value' => 'xml'
);
$form['xml'] = array(
'#type' => 'textarea',
'#title' => t('Pattern\'s code'),
'#rows' => 25,
'#default_value' => $xml
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit')
);
return $form;
}
/**
* Validate pattern modifications (make sure proper XML)
*/
function patterns_edit_validate($form, &$form_state) {
// @TODO Do validations....
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (!file_check_directory($path, true)) {
form_set_error('form_token', t('Unable to create @path to save the new pattern to.', array('@path' => $path)));
}
}
/**
* Submit edits to the pattern
*/
function patterns_edit_submit($form, &$form_state) {
// If this is an enabled pattern, make sure the enabled pattern is saved in its current state
if ($file = db_result(db_query('SELECT file FROM {patterns} WHERE status = 1 AND name = "%s"', $form_state['values']['name']))) {
$dir = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/enabled';
file_check_directory($dir, true);
$path = $dir .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
if (!file_exists($path)) {
file_copy($file, $path, FILE_EXISTS_ERROR);
}
}
// Save the new pattern into the pattern files dir.
$path = file_directory_path() .'/'. variable_get('patterns_save_xml', 'patterns') .'/'. $form_state['values']['name'] .'.'. $form_state['values']['format'];
file_save_data($form_state['values']['xml'], $path, FILE_EXISTS_REPLACE);
$old = db_result(db_query('SELECT file FROM {patterns} WHERE name = "%s"', $form_state['values']['name']));
// Load and save pattern
$load_func = 'patterns_load_' .$form_state['values']['format'];
if ($pattern = $load_func($path)) {
if ($old) {
db_query('UPDATE {patterns} SET file = "%s", updated = "%s" WHERE pid = "%d"', $path, time(), $form_state['values']['pid']);
}
patterns_save_pattern($pattern, $path, $form_state['values']['name']);
drupal_set_message(t('%name was saved.', array('%name' => $form_state['values']['name'])));
$form_state['redirect'] = 'admin/build/patterns';
}
else {
drupal_set_message(t("Pattern '%name' couldn't be saved. Make sure edited code is well-formed.", array('%name' => $form_state['values']['name'])), 'error');
}
}
/**
* List the modules used by a particular pattern
*/
function patterns_modules_page($pid) {
$pattern = patterns_get_pattern($pid);
drupal_set_title($pattern->title .' '. t('(Pattern Modules)'));
$modules = isset($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$modules_info = module_rebuild_cache();
$modules_list = module_list();
// Get module name, whether its to be disabled or enabled,
// whether the module is available or not, and whether it is
// currently enabled or not
foreach($modules as $module) {
$row = array();
$delete = is_array($module) ? $module['delete'] : false;
$module = is_array($module) ? $module['value'] : $module;
$available = array_key_exists($module, $modules_info);
$enabled = array_key_exists($module, $modules_list);
$row[] = $module;
$row[] = $available ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $enabled ? t('Yes') : '<span class="alert">'. t('No') .'</span>';
$row[] = $delete ? t('Delete') : t('Enable');
$rows[] = $row;
if (!$available) {
$not_available = true;
}
}
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
$enabled[] = $result->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
+ // ensure the 'modules' array is collapsed - this is necessary to do if,
+ // for example, we're including multiple sub-patterns which each include
+ // their own list of modules
+ if ('modules' == $values['tag']) {
+ if (isset($values['module'])) {
+ if (is_array($values['module'])) {
+ $pattern['modules'] = $values['module'];
+ } else {
+ $pattern['modules'] = array($values['module']);
+ }
+ }
+ }
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
@include($path);
// That should have declared a 'pattern' into current scope.
if (!patterns_validate_pattern($pattern)) {
trigger_error("Failed to evaluate a useful pattern from the input file $path. Pattern did not validate. May have been invalid syntax. ", E_USER_WARNING);
return FALSE;
}
return $pattern;
}
/**
* Create a pattern from an XML data source
*/
function patterns_from_source($xml) {
$parse = drupal_xml_parser_create($xml);
if (!xml_parse_into_struct($parse, $xml, $vals, $index)) {
return false;
}
// Create a multi-dimensional array representing the XML structure
$pattern = current(_patterns_parse_tag($vals));
return $pattern;
}
/**
* Recurse through the values of a parsed xml file to create a
* multi-dimensional representation of the data.
*/
function _patterns_parse_tag($data, &$index = 0) {
$pattern = array();
while (isset($data[$index]) && ($current = $data[$index])) {
$type = $current['type'];
if (isset($current['attributes'])) {
foreach((array)$current['attributes'] as $key => $value) {
$current[strtolower($key)] = $value;
}
}
$current['tag'] = strtolower($current['tag']);
unset($current['type'], $current['level'], $current['attributes']);
if (isset($current['value']) && !trim($current['value']) && $current['value'] != "0") {
unset($current['value']);
}
switch($type) {
case 'open':
$index++;
$current += _patterns_parse_tag($data, $index);
$pattern[] = $current;
break;
case 'close':
$index++;
return $pattern;
break;
case 'complete':
// In order to support more complex/non-standard features we can use serialized data
if (isset($current['attributes']) && $current['attributes']['serialized']) {
$value = unserialize($current['value']);
if (isset($value)) {
$current['value'] = $value;
}
}
// If no value was specified, make sure an empty value is there
if (!isset($current['value'])) {
$current['value'] = '';
}
$pattern[] = $current;
break;
}
$index++;
}
return $pattern;
}
// function patterns_disable_pattern($pid) {
// $form['pid'] = array(
// '#type' => 'value',
// '#value' => $pid
// );
//
// $pattern = patterns_get_pattern($pid);
//
// return confirm_form($form, t('Proceed with disabling pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', '');
// }
function patterns_enable_pattern(&$form_state, $pid) {
$form['pid'] = array(
'#type' => 'value',
'#value' => $pid
);
$options = array(
'first-update' => t('only if disabled or if updated since last run (recommended)'),
'always' => t('always'),
'update' => t('only if updated since last run'),
'first' => t('only if disabled'),
'never' => t("don't run sub-patterns at all"),
);
$form['run-subpatterns'] = array(
'#type' => 'radios',
'#title' => t('Run sub-patterns:'),
'#description' => t("Decide when to run sub-patterns that are called by the currently run pattern. If unsure, stick to recommended setting. Note that your choice won't have any effect if your pattern doesn't contain sub-patterns or if this setting has been defined within the pattern file itself."),
'#options' => $options,
'#default_value' => 'first-update',
);
$disclaimer = t('Please be sure to backup your site before running a pattern. Patterns are not guaranteed to be reversable in case they do not execute well or if unforseen side effects occur.');
$pattern = patterns_get_pattern($pid);
return confirm_form($form, t('Proceed with running pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', $disclaimer);
}
// function patterns_disable_pattern_submit($form_id, $form_values) {
// $pid = $form_values['pid'];
// $pattern = patterns_get_pattern($pid);
//
// if (patterns_execute_pattern($pattern, true, true)) {
// return 'admin/build/patterns';
// }
// }
function patterns_enable_pattern_submit($form, &$form_state) {
$pid = $form_state['values']['pid'];
patterns_load_components();
$pattern = patterns_get_pattern($pid);
patterns_execute_pattern($pattern, $form_state['values']);
$form_state['redirect'] = 'admin/build/patterns';
}
/**
* Execute default configuration for module during the module installation
*
* This function should be called by other modules from
* within their hook_enable() implementation.
* Module should also provide modulename.config file containing PHP array
* with the actions that need to be executed.
*
* @param $module
* name of the module calling the function
*/
function patterns_execute_config($module) {
// since this function is called from hook_enable(), we need to ensure that
// it's executed only at module installation (first time module is enabled)
if (drupal_get_installed_schema_version($module) == SCHEMA_INSTALLED) return;
$path = drupal_get_path('module', $module) .'/'. $module .'.config';
if (file_exists($path)) {
include_once($path);
if (empty($actions)) return;
$pattern = new stdClass();
$pattern->title = t('Default configuration for @module module', array('@module' => $module));
$pattern->status = false;
$pattern->pattern['actions'] = $actions;
patterns_execute_pattern($pattern);
}
}
function patterns_execute_pattern($pattern, $params = array(), $mode = 'batch') {
$args = array($pattern, $params);
$function = 'patterns_execute_pattern_'. $mode;
if (!function_exists($function) || !is_object($pattern)) return FALSE;
return call_user_func_array($function, $args);
}
function patterns_execute_pattern_batch($pattern, $params = array()) {
set_time_limit(0);
if (!is_object($pattern)) {
$pattern = patterns_get_pattern($pattern);
if (!$pattern) {
return FALSE;
}
}
$pattern->subpatterns_run_mode = isset($params['run-subpatterns']) ? $params['run-subpatterns'] : FALSE;
$pattern_details = patterns_get_pattern_details($pattern, TRUE);
$modules = $pattern_details['modules'];
$actions = $pattern_details['actions'];
$actions_map = array('patterns' => $pattern_details['info'], 'map' => $pattern_details['actions_map']);
$info = reset($pattern_details['info']);
// If there are no actions or modules, most likely the pattern
// was not created correctly.
if (empty($actions) && empty($modules)) {
drupal_set_message(t('Could not recognize pattern %title, aborting.', array('%title' => $info['title'])), 'error');
return FALSE;
}
$result = patterns_install_modules($modules);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
// lets clear the caches here to ensure that newly added modules
// and future pattern actions work as expected.
module_load_include('inc', 'system', 'system.admin');
$form = $form_state = array();
system_clear_cache_submit($form, $form_state);
$result = patterns_prepare_actions($actions, $actions_map);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
$batch = array(
'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
// 'init_message' => t('Running action @current out of @total', array('@current' => 1, '@total' => count($actions))),
'progress_message' => t('Running action @current out of @total'),
'operations' => array(),
'finished' => 'patterns_batch_finish'
);
for($i=0;$i<count($actions);$i++) {
$batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
}
$_SESSION['patterns_batch_info'] = $pattern_details['info'];
batch_set($batch);
return TRUE;
}
function patterns_install_modules(&$modules) {
$result = array('success' => TRUE);
if (empty($modules)) return $result;
$missing = patterns_check_module_dependencies($modules, TRUE);
if (!empty($missing)) {
$result['success'] = FALSE;
$result['error_message'] = t('Following required modules are missing: %modules', array('%modules' => implode(', ', $missing)));
$result['missing_modules'] = $missing;
return $result;
}
require_once './includes/install.inc';
drupal_install_modules($modules);
module_rebuild_cache();
$result['installed_modules'] = $modules;
return $result;
}
function patterns_locate_action($key, $actions_map) {
$result['key'] = $actions_map['map'][$key]['index'];
$result['title'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['title'];
$result['file'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['file'];
return $result;
}
function patterns_prepare_actions(&$actions, $actions_map) {
$result = array('success' => TRUE);
if (empty($actions)) return $result;
patterns_load_components();
// Keep a list of what modules handle what tags
$tag_modules = patterns_invoke($empty, 'tag modules');
// TODO Finish basic setup and execution of the 'config' operation
// TODO Make a better streamlined config framework process. For instance collect form_ids
// from here and give the form_id and matching data to the 'build' process
foreach($actions as $key => &$data) {
if (($config = patterns_invoke($actions[$key], 'config')) && !empty($config)) {
patterns_config_data($data, $config);
}
}
// Prepare actions for validation/processing
foreach($actions as $key => &$data) {
patterns_invoke($actions[$key], 'prepare');
}
$errors = array();
// Pre validate tags with their appropriate components
foreach($actions as $key => &$data) {
$action_location = patterns_locate_action($key, $actions_map);
$index = $action_location['key'];
$pattern_title = $action_location['title'];
// $pattern_file = $action_location['file'];
if (!array_key_exists($data['tag'], $tag_modules)) {
$errors[] = t('Action #%num (%tag) in pattern %title: <%tag> is not a valid tag', array('%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
else {
$error = patterns_invoke($actions[$key], 'pre-validate');
if ($error) {
$errors[] = t('Action #%num (%tag) in pattern %title: !msg', array('!msg' => $error, '%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
}
}
if (count($errors)) {
$message = t('Errors encountered during pre-processing:') .'<br>'. implode('<br>', $errors);
$result['success'] = FALSE;
$result['error_message'] = $message;
}
return $result;
}
/**
* Execute a batch action
*/
function patterns_batch_actions($action, $place, $actions_map, &$context) {
patterns_load_components();
// Nothing to do if there is no action
if (empty($action)) {
$context['finished'] = 1;
return;
}
// Start a timer. Since we want each action to be its own http request, we need
// to ensure the batch api will decide to do it like that by making each action
// take at least a second to execute
timer_start('patterns_action');
// skip action execution if an error is encountered in some of the previous operations
if (!empty($context['results']['abort'])) return;
$result = patterns_implement_action($action, $context['results']['identifiers'], $place, $actions_map);
if (!$result['success']) {
// we use 'results' to keep track of errors and abort execution if required
$context['results']['abort'] = TRUE;
$context['results']['error_message'] = $result['error_message'];
}
if (timer_read('patterns_action') < 1000) {
@usleep(1000 - timer_read('patterns_action'));
}
}
/**
* Finish a batch operation
*/
function patterns_batch_finish($success, $results, $operations) {
$info = $_SESSION['patterns_batch_info'];
if (!isset($results['abort']) || !($results['abort'])) {
foreach ($info as $key => $i) {
drupal_set_message(t('Pattern "@pattern" ran successfully.', array('@pattern' => $i['title'])));
db_query('UPDATE {patterns} SET status = 1, enabled = "%s" WHERE pid = %d', time(), $key);
}
}
else {
$pattern = reset($info);
drupal_set_message(t('Pattern "@pattern" ran with the errors. Check the error messages to get more details.', array('@pattern' => $pattern['title'])));
drupal_set_message($results['error_message'], 'error');
}
unset($_SESSION['patterns_batch_info']);
drupal_flush_all_caches();
}
/**
* Setup and run an action
*/
function patterns_implement_action($action, &$identifiers, $place = 0, $actions_map = NULL) {
patterns_set_error_handler();
$result = array('success' => TRUE);
// Prepare actions for processing, ensure smooth pattern executions, and return form ids for execution
$return = patterns_invoke($action, 'form_id');
// If prepare removed the data, dont continue with this action
if (!$action || !$return) {
return $result;
}
if (is_string($return)) {
$form_ids = array($return);
}
else if ($return) {
$form_ids = $return;
}
$action_descriptions = patterns_invoke($action, 'actions');
$action_location = patterns_locate_action($place, $actions_map);
$index = $action_location['key'] + 1;
$pattern_title = $action_location['title'];
$pattern_file = $action_location['file'];
// Build the action
foreach($form_ids as $form_id) {
$clone = $action;
$action_description = isset($action_descriptions[$form_id]) ? $action_descriptions[$form_id] : t('System: Execute form');
$result['action_descriptions'][$place][] = $action_description;
// If tokens are enabled, apply tokens to the action values
// before processing
if (module_exists('token')) {
_patterns_recurse_tokens($clone, $identifiers);
//array_walk($clone, '_patterns_replace_tokens', $identifiers);
}
$error = patterns_invoke($clone, 'validate', $form_id);
if ($message = patterns_error_get_last('validate', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($error) {
$message = t('An error occured while validating action #%num (%action) in %title pattern', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title));
$result['error_message'] = $message .'<br>'. $error;
$result['success'] = FALSE;
return $result;
}
// Get the form data for the action. This can either just be the form values,
// or it can be the full form_state object
$form_obj = patterns_invoke($clone, 'build', $form_id);
if ($message = patterns_error_get_last('build', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// Dont execute the action if a string was returned, indicating the pattern component
// most likely handled the action on its own and this is the message to display.
if (is_string($form_obj)) {
drupal_set_message($form_obj);
}
else {
// We check for the 'storage' and 'submitted' values in the object to see
// if it is a form_state instead of form_values. There could be a better way
// to do this.
if (array_key_exists('submitted', (array)$form_obj) && array_key_exists('storage', (array)$form_obj)) {
$action_state = $form_obj;
}
else {
$action_state = array(
'storage' => null,
'submitted' => false,
'values' => $form_obj
);
}
// Get any extra parameters required for the action
$params = patterns_invoke($clone, 'params', $form_id, $action_state);
if ($message = patterns_error_get_last('params', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// A single, simple value can be returned as a parameter, which is then
// put into an array here.
if (isset($params) && !is_array($params)) {
$params = array($params);
}
// Execute action
|
hiddentao/patterns2
|
65ddb788822119d8ddd6b58b63f8b4c17de2d32a
|
When adding nodes you can now use the 'path' tag to specify a custom path alias to the node (pathauto is bypassed).
|
diff --git a/components/node.inc b/components/node.inc
index 2bc740b..5115976 100644
--- a/components/node.inc
+++ b/components/node.inc
@@ -1,412 +1,412 @@
<?php
require_once('_common.php');
function node_patterns($op, $id = null, &$data = null, $a = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('node');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
$data['type'] .'_node_form' => t('Node: Create/update content.'),
'node_delete_confirm' => t('Node: Delete content.'),
);
break;
// Return a summary of an action
case 'summary':
$variables = array(
'%type' => $data['type'],
'%title' => $data['title'],
);
if (empty($data['nid'])) {
return t('Create %type: "%title"', $variables);
}
elseif ($data['delete']) {
return t('Delete %type: "%title"', $variables);
}
else {
return t('Update %type: "%title"', $variables);
}
break;
// Prepare data for processing
case 'prepare':
global $user;
if (empty($data['nid']) && !empty($data['id'])) {
$data['nid'] = $data['id'];
}
unset($data['id']);
if (empty($data['name']) && !empty($data['author'])) {
$data['name'] = $data['author'];
}
unset($data['author']);
if (empty($data['uid'])) $data['uid'] = $user->uid;
if (empty($data['name'])) $data['name'] = $user->name;
if (is_numeric($data['nid']) && $data['node'] = node_load($data['nid'])) {
$data['update'] = TRUE;
}
else {
unset($data['nid']);
unset($data['vid']);
$data['node'] = (object) $data;
$data['update'] = FALSE;
}
break;
// Pre validate actions
case 'pre-validate':
if (empty($data['type']) && !$data['delete']) {
return t('"type" field is required.');
}
if ($data['delete'] && empty($data['nid'])) {
return t('"id" field is required.');
}
if ($data['update'] && $data['type'] != $data['node']->type) {
return t("You can't change content type for already existing node.");
}
break;
// Return the form_id('s) for each action
case 'form_id':
if ($data['delete']) {
return 'node_delete_confirm';
}
else {
return $data['type'] .'_node_form';
}
break;
// Prepare for valid processing of this type of component
case 'build':
_pattern_component_replace_format_name_with_id($data);
module_load_include('inc', 'node', 'node.pages');
if ($id == 'node_delete_confirm') {
$data['confirm'] = 1;
return $data;
}
$data['changed'] = time();
$data['op'] = t('Save');
$node = drupal_clone($data['node']);
if (module_exists('content')) {
// build CCK fields
$type = $data['type'];
$form_id = $type .'_node_form';
$form_state = array();
$form = drupal_retrieve_form($form_id, $form_state, $node);
drupal_prepare_form($form_id, $form, $form_state);
$content_type = content_types($type);
$fields_info = $content_type['fields'];
if (module_exists('fieldgroup')) {
$groups = fieldgroup_groups($type, FALSE, TRUE);
}
// TODO: make this work for PHP4
$fields = array();
$fields_diff = array();
if (!empty($groups)) {
foreach($groups as $key => $group) {
$fields = array_merge($fields, array_intersect_ukey($form[$key], $group['fields'], '_patterns_compare_keys'));
}
$fields_diff = array_diff_ukey($fields_info, $fields, '_patterns_compare_keys');
$fields = array_merge($fields, array_intersect_ukey($form, $fields_diff, '_patterns_compare_keys'));
}
else {
$fields = array_merge($fields, array_intersect_ukey($form, $fields_info, '_patterns_compare_keys'));
}
if (!empty($fields)) {
$defaults = array();
foreach($fields as $field_name => $field) {
$alias = str_replace('field_', '', $field_name);
if (isset($field['#default_value']) && !isset($field[0])) {
$col = $field['#columns'][0];
// prepare default value
if (is_numeric($field['#default_value']) || is_string($field['#default_value'])) {
$default = $field['#default_value'];
}
elseif (empty($field['#default_value'])) {
$default = NULL;
}
else {
$default = array();
foreach ($field['#default_value'] as $value) {
foreach ($value as $key => $val) {
if (empty($default[$key])) {
$default[$key] = array();
}
$v = array($val => $val);
$default[$key] = $default[$key] + $v;
}
}
}
// fix for non-standard format of nodereference and userreference fields
if (preg_match('/^(nodereference|userreference)/', $field['#type'])) {
$defaults[$field_name][$col][$col] = _patterns_get_field_value($data['fields'][$alias], $col, $default[$col]);
}
else {
$defaults[$field_name][$col] = _patterns_get_field_value($data['fields'][$alias], $col, $default[$col]);
}
}
else {
// prepare field value provided by pattern
if (!isset($data['fields'][$alias])) {
$data['fields'][$alias] = array(0 => NULL);
}
elseif (is_array($data['fields'][$alias]) && !isset($data['fields'][$alias][0])) {
$data['fields'][$alias] = array(0 => $data['fields'][$alias]);
}
elseif (is_string($data['fields'][$alias])) {
$data['fields'][$alias] = array(0 => array('value' =>$data['fields'][$alias]));
}
// get the number of fields defined by CCK module
$field_count = 0;
while (isset($field[$field_count])) {
$field_count++;
}
// CCK always provides one additional empty field for multiple values fields so we remove it
$field_count = $field_count > 1 ? $field_count -1 : $field_count;
$count = $field_count < count($data['fields'][$alias]) ? count($data['fields'][$alias]) : $field_count;
$i = 0;
while ($i < $count) {
// column names are same for all the fields so we use $field[0]['#columns'] always
// because $field[$i] may not exist in the case when number of fields defined by pattern
// is greater then number of fields defined by CCK
foreach ($field[0]['#columns'] as $col) {
if (isset($field[$i][$col])) {
$value = _patterns_get_field_value($data['fields'][$alias][$i], $col, $field[$i][$col]['#default_value']);
$defaults[$field_name][$i][$col] = array($col => $value);
}
else {
$default = isset($field[$i]['#default_value'][$col]) ? $field[$i]['#default_value'][$col] : NULL;
// fix for non-standard implementation of viewfield module
if (preg_match('/^(viewfield)/', $field[$i]['#type'])) {
$defaults[$field_name][$i]['fieldset'][$col] = _patterns_get_field_value($data['fields'][$alias][$i], $col, $default);
}
else {
$defaults[$field_name][$i][$col] = _patterns_get_field_value($data['fields'][$alias][$i], $col, $default);
}
}
}
$i++;
}
}
}
$data = $data + $defaults;
}
}
// build taxonomy array
$vocabularies = taxonomy_get_vocabularies($data['type']);
$vocabs = array();
// we assume that all the vocabularies have unique names
foreach ($vocabularies as $v) {
$vocabs[$v->name] = $v;
}
$new_taxonomy = array();
// PHP array produced by XML parser when single vocabulary
// is defined in the pattern differs from the one produced
// when mutiple vocabs are defined.
// We need to convert single vocab array to the array
// structure for multiple vocabs.
if (isset($data['taxonomy']['vocabulary'])) {
$data['taxonomy'] = array(0 => $data['taxonomy']);
}
if (!empty($data['taxonomy']) && is_array($data['taxonomy'])) {
foreach ($data['taxonomy'] as $key => $v) {
if (!isset($vocabs[$v['vocabulary']])) continue;
$vocabulary = $vocabs[$v['vocabulary']];
unset($data['taxonomy'][$key]['vocabulary']);
$terms = $data['taxonomy'][$key];
if (!is_array($terms)) continue;
if ($vocabulary->tags) {
$new_taxonomy['tags'][$vocabulary->vid] = reset($terms);
}
else {
// get tids for all term names
$tids = array();
foreach($terms as $name) {
if (!is_string($name)) continue;
$term = taxonomy_get_term_by_name($name);
// take the first term that belongs to given vocabulary
foreach ($term as $t) {
if ($t->vid == $vocabulary->vid) {
$tids[$t->tid] = $t->tid;
break;
}
}
}
$new_taxonomy[$vocabulary->vid] = $vocabulary->multiple ? $tids : (empty($tids) ? '' : reset($tids));
}
}
}
if (!$data['update'] || ($data['update'] && $data['taxonomy_overwrite'])) {
if (empty($new_taxonomy)) {
unset($data['taxonomy']);
}
else {
$data['taxonomy'] = $new_taxonomy;
}
}
else {
$taxonomy = array();
$defaults = array();
foreach ($form['taxonomy'] as $vid => $terms) {
if (!is_numeric($vid)) continue;
$tids = array();
foreach ($terms['#default_value'] as $tid) {
$tids[$tid] = $tid;
}
$empty = $terms['#multiple'] ? array() : '';
$default = $terms['#multiple'] ? $tids : reset($tids);
if (empty($tids)) {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $empty : $new_taxonomy[$vid];
}
else {
if ($terms['#multiple']) {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $default : $new_taxonomy[$vid] + $default;
}
else {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $default : $new_taxonomy[$vid];
}
}
}
if (!empty($form['taxonomy']['tags'])) {
foreach ($form['taxonomy']['tags'] as $vid => $tags) {
$defaults['tags'][$vid] = $tags['#default_value'];
if (!empty($new_taxonomy['tags'][$vid])) {
$taxonomy['tags'][$vid] = !empty($defaults['tags'][$vid]) ? $defaults['tags'][$vid] .','. $new_taxonomy['tags'][$vid] : $new_taxonomy['tags'][$vid];
}
else {
$taxonomy['tags'][$vid] = $defaults['tags'][$vid];
}
}
}
$data['taxonomy'] = $taxonomy;
}
unset($data['fields']);
unset($data['node']);
unset($data['taxonomy_overwrite']);
$node->taxonomy = array();
if ($data['update']) $data = array_merge((array)$node, $data);
// // required for proper functioning of pathauto module
// static $old_q;
// $old_q = $_GET['q'];
// if ($data['update']) {
// $_GET['q'] = 'node/'. $data['nid'] .'/edit';
// }
// else {
// $_GET['q'] = 'node/add/'. str_replace('_', '-', $data['type']);
// }
unset($data['update']);
- // Until manual path setting is fixed,
- // unset all path related elements to prevent
- // potential database errors.
- unset($data['path']);
+ if (isset($data['path'])) {
+ $data['pathauto_perform_alias'] = 0;
+ } else {
+ $data['pathauto_perform_alias'] = 1;
+ }
unset($data['pid']);
unset($data['old_alias']);
- unset($data['pathauto_perform_alias']);
return $data;
break;
// Validate the values for an action before running the pattern
case 'validate':
if (TRUE !== ($ret = _pattern_component_validate_format($data))) {
return $ret;
}
// TODO: validate name field - should be valid/existing username
if (!node_get_types('types', $data['type'], TRUE) && !$data['delete']) {
return t('Invalid content type: %type', array('%type' => $data['type']));
}
break;
// Build a patterns actions and parameters
case 'params':
return array((object) $data);
break;
// Cleanup any global settings after the action runs
case 'cleanup':
// static $old_q;
// if ($old_q) {
// $_GET['q'] = $old_q;
// unset($old_q);
// }
break;
// Return the primary ID if possible from this action
case 'identifier':
$form_state = $a;
if (!empty($form_state['nid']) && is_numeric($form_state['nid'])) {
return $form_state['nid'];
}
break;
}
}
function _patterns_compare_keys($key1, $key2) {
if ($key1 == $key2)
return 0;
elseif ($key1 > $key2)
return 1;
else
return -1;
}
function _patterns_get_field_value($field, $key, $default) {
if (is_array($field)) {
return isset($field[$key]) ? $field[$key] : $default;
}
elseif (is_numeric($field) || is_string($field)) {
return $field;
}
else {
return $default;
}
}
|
hiddentao/patterns2
|
72eb1bc2079835fca3d2ca3f9419b1777d0a6464
|
- After loading the specified modules, we now clear all caches before running the actions, to ensure that certain actions (e.g. setting user permissions on CCK fields) work as expected.
|
diff --git a/README.txt b/README.txt
index 1303e72..e905bbb 100644
--- a/README.txt
+++ b/README.txt
@@ -1,8 +1,18 @@
Patterns2
=========
An improved version of the Drupal Patterns module.
-This incorporates a number of patches submitted to the original module version 6.x-1.x-dev (see http://drupal.org/project/issues/patterns?categories=All) as well as further improvements. The motivation for creating this repository is to track all the new improvements being made to the module via Git (better than tracking through the patches submitted) and to (hopefully!) encourage the original module authors to roll the changes in this fork back into the original module.
+This incorporates a number of patches submitted to the original module version 6.x-1.x-dev as well as further improvements. The motivation for creating this repository is to track all the new improvements being made to the module via Git (better than tracking through the patches submitted) and to (hopefully!) encourage the original module authors to roll the changes in this fork back into the original module.
+
+At the moment this code incorporates the following patches:
+
+http://drupal.org/node/853720
+http://drupal.org/node/853746
+http://drupal.org/node/852620
+http://drupal.org/node/848270
+http://drupal.org/node/845440
+http://drupal.org/node/845448
+http://drupal.org/node/842838
Grab the latest source at http://github.com/hiddentao/patterns2
\ No newline at end of file
diff --git a/index.html b/index.html
deleted file mode 100644
index afde1ef..0000000
--- a/index.html
+++ /dev/null
@@ -1,87 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
-
- <title>hiddentao/patterns2 @ GitHub</title>
-
- <style type="text/css">
- body {
- margin-top: 1.0em;
- background-color: #ffffff;
- font-family: "Helvetica,Arial,FreeSans";
- color: #000000;
- }
- #container {
- margin: 0 auto;
- width: 700px;
- }
- h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; }
- h1 .small { font-size: 0.4em; }
- h1 a { text-decoration: none }
- h2 { font-size: 1.5em; color: #000000; }
- h3 { text-align: center; color: #000000; }
- a { color: #000000; }
- .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;}
- .download { float: right; }
- pre { background: #000; color: #fff; padding: 15px;}
- hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
- .footer { text-align:center; padding-top:30px; font-style: italic; }
- </style>
-
-</head>
-
-<body>
- <a href="http://github.com/hiddentao/patterns2"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
-
- <div id="container">
-
- <div class="download">
- <a href="http://github.com/hiddentao/patterns2/zipball/master">
- <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a>
- <a href="http://github.com/hiddentao/patterns2/tarball/master">
- <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a>
- </div>
-
- <h1><a href="http://github.com/hiddentao/patterns2">Patterns2</a>
- <span class="small">by <a href="http://github.com/hiddentao">hiddentao</a></span></h1>
-
- <div class="description">
- An improved version of the Drupal Patterns module.
- </div>
-
- <p>This incorporates a number of patches submitted to the original module version 6.x-1.x-dev (see http://drupal.org/project/issues/patterns?categories=All) as well as further improvements.
-
-The motivation for creating this repository is to track all the new improvements being made to the module via Git (better than tracking through the patches submitted).</p>
-
-<h2>Dependencies</h2>
-<p>Drupal 6, PHP 5.1, Token module (http://drupal.org/project/token).</p>
-<h2>Install</h2>
-<p>Simply overwrite your patterns module folder with this one.</p>
-<h2>License</h2>
-<p>GPLv2</p>
-<br/> </p>
-
-
- <h2>Download</h2>
- <p>
- You can download this project in either
- <a href="http://github.com/hiddentao/patterns2/zipball/master">zip</a> or
- <a href="http://github.com/hiddentao/patterns2/tarball/master">tar</a> formats.
- </p>
- <p>You can also clone the project with <a href="http://git-scm.com">Git</a>
- by running:
- <pre>$ git clone git://github.com/hiddentao/patterns2</pre>
- </p>
-
- <div class="footer">
- get the source code on GitHub : <a href="http://github.com/hiddentao/patterns2">hiddentao/patterns2</a>
- </div>
-
- </div>
-
-
-</body>
-</html>
diff --git a/patterns.info b/patterns.info
index 7c0bd00..4f50e97 100644
--- a/patterns.info
+++ b/patterns.info
@@ -1,11 +1,10 @@
name = Patterns2
description = Enables extremely simple adding/removing features to your site with minimal to no configuration. Forked version of original module, hosted at http://github.com/hiddentao/patterns2.
dependencies[] = token
core = 6.x
package = Site Setup
php = 5.1
version = "6.x-2.x-dev"
core = "6.x"
-project = "patterns"
diff --git a/patterns.module b/patterns.module
index 9d825f2..4e96d2e 100644
--- a/patterns.module
+++ b/patterns.module
@@ -892,1024 +892,1031 @@ function patterns_modules_page($pid) {
if ($not_available) {
drupal_set_message(t('Some modules are not availalble, please download them before running this pattern.'), 'error');
}
else {
drupal_set_message(t('All modules required by this module are available. Click !here to run this pattern.', array('!here' => l(t('here'), 'admin/build/patterns/enable/'. $pid))));
}
return theme('table', array(t('Name'), t('Available'), t('Enabled'), t('Pattern Action')), $rows, t('Modules used for this pattern'));
}
function patterns_load_components() {
static $loaded = false;
if ($loaded) {
return;
}
require_once drupal_get_path('module', 'patterns') .'/patterns.inc';
// Get a list of directories to search
$paths = module_invoke_all('patterns_directory');
foreach($paths as $path) {
foreach(file_scan_directory($path .'/components', '.\.inc$') as $file) {
include_once $file->filename;
}
}
$loaded = true;
}
function patterns_get_patterns($reset = true) {
patterns_load_components();
if ($reset || !variable_get('patterns_loaded', false)) {
// Get a listing of enabled patterns
$enabled = array();
$result = db_query('SELECT file FROM {patterns} WHERE status = 1');
while ($pattern = db_fetch_object($result)) {
$enabled[] = $result->file;
}
$priority = array();
$errors = array();
// Get list of directories to scan for patterns
$patterns_paths = patterns_paths();
// get valid file extensions
$mask = '.\.('. implode('|', patterns_file_types()) .')$';
// prepare list of files/folders to be excluded
// 'enabled' - Don't save enabled pattern backups
$no_mask = array('.', '..', 'CVS', '.svn', 'enabled');
foreach ($patterns_paths as $path) {
foreach(file_scan_directory($path, $mask, $no_mask) as $file) {
// Can't update existing patterns that are enabled
if (in_array($file->filename, $enabled) || in_array($file->name, $priority)) {
continue;
}
$priority[] = $file->name;
// choose appropriate function based on the file extension
$func = 'patterns_load_'. substr($file->basename, strlen($file->name) + 1);
// Load and save pattern
if ($pattern = $func($file->filename)) {
patterns_save_pattern($pattern, $file->filename, $file->name);
}
else {
$errors[] = $file->filename;
}
}
}
variable_set('patterns_loaded', time());
}
$result = db_query('SELECT * FROM {patterns}');
$messages = array();
while ($pattern = db_fetch_object($result)) {
// skip pattern if its file is missing
if (!is_file($pattern->file)) continue;
// skip pattern if loading failed and report that to the user
if (in_array($pattern->file, $errors)) {
$messages[] = t("Pattern couldn't be loaded from the file '%file'", array('%file' => $pattern->file));
continue;
}
$patterns[$pattern->pid] = $pattern;
$data = unserialize($pattern->pattern);
$patterns[$pattern->pid]->pattern = $data;
$patterns[$pattern->pid]->info = $data['info'];
}
if (!empty($messages)) {
drupal_set_message(implode('<br>', $messages) .'<br>'. t('Make sure that above file(s) are readable and contain valid data.'), 'error');
}
return $patterns;
}
/**
* return a list of paths that will be scanned for patterns
*/
function patterns_paths() {
global $profile;
if (!isset($profile)) {
$profile = variable_get('install_profile', 'default');
}
// array of all the paths where we should look for patterns
$patterns_paths = array(
conf_path() .'/patterns',
'profiles/'. $profile .'/patterns',
'sites/all/patterns'
);
// allow any module to include patterns too
foreach(module_invoke_all('patterns_directory') as $path) {
if (is_dir($path)) {
$patterns_paths[] = $path .'/patterns';
}
}
// also prepend files folder if it's valid
$path = file_create_path(variable_get('patterns_save_xml', 'patterns'));
if (file_check_directory($path)) {
array_unshift($patterns_paths, $path);
}
return $patterns_paths;
}
/**
* Implementation of hook_patterns_directory()
*
* Let us know about where the pattern files are at
*/
function patterns_patterns_directory() {
return drupal_get_path('module', 'patterns');
}
function patterns_save_pattern($pattern, $path = '', $name = '') {
$title = $pattern['info']['title'];
$description = $pattern['info']['description'];
$author = $pattern['info']['author'];
if ($pid = db_result(db_query('SELECT pid FROM {patterns} WHERE name = "%s"', $name))) {
$updated = db_result(db_query('SELECT updated FROM {patterns} WHERE pid = "%d"', $pid));
if (($new_updated = filemtime($path)) > $updated) {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", updated = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $new_updated, $description, $pid);
}
else {
db_query('UPDATE {patterns} SET pattern = "%s", title = "%s", file = "%s", description = "%s" WHERE pid = %d', serialize($pattern), $title, $path, $description, $pid);
}
}
else {
db_query('INSERT INTO {patterns} (name, status, file, updated, enabled, title, description, pattern) VALUES ( "%s", 0, "%s", "%s", 0, "%s", "%s", "%s")', $name, $path, time(), $title, $description, serialize($pattern));
}
}
function patterns_get_pattern($id) {
if (is_numeric($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE pid = "%d"', $id));
}
else if (is_string($id)) {
$pattern = db_fetch_object(db_query('SELECT * FROM {patterns} WHERE name = "%s"', $id));
}
if (!$pattern) return FALSE;
// Get the actual data. Data is stored in serialized form in the db.
$pattern->pattern = unserialize($pattern->pattern);
return $pattern;
}
/**
* Check if pattern array contains only allowed keys
*
* @param $pattern
* pattern array obtained by parsing pattern file
* @return
* TRUE when only allowed array keys are found, FALSE otherwise
*
* @todo expand this function to include much more detailed validation
*/
function patterns_validate_pattern($pattern) {
if (empty($pattern)) {
return FALSE;
}
$allowed_keys = array('info', 'modules', 'actions');
$diff = array_diff(array_keys($pattern), $allowed_keys);
return empty($diff) ? TRUE : FALSE;
}
/**
* Return file extensions supported by patterns module
*
* @return array of supported file types
*
* @todo convert this into pluggable system
*/
function patterns_file_types() {
$result = array('xml', 'php');
if (file_exists(drupal_get_path('module', 'patterns') .'/spyc/spyc.php')) {
$result[] = 'yaml';
}
return $result;
}
function patterns_load_yaml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
include_once 'spyc/spyc.php';
$pattern = Spyc::YAMLLoad($path);
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
function patterns_load_string_yaml($source) {
// loading yaml from source doesn't preserve line breaks
// so we need to save it as a file first
$path = file_directory_temp() .'/import.yaml';
file_save_data($source, $path, FILE_EXISTS_REPLACE);
$pattern = patterns_load_yaml($path);
unlink($path);
return $pattern;
}
function patterns_load_xml($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
if (!$xml = file_get_contents($path)) {
return FALSE;
}
return patterns_load_string_xml($xml);
}
function patterns_load_string_xml($source) {
$pattern = patterns_from_source($source);
if (empty($pattern) || $pattern['tag'] != 'pattern') {
return FALSE;
}
// Rearrange the data in a nice way for each component.
// Make sure actions are processed differently so order is preserved.
$pattern = patterns_rearrange_data($pattern);
foreach($pattern as $key => $values) {
$pattern[$values['tag']] = $values;
unset($pattern[$values['tag']]['tag']);
unset($pattern[$key]);
}
if (!patterns_validate_pattern($pattern)) {
return FALSE;
}
return $pattern;
}
/**
* Read and evaluate a php file to return a 'pattern'
*/
function patterns_load_php($path, $local = TRUE) {
if ($local && !file_exists($path)) {
return FALSE;
}
$pattern = array();
@include($path);
// That should have declared a 'pattern' into current scope.
if (!patterns_validate_pattern($pattern)) {
trigger_error("Failed to evaluate a useful pattern from the input file $path. Pattern did not validate. May have been invalid syntax. ", E_USER_WARNING);
return FALSE;
}
return $pattern;
}
/**
* Create a pattern from an XML data source
*/
function patterns_from_source($xml) {
$parse = drupal_xml_parser_create($xml);
if (!xml_parse_into_struct($parse, $xml, $vals, $index)) {
return false;
}
// Create a multi-dimensional array representing the XML structure
$pattern = current(_patterns_parse_tag($vals));
return $pattern;
}
/**
* Recurse through the values of a parsed xml file to create a
* multi-dimensional representation of the data.
*/
function _patterns_parse_tag($data, &$index = 0) {
$pattern = array();
while (isset($data[$index]) && ($current = $data[$index])) {
$type = $current['type'];
if (isset($current['attributes'])) {
foreach((array)$current['attributes'] as $key => $value) {
$current[strtolower($key)] = $value;
}
}
$current['tag'] = strtolower($current['tag']);
unset($current['type'], $current['level'], $current['attributes']);
if (isset($current['value']) && !trim($current['value']) && $current['value'] != "0") {
unset($current['value']);
}
switch($type) {
case 'open':
$index++;
$current += _patterns_parse_tag($data, $index);
$pattern[] = $current;
break;
case 'close':
$index++;
return $pattern;
break;
case 'complete':
// In order to support more complex/non-standard features we can use serialized data
if (isset($current['attributes']) && $current['attributes']['serialized']) {
$value = unserialize($current['value']);
if (isset($value)) {
$current['value'] = $value;
}
}
// If no value was specified, make sure an empty value is there
if (!isset($current['value'])) {
$current['value'] = '';
}
$pattern[] = $current;
break;
}
$index++;
}
return $pattern;
}
// function patterns_disable_pattern($pid) {
// $form['pid'] = array(
// '#type' => 'value',
// '#value' => $pid
// );
//
// $pattern = patterns_get_pattern($pid);
//
// return confirm_form($form, t('Proceed with disabling pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', '');
// }
function patterns_enable_pattern(&$form_state, $pid) {
$form['pid'] = array(
'#type' => 'value',
'#value' => $pid
);
$options = array(
'first-update' => t('only if disabled or if updated since last run (recommended)'),
'always' => t('always'),
'update' => t('only if updated since last run'),
'first' => t('only if disabled'),
'never' => t("don't run sub-patterns at all"),
);
$form['run-subpatterns'] = array(
'#type' => 'radios',
'#title' => t('Run sub-patterns:'),
'#description' => t("Decide when to run sub-patterns that are called by the currently run pattern. If unsure, stick to recommended setting. Note that your choice won't have any effect if your pattern doesn't contain sub-patterns or if this setting has been defined within the pattern file itself."),
'#options' => $options,
'#default_value' => 'first-update',
);
$disclaimer = t('Please be sure to backup your site before running a pattern. Patterns are not guaranteed to be reversable in case they do not execute well or if unforseen side effects occur.');
$pattern = patterns_get_pattern($pid);
return confirm_form($form, t('Proceed with running pattern %pattern?', array('%pattern' => $pattern->title)), 'admin/build/patterns', $disclaimer);
}
// function patterns_disable_pattern_submit($form_id, $form_values) {
// $pid = $form_values['pid'];
// $pattern = patterns_get_pattern($pid);
//
// if (patterns_execute_pattern($pattern, true, true)) {
// return 'admin/build/patterns';
// }
// }
function patterns_enable_pattern_submit($form, &$form_state) {
$pid = $form_state['values']['pid'];
patterns_load_components();
$pattern = patterns_get_pattern($pid);
patterns_execute_pattern($pattern, $form_state['values']);
$form_state['redirect'] = 'admin/build/patterns';
}
/**
* Execute default configuration for module during the module installation
*
* This function should be called by other modules from
* within their hook_enable() implementation.
* Module should also provide modulename.config file containing PHP array
* with the actions that need to be executed.
*
* @param $module
* name of the module calling the function
*/
function patterns_execute_config($module) {
// since this function is called from hook_enable(), we need to ensure that
// it's executed only at module installation (first time module is enabled)
if (drupal_get_installed_schema_version($module) == SCHEMA_INSTALLED) return;
$path = drupal_get_path('module', $module) .'/'. $module .'.config';
if (file_exists($path)) {
include_once($path);
if (empty($actions)) return;
$pattern = new stdClass();
$pattern->title = t('Default configuration for @module module', array('@module' => $module));
$pattern->status = false;
$pattern->pattern['actions'] = $actions;
patterns_execute_pattern($pattern);
}
}
function patterns_execute_pattern($pattern, $params = array(), $mode = 'batch') {
$args = array($pattern, $params);
$function = 'patterns_execute_pattern_'. $mode;
if (!function_exists($function) || !is_object($pattern)) return FALSE;
return call_user_func_array($function, $args);
}
function patterns_execute_pattern_batch($pattern, $params = array()) {
set_time_limit(0);
if (!is_object($pattern)) {
$pattern = patterns_get_pattern($pattern);
if (!$pattern) {
return FALSE;
}
}
$pattern->subpatterns_run_mode = isset($params['run-subpatterns']) ? $params['run-subpatterns'] : FALSE;
$pattern_details = patterns_get_pattern_details($pattern, TRUE);
$modules = $pattern_details['modules'];
$actions = $pattern_details['actions'];
$actions_map = array('patterns' => $pattern_details['info'], 'map' => $pattern_details['actions_map']);
$info = reset($pattern_details['info']);
// If there are no actions or modules, most likely the pattern
// was not created correctly.
if (empty($actions) && empty($modules)) {
drupal_set_message(t('Could not recognize pattern %title, aborting.', array('%title' => $info['title'])), 'error');
return FALSE;
}
$result = patterns_install_modules($modules);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
+ // lets clear the caches here to ensure that newly added modules
+ // and future pattern actions work as expected.
+ module_load_include('inc', 'system', 'system.admin');
+ $form = $form_state = array();
+ system_clear_cache_submit($form, $form_state);
+
+
$result = patterns_prepare_actions($actions, $actions_map);
if (!$result['success']) {
drupal_set_message($result['error_message'], 'error');
return FALSE;
}
$batch = array(
'title' => t('Processing pattern %pattern', array('%pattern' => $info['title'])),
// 'init_message' => t('Running action @current out of @total', array('@current' => 1, '@total' => count($actions))),
'progress_message' => t('Running action @current out of @total'),
'operations' => array(),
'finished' => 'patterns_batch_finish'
);
for($i=0;$i<count($actions);$i++) {
$batch['operations'][] = array('patterns_batch_actions', array($actions[$i], $i, $actions_map));
}
$_SESSION['patterns_batch_info'] = $pattern_details['info'];
batch_set($batch);
return TRUE;
}
function patterns_install_modules(&$modules) {
$result = array('success' => TRUE);
if (empty($modules)) return $result;
$missing = patterns_check_module_dependencies($modules, TRUE);
if (!empty($missing)) {
$result['success'] = FALSE;
$result['error_message'] = t('Following required modules are missing: %modules', array('%modules' => implode(', ', $missing)));
$result['missing_modules'] = $missing;
return $result;
}
require_once './includes/install.inc';
drupal_install_modules($modules);
module_rebuild_cache();
$result['installed_modules'] = $modules;
return $result;
}
function patterns_locate_action($key, $actions_map) {
$result['key'] = $actions_map['map'][$key]['index'];
$result['title'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['title'];
$result['file'] = $actions_map['patterns'][$actions_map['map'][$key]['pid']]['file'];
return $result;
}
function patterns_prepare_actions(&$actions, $actions_map) {
$result = array('success' => TRUE);
if (empty($actions)) return $result;
patterns_load_components();
// Keep a list of what modules handle what tags
$tag_modules = patterns_invoke($empty, 'tag modules');
// TODO Finish basic setup and execution of the 'config' operation
// TODO Make a better streamlined config framework process. For instance collect form_ids
// from here and give the form_id and matching data to the 'build' process
foreach($actions as $key => &$data) {
if (($config = patterns_invoke($actions[$key], 'config')) && !empty($config)) {
patterns_config_data($data, $config);
}
}
// Prepare actions for validation/processing
foreach($actions as $key => &$data) {
patterns_invoke($actions[$key], 'prepare');
}
$errors = array();
// Pre validate tags with their appropriate components
foreach($actions as $key => &$data) {
$action_location = patterns_locate_action($key, $actions_map);
$index = $action_location['key'];
$pattern_title = $action_location['title'];
// $pattern_file = $action_location['file'];
if (!array_key_exists($data['tag'], $tag_modules)) {
$errors[] = t('Action #%num (%tag) in pattern %title: <%tag> is not a valid tag', array('%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
else {
$error = patterns_invoke($actions[$key], 'pre-validate');
if ($error) {
$errors[] = t('Action #%num (%tag) in pattern %title: !msg', array('!msg' => $error, '%num' => $index+1, '%tag' => $data['tag'], '%title' => $pattern_title));
}
}
}
if (count($errors)) {
$message = t('Errors encountered during pre-processing:') .'<br>'. implode('<br>', $errors);
$result['success'] = FALSE;
$result['error_message'] = $message;
}
return $result;
}
/**
* Execute a batch action
*/
function patterns_batch_actions($action, $place, $actions_map, &$context) {
patterns_load_components();
// Nothing to do if there is no action
if (empty($action)) {
$context['finished'] = 1;
return;
}
// Start a timer. Since we want each action to be its own http request, we need
// to ensure the batch api will decide to do it like that by making each action
// take at least a second to execute
timer_start('patterns_action');
// skip action execution if an error is encountered in some of the previous operations
if (!empty($context['results']['abort'])) return;
$result = patterns_implement_action($action, $context['results']['identifiers'], $place, $actions_map);
if (!$result['success']) {
// we use 'results' to keep track of errors and abort execution if required
$context['results']['abort'] = TRUE;
$context['results']['error_message'] = $result['error_message'];
}
if (timer_read('patterns_action') < 1000) {
@usleep(1000 - timer_read('patterns_action'));
}
}
/**
* Finish a batch operation
*/
function patterns_batch_finish($success, $results, $operations) {
$info = $_SESSION['patterns_batch_info'];
if (!isset($results['abort']) || !($results['abort'])) {
foreach ($info as $key => $i) {
drupal_set_message(t('Pattern "@pattern" ran successfully.', array('@pattern' => $i['title'])));
db_query('UPDATE {patterns} SET status = 1, enabled = "%s" WHERE pid = %d', time(), $key);
}
}
else {
$pattern = reset($info);
drupal_set_message(t('Pattern "@pattern" ran with the errors. Check the error messages to get more details.', array('@pattern' => $pattern['title'])));
drupal_set_message($results['error_message'], 'error');
}
unset($_SESSION['patterns_batch_info']);
drupal_flush_all_caches();
}
/**
* Setup and run an action
*/
function patterns_implement_action($action, &$identifiers, $place = 0, $actions_map = NULL) {
patterns_set_error_handler();
$result = array('success' => TRUE);
// Prepare actions for processing, ensure smooth pattern executions, and return form ids for execution
$return = patterns_invoke($action, 'form_id');
// If prepare removed the data, dont continue with this action
if (!$action || !$return) {
return $result;
}
if (is_string($return)) {
$form_ids = array($return);
}
else if ($return) {
$form_ids = $return;
}
$action_descriptions = patterns_invoke($action, 'actions');
$action_location = patterns_locate_action($place, $actions_map);
$index = $action_location['key'] + 1;
$pattern_title = $action_location['title'];
$pattern_file = $action_location['file'];
// Build the action
foreach($form_ids as $form_id) {
$clone = $action;
$action_description = isset($action_descriptions[$form_id]) ? $action_descriptions[$form_id] : t('System: Execute form');
$result['action_descriptions'][$place][] = $action_description;
// If tokens are enabled, apply tokens to the action values
// before processing
if (module_exists('token')) {
_patterns_recurse_tokens($clone, $identifiers);
//array_walk($clone, '_patterns_replace_tokens', $identifiers);
}
$error = patterns_invoke($clone, 'validate', $form_id);
if ($message = patterns_error_get_last('validate', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($error) {
$message = t('An error occured while validating action #%num (%action) in %title pattern', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title));
$result['error_message'] = $message .'<br>'. $error;
$result['success'] = FALSE;
return $result;
}
// Get the form data for the action. This can either just be the form values,
// or it can be the full form_state object
$form_obj = patterns_invoke($clone, 'build', $form_id);
if ($message = patterns_error_get_last('build', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// Dont execute the action if a string was returned, indicating the pattern component
// most likely handled the action on its own and this is the message to display.
if (is_string($form_obj)) {
drupal_set_message($form_obj);
}
else {
// We check for the 'storage' and 'submitted' values in the object to see
// if it is a form_state instead of form_values. There could be a better way
// to do this.
if (array_key_exists('submitted', (array)$form_obj) && array_key_exists('storage', (array)$form_obj)) {
$action_state = $form_obj;
}
else {
$action_state = array(
'storage' => null,
'submitted' => false,
'values' => $form_obj
);
}
// Get any extra parameters required for the action
$params = patterns_invoke($clone, 'params', $form_id, $action_state);
if ($message = patterns_error_get_last('params', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
// A single, simple value can be returned as a parameter, which is then
// put into an array here.
if (isset($params) && !is_array($params)) {
$params = array($params);
}
// Execute action
patterns_execute_action($form_id, $action_state, $params);
if ($message = patterns_error_get_last('execute', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
if ($errors = form_get_errors()) {
$result['error_message'] = t('Above error(s) occured while executing action #%num (%action) in %title pattern. Error location(s) are: %errors', array('%num' => $index, '%action' => $action_description, '%title' => $pattern_title, '%errors' => str_replace('][', '->', implode(', ', array_keys($errors)))));
$result['success'] = FALSE;
return $result;
}
// Let a component cleanup after each action
patterns_invoke($clone, 'cleanup', $form_id, $action_state);
if ($message = patterns_error_get_last('cleanup', $index, $action_description, $pattern_title, $pattern_file)) {
$result['error_message'] = $message;
$result['success'] = FALSE;
return $result;
}
}
// Clear the cache in case it causes problems
cache_clear_all();
// Rebuild the menu
// TODO Should this go at the end only when a pattern successfully runs?
variable_set('menu_rebuild_needed', true);
}
// Get any primary identifiers from the action for further actions to take advantage of
$id = null;
$id = patterns_invoke($clone, 'identifier', $form_id, $action_state);
if (isset($id)) {
$index = isset($clone['action_label']) ? $clone['action_label'] : $place+1;
$identifiers[$index] = $id;
}
patterns_restore_error_handler();
return $result;
}
/**
* Execute an action
*/
function patterns_execute_action($form_id, &$form_state, $params) {
// Make sure we always have a clear cache for everything
// Beware - this direct database access needs to be db-prefix-safe!
global $db_prefix;
$result = db_query('SHOW TABLES LIKE "{cache}_%"');
while ($table = db_fetch_array($result)) {
// Remove the db prefix if any. cache_clear_all() will put it back again.
$table = substr(current($table), strlen($db_prefix));
cache_clear_all(null, $table);
}
$args = array($form_id, &$form_state);
if (is_array($params)) {
$args = array_merge($args, $params);
}
patterns_executing(true);
// If we are in batch mode, trick the form api to think
// otherwise to avoid potential problems
$batch =& batch_get();
$batch_clone = $batch;
$batch = null;
//$form = call_user_func_array('drupal_retrieve_form', $args);
//$form['#post'] = $values;
//$return = drupal_process_form($form_id, $form);
//dpm($args);
// drupal_execute fails to keep $form_state in-sync through the
// whole FAPI process. Issue http://drupal.org/node/346244
//$return = call_user_func_array('drupal_execute', $args);
// Fix some parts of the #post values based on the original form
patterns_sync_form_values($args);
// Copy of drupal_execute until above issue is fixed
$form = call_user_func_array('drupal_retrieve_form', $args);
$form['#post'] = $form_state['values'];
drupal_prepare_form($form_id, $form, $form_state);
// If you call drupal_validate_form() on the same form more
// than once per page request, validation is not performed
// on any but the first call.
// see issue: http://drupal.org/node/260934
// drupal_process_form($form_id, $form, $form_state);
// Until above issue is fixed we use our own implementation
// of drupal_process_form() and drupal_validate_form().
_patterns_process_form($form_id, $form, $form_state);
patterns_executing(false);
$batch = $batch_clone;
return $return;
}
function patterns_executing($b = null) {
static $executing = false;
if (is_bool($b)) {
$executing = $b;
}
return $executing;
}
function patterns_rearrange_data($pattern) {
foreach($pattern as $key => $value) {
if (is_string($key)) {
unset($pattern[$key]);
}
else {
if ($value['tag'] == 'actions') {
$pattern[$key] = patterns_rearrange_data($value);
$pattern[$key]['tag'] = 'actions';
}
else {
$pattern[$key] = _patterns_rearrange_data($value);
}
}
}
return $pattern;
}
/**
* Return an array with detailed information about the pattern
*/
function patterns_get_pattern_details($pattern, $recursive = FALSE, &$pids = array()) {
// prevent infinite recursion
if (in_array($pattern->pid, $pids)) return array();
$pids[$pattern->pid] = $pattern->pid;
$actions = !empty($pattern->pattern['actions']) ? $pattern->pattern['actions'] : array();
$modules = !empty($pattern->pattern['modules']) ? $pattern->pattern['modules'] : array();
$patterns[$pattern->pid] = (array)$pattern;
$patterns[$pattern->pid] = array_merge($patterns[$pattern->pid], $patterns[$pattern->pid]['pattern']['info']);
unset($patterns[$pattern->pid]['pattern']);
if ($recursive) {
$result = array('modules' => $modules, 'info' => $patterns);
foreach($actions as $key => $action) {
if ($action['tag'] == 'pattern') {
// determine pattern name
if (!empty($action['value'])) {
$name = $action['value'];
}
elseif (!empty($action['name'])) {
$name = $action['name'];
}
if (!$p = patterns_get_pattern($name)) {
// just give a warning and try to continue
drupal_set_message(t('Action #%key in %file: Pattern %pattern not found.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// Decide if sub-pattern needs to be run based on the mode defined within the pattern or selected in UI at the time of form submission
// @TODO: UI setting should be able to override a setting defined within the pattern
$modes = array('first-update', 'always', 'update', 'first', 'never');
if (!empty($action['run']) && in_array($action['run'], $modes)) {
$mode = $action['run'];
}
else {
$mode = $pattern->subpatterns_run_mode;
}
switch ($mode) {
case 'never':
// don't run sub-pattern
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to be skipped.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
break;
case 'first':
// Only run on first run
if ($p->status) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on the first run.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'update':
// Only run on pattern update
if ($p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on pattern update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'first-update':
// Only run on first run or pattern update
if ($p->status && $p->enabled >= $p->updated) {
drupal_set_message(t('Action #%key in %file: Pattern %pattern not ran because the pattern was set to execute only on first run or update.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'status');
continue 2;
}
break;
case 'always':
default:
// Run always
break;
}
$a = patterns_get_pattern_details($p, TRUE, $pids);
if (is_array($a) && empty($a)) {
// An empty array is returned on infinite recursion detection
drupal_set_message(t('Action #%key in %file: Infinite recursion detected while attempting to run pattern %pattern.<br>Pattern execution will try to continue without it.', array('%key' => $key+1, '%file' => $pattern->title, '%pattern' => $name)), 'warning');
continue;
}
// array_merge doesn't preserve numeric array keys
// so we handle 'info' separately
$info = $result['info'];
$result = array_merge_recursive($result, $a);
$result['info'] = $info + $a['info'];
}
else {
$result['actions'][] = $action;
$result['actions_map'][] = array(
'pid' => $pattern->pid,
'index' => $key,
);
}
}
$result['modules'] = array_merge(array_unique($result['modules']));
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return $result;
}
// Remove pid from recursion stack
//unset($pids[$pattern->pid]);
return array('actions' => $actions, 'modules' => $modules, 'info' => $patterns);
}
//function patterns_process_modules($modules, $op = 'enable') {
// // Enable at the beginning of the pattern. Disable at the end.
// for($i=0;$module=$modules[$i];$i++) {
|
hiddentao/patterns2
|
2b7edcf732242e0b2c9f0f4234a4160b87dd76e8
|
Reverted filter.inc
|
diff --git a/components/filter.inc b/components/filter.inc
index 0346ec7..bd34a95 100644
--- a/components/filter.inc
+++ b/components/filter.inc
@@ -1,133 +1,145 @@
<?php
/**
* Component for updating filters.
- * @author Ramesh Nair
*/
-require_once('_common.php');
-
-
function filter_patterns($op, $id = null, &$data = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('format');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
'filter_admin_format_form' => t('Filter: Add/configure input format'),
);
break;
// Return a summary of an action
case 'summary':
if ('filter_admin_format_form' == $id) {
return t('Configuring input filter: %name', array('%name' => $data['name']));
}
break;
// Prepare data for processing
case 'prepare':
$formats = filter_formats();
if (isset($data['id']) && isset($formats[$data['id']])) {
$data['format_obj'] = $formats[$data['id']];
if (!isset($data['name']))
$data['name'] = $data['format_obj']->name;
$data['format'] = $data['id'];
} else if (isset($data['name'])) {
foreach ($formats as $id => $format) {
if ($data['name'] == $format->name) {
$data['format_obj'] = $format;
$data['format'] = $id;
break;
}
}
}
break;
// Pre validate actions
case 'pre-validate':
if (!isset($data['format']) && !isset($data['name'])) {
return t('Valid filter "name" or "id" is required.');
}
break;
// Return the form_id('s) for each action
case 'form_id':
return 'filter_admin_format_form';
break;
// Prepare for valid processing of this type of component
case 'build':
if ('filter_admin_format_form' == $id) {
module_load_include('inc', 'filter', 'filter.admin');
- _pattern_component_replace_role_names_with_ids($data);
+ if (!empty($data['roles']) && is_array($data['roles'])) {
+ $all_roles = array_flip(user_roles());
+ $role_ids = array();
+ foreach ($data['roles'] as $role_name) {
+ $role_ids[$all_roles[$role_name]] = 1;
+ }
+ $data['roles'] = $role_ids;
+ }
if (!empty($data['filters']) && is_array($data['filters'])) {
$filters_all = filter_list_all();
$filters_ids = array();
foreach ($filters_all as $id => $f) {
$filters_ids[$f->name] = $id;
}
$enabled_filters = array();
foreach ($data['filters'] as $filter) {
$enabled_filters[$filters_ids[$filter]] = 1;
}
$data['filters'] = $enabled_filters;
}
}
return $data;
break;
// Validate the values for an action before running the pattern
//
// Check here rather than in pre-validate in case we're adding
// roles or filters in the same pattern.
//
case 'validate':
-
- if (TRUE !== ($ret = _pattern_component_validate_role_names($data))) {
- return $ret;
- }
-
+ // check roles
+ if (!empty($data['roles']) && is_array($data['roles'])) {
+ $role_ids = array_flip(user_roles());
+ $bad_roles = array();
+ foreach ($data['roles'] as $role) {
+ if (!isset($role_ids[$role])) {
+ $bad_roles[] = $role;
+ }
+ }
+ if (!empty($bad_roles)) {
+ return t('Invalid role names: %roles', array('%roles' => implode(', ',$bad_roles)));
+ }
+ }
+
// check filters
if (!empty($data['filters']) && is_array($data['roles'])) {
$filters_all = filter_list_all();
$filters_ids = array();
foreach ($filters_all as $id => $f) {
$filters_ids[$f->name] = $id;
}
$bad_filters = array();
foreach ($data['filters'] as $filter) {
if (!isset($filters_ids[$filter])) {
$bad_filters[] = $filter;
}
}
if (!empty($bad_filters)) {
return t('Invalid filter names: %filters', array('%filters' => implode(', ',$bad_filters)));
}
}
break;
// Build a patterns actions and parameters
case 'params':
$params = array();
if ('filter_admin_format_form' == $id) {
$params['format'] = isset($data['format_obj']) ? $data['format_obj'] : NULL;
unset($data['format_obj']);
}
return $params;
break;
// Cleanup any global settings or check created data
case 'cleanup':
break;
}
}
|
hiddentao/patterns2
|
51211cc1a99dd1c57a05d716d4ce63f86c6a7e15
|
Added missing code line to node.inc
|
diff --git a/components/node.inc b/components/node.inc
index 39cd1f4..2bc740b 100644
--- a/components/node.inc
+++ b/components/node.inc
@@ -1,410 +1,412 @@
<?php
+require_once('_common.php');
+
function node_patterns($op, $id = null, &$data = null, $a = null) {
switch($op) {
// Return the valid tags that this component can prepare and process
case 'tags':
return array('node');
break;
// Return a list of forms/actions this component can handle
case 'actions':
return array(
$data['type'] .'_node_form' => t('Node: Create/update content.'),
'node_delete_confirm' => t('Node: Delete content.'),
);
break;
// Return a summary of an action
case 'summary':
$variables = array(
'%type' => $data['type'],
'%title' => $data['title'],
);
if (empty($data['nid'])) {
return t('Create %type: "%title"', $variables);
}
elseif ($data['delete']) {
return t('Delete %type: "%title"', $variables);
}
else {
return t('Update %type: "%title"', $variables);
}
break;
// Prepare data for processing
case 'prepare':
global $user;
if (empty($data['nid']) && !empty($data['id'])) {
$data['nid'] = $data['id'];
}
unset($data['id']);
if (empty($data['name']) && !empty($data['author'])) {
$data['name'] = $data['author'];
}
unset($data['author']);
if (empty($data['uid'])) $data['uid'] = $user->uid;
if (empty($data['name'])) $data['name'] = $user->name;
if (is_numeric($data['nid']) && $data['node'] = node_load($data['nid'])) {
$data['update'] = TRUE;
}
else {
unset($data['nid']);
unset($data['vid']);
$data['node'] = (object) $data;
$data['update'] = FALSE;
}
break;
// Pre validate actions
case 'pre-validate':
if (empty($data['type']) && !$data['delete']) {
return t('"type" field is required.');
}
if ($data['delete'] && empty($data['nid'])) {
return t('"id" field is required.');
}
if ($data['update'] && $data['type'] != $data['node']->type) {
return t("You can't change content type for already existing node.");
}
break;
// Return the form_id('s) for each action
case 'form_id':
if ($data['delete']) {
return 'node_delete_confirm';
}
else {
return $data['type'] .'_node_form';
}
break;
// Prepare for valid processing of this type of component
case 'build':
_pattern_component_replace_format_name_with_id($data);
module_load_include('inc', 'node', 'node.pages');
if ($id == 'node_delete_confirm') {
$data['confirm'] = 1;
return $data;
}
$data['changed'] = time();
$data['op'] = t('Save');
$node = drupal_clone($data['node']);
if (module_exists('content')) {
// build CCK fields
$type = $data['type'];
$form_id = $type .'_node_form';
$form_state = array();
$form = drupal_retrieve_form($form_id, $form_state, $node);
drupal_prepare_form($form_id, $form, $form_state);
$content_type = content_types($type);
$fields_info = $content_type['fields'];
if (module_exists('fieldgroup')) {
$groups = fieldgroup_groups($type, FALSE, TRUE);
}
// TODO: make this work for PHP4
$fields = array();
$fields_diff = array();
if (!empty($groups)) {
foreach($groups as $key => $group) {
$fields = array_merge($fields, array_intersect_ukey($form[$key], $group['fields'], '_patterns_compare_keys'));
}
$fields_diff = array_diff_ukey($fields_info, $fields, '_patterns_compare_keys');
$fields = array_merge($fields, array_intersect_ukey($form, $fields_diff, '_patterns_compare_keys'));
}
else {
$fields = array_merge($fields, array_intersect_ukey($form, $fields_info, '_patterns_compare_keys'));
}
if (!empty($fields)) {
$defaults = array();
foreach($fields as $field_name => $field) {
$alias = str_replace('field_', '', $field_name);
if (isset($field['#default_value']) && !isset($field[0])) {
$col = $field['#columns'][0];
// prepare default value
if (is_numeric($field['#default_value']) || is_string($field['#default_value'])) {
$default = $field['#default_value'];
}
elseif (empty($field['#default_value'])) {
$default = NULL;
}
else {
$default = array();
foreach ($field['#default_value'] as $value) {
foreach ($value as $key => $val) {
if (empty($default[$key])) {
$default[$key] = array();
}
$v = array($val => $val);
$default[$key] = $default[$key] + $v;
}
}
}
// fix for non-standard format of nodereference and userreference fields
if (preg_match('/^(nodereference|userreference)/', $field['#type'])) {
$defaults[$field_name][$col][$col] = _patterns_get_field_value($data['fields'][$alias], $col, $default[$col]);
}
else {
$defaults[$field_name][$col] = _patterns_get_field_value($data['fields'][$alias], $col, $default[$col]);
}
}
else {
// prepare field value provided by pattern
if (!isset($data['fields'][$alias])) {
$data['fields'][$alias] = array(0 => NULL);
}
elseif (is_array($data['fields'][$alias]) && !isset($data['fields'][$alias][0])) {
$data['fields'][$alias] = array(0 => $data['fields'][$alias]);
}
elseif (is_string($data['fields'][$alias])) {
$data['fields'][$alias] = array(0 => array('value' =>$data['fields'][$alias]));
}
// get the number of fields defined by CCK module
$field_count = 0;
while (isset($field[$field_count])) {
$field_count++;
}
// CCK always provides one additional empty field for multiple values fields so we remove it
$field_count = $field_count > 1 ? $field_count -1 : $field_count;
$count = $field_count < count($data['fields'][$alias]) ? count($data['fields'][$alias]) : $field_count;
$i = 0;
while ($i < $count) {
// column names are same for all the fields so we use $field[0]['#columns'] always
// because $field[$i] may not exist in the case when number of fields defined by pattern
// is greater then number of fields defined by CCK
foreach ($field[0]['#columns'] as $col) {
if (isset($field[$i][$col])) {
$value = _patterns_get_field_value($data['fields'][$alias][$i], $col, $field[$i][$col]['#default_value']);
$defaults[$field_name][$i][$col] = array($col => $value);
}
else {
$default = isset($field[$i]['#default_value'][$col]) ? $field[$i]['#default_value'][$col] : NULL;
// fix for non-standard implementation of viewfield module
if (preg_match('/^(viewfield)/', $field[$i]['#type'])) {
$defaults[$field_name][$i]['fieldset'][$col] = _patterns_get_field_value($data['fields'][$alias][$i], $col, $default);
}
else {
$defaults[$field_name][$i][$col] = _patterns_get_field_value($data['fields'][$alias][$i], $col, $default);
}
}
}
$i++;
}
}
}
$data = $data + $defaults;
}
}
// build taxonomy array
$vocabularies = taxonomy_get_vocabularies($data['type']);
$vocabs = array();
// we assume that all the vocabularies have unique names
foreach ($vocabularies as $v) {
$vocabs[$v->name] = $v;
}
$new_taxonomy = array();
// PHP array produced by XML parser when single vocabulary
// is defined in the pattern differs from the one produced
// when mutiple vocabs are defined.
// We need to convert single vocab array to the array
// structure for multiple vocabs.
if (isset($data['taxonomy']['vocabulary'])) {
$data['taxonomy'] = array(0 => $data['taxonomy']);
}
if (!empty($data['taxonomy']) && is_array($data['taxonomy'])) {
foreach ($data['taxonomy'] as $key => $v) {
if (!isset($vocabs[$v['vocabulary']])) continue;
$vocabulary = $vocabs[$v['vocabulary']];
unset($data['taxonomy'][$key]['vocabulary']);
$terms = $data['taxonomy'][$key];
if (!is_array($terms)) continue;
if ($vocabulary->tags) {
$new_taxonomy['tags'][$vocabulary->vid] = reset($terms);
}
else {
// get tids for all term names
$tids = array();
foreach($terms as $name) {
if (!is_string($name)) continue;
$term = taxonomy_get_term_by_name($name);
// take the first term that belongs to given vocabulary
foreach ($term as $t) {
if ($t->vid == $vocabulary->vid) {
$tids[$t->tid] = $t->tid;
break;
}
}
}
$new_taxonomy[$vocabulary->vid] = $vocabulary->multiple ? $tids : (empty($tids) ? '' : reset($tids));
}
}
}
if (!$data['update'] || ($data['update'] && $data['taxonomy_overwrite'])) {
if (empty($new_taxonomy)) {
unset($data['taxonomy']);
}
else {
$data['taxonomy'] = $new_taxonomy;
}
}
else {
$taxonomy = array();
$defaults = array();
foreach ($form['taxonomy'] as $vid => $terms) {
if (!is_numeric($vid)) continue;
$tids = array();
foreach ($terms['#default_value'] as $tid) {
$tids[$tid] = $tid;
}
$empty = $terms['#multiple'] ? array() : '';
$default = $terms['#multiple'] ? $tids : reset($tids);
if (empty($tids)) {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $empty : $new_taxonomy[$vid];
}
else {
if ($terms['#multiple']) {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $default : $new_taxonomy[$vid] + $default;
}
else {
$taxonomy[$vid] = empty($new_taxonomy[$vid]) ? $default : $new_taxonomy[$vid];
}
}
}
if (!empty($form['taxonomy']['tags'])) {
foreach ($form['taxonomy']['tags'] as $vid => $tags) {
$defaults['tags'][$vid] = $tags['#default_value'];
if (!empty($new_taxonomy['tags'][$vid])) {
$taxonomy['tags'][$vid] = !empty($defaults['tags'][$vid]) ? $defaults['tags'][$vid] .','. $new_taxonomy['tags'][$vid] : $new_taxonomy['tags'][$vid];
}
else {
$taxonomy['tags'][$vid] = $defaults['tags'][$vid];
}
}
}
$data['taxonomy'] = $taxonomy;
}
unset($data['fields']);
unset($data['node']);
unset($data['taxonomy_overwrite']);
$node->taxonomy = array();
if ($data['update']) $data = array_merge((array)$node, $data);
// // required for proper functioning of pathauto module
// static $old_q;
// $old_q = $_GET['q'];
// if ($data['update']) {
// $_GET['q'] = 'node/'. $data['nid'] .'/edit';
// }
// else {
// $_GET['q'] = 'node/add/'. str_replace('_', '-', $data['type']);
// }
unset($data['update']);
// Until manual path setting is fixed,
// unset all path related elements to prevent
// potential database errors.
unset($data['path']);
unset($data['pid']);
unset($data['old_alias']);
unset($data['pathauto_perform_alias']);
return $data;
break;
// Validate the values for an action before running the pattern
case 'validate':
if (TRUE !== ($ret = _pattern_component_validate_format($data))) {
return $ret;
}
// TODO: validate name field - should be valid/existing username
if (!node_get_types('types', $data['type'], TRUE) && !$data['delete']) {
return t('Invalid content type: %type', array('%type' => $data['type']));
}
break;
// Build a patterns actions and parameters
case 'params':
return array((object) $data);
break;
// Cleanup any global settings after the action runs
case 'cleanup':
// static $old_q;
// if ($old_q) {
// $_GET['q'] = $old_q;
// unset($old_q);
// }
break;
// Return the primary ID if possible from this action
case 'identifier':
$form_state = $a;
if (!empty($form_state['nid']) && is_numeric($form_state['nid'])) {
return $form_state['nid'];
}
break;
}
}
function _patterns_compare_keys($key1, $key2) {
if ($key1 == $key2)
return 0;
elseif ($key1 > $key2)
return 1;
else
return -1;
}
function _patterns_get_field_value($field, $key, $default) {
if (is_array($field)) {
return isset($field[$key]) ? $field[$key] : $default;
}
elseif (is_numeric($field) || is_string($field)) {
return $field;
}
else {
return $default;
}
}
|
hiddentao/patterns2
|
da03c8f509f8fa0a43286b2b2435fd4265963e80
|
github generated gh-pages branch
|
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..8b69286
--- /dev/null
+++ b/index.html
@@ -0,0 +1,88 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+
+<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
+
+ <title>hiddentao/patterns2 @ GitHub</title>
+
+ <style type="text/css">
+ body {
+ margin-top: 1.0em;
+ background-color: #ffffff;
+ font-family: "Helvetica,Arial,FreeSans";
+ color: #000000;
+ }
+ #container {
+ margin: 0 auto;
+ width: 700px;
+ }
+ h1 { font-size: 3.8em; color: #000000; margin-bottom: 3px; }
+ h1 .small { font-size: 0.4em; }
+ h1 a { text-decoration: none }
+ h2 { font-size: 1.5em; color: #000000; }
+ h3 { text-align: center; color: #000000; }
+ a { color: #000000; }
+ .description { font-size: 1.2em; margin-bottom: 30px; margin-top: 30px; font-style: italic;}
+ .download { float: right; }
+ pre { background: #000; color: #fff; padding: 15px;}
+ hr { border: 0; width: 80%; border-bottom: 1px solid #aaa}
+ .footer { text-align:center; padding-top:30px; font-style: italic; }
+ </style>
+
+</head>
+
+<body>
+ <a href="http://github.com/hiddentao/patterns2"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub" /></a>
+
+ <div id="container">
+
+ <div class="download">
+ <a href="http://github.com/hiddentao/patterns2/zipball/master">
+ <img border="0" width="90" src="http://github.com/images/modules/download/zip.png"></a>
+ <a href="http://github.com/hiddentao/patterns2/tarball/master">
+ <img border="0" width="90" src="http://github.com/images/modules/download/tar.png"></a>
+ </div>
+
+ <h1><a href="http://github.com/hiddentao/patterns2">Patterns2</a>
+ <span class="small">by <a href="http://github.com/hiddentao">hiddentao</a></span></h1>
+
+ <div class="description">
+ An improved version of the Drupal Patterns module.
+ </div>
+
+ <p>This incorporates a number of patches submitted to the original module version 6.x-1.x-dev (see http://drupal.org/project/issues/patterns?categories=All) as well as further improvements.
+
+The motivation for creating this repository is to track all the new improvements being made to the module via Git (better than tracking through the patches submitted) and to (hopefully!) encourage the original module authors to roll the changes in this fork back into the original module.</p><h2>Dependencies</h2>
+<p>Drupal 6, PHP 5.1, Token module (http://drupal.org/project/token).</p>
+<h2>Install</h2>
+<p>Simply overwrite your patterns module folder with this one.</p>
+<h2>License</h2>
+<p>GPLv2</p>
+<h2>Authors</h2>
+<p>Ramesh Nair</p>
+<h2>Contact</h2>
+<p> ([email protected])
<br/> </p>
+
+
+ <h2>Download</h2>
+ <p>
+ You can download this project in either
+ <a href="http://github.com/hiddentao/patterns2/zipball/master">zip</a> or
+ <a href="http://github.com/hiddentao/patterns2/tarball/master">tar</a> formats.
+ </p>
+ <p>You can also clone the project with <a href="http://git-scm.com">Git</a>
+ by running:
+ <pre>$ git clone git://github.com/hiddentao/patterns2</pre>
+ </p>
+
+ <div class="footer">
+ get the source code on GitHub : <a href="http://github.com/hiddentao/patterns2">hiddentao/patterns2</a>
+ </div>
+
+ </div>
+
+
+</body>
+</html>
|
sbma44/artomatic
|
639b737e84f32915af9fec7bf09301d3aeed7cc7
|
better logging capabilities (non-volatile location, defined in settings)
|
diff --git a/bellserver/bellserver.py b/bellserver/bellserver.py
index 3bce2df..ee222b9 100644
--- a/bellserver/bellserver.py
+++ b/bellserver/bellserver.py
@@ -1,176 +1,186 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
import os
import serial
import time
import settings
import SocketServer
def log(message):
- f = open('/var/log/bellserver.log', 'a')
- f.write("%f - %s\n" % (time.time(), message))
- f.close()
+ line = "%f - %s\n" % (time.time(), message)
+
+ filename = getattr(settings,'LOG',False)
+ if filename:
+ try:
+ f = open(filename, 'a')
+ f.write(line)
+ f.close()
+ except Exception, e:
+ filename = False
+
+ if not filename:
+ print line
class SerialHolder(object):
SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
super(SerialHolder, self).__init__()
# create a serial connection
log("Establishing serial connection")
self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
# clear serial backlog
waiting = self.serial_connection.inWaiting()
self.serial_connection.read(waiting)
def strike_bell(self):
self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
log("Struck bell")
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
char = ''
try:
waiting = self.serial_connection.inWaiting()
if waiting>0:
char = self.serial_connection.read(waiting)
except Exception, e:
pass
if len(char.strip())>0:
log("Detected serial communication - %s" % (char))
return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
return False
def close(self):
self.serial_connection.close()
class SocketServerWrapper(SocketServer.TCPServer):
"""docstring for SocketServerWrapper"""
def __init__(self, *args):
log("Starting server")
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,*args)
class BellServer(SocketServer.StreamRequestHandler):
NETWORK_BELL_STRIKE_SIGNAL = 'DING'
NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
log("Striking bell")
global serialholder
if serialholder is not None:
serialholder.strike_bell()
def handle(self):
data = self.rfile.readline().strip()
log("Received data %s" % data)
if data==self.NETWORK_BELL_STRIKE_SIGNAL:
self.strike_bell()
self.wfile.write(self.NETWORK_BELL_STRIKE_CONFIRMATION)
class BellClient(object):
"""
Monitors the serial port for strikes and sends network messages when they're found
"""
def __init__(self):
log("Starting client")
super(BellClient, self).__init__()
self.RECIPIENTS = settings.RECIPIENTS
self.PORT = settings.PORT
self.NETWORK_BELL_STRIKE_SIGNAL = 'DING'
self.NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
global serialholder
if serialholder is not None:
return serialholder.bell_strike_detected()
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
log("Transmitting bell strike to %d recipient(s)" % len(self.RECIPIENTS))
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(1)
try:
s.connect((recipient, self.PORT))
s.send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
data = ''
try:
data = s.recv(1024)
except Exception, e:
pass
s.close()
if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
log("Successfully sent bell strike to %s" % recipient)
else:
log("Unable to confirm bell strike to %s (network timeout?)" % recipient)
except Exception, e:
log("Tried to send bell strike to %s but failed" % recipient)
def listen(self):
while True:
# check serial input for bell strike notification
strikes_in_waiting = self.bell_strike_detected()
if strikes_in_waiting is not False:
log("Heard at least one strike")
for i in range(0, strikes_in_waiting):
self.transmit_bell_strike()
time.sleep(0.01)
def close(self):
global serialholder
if serialholder is not None:
serialholder.close()
global serialholder
serialholder = SerialHolder()
if __name__ == '__main__':
if os.fork():
server = SocketServerWrapper( (settings.HOST, settings.PORT), BellServer)
server.serve_forever()
else:
client = BellClient()
try:
client.listen()
finally:
client.close()
\ No newline at end of file
diff --git a/bellserver/settings.py b/bellserver/settings.py
index ebdb46b..6695492 100644
--- a/bellserver/settings.py
+++ b/bellserver/settings.py
@@ -1,5 +1,6 @@
HOST = ''
RECIPIENTS = ['192.168.11.1']
PORT = 50008
SERIAL_PORT = '/dev/ttyS0'
BAUD_RATE = 9600
+LOG = '/root/bellserver/bellserver.log'
|
sbma44/artomatic
|
3e3711593a6a89b5e977a0a2c762eeeaca530fa8
|
moving missing libraries into more descriptive folder
|
diff --git a/openwrt/missing_libraries/SocketServer.py b/openwrt/missing_libraries/SocketServer.py
new file mode 100644
index 0000000..3a74c44
--- /dev/null
+++ b/openwrt/missing_libraries/SocketServer.py
@@ -0,0 +1,587 @@
+"""Generic socket server classes.
+
+This module tries to capture the various aspects of defining a server:
+
+For socket-based servers:
+
+- address family:
+ - AF_INET{,6}: IP (Internet Protocol) sockets (default)
+ - AF_UNIX: Unix domain sockets
+ - others, e.g. AF_DECNET are conceivable (see <socket.h>
+- socket type:
+ - SOCK_STREAM (reliable stream, e.g. TCP)
+ - SOCK_DGRAM (datagrams, e.g. UDP)
+
+For request-based servers (including socket-based):
+
+- client address verification before further looking at the request
+ (This is actually a hook for any processing that needs to look
+ at the request before anything else, e.g. logging)
+- how to handle multiple requests:
+ - synchronous (one request is handled at a time)
+ - forking (each request is handled by a new process)
+ - threading (each request is handled by a new thread)
+
+The classes in this module favor the server type that is simplest to
+write: a synchronous TCP/IP server. This is bad class design, but
+save some typing. (There's also the issue that a deep class hierarchy
+slows down method lookups.)
+
+There are five classes in an inheritance diagram, four of which represent
+synchronous servers of four types:
+
+ +------------+
+ | BaseServer |
+ +------------+
+ |
+ v
+ +-----------+ +------------------+
+ | TCPServer |------->| UnixStreamServer |
+ +-----------+ +------------------+
+ |
+ v
+ +-----------+ +--------------------+
+ | UDPServer |------->| UnixDatagramServer |
+ +-----------+ +--------------------+
+
+Note that UnixDatagramServer derives from UDPServer, not from
+UnixStreamServer -- the only difference between an IP and a Unix
+stream server is the address family, which is simply repeated in both
+unix server classes.
+
+Forking and threading versions of each type of server can be created
+using the ForkingMixIn and ThreadingMixIn mix-in classes. For
+instance, a threading UDP server class is created as follows:
+
+ class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+
+The Mix-in class must come first, since it overrides a method defined
+in UDPServer! Setting the various member variables also changes
+the behavior of the underlying server mechanism.
+
+To implement a service, you must derive a class from
+BaseRequestHandler and redefine its handle() method. You can then run
+various versions of the service by combining one of the server classes
+with your request handler class.
+
+The request handler class must be different for datagram or stream
+services. This can be hidden by using the request handler
+subclasses StreamRequestHandler or DatagramRequestHandler.
+
+Of course, you still have to use your head!
+
+For instance, it makes no sense to use a forking server if the service
+contains state in memory that can be modified by requests (since the
+modifications in the child process would never reach the initial state
+kept in the parent process and passed to each child). In this case,
+you can use a threading server, but you will probably have to use
+locks to avoid two requests that come in nearly simultaneous to apply
+conflicting changes to the server state.
+
+On the other hand, if you are building e.g. an HTTP server, where all
+data is stored externally (e.g. in the file system), a synchronous
+class will essentially render the service "deaf" while one request is
+being handled -- which may be for a very long time if a client is slow
+to reqd all the data it has requested. Here a threading or forking
+server is appropriate.
+
+In some cases, it may be appropriate to process part of a request
+synchronously, but to finish processing in a forked child depending on
+the request data. This can be implemented by using a synchronous
+server and doing an explicit fork in the request handler class
+handle() method.
+
+Another approach to handling multiple simultaneous requests in an
+environment that supports neither threads nor fork (or where these are
+too expensive or inappropriate for the service) is to maintain an
+explicit table of partially finished requests and to use select() to
+decide which request to work on next (or whether to handle a new
+incoming request). This is particularly important for stream services
+where each client can potentially be connected for a long time (if
+threads or subprocesses cannot be used).
+
+Future work:
+- Standard classes for Sun RPC (which uses either UDP or TCP)
+- Standard mix-in classes to implement various authentication
+ and encryption schemes
+- Standard framework for select-based multiplexing
+
+XXX Open problems:
+- What to do with out-of-band data?
+
+BaseServer:
+- split generic "request" functionality out into BaseServer class.
+ Copyright (C) 2000 Luke Kenneth Casson Leighton <[email protected]>
+
+ example: read entries from a SQL database (requires overriding
+ get_request() to return a table entry from the database).
+ entry is processed by a RequestHandlerClass.
+
+"""
+
+# Author of the BaseServer patch: Luke Kenneth Casson Leighton
+
+# XXX Warning!
+# There is a test suite for this module, but it cannot be run by the
+# standard regression test.
+# To run it manually, run Lib/test/test_socketserver.py.
+
+__version__ = "0.4"
+
+
+import socket
+import sys
+import os
+
+__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
+ "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
+ "StreamRequestHandler","DatagramRequestHandler",
+ "ThreadingMixIn", "ForkingMixIn"]
+if hasattr(socket, "AF_UNIX"):
+ __all__.extend(["UnixStreamServer","UnixDatagramServer",
+ "ThreadingUnixStreamServer",
+ "ThreadingUnixDatagramServer"])
+
+class BaseServer:
+
+ """Base class for server classes.
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass)
+ - serve_forever()
+ - handle_request() # if you do not use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - verify_request(request, client_address)
+ - server_close()
+ - process_request(request, client_address)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - address_family
+ - socket_type
+ - allow_reuse_address
+
+ Instance variables:
+
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ def __init__(self, server_address, RequestHandlerClass):
+ """Constructor. May be extended, do not override."""
+ self.server_address = server_address
+ self.RequestHandlerClass = RequestHandlerClass
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def serve_forever(self):
+ """Handle one request at a time until doomsday."""
+ while 1:
+ self.handle_request()
+
+ # The distinction between handling, getting, processing and
+ # finishing a request is fairly arbitrary. Remember:
+ #
+ # - handle_request() is the top-level call. It calls
+ # get_request(), verify_request() and process_request()
+ # - get_request() is different for stream or datagram sockets
+ # - process_request() is the place that may fork a new process
+ # or create a new thread to finish the request
+ # - finish_request() instantiates the request handler class;
+ # this constructor will handle the request all by itself
+
+ def handle_request(self):
+ """Handle one request, possibly blocking."""
+ try:
+ request, client_address = self.get_request()
+ except socket.error:
+ return
+ if self.verify_request(request, client_address):
+ try:
+ self.process_request(request, client_address)
+ except:
+ self.handle_error(request, client_address)
+ self.close_request(request)
+
+ def verify_request(self, request, client_address):
+ """Verify the request. May be overridden.
+
+ Return True if we should proceed with this request.
+
+ """
+ return True
+
+ def process_request(self, request, client_address):
+ """Call finish_request.
+
+ Overridden by ForkingMixIn and ThreadingMixIn.
+
+ """
+ self.finish_request(request, client_address)
+ self.close_request(request)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def finish_request(self, request, client_address):
+ """Finish one request by instantiating RequestHandlerClass."""
+ self.RequestHandlerClass(request, client_address, self)
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ pass
+
+ def handle_error(self, request, client_address):
+ """Handle an error gracefully. May be overridden.
+
+ The default is to print a traceback and continue.
+
+ """
+ print '-'*40
+ print 'Exception happened during processing of request from',
+ print client_address
+ import traceback
+ traceback.print_exc() # XXX But this goes to stderr!
+ print '-'*40
+
+
+class TCPServer(BaseServer):
+
+ """Base class for various socket-based server classes.
+
+ Defaults to synchronous IP stream (i.e., TCP).
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass)
+ - serve_forever()
+ - handle_request() # if you don't use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - verify_request(request, client_address)
+ - process_request(request, client_address)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - address_family
+ - socket_type
+ - request_queue_size (only for stream sockets)
+ - allow_reuse_address
+
+ Instance variables:
+
+ - server_address
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ address_family = socket.AF_INET
+
+ socket_type = socket.SOCK_STREAM
+
+ request_queue_size = 5
+
+ allow_reuse_address = False
+
+ def __init__(self, server_address, RequestHandlerClass):
+ """Constructor. May be extended, do not override."""
+ BaseServer.__init__(self, server_address, RequestHandlerClass)
+ self.socket = socket.socket(self.address_family,
+ self.socket_type)
+ self.server_bind()
+ self.server_activate()
+
+ def server_bind(self):
+ """Called by constructor to bind the socket.
+
+ May be overridden.
+
+ """
+ if self.allow_reuse_address:
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.socket.bind(self.server_address)
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ self.socket.listen(self.request_queue_size)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ self.socket.close()
+
+ def fileno(self):
+ """Return socket file number.
+
+ Interface required by select().
+
+ """
+ return self.socket.fileno()
+
+ def get_request(self):
+ """Get the request and client address from the socket.
+
+ May be overridden.
+
+ """
+ return self.socket.accept()
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ request.close()
+
+
+class UDPServer(TCPServer):
+
+ """UDP server class."""
+
+ allow_reuse_address = False
+
+ socket_type = socket.SOCK_DGRAM
+
+ max_packet_size = 8192
+
+ def get_request(self):
+ data, client_addr = self.socket.recvfrom(self.max_packet_size)
+ return (data, self.socket), client_addr
+
+ def server_activate(self):
+ # No need to call listen() for UDP.
+ pass
+
+ def close_request(self, request):
+ # No need to close anything.
+ pass
+
+class ForkingMixIn:
+
+ """Mix-in class to handle each request in a new process."""
+
+ active_children = None
+ max_children = 40
+
+ def collect_children(self):
+ """Internal routine to wait for died children."""
+ while self.active_children:
+ if len(self.active_children) < self.max_children:
+ options = os.WNOHANG
+ else:
+ # If the maximum number of children are already
+ # running, block while waiting for a child to exit
+ options = 0
+ try:
+ pid, status = os.waitpid(0, options)
+ except os.error:
+ pid = None
+ if not pid: break
+ self.active_children.remove(pid)
+
+ def process_request(self, request, client_address):
+ """Fork a new subprocess to process the request."""
+ self.collect_children()
+ pid = os.fork()
+ if pid:
+ # Parent process
+ if self.active_children is None:
+ self.active_children = []
+ self.active_children.append(pid)
+ self.close_request(request)
+ return
+ else:
+ # Child process.
+ # This must never return, hence os._exit()!
+ try:
+ self.finish_request(request, client_address)
+ os._exit(0)
+ except:
+ try:
+ self.handle_error(request, client_address)
+ finally:
+ os._exit(1)
+
+
+class ThreadingMixIn:
+ """Mix-in class to handle each request in a new thread."""
+
+ # Decides how threads will act upon termination of the
+ # main process
+ daemon_threads = False
+
+ def process_request_thread(self, request, client_address):
+ """Same as in BaseServer but as a thread.
+
+ In addition, exception handling is done here.
+
+ """
+ try:
+ self.finish_request(request, client_address)
+ self.close_request(request)
+ except:
+ self.handle_error(request, client_address)
+ self.close_request(request)
+
+ def process_request(self, request, client_address):
+ """Start a new thread to process the request."""
+ import threading
+ t = threading.Thread(target = self.process_request_thread,
+ args = (request, client_address))
+ if self.daemon_threads:
+ t.setDaemon (1)
+ t.start()
+
+
+class ForkingUDPServer(ForkingMixIn, UDPServer): pass
+class ForkingTCPServer(ForkingMixIn, TCPServer): pass
+
+class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
+
+if hasattr(socket, 'AF_UNIX'):
+
+ class UnixStreamServer(TCPServer):
+ address_family = socket.AF_UNIX
+
+ class UnixDatagramServer(UDPServer):
+ address_family = socket.AF_UNIX
+
+ class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
+
+ class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
+
+class BaseRequestHandler:
+
+ """Base class for request handler classes.
+
+ This class is instantiated for each request to be handled. The
+ constructor sets the instance variables request, client_address
+ and server, and then calls the handle() method. To implement a
+ specific service, all you need to do is to derive a class which
+ defines a handle() method.
+
+ The handle() method can find the request as self.request, the
+ client address as self.client_address, and the server (in case it
+ needs access to per-server information) as self.server. Since a
+ separate instance is created for each request, the handle() method
+ can define arbitrary other instance variariables.
+
+ """
+
+ def __init__(self, request, client_address, server):
+ self.request = request
+ self.client_address = client_address
+ self.server = server
+ try:
+ self.setup()
+ self.handle()
+ self.finish()
+ finally:
+ sys.exc_traceback = None # Help garbage collection
+
+ def setup(self):
+ pass
+
+ def handle(self):
+ pass
+
+ def finish(self):
+ pass
+
+
+# The following two classes make it possible to use the same service
+# class for stream or datagram servers.
+# Each class sets up these instance variables:
+# - rfile: a file object from which receives the request is read
+# - wfile: a file object to which the reply is written
+# When the handle() method returns, wfile is flushed properly
+
+
+class StreamRequestHandler(BaseRequestHandler):
+
+ """Define self.rfile and self.wfile for stream sockets."""
+
+ # Default buffer sizes for rfile, wfile.
+ # We default rfile to buffered because otherwise it could be
+ # really slow for large data (a getc() call per byte); we make
+ # wfile unbuffered because (a) often after a write() we want to
+ # read and we need to flush the line; (b) big writes to unbuffered
+ # files are typically optimized by stdio even when big reads
+ # aren't.
+ rbufsize = -1
+ wbufsize = 0
+
+ def setup(self):
+ self.connection = self.request
+ self.rfile = self.connection.makefile('rb', self.rbufsize)
+ self.wfile = self.connection.makefile('wb', self.wbufsize)
+
+ def finish(self):
+ if not self.wfile.closed:
+ self.wfile.flush()
+ self.wfile.close()
+ self.rfile.close()
+
+
+class DatagramRequestHandler(BaseRequestHandler):
+
+ # XXX Regrettably, I cannot get this working on Linux;
+ # s.recvfrom() doesn't return a meaningful client address.
+
+ """Define self.rfile and self.wfile for datagram sockets."""
+
+ def setup(self):
+ try:
+ from cStringIO import StringIO
+ except ImportError:
+ from StringIO import StringIO
+ self.packet, self.socket = self.request
+ self.rfile = StringIO(self.packet)
+ self.wfile = StringIO()
+
+ def finish(self):
+ self.socket.sendto(self.wfile.getvalue(), self.client_address)
diff --git a/openwrt/missing_libraries/termios.so b/openwrt/missing_libraries/termios.so
new file mode 100644
index 0000000..4ce8d9e
Binary files /dev/null and b/openwrt/missing_libraries/termios.so differ
|
sbma44/artomatic
|
87591508897ad382ddaac6f691ee9fae06f1b69e
|
adding arduino code to project
|
diff --git a/arduino/artomatic_2009.pde b/arduino/artomatic_2009.pde
new file mode 100644
index 0000000..3d4acab
--- /dev/null
+++ b/arduino/artomatic_2009.pde
@@ -0,0 +1,99 @@
+#define SOLENOID_PIN 8
+#define LED_PIN 13
+#define SENSOR_PIN 0
+#define BAUD_RATE 9600
+#define BELL_CHAR '#'
+#define STARTUP_DELAY_IN_SECONDS 80
+
+int lastRing = 0;
+int minimum_observed = 999;
+int maximum_observed = 0;
+bool last_ring_state = false;
+bool past_startup_delay = false;
+
+float load;
+
+void setup()
+{
+ load = 0;
+
+ pinMode(LED_PIN, OUTPUT);
+ pinMode(SOLENOID_PIN, OUTPUT);
+ pinMode(SENSOR_PIN, INPUT);
+
+ digitalWrite(LED_PIN, LOW);
+ digitalWrite(SOLENOID_PIN, LOW);
+
+ Serial.begin(BAUD_RATE);
+}
+
+bool BellIsRinging()
+{
+ int val = analogRead(SENSOR_PIN); // read the value from the sensor
+ minimum_observed = min(minimum_observed, val);
+ maximum_observed = max(maximum_observed, val);
+
+ if(val > ((minimum_observed + maximum_observed)/2))
+ {
+ // digitalWrite(LED_PIN, HIGH);
+ return true;
+ }
+ else
+ {
+ // digitalWrite(LED_PIN, LOW);
+ return false;
+ }
+}
+
+void RingBell()
+{
+ // assumes one ring every 100 ms max -- this is 50% solenoid utilization
+ if(load<1.0)
+ {
+ digitalWrite(SOLENOID_PIN, HIGH);
+ delay(20); // waits for a brief moment to properly energize the solenoid
+ digitalWrite(SOLENOID_PIN, LOW);
+
+ // prevent looping of strikes (?)
+ delay(30);
+
+ last_ring_state = true;
+
+ load = (0.9*load) + (0.1 * (100 / (millis() - lastRing)));
+ lastRing = millis();
+ }
+}
+
+void SendBellRing()
+{
+ Serial.println(BELL_CHAR);
+
+ digitalWrite(LED_PIN, HIGH);
+ delay(100);
+ digitalWrite(LED_PIN, LOW);
+}
+
+void loop()
+{
+ // do it this way in case millis() loops around
+ if (millis()>=(STARTUP_DELAY_IN_SECONDS*1000))
+ {
+ past_startup_delay = true;
+ }
+
+ if (Serial.available() > 0)
+ {
+ int incoming = Serial.read();
+ if ((char(incoming)==BELL_CHAR) && past_startup_delay)
+ {
+ RingBell();
+ }
+ }
+
+ bool bell_is_ringing = BellIsRinging();
+ if(bell_is_ringing && !last_ring_state)
+ {
+ SendBellRing();
+ }
+ last_ring_state = bell_is_ringing;
+}
|
sbma44/artomatic
|
f4d88024f187583f03fc1cf35b862169041dba9a
|
corrected settings to reflect lower baud rate
|
diff --git a/scripts/settings.py b/scripts/settings.py
index 6017f8a..ebdb46b 100644
--- a/scripts/settings.py
+++ b/scripts/settings.py
@@ -1,5 +1,5 @@
HOST = ''
RECIPIENTS = ['192.168.11.1']
PORT = 50008
SERIAL_PORT = '/dev/ttyS0'
-BAUD_RATE = 115200
+BAUD_RATE = 9600
|
sbma44/artomatic
|
926c3485a6ba83382da60619c446868f735bbbcf
|
proper try..except wrapping for network methods
|
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 12656bf..3bce2df 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,171 +1,176 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
import os
import serial
import time
import settings
import SocketServer
def log(message):
f = open('/var/log/bellserver.log', 'a')
f.write("%f - %s\n" % (time.time(), message))
f.close()
class SerialHolder(object):
SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
super(SerialHolder, self).__init__()
# create a serial connection
log("Establishing serial connection")
self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
# clear serial backlog
waiting = self.serial_connection.inWaiting()
self.serial_connection.read(waiting)
def strike_bell(self):
self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
log("Struck bell")
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
char = ''
try:
waiting = self.serial_connection.inWaiting()
if waiting>0:
char = self.serial_connection.read(waiting)
except Exception, e:
pass
if len(char.strip())>0:
log("Detected serial communication - %s" % (char))
return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
return False
def close(self):
self.serial_connection.close()
class SocketServerWrapper(SocketServer.TCPServer):
"""docstring for SocketServerWrapper"""
def __init__(self, *args):
log("Starting server")
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,*args)
class BellServer(SocketServer.StreamRequestHandler):
NETWORK_BELL_STRIKE_SIGNAL = 'DING'
NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
log("Striking bell")
global serialholder
if serialholder is not None:
serialholder.strike_bell()
def handle(self):
data = self.rfile.readline().strip()
log("Received data %s" % data)
if data==self.NETWORK_BELL_STRIKE_SIGNAL:
self.strike_bell()
self.wfile.write(self.NETWORK_BELL_STRIKE_CONFIRMATION)
class BellClient(object):
"""
Monitors the serial port for strikes and sends network messages when they're found
"""
def __init__(self):
log("Starting client")
super(BellClient, self).__init__()
self.RECIPIENTS = settings.RECIPIENTS
self.PORT = settings.PORT
self.NETWORK_BELL_STRIKE_SIGNAL = 'DING'
self.NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
global serialholder
if serialholder is not None:
return serialholder.bell_strike_detected()
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
log("Transmitting bell strike to %d recipient(s)" % len(self.RECIPIENTS))
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.settimeout(1)
- s.connect((recipient, self.PORT))
- s.send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
+
+ try:
+ s.connect((recipient, self.PORT))
+ s.send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
- data = ''
- try:
- data = s.recv(1024)
- except Exception, e:
- pass
+ data = ''
+ try:
+ data = s.recv(1024)
+ except Exception, e:
+ pass
- s.close()
+ s.close()
- if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
- log("Successfully sent bell strike to %s" % recipient)
- else:
- log("Unable to confirm bell strike to %s (network timeout?)" % recipient)
+ if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
+ log("Successfully sent bell strike to %s" % recipient)
+ else:
+ log("Unable to confirm bell strike to %s (network timeout?)" % recipient)
+
+ except Exception, e:
+ log("Tried to send bell strike to %s but failed" % recipient)
def listen(self):
while True:
# check serial input for bell strike notification
strikes_in_waiting = self.bell_strike_detected()
if strikes_in_waiting is not False:
log("Heard at least one strike")
for i in range(0, strikes_in_waiting):
self.transmit_bell_strike()
time.sleep(0.01)
def close(self):
global serialholder
if serialholder is not None:
serialholder.close()
global serialholder
serialholder = SerialHolder()
if __name__ == '__main__':
if os.fork():
server = SocketServerWrapper( (settings.HOST, settings.PORT), BellServer)
server.serve_forever()
else:
client = BellClient()
try:
client.listen()
finally:
client.close()
\ No newline at end of file
|
sbma44/artomatic
|
b823f7187c6d6e597262bd507b5bcec4173dd306
|
working version
|
diff --git a/fonera-python/SocketServer.py b/fonera-python/SocketServer.py
new file mode 100644
index 0000000..3a74c44
--- /dev/null
+++ b/fonera-python/SocketServer.py
@@ -0,0 +1,587 @@
+"""Generic socket server classes.
+
+This module tries to capture the various aspects of defining a server:
+
+For socket-based servers:
+
+- address family:
+ - AF_INET{,6}: IP (Internet Protocol) sockets (default)
+ - AF_UNIX: Unix domain sockets
+ - others, e.g. AF_DECNET are conceivable (see <socket.h>
+- socket type:
+ - SOCK_STREAM (reliable stream, e.g. TCP)
+ - SOCK_DGRAM (datagrams, e.g. UDP)
+
+For request-based servers (including socket-based):
+
+- client address verification before further looking at the request
+ (This is actually a hook for any processing that needs to look
+ at the request before anything else, e.g. logging)
+- how to handle multiple requests:
+ - synchronous (one request is handled at a time)
+ - forking (each request is handled by a new process)
+ - threading (each request is handled by a new thread)
+
+The classes in this module favor the server type that is simplest to
+write: a synchronous TCP/IP server. This is bad class design, but
+save some typing. (There's also the issue that a deep class hierarchy
+slows down method lookups.)
+
+There are five classes in an inheritance diagram, four of which represent
+synchronous servers of four types:
+
+ +------------+
+ | BaseServer |
+ +------------+
+ |
+ v
+ +-----------+ +------------------+
+ | TCPServer |------->| UnixStreamServer |
+ +-----------+ +------------------+
+ |
+ v
+ +-----------+ +--------------------+
+ | UDPServer |------->| UnixDatagramServer |
+ +-----------+ +--------------------+
+
+Note that UnixDatagramServer derives from UDPServer, not from
+UnixStreamServer -- the only difference between an IP and a Unix
+stream server is the address family, which is simply repeated in both
+unix server classes.
+
+Forking and threading versions of each type of server can be created
+using the ForkingMixIn and ThreadingMixIn mix-in classes. For
+instance, a threading UDP server class is created as follows:
+
+ class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+
+The Mix-in class must come first, since it overrides a method defined
+in UDPServer! Setting the various member variables also changes
+the behavior of the underlying server mechanism.
+
+To implement a service, you must derive a class from
+BaseRequestHandler and redefine its handle() method. You can then run
+various versions of the service by combining one of the server classes
+with your request handler class.
+
+The request handler class must be different for datagram or stream
+services. This can be hidden by using the request handler
+subclasses StreamRequestHandler or DatagramRequestHandler.
+
+Of course, you still have to use your head!
+
+For instance, it makes no sense to use a forking server if the service
+contains state in memory that can be modified by requests (since the
+modifications in the child process would never reach the initial state
+kept in the parent process and passed to each child). In this case,
+you can use a threading server, but you will probably have to use
+locks to avoid two requests that come in nearly simultaneous to apply
+conflicting changes to the server state.
+
+On the other hand, if you are building e.g. an HTTP server, where all
+data is stored externally (e.g. in the file system), a synchronous
+class will essentially render the service "deaf" while one request is
+being handled -- which may be for a very long time if a client is slow
+to reqd all the data it has requested. Here a threading or forking
+server is appropriate.
+
+In some cases, it may be appropriate to process part of a request
+synchronously, but to finish processing in a forked child depending on
+the request data. This can be implemented by using a synchronous
+server and doing an explicit fork in the request handler class
+handle() method.
+
+Another approach to handling multiple simultaneous requests in an
+environment that supports neither threads nor fork (or where these are
+too expensive or inappropriate for the service) is to maintain an
+explicit table of partially finished requests and to use select() to
+decide which request to work on next (or whether to handle a new
+incoming request). This is particularly important for stream services
+where each client can potentially be connected for a long time (if
+threads or subprocesses cannot be used).
+
+Future work:
+- Standard classes for Sun RPC (which uses either UDP or TCP)
+- Standard mix-in classes to implement various authentication
+ and encryption schemes
+- Standard framework for select-based multiplexing
+
+XXX Open problems:
+- What to do with out-of-band data?
+
+BaseServer:
+- split generic "request" functionality out into BaseServer class.
+ Copyright (C) 2000 Luke Kenneth Casson Leighton <[email protected]>
+
+ example: read entries from a SQL database (requires overriding
+ get_request() to return a table entry from the database).
+ entry is processed by a RequestHandlerClass.
+
+"""
+
+# Author of the BaseServer patch: Luke Kenneth Casson Leighton
+
+# XXX Warning!
+# There is a test suite for this module, but it cannot be run by the
+# standard regression test.
+# To run it manually, run Lib/test/test_socketserver.py.
+
+__version__ = "0.4"
+
+
+import socket
+import sys
+import os
+
+__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
+ "ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
+ "StreamRequestHandler","DatagramRequestHandler",
+ "ThreadingMixIn", "ForkingMixIn"]
+if hasattr(socket, "AF_UNIX"):
+ __all__.extend(["UnixStreamServer","UnixDatagramServer",
+ "ThreadingUnixStreamServer",
+ "ThreadingUnixDatagramServer"])
+
+class BaseServer:
+
+ """Base class for server classes.
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass)
+ - serve_forever()
+ - handle_request() # if you do not use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - verify_request(request, client_address)
+ - server_close()
+ - process_request(request, client_address)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - address_family
+ - socket_type
+ - allow_reuse_address
+
+ Instance variables:
+
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ def __init__(self, server_address, RequestHandlerClass):
+ """Constructor. May be extended, do not override."""
+ self.server_address = server_address
+ self.RequestHandlerClass = RequestHandlerClass
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def serve_forever(self):
+ """Handle one request at a time until doomsday."""
+ while 1:
+ self.handle_request()
+
+ # The distinction between handling, getting, processing and
+ # finishing a request is fairly arbitrary. Remember:
+ #
+ # - handle_request() is the top-level call. It calls
+ # get_request(), verify_request() and process_request()
+ # - get_request() is different for stream or datagram sockets
+ # - process_request() is the place that may fork a new process
+ # or create a new thread to finish the request
+ # - finish_request() instantiates the request handler class;
+ # this constructor will handle the request all by itself
+
+ def handle_request(self):
+ """Handle one request, possibly blocking."""
+ try:
+ request, client_address = self.get_request()
+ except socket.error:
+ return
+ if self.verify_request(request, client_address):
+ try:
+ self.process_request(request, client_address)
+ except:
+ self.handle_error(request, client_address)
+ self.close_request(request)
+
+ def verify_request(self, request, client_address):
+ """Verify the request. May be overridden.
+
+ Return True if we should proceed with this request.
+
+ """
+ return True
+
+ def process_request(self, request, client_address):
+ """Call finish_request.
+
+ Overridden by ForkingMixIn and ThreadingMixIn.
+
+ """
+ self.finish_request(request, client_address)
+ self.close_request(request)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ pass
+
+ def finish_request(self, request, client_address):
+ """Finish one request by instantiating RequestHandlerClass."""
+ self.RequestHandlerClass(request, client_address, self)
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ pass
+
+ def handle_error(self, request, client_address):
+ """Handle an error gracefully. May be overridden.
+
+ The default is to print a traceback and continue.
+
+ """
+ print '-'*40
+ print 'Exception happened during processing of request from',
+ print client_address
+ import traceback
+ traceback.print_exc() # XXX But this goes to stderr!
+ print '-'*40
+
+
+class TCPServer(BaseServer):
+
+ """Base class for various socket-based server classes.
+
+ Defaults to synchronous IP stream (i.e., TCP).
+
+ Methods for the caller:
+
+ - __init__(server_address, RequestHandlerClass)
+ - serve_forever()
+ - handle_request() # if you don't use serve_forever()
+ - fileno() -> int # for select()
+
+ Methods that may be overridden:
+
+ - server_bind()
+ - server_activate()
+ - get_request() -> request, client_address
+ - verify_request(request, client_address)
+ - process_request(request, client_address)
+ - close_request(request)
+ - handle_error()
+
+ Methods for derived classes:
+
+ - finish_request(request, client_address)
+
+ Class variables that may be overridden by derived classes or
+ instances:
+
+ - address_family
+ - socket_type
+ - request_queue_size (only for stream sockets)
+ - allow_reuse_address
+
+ Instance variables:
+
+ - server_address
+ - RequestHandlerClass
+ - socket
+
+ """
+
+ address_family = socket.AF_INET
+
+ socket_type = socket.SOCK_STREAM
+
+ request_queue_size = 5
+
+ allow_reuse_address = False
+
+ def __init__(self, server_address, RequestHandlerClass):
+ """Constructor. May be extended, do not override."""
+ BaseServer.__init__(self, server_address, RequestHandlerClass)
+ self.socket = socket.socket(self.address_family,
+ self.socket_type)
+ self.server_bind()
+ self.server_activate()
+
+ def server_bind(self):
+ """Called by constructor to bind the socket.
+
+ May be overridden.
+
+ """
+ if self.allow_reuse_address:
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.socket.bind(self.server_address)
+
+ def server_activate(self):
+ """Called by constructor to activate the server.
+
+ May be overridden.
+
+ """
+ self.socket.listen(self.request_queue_size)
+
+ def server_close(self):
+ """Called to clean-up the server.
+
+ May be overridden.
+
+ """
+ self.socket.close()
+
+ def fileno(self):
+ """Return socket file number.
+
+ Interface required by select().
+
+ """
+ return self.socket.fileno()
+
+ def get_request(self):
+ """Get the request and client address from the socket.
+
+ May be overridden.
+
+ """
+ return self.socket.accept()
+
+ def close_request(self, request):
+ """Called to clean up an individual request."""
+ request.close()
+
+
+class UDPServer(TCPServer):
+
+ """UDP server class."""
+
+ allow_reuse_address = False
+
+ socket_type = socket.SOCK_DGRAM
+
+ max_packet_size = 8192
+
+ def get_request(self):
+ data, client_addr = self.socket.recvfrom(self.max_packet_size)
+ return (data, self.socket), client_addr
+
+ def server_activate(self):
+ # No need to call listen() for UDP.
+ pass
+
+ def close_request(self, request):
+ # No need to close anything.
+ pass
+
+class ForkingMixIn:
+
+ """Mix-in class to handle each request in a new process."""
+
+ active_children = None
+ max_children = 40
+
+ def collect_children(self):
+ """Internal routine to wait for died children."""
+ while self.active_children:
+ if len(self.active_children) < self.max_children:
+ options = os.WNOHANG
+ else:
+ # If the maximum number of children are already
+ # running, block while waiting for a child to exit
+ options = 0
+ try:
+ pid, status = os.waitpid(0, options)
+ except os.error:
+ pid = None
+ if not pid: break
+ self.active_children.remove(pid)
+
+ def process_request(self, request, client_address):
+ """Fork a new subprocess to process the request."""
+ self.collect_children()
+ pid = os.fork()
+ if pid:
+ # Parent process
+ if self.active_children is None:
+ self.active_children = []
+ self.active_children.append(pid)
+ self.close_request(request)
+ return
+ else:
+ # Child process.
+ # This must never return, hence os._exit()!
+ try:
+ self.finish_request(request, client_address)
+ os._exit(0)
+ except:
+ try:
+ self.handle_error(request, client_address)
+ finally:
+ os._exit(1)
+
+
+class ThreadingMixIn:
+ """Mix-in class to handle each request in a new thread."""
+
+ # Decides how threads will act upon termination of the
+ # main process
+ daemon_threads = False
+
+ def process_request_thread(self, request, client_address):
+ """Same as in BaseServer but as a thread.
+
+ In addition, exception handling is done here.
+
+ """
+ try:
+ self.finish_request(request, client_address)
+ self.close_request(request)
+ except:
+ self.handle_error(request, client_address)
+ self.close_request(request)
+
+ def process_request(self, request, client_address):
+ """Start a new thread to process the request."""
+ import threading
+ t = threading.Thread(target = self.process_request_thread,
+ args = (request, client_address))
+ if self.daemon_threads:
+ t.setDaemon (1)
+ t.start()
+
+
+class ForkingUDPServer(ForkingMixIn, UDPServer): pass
+class ForkingTCPServer(ForkingMixIn, TCPServer): pass
+
+class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
+class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
+
+if hasattr(socket, 'AF_UNIX'):
+
+ class UnixStreamServer(TCPServer):
+ address_family = socket.AF_UNIX
+
+ class UnixDatagramServer(UDPServer):
+ address_family = socket.AF_UNIX
+
+ class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
+
+ class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
+
+class BaseRequestHandler:
+
+ """Base class for request handler classes.
+
+ This class is instantiated for each request to be handled. The
+ constructor sets the instance variables request, client_address
+ and server, and then calls the handle() method. To implement a
+ specific service, all you need to do is to derive a class which
+ defines a handle() method.
+
+ The handle() method can find the request as self.request, the
+ client address as self.client_address, and the server (in case it
+ needs access to per-server information) as self.server. Since a
+ separate instance is created for each request, the handle() method
+ can define arbitrary other instance variariables.
+
+ """
+
+ def __init__(self, request, client_address, server):
+ self.request = request
+ self.client_address = client_address
+ self.server = server
+ try:
+ self.setup()
+ self.handle()
+ self.finish()
+ finally:
+ sys.exc_traceback = None # Help garbage collection
+
+ def setup(self):
+ pass
+
+ def handle(self):
+ pass
+
+ def finish(self):
+ pass
+
+
+# The following two classes make it possible to use the same service
+# class for stream or datagram servers.
+# Each class sets up these instance variables:
+# - rfile: a file object from which receives the request is read
+# - wfile: a file object to which the reply is written
+# When the handle() method returns, wfile is flushed properly
+
+
+class StreamRequestHandler(BaseRequestHandler):
+
+ """Define self.rfile and self.wfile for stream sockets."""
+
+ # Default buffer sizes for rfile, wfile.
+ # We default rfile to buffered because otherwise it could be
+ # really slow for large data (a getc() call per byte); we make
+ # wfile unbuffered because (a) often after a write() we want to
+ # read and we need to flush the line; (b) big writes to unbuffered
+ # files are typically optimized by stdio even when big reads
+ # aren't.
+ rbufsize = -1
+ wbufsize = 0
+
+ def setup(self):
+ self.connection = self.request
+ self.rfile = self.connection.makefile('rb', self.rbufsize)
+ self.wfile = self.connection.makefile('wb', self.wbufsize)
+
+ def finish(self):
+ if not self.wfile.closed:
+ self.wfile.flush()
+ self.wfile.close()
+ self.rfile.close()
+
+
+class DatagramRequestHandler(BaseRequestHandler):
+
+ # XXX Regrettably, I cannot get this working on Linux;
+ # s.recvfrom() doesn't return a meaningful client address.
+
+ """Define self.rfile and self.wfile for datagram sockets."""
+
+ def setup(self):
+ try:
+ from cStringIO import StringIO
+ except ImportError:
+ from StringIO import StringIO
+ self.packet, self.socket = self.request
+ self.rfile = StringIO(self.packet)
+ self.wfile = StringIO()
+
+ def finish(self):
+ self.socket.sendto(self.wfile.getvalue(), self.client_address)
diff --git a/openwrt/config/dhcp b/openwrt/etc/config/dhcp
similarity index 100%
rename from openwrt/config/dhcp
rename to openwrt/etc/config/dhcp
diff --git a/openwrt/config/dropbear b/openwrt/etc/config/dropbear
similarity index 100%
rename from openwrt/config/dropbear
rename to openwrt/etc/config/dropbear
diff --git a/openwrt/config/firewall b/openwrt/etc/config/firewall
similarity index 100%
rename from openwrt/config/firewall
rename to openwrt/etc/config/firewall
diff --git a/openwrt/config/fstab b/openwrt/etc/config/fstab
similarity index 100%
rename from openwrt/config/fstab
rename to openwrt/etc/config/fstab
diff --git a/openwrt/config/httpd b/openwrt/etc/config/httpd
similarity index 100%
rename from openwrt/config/httpd
rename to openwrt/etc/config/httpd
diff --git a/openwrt/etc/config/network.client b/openwrt/etc/config/network.client
new file mode 100644
index 0000000..fa1bc06
--- /dev/null
+++ b/openwrt/etc/config/network.client
@@ -0,0 +1,21 @@
+# Copyright (C) 2006 OpenWrt.org
+
+config interface loopback
+ option ifname lo
+ option proto static
+ option ipaddr 127.0.0.1
+ option netmask 255.0.0.0
+
+config interface lan
+ option ifname eth0
+ option type bridge
+ option proto static
+ option ipaddr 192.168.1.1
+ option netmask 255.255.255.0
+
+config interface wifi
+ option ifname eth0
+ option type bridge
+ option proto static
+ option ipaddr 192.168.11.2
+ option netmask 255.255.255.0
diff --git a/openwrt/etc/config/network.server b/openwrt/etc/config/network.server
new file mode 100644
index 0000000..5fa75e4
--- /dev/null
+++ b/openwrt/etc/config/network.server
@@ -0,0 +1,21 @@
+# Copyright (C) 2006 OpenWrt.org
+
+config interface loopback
+ option ifname lo
+ option proto static
+ option ipaddr 127.0.0.1
+ option netmask 255.0.0.0
+
+config interface lan
+ option ifname eth0
+ option type bridge
+ option proto static
+ option ipaddr 192.168.1.1
+ option netmask 255.255.255.0
+
+config interface wifi
+ option ifname eth0
+ option type bridge
+ option proto static
+ option ipaddr 192.168.11.1
+ option netmask 255.255.255.0
diff --git a/openwrt/config/system b/openwrt/etc/config/system
similarity index 100%
rename from openwrt/config/system
rename to openwrt/etc/config/system
diff --git a/openwrt/etc/config/wireless.client b/openwrt/etc/config/wireless.client
new file mode 100644
index 0000000..e94c17e
--- /dev/null
+++ b/openwrt/etc/config/wireless.client
@@ -0,0 +1,15 @@
+config wifi-device wifi0
+ option type atheros
+ option channel auto
+
+ # REMOVE THIS LINE TO ENABLE WIFI:
+ # option disabled 1
+
+config wifi-iface
+ option device wifi0
+ option network wifi
+ option mode sta
+ option ssid RingForService
+ option encryption wep
+ option key 1
+ option key1 "__________________________"
diff --git a/openwrt/etc/config/wireless.server b/openwrt/etc/config/wireless.server
new file mode 100644
index 0000000..e94c17e
--- /dev/null
+++ b/openwrt/etc/config/wireless.server
@@ -0,0 +1,15 @@
+config wifi-device wifi0
+ option type atheros
+ option channel auto
+
+ # REMOVE THIS LINE TO ENABLE WIFI:
+ # option disabled 1
+
+config wifi-iface
+ option device wifi0
+ option network wifi
+ option mode sta
+ option ssid RingForService
+ option encryption wep
+ option key 1
+ option key1 "__________________________"
diff --git a/openwrt/etc/init.d/bellserver b/openwrt/etc/init.d/bellserver
new file mode 100644
index 0000000..27c27e4
--- /dev/null
+++ b/openwrt/etc/init.d/bellserver
@@ -0,0 +1,16 @@
+#!/bin/sh /etc/rc.common
+# BellServer startup script
+# Copyright (C) 2007 OpenWrt.org
+
+START=90
+STOP=10
+
+start() {
+ echo starting bellserver
+ python /root/bellserver/bellserver.py &
+}
+
+stop() {
+ echo stopping bellserver
+ ps ax | grep bellserver | grep -v grep | awk '{print $1}' | xargs kill
+}
\ No newline at end of file
diff --git a/openwrt/etc/init.d/bellserver.pid b/openwrt/etc/init.d/bellserver.pid
new file mode 100644
index 0000000..ecf8098
--- /dev/null
+++ b/openwrt/etc/init.d/bellserver.pid
@@ -0,0 +1 @@
+96607
\ No newline at end of file
diff --git a/openwrt/flashing_instructions.txt b/openwrt/flashing_instructions.txt
new file mode 100644
index 0000000..e0bf72a
--- /dev/null
+++ b/openwrt/flashing_instructions.txt
@@ -0,0 +1,8 @@
+ip_address -l 192.168.1.254/24 -h 192.168.1.166
+fis init
+load -r -b 0x80041000 openwrt-atheros-root.squashfs
+fis create -l 0x06F0000 rootfs
+load -r -b 0x80041000 openwrt-atheros-vmlinux.lzma
+fis create -r 0x80041000 -e 0x80041000 vmlinux.bin.l7
+fis load -l vmlinux.bin.l7
+exec
\ No newline at end of file
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 502b4a1..12656bf 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,303 +1,171 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
import os
import serial
import time
import settings
import SocketServer
def log(message):
- print "%f - %s" % (time.time(), message)
+ f = open('/var/log/bellserver.log', 'a')
+ f.write("%f - %s\n" % (time.time(), message))
+ f.close()
class SerialHolder(object):
SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
super(SerialHolder, self).__init__()
# create a serial connection
log("Establishing serial connection")
self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
# clear serial backlog
waiting = self.serial_connection.inWaiting()
self.serial_connection.read(waiting)
def strike_bell(self):
self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
log("Struck bell")
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
char = ''
try:
waiting = self.serial_connection.inWaiting()
if waiting>0:
char = self.serial_connection.read(waiting)
except Exception, e:
pass
if len(char.strip())>0:
log("Detected serial communication - %s" % (char))
return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
return False
def close(self):
self.serial_connection.close()
-
-class adsas(object):
- """docstring for adsas"""
- def __init__(self, arg):
- super(adsas, self).__init__()
- self.arg = arg
-
+
class SocketServerWrapper(SocketServer.TCPServer):
"""docstring for SocketServerWrapper"""
def __init__(self, *args):
+ log("Starting server")
self.allow_reuse_address = True
SocketServer.TCPServer.__init__(self,*args)
class BellServer(SocketServer.StreamRequestHandler):
NETWORK_BELL_STRIKE_SIGNAL = 'DING'
NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
-
-
+
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
+ log("Striking bell")
global serialholder
if serialholder is not None:
serialholder.strike_bell()
def handle(self):
data = self.rfile.readline().strip()
log("Received data %s" % data)
if data==self.NETWORK_BELL_STRIKE_SIGNAL:
self.strike_bell()
self.wfile.write(self.NETWORK_BELL_STRIKE_CONFIRMATION)
class BellClient(object):
-
+ """
+ Monitors the serial port for strikes and sends network messages when they're found
+ """
-
def __init__(self):
+ log("Starting client")
super(BellClient, self).__init__()
self.RECIPIENTS = settings.RECIPIENTS
self.PORT = settings.PORT
self.NETWORK_BELL_STRIKE_SIGNAL = 'DING'
self.NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
-
- # create another socket to send communication to each recipient
- # log("Creating outbound sockets")
- # self.outbound_sockets = {}
- # self.setup_outbound_sockets()
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
global serialholder
if serialholder is not None:
return serialholder.bell_strike_detected()
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
- # failed_sockets = {}
- # for s in self.outbound_sockets:
- # data = None
- # try:
- # self.outbound_sockets[s].send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
- # data = self.outbound_sockets[s].recv(1024)
- # self.outbound_sockets[s].close()
- # except:
- # failed_sockets[s] = self.outbound_sockets[s]
- # if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
- # log("Successfully sent bell strike")
- #
- # self.reset_sockets(failed_sockets)
- log("Transmitting bell strike")
+ log("Transmitting bell strike to %d recipient(s)" % len(self.RECIPIENTS))
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s.settimeout(0.5)
+ s.settimeout(1)
s.connect((recipient, self.PORT))
s.send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
- log("Receiving data")
- data = s.recv(1024)
- log("Done receiving data")
- s.close()
-
- if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
- log("Successfully sent bell strike to %s" % recipient)
-
-
- def _open_xmit_socket(self, recipient):
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s.connect((recipient, self.PORT))
- return s
-
-
- def setup_outbound_sockets(self):
-
- # try to close any open sockets
- for recipient in self.outbound_sockets:
- try:
- self.outbound_sockets[recipient].close()
- except:
- pass
-
- # create connections
- for recipient in settings.RECIPIENTS:
- socket_creation_successful = False
-
- while not socket_creation_successful:
- # s = self._open_xmit_socket(recipient)
- try:
- s = self._open_xmit_socket(recipient)
- except socket.error:
- log("Failed to establish connection to %s" % recipient)
- socket_creation_successful = False
- time.sleep(10)
- else:
- socket_creation_successful = True
- if socket_creation_successful:
- log("Successfully created connection to %s" % recipient)
- self.outbound_sockets[recipient] = s
- break
-
- def reset_sockets(self, sockets):
- """
- Reset the passed sockets. Takes a dict in the form sockets[HOST] = SOCKET
- """
- for s in sockets:
+ data = ''
try:
- sockets[s].close()
- except:
+ data = s.recv(1024)
+ except Exception, e:
pass
- for recipient in sockets:
- socket_creation_successful = False
-
- while not socket_creation_successful:
- try:
- s = self._open_xmit_socket(recipient)
- except socket.error:
- log("Failed to re-establish connection to %s" % recipient)
- socket_creation_successful = False
- else:
- socket_creation_successful = True
-
- if socket_creation_successful:
- self.outbound_sockets[recipient] = s
- break
+ s.close()
+
+ if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
+ log("Successfully sent bell strike to %s" % recipient)
+ else:
+ log("Unable to confirm bell strike to %s (network timeout?)" % recipient)
def listen(self):
while True:
# check serial input for bell strike notification
strikes_in_waiting = self.bell_strike_detected()
if strikes_in_waiting is not False:
log("Heard at least one strike")
for i in range(0, strikes_in_waiting):
self.transmit_bell_strike()
time.sleep(0.01)
def close(self):
global serialholder
if serialholder is not None:
serialholder.close()
- #for s in self.outbound_sockets:
- # self.outbound_sockets[s].close()
-
-
-
-
-
-
-
-
-
- # def loop(self):
- # """
- # Main server loop
- # """
- # while True:
- # print "loop A"
- #
- #
- # # listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
- # data_received = False
- # try:
- # conn, addr = self.socket.accept()
- # data_received = True
- # except Exception, e:
- # data_received = False
- #
- # if data_received:
- # print 'Connected by', addr
- # while 1:
- # print "loop B"
- # data = False
- # try:
- # log("Trying to read data from connection...")
- # data = conn.recv(1024)
- # log("Finished reading data")
- # except Exception, e:
- # print str(e)
- #
- # if not data:
- # print "breaking"
- # break
- #
- # if data==self.NETWORK_BELL_STRIKE_SIGNAL:
- # self.strike_bell()
- # conn.send(self.NETWORK_BELL_STRIKE_CONFIRMATION)
- #
- # time.sleep(0.01)
-
global serialholder
serialholder = SerialHolder()
-
if __name__ == '__main__':
-
- # record pid
- pidfile = open('%s/bellserver.pid' % os.path.abspath(os.path.dirname(__file__)),'w')
- pidfile.write(str(os.getpid()))
- pidfile.close()
- if os.fork():
- #server = SocketServer.TCPServer( (settings.HOST, settings.PORT), BellServer)
+ if os.fork():
server = SocketServerWrapper( (settings.HOST, settings.PORT), BellServer)
server.serve_forever()
else:
client = BellClient()
try:
client.listen()
finally:
client.close()
\ No newline at end of file
|
sbma44/artomatic
|
da680f5a83858e960ac8641d4fcadca2fc39877d
|
working bellserver script
|
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 5eb8b6a..502b4a1 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,229 +1,303 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
import os
import serial
import time
import settings
import SocketServer
-class BellServer(SocketServer.StreamRequestHandler):
- """
- Handles listening for and responding to network and serial events within the Ring For Service project
- """
- NETWORK_BELL_STRIKE_SIGNAL = 'DING'
- NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
+def log(message):
+ print "%f - %s" % (time.time(), message)
+
+class SerialHolder(object):
SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
- super(BellServer, self).__init__()
-
- self.log("Starting up")
+ super(SerialHolder, self).__init__()
- # set settings
- self.HOST = settings.HOST
- self.RECIPIENTS = settings.RECIPIENTS
- self.PORT = settings.PORT
-
- # create a nonblocking socket to handle server responsibilities
- self.log("Creating server socket")
- self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-
- self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- self.socket.setblocking(0)
- self.socket.settimeout(0)
- self.socket.bind((self.HOST, self.PORT))
- self.socket.listen(1)
-
# create a serial connection
- self.log("Establishing serial connection")
+ log("Establishing serial connection")
self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
+
# clear serial backlog
waiting = self.serial_connection.inWaiting()
self.serial_connection.read(waiting)
+
+ def strike_bell(self):
+ self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
+ log("Struck bell")
+
+ def bell_strike_detected(self):
+ """
+ Checks the serial connection for notice of a bell strike from the Arduino.
+ """
+ char = ''
+ try:
+ waiting = self.serial_connection.inWaiting()
+ if waiting>0:
+ char = self.serial_connection.read(waiting)
+ except Exception, e:
+ pass
- # create another socket to send communication to each recipient
- self.log("Creating outbound sockets")
- self.outbound_sockets = {}
- self.setup_outbound_sockets()
+ if len(char.strip())>0:
+ log("Detected serial communication - %s" % (char))
+ return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
- def handle(self):
- print self.rfile.readline().strip()
+ return False
+
+ def close(self):
+ self.serial_connection.close()
+
+
+class adsas(object):
+ """docstring for adsas"""
+ def __init__(self, arg):
+ super(adsas, self).__init__()
+ self.arg = arg
+
+
+class SocketServerWrapper(SocketServer.TCPServer):
+ """docstring for SocketServerWrapper"""
+ def __init__(self, *args):
+ self.allow_reuse_address = True
+ SocketServer.TCPServer.__init__(self,*args)
- def log(self, message):
- print "%f - %s" % (time.time(), message)
- def setup_outbound_sockets(self):
+
+class BellServer(SocketServer.StreamRequestHandler):
+
+ NETWORK_BELL_STRIKE_SIGNAL = 'DING'
+ NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
+
+ def strike_bell(self):
+ """
+ Send a bell strike notification to the Arduino over the serial link
+ """
+ global serialholder
+ if serialholder is not None:
+ serialholder.strike_bell()
+
+ def handle(self):
+ data = self.rfile.readline().strip()
+ log("Received data %s" % data)
+ if data==self.NETWORK_BELL_STRIKE_SIGNAL:
+ self.strike_bell()
+ self.wfile.write(self.NETWORK_BELL_STRIKE_CONFIRMATION)
+
+
+class BellClient(object):
+
+
+
+ def __init__(self):
+ super(BellClient, self).__init__()
+
+ self.RECIPIENTS = settings.RECIPIENTS
+ self.PORT = settings.PORT
+
+ self.NETWORK_BELL_STRIKE_SIGNAL = 'DING'
+ self.NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
+
+ # create another socket to send communication to each recipient
+ # log("Creating outbound sockets")
+ # self.outbound_sockets = {}
+ # self.setup_outbound_sockets()
+
+ def bell_strike_detected(self):
+ """
+ Checks the serial connection for notice of a bell strike from the Arduino.
+ """
+ global serialholder
+ if serialholder is not None:
+ return serialholder.bell_strike_detected()
+
+ return False
+
+ def transmit_bell_strike(self):
+ """
+ Send a bell strike notification across the network
+ """
+ # failed_sockets = {}
+ # for s in self.outbound_sockets:
+ # data = None
+ # try:
+ # self.outbound_sockets[s].send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
+ # data = self.outbound_sockets[s].recv(1024)
+ # self.outbound_sockets[s].close()
+ # except:
+ # failed_sockets[s] = self.outbound_sockets[s]
+ # if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
+ # log("Successfully sent bell strike")
+ #
+ # self.reset_sockets(failed_sockets)
+ log("Transmitting bell strike")
+
+ for recipient in self.RECIPIENTS:
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.settimeout(0.5)
+ s.connect((recipient, self.PORT))
+ s.send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
+ log("Receiving data")
+ data = s.recv(1024)
+ log("Done receiving data")
+ s.close()
+
+ if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
+ log("Successfully sent bell strike to %s" % recipient)
+
+
+ def _open_xmit_socket(self, recipient):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.connect((recipient, self.PORT))
+ return s
+
+
+ def setup_outbound_sockets(self):
+
# try to close any open sockets
for recipient in self.outbound_sockets:
try:
self.outbound_sockets[recipient].close()
except:
pass
-
+
# create connections
for recipient in settings.RECIPIENTS:
socket_creation_successful = False
while not socket_creation_successful:
# s = self._open_xmit_socket(recipient)
try:
s = self._open_xmit_socket(recipient)
except socket.error:
- self.log("Failed to establish connection to %s" % recipient)
+ log("Failed to establish connection to %s" % recipient)
socket_creation_successful = False
time.sleep(10)
else:
socket_creation_successful = True
-
+
if socket_creation_successful:
- self.log("Successfully created connection to %s" % recipient)
+ log("Successfully created connection to %s" % recipient)
self.outbound_sockets[recipient] = s
break
-
- def _open_xmit_socket(self, recipient):
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s.connect((recipient, self.PORT))
- return s
-
+
def reset_sockets(self, sockets):
"""
Reset the passed sockets. Takes a dict in the form sockets[HOST] = SOCKET
"""
for s in sockets:
try:
sockets[s].close()
except:
pass
-
+
for recipient in sockets:
socket_creation_successful = False
while not socket_creation_successful:
try:
s = self._open_xmit_socket(recipient)
except socket.error:
- self.log("Failed to re-establish connection to %s" % recipient)
+ log("Failed to re-establish connection to %s" % recipient)
socket_creation_successful = False
else:
socket_creation_successful = True
if socket_creation_successful:
self.outbound_sockets[recipient] = s
break
-
-
-
- def close(self):
- """
- Close socket to free it up for server restart or other uses.
- """
- self.socket.close()
- self.serial_connection.close()
-
- for s in self.outbound_sockets:
- self.outbound_sockets[s].close()
-
- def bell_strike_detected(self):
- """
- Checks the serial connection for notice of a bell strike from the Arduino.
- """
- # waiting = self.serial_connection.inWaiting()
- char = ''
- try:
- waiting = self.serial_connection.inWaiting()
- if waiting>0:
- char = self.serial_connection.read(waiting)
- except Exception, e:
- pass
-
- if len(char.strip())>0:
- self.log("Detected serial communication - %s" % (char))
- return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
-
- return False
-
- def transmit_bell_strike(self):
- """
- Send a bell strike notification across the network
- """
- failed_sockets = {}
- for s in self.outbound_sockets:
- data = None
- try:
- self.outbound_sockets[s].send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
- data = self.outbound_sockets[s].recv(1024)
- except:
- failed_sockets[s] = self.outbound_sockets[s]
- if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
- self.log("Successfully sent bell strike")
-
- self.reset_sockets(failed_sockets)
-
- def strike_bell(self):
- """
- Send a bell strike notification to the Arduino over the serial link
- """
- self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
- self.log("Struck bell")
-
- def loop(self):
- """
- Main server loop
- """
- while 1:
+
+ def listen(self):
+ while True:
# check serial input for bell strike notification
strikes_in_waiting = self.bell_strike_detected()
if strikes_in_waiting is not False:
+ log("Heard at least one strike")
for i in range(0, strikes_in_waiting):
self.transmit_bell_strike()
-
- # listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
- data_received = False
- try:
- conn, addr = self.socket.accept()
- data_received = True
- except Exception, e:
- data_received = False
-
- if data_received:
- print 'Connected by', addr
- while 1:
- print "loop"
- data = False
- try:
- self.log("Trying to read data from connection...")
- data = conn.recv(1024)
- self.log("Finished reading data")
- except Exception, e:
- print str(e)
-
- if not data: break
-
- if data==self.NETWORK_BELL_STRIKE_SIGNAL:
- self.strike_bell()
- conn.send(self.NETWORK_BELL_STRIKE_CONFIRMATION)
-
time.sleep(0.01)
+ def close(self):
+ global serialholder
+ if serialholder is not None:
+ serialholder.close()
+
+ #for s in self.outbound_sockets:
+ # self.outbound_sockets[s].close()
+
+
+
+
+
+
+
+
+
+ # def loop(self):
+ # """
+ # Main server loop
+ # """
+ # while True:
+ # print "loop A"
+ #
+ #
+ # # listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
+ # data_received = False
+ # try:
+ # conn, addr = self.socket.accept()
+ # data_received = True
+ # except Exception, e:
+ # data_received = False
+ #
+ # if data_received:
+ # print 'Connected by', addr
+ # while 1:
+ # print "loop B"
+ # data = False
+ # try:
+ # log("Trying to read data from connection...")
+ # data = conn.recv(1024)
+ # log("Finished reading data")
+ # except Exception, e:
+ # print str(e)
+ #
+ # if not data:
+ # print "breaking"
+ # break
+ #
+ # if data==self.NETWORK_BELL_STRIKE_SIGNAL:
+ # self.strike_bell()
+ # conn.send(self.NETWORK_BELL_STRIKE_CONFIRMATION)
+ #
+ # time.sleep(0.01)
+
+
+global serialholder
+serialholder = SerialHolder()
+
if __name__ == '__main__':
# record pid
pidfile = open('%s/bellserver.pid' % os.path.abspath(os.path.dirname(__file__)),'w')
pidfile.write(str(os.getpid()))
- pidfile.close()
-
- B = BellServer()
- try:
- B.loop()
- finally:
- # shutdown socket
- B.close()
- os.unlink('%s/bellserver.pid' % os.path.abspath(os.path.dirname(__file__)))
\ No newline at end of file
+ pidfile.close()
+
+ if os.fork():
+ #server = SocketServer.TCPServer( (settings.HOST, settings.PORT), BellServer)
+ server = SocketServerWrapper( (settings.HOST, settings.PORT), BellServer)
+ server.serve_forever()
+ else:
+ client = BellClient()
+ try:
+ client.listen()
+ finally:
+ client.close()
\ No newline at end of file
|
sbma44/artomatic
|
0ba3befcf09126a4ec056b02db830cf5b3f87b32
|
starting to convert bellserver to use SocketServer
|
diff --git a/openwrt/config/dhcp b/openwrt/config/dhcp
new file mode 100644
index 0000000..8522897
--- /dev/null
+++ b/openwrt/config/dhcp
@@ -0,0 +1,26 @@
+config dnsmasq
+ option domainneeded 1
+ option boguspriv 1
+ option filterwin2k '0' #enable for dial on demand
+ option localise_queries 1
+ option local '/lan/'
+ option domain 'lan'
+ option expandhosts 1
+ option nonegcache 0
+ option authoritative 1
+ option readethers 1
+ option leasefile '/tmp/dhcp.leases'
+ option resolvfile '/tmp/resolv.conf.auto'
+ #list server '/mycompany.local/1.2.3.4'
+ #option nonwildcard 0
+ #list interface br-lan
+
+config dhcp lan
+ option interface lan
+ option start 100
+ option limit 150
+ option leasetime 12h
+
+config dhcp wan
+ option interface wan
+ option ignore 1
diff --git a/openwrt/config/dropbear b/openwrt/config/dropbear
new file mode 100644
index 0000000..e660ac7
--- /dev/null
+++ b/openwrt/config/dropbear
@@ -0,0 +1,3 @@
+config dropbear
+ option PasswordAuth 'on'
+ option Port '22'
diff --git a/openwrt/config/firewall b/openwrt/config/firewall
new file mode 100644
index 0000000..464540f
--- /dev/null
+++ b/openwrt/config/firewall
@@ -0,0 +1,81 @@
+config defaults
+ option syn_flood 1
+ option input ACCEPT
+ option output ACCEPT
+ option forward REJECT
+
+config zone
+ option name lan
+ option input ACCEPT
+ option output ACCEPT
+ option forward REJECT
+
+config zone
+ option name wan
+ option input REJECT
+ option output ACCEPT
+ option forward REJECT
+ option masq 1
+
+config forwarding
+ option src lan
+ option dest wan
+ option mtu_fix 1
+
+# include a file with users custom iptables rules
+config include
+ option path /etc/firewall.user
+
+
+### EXAMPLE CONFIG SECTIONS
+# do not allow a specific ip to access wan
+#config rule
+# option src lan
+# option src_ip 192.168.45.2
+# option dest wan
+# option proto tcp
+# option target REJECT
+
+# block a specific mac on wan
+#config rule
+# option dest wan
+# option src_mac 00:11:22:33:44:66
+# option target REJECT
+
+# block incoming ICMP traffic on a zone
+#config rule
+# option src lan
+# option proto ICMP
+# option target DROP
+
+# port redirect port coming in on wan to lan
+#config redirect
+# option src wan
+# option src_dport 80
+# option dest lan
+# option dest_ip 192.168.16.235
+# option dest_port 80
+# option proto tcp
+
+
+### FULL CONFIG SECTIONS
+#config rule
+# option src lan
+# option src_ip 192.168.45.2
+# option src_mac 00:11:22:33:44:55
+# option src_port 80
+# option dest wan
+# option dest_ip 194.25.2.129
+# option dest_port 120
+# option proto tcp
+# option target REJECT
+
+#config redirect
+# option src lan
+# option src_ip 192.168.45.2
+# option src_mac 00:11:22:33:44:55
+# option src_port 1024
+# option src_dport 80
+# option dest_ip 194.25.2.129
+# option dest_port 120
+# option proto tcp
diff --git a/openwrt/config/fstab b/openwrt/config/fstab
new file mode 100644
index 0000000..eccf0ce
--- /dev/null
+++ b/openwrt/config/fstab
@@ -0,0 +1,10 @@
+config mount
+ option target /home
+ option device /dev/sda1
+ option fstype ext3
+ option options rw,sync
+ option enabled 0
+
+config swap
+ option device /dev/sda2
+ option enabled 0
diff --git a/openwrt/config/httpd b/openwrt/config/httpd
new file mode 100644
index 0000000..2f8020f
--- /dev/null
+++ b/openwrt/config/httpd
@@ -0,0 +1,5 @@
+
+config 'httpd'
+ option 'port' '80'
+ option 'home' '/www'
+
diff --git a/openwrt/config/system b/openwrt/config/system
new file mode 100644
index 0000000..47faa3c
--- /dev/null
+++ b/openwrt/config/system
@@ -0,0 +1,17 @@
+config system
+ option hostname OpenWrt
+ option timezone UTC
+
+config button
+ option button reset
+ option action released
+ option handler "logger reboot"
+ option min 0
+ option max 4
+
+config button
+ option button reset
+ option action released
+ option handler "logger factory default"
+ option min 5
+ option max 30
diff --git a/openwrt/openwrt-atheros-root.squashfs b/openwrt/openwrt-atheros-root.squashfs
new file mode 100755
index 0000000..b498a4c
Binary files /dev/null and b/openwrt/openwrt-atheros-root.squashfs differ
diff --git a/openwrt/openwrt-atheros-vmlinux.lzma b/openwrt/openwrt-atheros-vmlinux.lzma
new file mode 100755
index 0000000..5f208bc
Binary files /dev/null and b/openwrt/openwrt-atheros-vmlinux.lzma differ
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 07f8bee..5eb8b6a 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,121 +1,229 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
+import os
import serial
import time
import settings
+import SocketServer
-class BellServer(object):
+class BellServer(SocketServer.StreamRequestHandler):
"""
Handles listening for and responding to network and serial events within the Ring For Service project
"""
NETWORK_BELL_STRIKE_SIGNAL = 'DING'
NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
super(BellServer, self).__init__()
+ self.log("Starting up")
+
+ # set settings
self.HOST = settings.HOST
self.RECIPIENTS = settings.RECIPIENTS
- self.PORT = settings.PORT
+ self.PORT = settings.PORT
# create a nonblocking socket to handle server responsibilities
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.setblocking(0)
- s.bind((self.HOST, self.PORT))
- self.socket = s
-
+ self.log("Creating server socket")
+ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+
+ self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ self.socket.setblocking(0)
+ self.socket.settimeout(0)
+ self.socket.bind((self.HOST, self.PORT))
+ self.socket.listen(1)
+
# create a serial connection
+ self.log("Establishing serial connection")
self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
-
+ # clear serial backlog
+ waiting = self.serial_connection.inWaiting()
+ self.serial_connection.read(waiting)
+
+ # create another socket to send communication to each recipient
+ self.log("Creating outbound sockets")
+ self.outbound_sockets = {}
+ self.setup_outbound_sockets()
+
+ def handle(self):
+ print self.rfile.readline().strip()
def log(self, message):
print "%f - %s" % (time.time(), message)
+ def setup_outbound_sockets(self):
+
+ # try to close any open sockets
+ for recipient in self.outbound_sockets:
+ try:
+ self.outbound_sockets[recipient].close()
+ except:
+ pass
+
+ # create connections
+ for recipient in settings.RECIPIENTS:
+ socket_creation_successful = False
+
+ while not socket_creation_successful:
+ # s = self._open_xmit_socket(recipient)
+ try:
+ s = self._open_xmit_socket(recipient)
+ except socket.error:
+ self.log("Failed to establish connection to %s" % recipient)
+ socket_creation_successful = False
+ time.sleep(10)
+ else:
+ socket_creation_successful = True
+
+ if socket_creation_successful:
+ self.log("Successfully created connection to %s" % recipient)
+ self.outbound_sockets[recipient] = s
+ break
+
+ def _open_xmit_socket(self, recipient):
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ s.connect((recipient, self.PORT))
+ return s
+
+ def reset_sockets(self, sockets):
+ """
+ Reset the passed sockets. Takes a dict in the form sockets[HOST] = SOCKET
+ """
+ for s in sockets:
+ try:
+ sockets[s].close()
+ except:
+ pass
+
+ for recipient in sockets:
+ socket_creation_successful = False
+
+ while not socket_creation_successful:
+ try:
+ s = self._open_xmit_socket(recipient)
+ except socket.error:
+ self.log("Failed to re-establish connection to %s" % recipient)
+ socket_creation_successful = False
+ else:
+ socket_creation_successful = True
+
+ if socket_creation_successful:
+ self.outbound_sockets[recipient] = s
+ break
+
+
def close(self):
"""
Close socket to free it up for server restart or other uses.
"""
self.socket.close()
- self.serial_connectsion.close()
+ self.serial_connection.close()
+
+ for s in self.outbound_sockets:
+ self.outbound_sockets[s].close()
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
- if self.serial_connection.inWaiting()>0:
- return self.serial_connection.read()==self.SERIAL_BELL_STRIKE_SIGNAL
+ # waiting = self.serial_connection.inWaiting()
+ char = ''
+ try:
+ waiting = self.serial_connection.inWaiting()
+ if waiting>0:
+ char = self.serial_connection.read(waiting)
+ except Exception, e:
+ pass
+
+ if len(char.strip())>0:
+ self.log("Detected serial communication - %s" % (char))
+ return char.count(self.SERIAL_BELL_STRIKE_SIGNAL)
+
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
- """
- for recipient in self.RECIPIENTS:
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect((recipient, self.PORT))
- s.send(self.NETWORK_BELL_STRIKE_SIGNAL)
- data = s.recv(1024)
- s.close()
+ """
+ failed_sockets = {}
+ for s in self.outbound_sockets:
+ data = None
+ try:
+ self.outbound_sockets[s].send(self.NETWORK_BELL_STRIKE_SIGNAL + "\n")
+ data = self.outbound_sockets[s].recv(1024)
+ except:
+ failed_sockets[s] = self.outbound_sockets[s]
+
if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
- print 'bell successfully struck'
- self.log("Sent bell strike")
+ self.log("Successfully sent bell strike")
+
+ self.reset_sockets(failed_sockets)
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
- self.serial_connection.write(SERIAL_BELL_STRIKE_SIGNAL)
+ self.serial_connection.write(self.SERIAL_BELL_STRIKE_SIGNAL)
self.log("Struck bell")
- print 'DING!'
def loop(self):
"""
Main server loop
"""
-
- self.socket.listen(1)
while 1:
# check serial input for bell strike notification
- while self.bell_strike_detected():
- self.transmit_bell_strike()
+ strikes_in_waiting = self.bell_strike_detected()
+ if strikes_in_waiting is not False:
+ for i in range(0, strikes_in_waiting):
+ self.transmit_bell_strike()
# listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
data_received = False
try:
conn, addr = self.socket.accept()
data_received = True
except Exception, e:
data_received = False
if data_received:
print 'Connected by', addr
while 1:
+ print "loop"
data = False
try:
+ self.log("Trying to read data from connection...")
data = conn.recv(1024)
+ self.log("Finished reading data")
except Exception, e:
- pass
+ print str(e)
if not data: break
- # TODO: replace echo with write to serial output to initiate bell strike
if data==self.NETWORK_BELL_STRIKE_SIGNAL:
self.strike_bell()
conn.send(self.NETWORK_BELL_STRIKE_CONFIRMATION)
time.sleep(0.01)
if __name__ == '__main__':
+
+ # record pid
+ pidfile = open('%s/bellserver.pid' % os.path.abspath(os.path.dirname(__file__)),'w')
+ pidfile.write(str(os.getpid()))
+ pidfile.close()
+
B = BellServer()
try:
B.loop()
finally:
# shutdown socket
- B.close()
\ No newline at end of file
+ B.close()
+ os.unlink('%s/bellserver.pid' % os.path.abspath(os.path.dirname(__file__)))
\ No newline at end of file
|
sbma44/artomatic
|
2630d50c83aefe321c31f5837d4be60c6ae622c1
|
adding serial code
|
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index a53365b..07f8bee 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,107 +1,121 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
+import serial
import time
import settings
class BellServer(object):
"""
Handles listening for and responding to network and serial events within the Ring For Service project
"""
- BELL_STRIKE_SIGNAL = 'DING'
- BELL_STRIKE_CONFIRMATION = 'DONG'
+ NETWORK_BELL_STRIKE_SIGNAL = 'DING'
+ NETWORK_BELL_STRIKE_CONFIRMATION = 'DONG'
+ SERIAL_BELL_STRIKE_SIGNAL = '#'
def __init__(self):
super(BellServer, self).__init__()
self.HOST = settings.HOST
self.RECIPIENTS = settings.RECIPIENTS
self.PORT = settings.PORT
# create a nonblocking socket to handle server responsibilities
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.bind((self.HOST, self.PORT))
self.socket = s
+ # create a serial connection
+ self.serial_connection = serial.Serial(settings.SERIAL_PORT, settings.BAUD_RATE, timeout=0)
+
+
+ def log(self, message):
+ print "%f - %s" % (time.time(), message)
+
+
def close(self):
"""
Close socket to free it up for server restart or other uses.
"""
self.socket.close()
+ self.serial_connectsion.close()
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
- # TODO: everything
+ if self.serial_connection.inWaiting()>0:
+ return self.serial_connection.read()==self.SERIAL_BELL_STRIKE_SIGNAL
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((recipient, self.PORT))
- s.send(self.BELL_STRIKE_SIGNAL)
+ s.send(self.NETWORK_BELL_STRIKE_SIGNAL)
data = s.recv(1024)
s.close()
- if data==self.BELL_STRIKE_CONFIRMATION:
+ if data==self.NETWORK_BELL_STRIKE_CONFIRMATION:
print 'bell successfully struck'
+ self.log("Sent bell strike")
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
- print 'DING!'
- pass
+ self.serial_connection.write(SERIAL_BELL_STRIKE_SIGNAL)
+ self.log("Struck bell")
+ print 'DING!'
def loop(self):
"""
Main server loop
"""
self.socket.listen(1)
while 1:
# check serial input for bell strike notification
- if self.bell_strike_detected():
+ while self.bell_strike_detected():
self.transmit_bell_strike()
# listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
data_received = False
try:
conn, addr = self.socket.accept()
data_received = True
except Exception, e:
data_received = False
if data_received:
print 'Connected by', addr
while 1:
data = False
try:
data = conn.recv(1024)
except Exception, e:
pass
if not data: break
# TODO: replace echo with write to serial output to initiate bell strike
- if data==self.BELL_STRIKE_SIGNAL:
+ if data==self.NETWORK_BELL_STRIKE_SIGNAL:
self.strike_bell()
- conn.send(self.BELL_STRIKE_CONFIRMATION)
+ conn.send(self.NETWORK_BELL_STRIKE_CONFIRMATION)
time.sleep(0.01)
if __name__ == '__main__':
B = BellServer()
try:
B.loop()
finally:
# shutdown socket
B.close()
\ No newline at end of file
diff --git a/scripts/settings.py b/scripts/settings.py
index 43414b1..6017f8a 100644
--- a/scripts/settings.py
+++ b/scripts/settings.py
@@ -1,3 +1,5 @@
HOST = ''
-RECIPIENTS = ['127.0.0.1']
+RECIPIENTS = ['192.168.11.1']
PORT = 50008
+SERIAL_PORT = '/dev/ttyS0'
+BAUD_RATE = 115200
|
sbma44/artomatic
|
6bd36cfb24bb16209783db5fe5e173100f4afbd9
|
adding sleep cycle to keep from pegging CPU; also adding ACK for bell strikes
|
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 454ee0c..a53365b 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,99 +1,107 @@
# Echo server program
try:
import socket
except Exception, e:
import _socket as socket
import time
import settings
class BellServer(object):
"""
Handles listening for and responding to network and serial events within the Ring For Service project
"""
+ BELL_STRIKE_SIGNAL = 'DING'
+ BELL_STRIKE_CONFIRMATION = 'DONG'
+
def __init__(self):
super(BellServer, self).__init__()
self.HOST = settings.HOST
self.RECIPIENTS = settings.RECIPIENTS
self.PORT = settings.PORT
# create a nonblocking socket to handle server responsibilities
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.bind((self.HOST, self.PORT))
self.socket = s
def close(self):
"""
Close socket to free it up for server restart or other uses.
"""
self.socket.close()
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
# TODO: everything
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((recipient, self.PORT))
- s.send('[X]')
+ s.send(self.BELL_STRIKE_SIGNAL)
data = s.recv(1024)
s.close()
- print 'Received', repr(data)
+ if data==self.BELL_STRIKE_CONFIRMATION:
+ print 'bell successfully struck'
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
+ print 'DING!'
pass
def loop(self):
"""
Main server loop
"""
self.socket.listen(1)
while 1:
# check serial input for bell strike notification
if self.bell_strike_detected():
- self.send_bell()
+ self.transmit_bell_strike()
# listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
data_received = False
try:
conn, addr = self.socket.accept()
data_received = True
except Exception, e:
data_received = False
if data_received:
print 'Connected by', addr
while 1:
data = False
try:
data = conn.recv(1024)
except Exception, e:
pass
if not data: break
# TODO: replace echo with write to serial output to initiate bell strike
- self.strike_bell()
- conn.send(data.upper())
+ if data==self.BELL_STRIKE_SIGNAL:
+ self.strike_bell()
+ conn.send(self.BELL_STRIKE_CONFIRMATION)
+
+ time.sleep(0.01)
if __name__ == '__main__':
B = BellServer()
try:
B.loop()
finally:
# shutdown socket
B.close()
\ No newline at end of file
|
sbma44/artomatic
|
b3c7d818eb2c0443e3a8c9109d17919d69dc3170
|
adding serial and firmware stuff
|
diff --git a/fonera-python/dd-wrt/README b/fonera-python/dd-wrt/README
new file mode 100644
index 0000000..207a656
--- /dev/null
+++ b/fonera-python/dd-wrt/README
@@ -0,0 +1,10 @@
+This is an old beta release of DD-WRT (DD-WRT v24 Beta (08/03/07) std - build 7603).
+
+It may be downloaded from:
+http://www.dd-wrt.com/dd-wrtv2/down.php?path=downloads%2Fobsolete%2Fbeta%2FFONERA%2F2007+-+0803/
+
+IF YOU ARE TRYING TO RUN PYTHON ON A DD-WRT FONERA, USE THIS FIRMWARE.
+
+Newer firmwares take up too much space, leaving insufficient room on the JFFS2 partition for Python. Other
+v24 betas introduce odd errors that prevent Python from running. I'm sorry, but you're stuck. If you need newer functionality, you may want to consider the OpenWRT project.
+
diff --git a/fonera-python/dd-wrt/fonera_flashing.txt b/fonera-python/dd-wrt/fonera_flashing.txt
new file mode 100644
index 0000000..4b7f16d
--- /dev/null
+++ b/fonera-python/dd-wrt/fonera_flashing.txt
@@ -0,0 +1,78 @@
+0.
+Install the RedBoot bootloader using a compatible method as detailed at
+
+http://www.dd-wrt.com/wiki/index.php/La_Fonera_Flashing#Step_4
+
+Follow the instructions up to and including step 2.4.
+
+This must only be done once.
+
+
+1. Edit ~/.telnetrc to include the following lines (between the snips). If you're not on *nix/OS X, find other means of configuring your telnet client to use line mode.
+
+==== snip ====
+192.168.1.254
+ mode line
+==== snip ====
+
+1. Configure your ethernet adapter to use an IP in the 192.168.1.* range (the final byte may not be 254). Subnet mask should be 255.255.255.0. For these instructions, we assume 192.168.1.166. Connect to the Fonera with an ethernet cable.
+
+2. Power on the Fonera. Very shortly after the "Internet" LED begins to blink, RedBoot will be open to telnet connections at the address 192.168.1.254:9000. This window is typically configured to last 10 seconds. Duyring this window of time, connect by typing
+
+telnet 192.168.1.254 9000
+
+(if on *nix/OS X -- otherwise, find and configure telnet software as necessary)
+
+3. You should see a prompt saying you can cancel boot by pressing control+c. Do so. You should now have a RedBoot> prompt.
+
+ORIGINAL DD-WRT FLASHING INSTRUCTIONS CONTINUE FROM HERE, AND ASSUME YOU HAVE A TFTP SERVER AVAILABLE
+
+4.
+copy root.fs and vmlinux.bin.l7 to your tftp server directory
+
+5.
+configure the RedBoot bootloader IP and TFTP server settings using
+ip_address -l [local ip address] -h [remote server address]
+(NOTE: if using the above-suggested IP, this command should be "ip_address -l 192.168.1.254 -h 192.168.1.166")
+
+6.
+flash the unit by entering the following commands
+
+RedBoot> fis init
+About to initialize [format] FLASH image system - continue (y/n)? y
+*** Initialize FLASH Image System
+... Erase from 0xa83e0000-0xa83f0000: .
+... Program from 0x80ff0000-0x81000000 at 0xa83e0000: .
+
+load -r -v -b 0x80041000 root.fs
+Using default protocol (TFTP)
+Raw file loaded 0x80041000-0x802e3fff, assumed entry at 0x80041000
+RedBoot> fis create -b 0x80041000 -f 0xA8030000 -l 0x002C0000 -e 0x00000000 rootfs
+... Erase from 0xa8030000-0xa82f0000: ............................................
+... Program from 0x80041000-0x80301000 at 0xa8030000: ............................................
+... Erase from 0xa83e0000-0xa83f0000: .
+... Program from 0x80ff0000-0x81000000 at 0xa83e0000: .
+
+RedBoot> load -r -v -b 0x80041000 vmlinux.bin.l7
+Using default protocol (TFTP)
+Raw file loaded 0x80041000-0x80120fff, assumed entry at 0x80041000
+
+RedBoot> fis create -r 0x80041000 -e 0x80041000 vmlinux.bin.l7
+... Erase from 0xa82f0000-0xa83d0000: ..............
+... Program from 0x80041000-0x80121000 at 0xa82f0000: ..............
+... Erase from 0xa83e0000-0xa83f0000: .
+... Program from 0x80ff0000-0x81000000 at 0xa83e0000: .
+
+RedBoot> fis create -f 0xA83D0000 -l 0x00010000 -n nvram
+... Erase from 0xa83e0000-0xa83f0000: .
+... Program from 0x80ff0000-0x81000000 at 0xa83e0000: .
+
+fconfig
+enter the bootscript:
+fis load -l vmlinux.bin.l7
+exec
+
+save the config and do
+
+reset
+
diff --git a/fonera-python/dd-wrt/root.fs b/fonera-python/dd-wrt/root.fs
new file mode 100644
index 0000000..28dbadf
Binary files /dev/null and b/fonera-python/dd-wrt/root.fs differ
diff --git a/fonera-python/dd-wrt/vmlinux.bin.l7 b/fonera-python/dd-wrt/vmlinux.bin.l7
new file mode 100644
index 0000000..90e195b
Binary files /dev/null and b/fonera-python/dd-wrt/vmlinux.bin.l7 differ
diff --git a/fonera-python/serial/.cvsignore b/fonera-python/serial/.cvsignore
new file mode 100644
index 0000000..7e99e36
--- /dev/null
+++ b/fonera-python/serial/.cvsignore
@@ -0,0 +1 @@
+*.pyc
\ No newline at end of file
diff --git a/fonera-python/serial/__init__.py b/fonera-python/serial/__init__.py
new file mode 100644
index 0000000..681ad5c
--- /dev/null
+++ b/fonera-python/serial/__init__.py
@@ -0,0 +1,25 @@
+#!/usr/bin/env python
+#portable serial port access with python
+#this is a wrapper module for different platform implementations
+#
+# (C)2001-2002 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+
+VERSION = '2.4'
+
+import sys
+
+if sys.platform == 'cli':
+ from serialcli import *
+else:
+ import os
+ #chose an implementation, depending on os
+ if os.name == 'nt': #sys.platform == 'win32':
+ from serialwin32 import *
+ elif os.name == 'posix':
+ from serialposix import *
+ elif os.name == 'java':
+ from serialjava import *
+ else:
+ raise Exception("Sorry: no implementation for your platform ('%s') available" % os.name)
+
diff --git a/fonera-python/serial/serialcli.py b/fonera-python/serial/serialcli.py
new file mode 100644
index 0000000..9864848
--- /dev/null
+++ b/fonera-python/serial/serialcli.py
@@ -0,0 +1,247 @@
+#! python
+# Python Serial Port Extension for Win32, Linux, BSD, Jython and .NET/Mono
+# serial driver for .NET/Mono (IronPython), .NET >= 2
+# see __init__.py
+#
+# (C) 2008 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+
+import clr
+import System
+import System.IO.Ports
+from serialutil import *
+
+def device(portnum):
+ """Turn a port number into a device name"""
+ return System.IO.Ports.SerialPort.GetPortNames()[portnum]
+
+# must invoke function with byte array, make a helper to convert strings
+# to byte arrays
+sab = System.Array[System.Byte]
+def as_byte_array(string):
+ return sab([ord(x) for x in string])
+
+class Serial(SerialBase):
+ """Serial port implemenation for .NET/Mono."""
+
+ BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
+ 19200,38400,57600,115200)
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ try:
+ self._port_handle = System.IO.Ports.SerialPort(self.portstr)
+ except Exception, msg:
+ self._port_handle = None
+ raise SerialException("could not open port %s: %s" % (self.portstr, msg))
+
+ self._reconfigurePort()
+ self._port_handle.Open()
+ self._isOpen = True
+ if not self._rtscts:
+ self.setRTS(True)
+ self.setDTR(True)
+ self.flushInput()
+ self.flushOutput()
+
+ def _reconfigurePort(self):
+ """Set communication parameters on opened port."""
+ if not self._port_handle:
+ raise SerialException("Can only operate on a valid port handle")
+
+ self.ReceivedBytesThreshold = 1
+
+ if self._timeout is None:
+ self._port_handle.ReadTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
+ else:
+ self._port_handle.ReadTimeout = int(self._timeout*1000)
+
+ # if self._timeout != 0 and self._interCharTimeout is not None:
+ # timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
+
+ if self._writeTimeout is None:
+ self._port_handle.WriteTimeout = System.IO.Ports.SerialPort.InfiniteTimeout
+ else:
+ self._port_handle.WriteTimeout = int(self._writeTimeout*1000)
+
+
+ # Setup the connection info.
+ try:
+ self._port_handle.BaudRate = self._baudrate
+ except IOError, e:
+ # catch errors from illegal baudrate settings
+ raise ValueError(str(e))
+
+ if self._bytesize == FIVEBITS:
+ self._port_handle.DataBits = 5
+ elif self._bytesize == SIXBITS:
+ self._port_handle.DataBits = 6
+ elif self._bytesize == SEVENBITS:
+ self._port_handle.DataBits = 7
+ elif self._bytesize == EIGHTBITS:
+ self._port_handle.DataBits = 8
+ else:
+ raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
+
+ if self._parity == PARITY_NONE:
+ self._port_handle.Parity = System.IO.Ports.Parity.None
+ elif self._parity == PARITY_EVEN:
+ self._port_handle.Parity = System.IO.Ports.Parity.Even
+ elif self._parity == PARITY_ODD:
+ self._port_handle.Parity = System.IO.Ports.Parity.Odd
+ elif self._parity == PARITY_MARK:
+ self._port_handle.Parity = System.IO.Ports.Parity.Mark
+ elif self._parity == PARITY_SPACE:
+ self._port_handle.Parity = System.IO.Ports.Parity.Space
+ else:
+ raise ValueError("Unsupported parity mode: %r" % self._parity)
+
+ if self._stopbits == STOPBITS_ONE:
+ self._port_handle.StopBits = System.IO.Ports.StopBits.One
+ elif self._stopbits == STOPBITS_TWO:
+ self._port_handle.StopBits = System.IO.Ports.StopBits.Two
+ else:
+ raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
+
+ if self._rtscts and self._xonxoff:
+ self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSendXOnXOff
+ elif self._rtscts:
+ self._port_handle.Handshake = System.IO.Ports.Handshake.RequestToSend
+ elif self._xonxoff:
+ self._port_handle.Handshake = System.IO.Ports.Handshake.XOnXOff
+ else:
+ self._port_handle.Handshake = System.IO.Ports.Handshake.None
+
+ #~ def __del__(self):
+ #~ self.close()
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self._port_handle:
+ try:
+ self._port_handle.Close()
+ except System.IO.Ports.InvalidOperationException:
+ # ignore errors. can happen for unplugged USB serial devices
+ pass
+ self._port_handle = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ try:
+ return device(port)
+ except TypeError, e:
+ raise SerialException(str(e))
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ if not self._port_handle: raise portNotOpenError
+ return self._port_handle.BytesToRead
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if not self._port_handle: raise portNotOpenError
+ # must use single byte reads as this is the only way to read
+ # without applying encodings
+ data = []
+ while size:
+ try:
+ data.append(chr(self._port_handle.ReadByte()))
+ except System.TimeoutException, e:
+ break
+ else:
+ size -= 1
+ return ''.join(data)
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if not self._port_handle: raise portNotOpenError
+ if not isinstance(data, str):
+ raise TypeError('expected str, got %s' % type(data))
+ try:
+ # must call overloaded method with byte array argument
+ # as this is the only one not applying encodings
+ self._port_handle.Write(as_byte_array(data), 0, len(data))
+ except System.TimeoutException, e:
+ raise writeTimeoutError
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if not self._port_handle: raise portNotOpenError
+ self._port_handle.DiscardInBuffer()
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if not self._port_handle: raise portNotOpenError
+ self._port_handle.DiscardOutBuffer()
+
+ def sendBreak(self, duration=0.25):
+ """Send break condition. Timed, returns to idle state after given duration."""
+ if not self._port_handle: raise portNotOpenError
+ import time
+ self._port_handle.BreakState = True
+ time.sleep(duration)
+ self._port_handle.BreakState = False
+
+ def setBreak(self, level=True):
+ """Set break: Controls TXD. When active, to transmitting is possible."""
+ if not self._port_handle: raise portNotOpenError
+ self._port_handle.BreakState = bool(level)
+
+ def setRTS(self, level=True):
+ """Set terminal status line: Request To Send"""
+ if not self._port_handle: raise portNotOpenError
+ self._port_handle.RtsEnable = bool(level)
+
+ def setDTR(self, level=True):
+ """Set terminal status line: Data Terminal Ready"""
+ if not self._port_handle: raise portNotOpenError
+ self._port_handle.DtrEnable = bool(level)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if not self._port_handle: raise portNotOpenError
+ return self._port_handle.CtsHolding
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if not self._port_handle: raise portNotOpenError
+ return self._port_handle.DsrHolding
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if not self._port_handle: raise portNotOpenError
+ #~ return self._port_handle.XXX
+ return False #XXX an error would be better
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if not self._port_handle: raise portNotOpenError
+ return self._port_handle.CDHolding
+
+ # - - platform specific - - - -
+
+#Nur Testfunktion!!
+if __name__ == '__main__':
+ s = Serial(0)
+ print s
+
+ s = Serial()
+ print s
+
+
+ s.baudrate = 19200
+ s.databits = 7
+ s.close()
+ s.port = 0
+ s.open()
+ print s
+
diff --git a/fonera-python/serial/serialjava.py b/fonera-python/serial/serialjava.py
new file mode 100644
index 0000000..cca46dc
--- /dev/null
+++ b/fonera-python/serial/serialjava.py
@@ -0,0 +1,240 @@
+#!jython
+#
+# Python Serial Port Extension for Win32, Linux, BSD, Jython
+# module for serial IO for Jython and JavaComm
+# see __init__.py
+#
+# (C) 2002-2008 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+
+from serialutil import *
+
+def my_import(name):
+ mod = __import__(name)
+ components = name.split('.')
+ for comp in components[1:]:
+ mod = getattr(mod, comp)
+ return mod
+
+def detect_java_comm(names):
+ """try given list of modules and return that imports"""
+ for name in names:
+ try:
+ mod = my_import(name)
+ mod.SerialPort
+ return mod
+ except (ImportError, AttributeError):
+ pass
+ raise ImportError("No Java Communications API implementation found")
+
+# Java Communications API implementations
+# http://mho.republika.pl/java/comm/
+
+comm = detect_java_comm([
+ 'javax.comm', # Sun/IBM
+ 'gnu.io', # RXTX
+])
+
+
+def device(portnumber):
+ """Turn a port number into a device name"""
+ enum = comm.CommPortIdentifier.getPortIdentifiers()
+ ports = []
+ while enum.hasMoreElements():
+ el = enum.nextElement()
+ if el.getPortType() == comm.CommPortIdentifier.PORT_SERIAL:
+ ports.append(el)
+ return ports[portnumber].getName()
+
+class Serial(SerialBase):
+ """Serial port class, implemented with Java Communications API and
+ thus usable with jython and the appropriate java extension."""
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ if type(self._port) == type(''): #strings are taken directly
+ portId = comm.CommPortIdentifier.getPortIdentifier(self._port)
+ else:
+ portId = comm.CommPortIdentifier.getPortIdentifier(device(self._port)) #numbers are transformed to a comportid obj
+ try:
+ self.sPort = portId.open("python serial module", 10)
+ except Exception, msg:
+ self.sPort = None
+ raise SerialException("Could not open port: %s" % msg)
+ self._reconfigurePort()
+ self._instream = self.sPort.getInputStream()
+ self._outstream = self.sPort.getOutputStream()
+ self._isOpen = True
+
+ def _reconfigurePort(self):
+ """Set commuication parameters on opened port."""
+ if not self.sPort:
+ raise SerialException("Can only operate on a valid port handle")
+
+ self.sPort.enableReceiveTimeout(30)
+ if self._bytesize == FIVEBITS:
+ jdatabits = comm.SerialPort.DATABITS_5
+ elif self._bytesize == SIXBITS:
+ jdatabits = comm.SerialPort.DATABITS_6
+ elif self._bytesize == SEVENBITS:
+ jdatabits = comm.SerialPort.DATABITS_7
+ elif self._bytesize == EIGHTBITS:
+ jdatabits = comm.SerialPort.DATABITS_8
+ else:
+ raise ValueError("unsupported bytesize: %r" % self._bytesize)
+
+ if self._stopbits == STOPBITS_ONE:
+ jstopbits = comm.SerialPort.STOPBITS_1
+ elif stopbits == STOPBITS_ONE_HALVE:
+ self._jstopbits = comm.SerialPort.STOPBITS_1_5
+ elif self._stopbits == STOPBITS_TWO:
+ jstopbits = comm.SerialPort.STOPBITS_2
+ else:
+ raise ValueError("unsupported number of stopbits: %r" % self._stopbits)
+
+ if self._parity == PARITY_NONE:
+ jparity = comm.SerialPort.PARITY_NONE
+ elif self._parity == PARITY_EVEN:
+ jparity = comm.SerialPort.PARITY_EVEN
+ elif self._parity == PARITY_ODD:
+ jparity = comm.SerialPort.PARITY_ODD
+ elif self._parity == PARITY_MARK:
+ jparity = comm.SerialPort.PARITY_MARK
+ elif self._parity == PARITY_SPACE:
+ jparity = comm.SerialPort.PARITY_SPACE
+ else:
+ raise ValueError("unsupported parity type: %r" % self._parity)
+
+ jflowin = jflowout = 0
+ if self._rtscts:
+ jflowin |= comm.SerialPort.FLOWCONTROL_RTSCTS_IN
+ jflowout |= comm.SerialPort.FLOWCONTROL_RTSCTS_OUT
+ if self._xonxoff:
+ jflowin |= comm.SerialPort.FLOWCONTROL_XONXOFF_IN
+ jflowout |= comm.SerialPort.FLOWCONTROL_XONXOFF_OUT
+
+ self.sPort.setSerialPortParams(baudrate, jdatabits, jstopbits, jparity)
+ self.sPort.setFlowControlMode(jflowin | jflowout)
+
+ if self._timeout >= 0:
+ self.sPort.enableReceiveTimeout(self._timeout*1000)
+ else:
+ self.sPort.disableReceiveTimeout()
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.sPort:
+ self._instream.close()
+ self._outstream.close()
+ self.sPort.close()
+ self.sPort = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ if not self.sPort: raise portNotOpenError
+ return self._instream.available()
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if not self.sPort: raise portNotOpenError
+ read = ''
+ if size > 0:
+ while len(read) < size:
+ x = self._instream.read()
+ if x == -1:
+ if self.timeout >= 0:
+ break
+ else:
+ read = read + chr(x)
+ return read
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if not self.sPort: raise portNotOpenError
+ self._outstream.write(data)
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if not self.sPort: raise portNotOpenError
+ self._instream.skip(self._instream.available())
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if not self.sPort: raise portNotOpenError
+ self._outstream.flush()
+
+ def sendBreak(self, duration=0.25):
+ """Send break condition. Timed, returns to idle state after given duration."""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.sendBreak(duration*1000.0)
+
+ def setBreak(self, level=1):
+ """Set break: Controls TXD. When active, to transmitting is possible."""
+ if self.fd is None: raise portNotOpenError
+ raise SerialException("The setBreak function is not implemented in java.")
+
+ def setRTS(self, level=1):
+ """Set terminal status line: Request To Send"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.setRTS(level)
+
+ def setDTR(self, level=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.setDTR(level)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isCTS()
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isDSR()
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isRI()
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if not self.sPort: raise portNotOpenError
+ self.sPort.isCD()
+
+
+
+if __name__ == '__main__':
+ s = Serial(0,
+ baudrate=19200, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_EVEN, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=3, #set a timeout value, None for waiting forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ )
+ s.setRTS(1)
+ s.setDTR(1)
+ s.flushInput()
+ s.flushOutput()
+ s.write('hello')
+ print repr(s.read(5))
+ print s.inWaiting()
+ del s
+
+
diff --git a/fonera-python/serial/serialposix.py b/fonera-python/serial/serialposix.py
new file mode 100644
index 0000000..174e2f7
--- /dev/null
+++ b/fonera-python/serial/serialposix.py
@@ -0,0 +1,492 @@
+#!/usr/bin/env python
+# Python Serial Port Extension for Win32, Linux, BSD, Jython
+# module for serial IO for POSIX compatible systems, like Linux
+# see __init__.py
+#
+# (C) 2001-2008 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+#
+# parts based on code from Grant B. Edwards <[email protected]>:
+# ftp://ftp.visi.com/users/grante/python/PosixSerial.py
+# references: http://www.easysw.com/~mike/serial/serial.html
+
+import sys, os, fcntl, termios, struct, select, errno
+from serialutil import *
+
+#Do check the Python version as some constants have moved.
+if (sys.hexversion < 0x020100f0):
+ import TERMIOS
+else:
+ TERMIOS = termios
+
+if (sys.hexversion < 0x020200f0):
+ import FCNTL
+else:
+ FCNTL = fcntl
+
+#try to detect the os so that a device can be selected...
+plat = sys.platform.lower()
+
+if plat[:5] == 'linux': #Linux (confirmed)
+ def device(port):
+ return '/dev/ttyS%d' % port
+
+elif plat == 'cygwin': #cywin/win32 (confirmed)
+ def device(port):
+ return '/dev/com%d' % (port + 1)
+
+elif plat == 'openbsd3': #BSD (confirmed)
+ def device(port):
+ return '/dev/ttyp%d' % port
+
+elif plat[:3] == 'bsd' or \
+ plat[:7] == 'freebsd' or \
+ plat[:7] == 'openbsd' or \
+ plat[:6] == 'darwin': #BSD (confirmed for freebsd4: cuaa%d)
+ def device(port):
+ return '/dev/cuad%d' % port
+
+elif plat[:6] == 'netbsd': #NetBSD 1.6 testing by Erk
+ def device(port):
+ return '/dev/dty%02d' % port
+
+elif plat[:4] == 'irix': #IRIX (partialy tested)
+ def device(port):
+ return '/dev/ttyf%d' % (port+1) #XXX different device names depending on flow control
+
+elif plat[:2] == 'hp': #HP-UX (not tested)
+ def device(port):
+ return '/dev/tty%dp0' % (port+1)
+
+elif plat[:5] == 'sunos': #Solaris/SunOS (confirmed)
+ def device(port):
+ return '/dev/tty%c' % (ord('a')+port)
+
+elif plat[:3] == 'aix': #aix
+ def device(port):
+ return '/dev/tty%d' % (port)
+
+else:
+ #platform detection has failed...
+ print """don't know how to number ttys on this system.
+! Use an explicit path (eg /dev/ttyS1) or send this information to
+! the author of this module:
+
+sys.platform = %r
+os.name = %r
+serialposix.py version = %s
+
+also add the device name of the serial port and where the
+counting starts for the first serial port.
+e.g. 'first serial port: /dev/ttyS0'
+and with a bit luck you can get this module running...
+""" % (sys.platform, os.name, VERSION)
+ #no exception, just continue with a brave attempt to build a device name
+ #even if the device name is not correct for the platform it has chances
+ #to work using a string with the real device name as port paramter.
+ def device(portum):
+ return '/dev/ttyS%d' % portnum
+ #~ raise Exception, "this module does not run on this platform, sorry."
+
+#whats up with "aix", "beos", ....
+#they should work, just need to know the device names.
+
+
+#load some constants for later use.
+#try to use values from TERMIOS, use defaults from linux otherwise
+TIOCMGET = hasattr(TERMIOS, 'TIOCMGET') and TERMIOS.TIOCMGET or 0x5415
+TIOCMBIS = hasattr(TERMIOS, 'TIOCMBIS') and TERMIOS.TIOCMBIS or 0x5416
+TIOCMBIC = hasattr(TERMIOS, 'TIOCMBIC') and TERMIOS.TIOCMBIC or 0x5417
+TIOCMSET = hasattr(TERMIOS, 'TIOCMSET') and TERMIOS.TIOCMSET or 0x5418
+
+#TIOCM_LE = hasattr(TERMIOS, 'TIOCM_LE') and TERMIOS.TIOCM_LE or 0x001
+TIOCM_DTR = hasattr(TERMIOS, 'TIOCM_DTR') and TERMIOS.TIOCM_DTR or 0x002
+TIOCM_RTS = hasattr(TERMIOS, 'TIOCM_RTS') and TERMIOS.TIOCM_RTS or 0x004
+#TIOCM_ST = hasattr(TERMIOS, 'TIOCM_ST') and TERMIOS.TIOCM_ST or 0x008
+#TIOCM_SR = hasattr(TERMIOS, 'TIOCM_SR') and TERMIOS.TIOCM_SR or 0x010
+
+TIOCM_CTS = hasattr(TERMIOS, 'TIOCM_CTS') and TERMIOS.TIOCM_CTS or 0x020
+TIOCM_CAR = hasattr(TERMIOS, 'TIOCM_CAR') and TERMIOS.TIOCM_CAR or 0x040
+TIOCM_RNG = hasattr(TERMIOS, 'TIOCM_RNG') and TERMIOS.TIOCM_RNG or 0x080
+TIOCM_DSR = hasattr(TERMIOS, 'TIOCM_DSR') and TERMIOS.TIOCM_DSR or 0x100
+TIOCM_CD = hasattr(TERMIOS, 'TIOCM_CD') and TERMIOS.TIOCM_CD or TIOCM_CAR
+TIOCM_RI = hasattr(TERMIOS, 'TIOCM_RI') and TERMIOS.TIOCM_RI or TIOCM_RNG
+#TIOCM_OUT1 = hasattr(TERMIOS, 'TIOCM_OUT1') and TERMIOS.TIOCM_OUT1 or 0x2000
+#TIOCM_OUT2 = hasattr(TERMIOS, 'TIOCM_OUT2') and TERMIOS.TIOCM_OUT2 or 0x4000
+TIOCINQ = hasattr(TERMIOS, 'FIONREAD') and TERMIOS.FIONREAD or 0x541B
+
+TIOCM_zero_str = struct.pack('I', 0)
+TIOCM_RTS_str = struct.pack('I', TIOCM_RTS)
+TIOCM_DTR_str = struct.pack('I', TIOCM_DTR)
+
+TIOCSBRK = hasattr(TERMIOS, 'TIOCSBRK') and TERMIOS.TIOCSBRK or 0x5427
+TIOCCBRK = hasattr(TERMIOS, 'TIOCCBRK') and TERMIOS.TIOCCBRK or 0x5428
+
+ASYNC_SPD_MASK = 0x1030
+ASYNC_SPD_CUST = 0x0030
+
+baudrate_constants = {
+ 0: 0000000, # hang up
+ 50: 0000001,
+ 75: 0000002,
+ 110: 0000003,
+ 134: 0000004,
+ 150: 0000005,
+ 200: 0000006,
+ 300: 0000007,
+ 600: 0000010,
+ 1200: 0000011,
+ 1800: 0000012,
+ 2400: 0000013,
+ 4800: 0000014,
+ 9600: 0000015,
+ 19200: 0000016,
+ 38400: 0000017,
+ 57600: 0010001,
+ 115200: 0010002,
+ 230400: 0010003,
+ 460800: 0010004,
+ 500000: 0010005,
+ 576000: 0010006,
+ 921600: 0010007,
+ 1000000: 0010010,
+ 1152000: 0010011,
+ 1500000: 0010012,
+ 2000000: 0010013,
+ 2500000: 0010014,
+ 3000000: 0010015,
+ 3500000: 0010016,
+ 4000000: 0010017
+}
+
+
+class Serial(SerialBase):
+ """Serial port class POSIX implementation. Serial port configuration is
+ done with termios and fcntl. Runs on Linux and many other Un*x like
+ systems."""
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ self.fd = None
+ #open
+ try:
+ self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)
+ except Exception, msg:
+ self.fd = None
+ raise SerialException("could not open port %s: %s" % (self._port, msg))
+ #~ fcntl.fcntl(self.fd, FCNTL.F_SETFL, 0) #set blocking
+
+ try:
+ self._reconfigurePort()
+ except:
+ os.close(self.fd)
+ self.fd = None
+ else:
+ self._isOpen = True
+ #~ self.flushInput()
+
+
+ def _reconfigurePort(self):
+ """Set communication parameters on opened port."""
+ if self.fd is None:
+ raise SerialException("Can only operate on a valid port handle")
+ custom_baud = None
+
+ vmin = vtime = 0 #timeout is done via select
+ if self._interCharTimeout is not None:
+ vmin = 1
+ vtime = int(self._interCharTimeout * 10)
+ try:
+ iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(self.fd)
+ except termios.error, msg: #if a port is nonexistent but has a /dev file, it'll fail here
+ raise SerialException("Could not configure port: %s" % msg)
+ #set up raw mode / no echo / binary
+ cflag |= (TERMIOS.CLOCAL|TERMIOS.CREAD)
+ lflag &= ~(TERMIOS.ICANON|TERMIOS.ECHO|TERMIOS.ECHOE|TERMIOS.ECHOK|TERMIOS.ECHONL|
+ TERMIOS.ISIG|TERMIOS.IEXTEN) #|TERMIOS.ECHOPRT
+ for flag in ('ECHOCTL', 'ECHOKE'): #netbsd workaround for Erk
+ if hasattr(TERMIOS, flag):
+ lflag &= ~getattr(TERMIOS, flag)
+
+ oflag &= ~(TERMIOS.OPOST)
+ iflag &= ~(TERMIOS.INLCR|TERMIOS.IGNCR|TERMIOS.ICRNL|TERMIOS.IGNBRK)
+ if hasattr(TERMIOS, 'IUCLC'):
+ iflag &= ~TERMIOS.IUCLC
+ if hasattr(TERMIOS, 'PARMRK'):
+ iflag &= ~TERMIOS.PARMRK
+
+ #setup baudrate
+ try:
+ ispeed = ospeed = getattr(TERMIOS,'B%s' % (self._baudrate))
+ except AttributeError:
+ try:
+ ispeed = ospeed = baudrate_constants[self._baudrate]
+ except KeyError:
+ #~ raise ValueError('Invalid baud rate: %r' % self._baudrate)
+ # may need custom baud rate, it isnt in our list.
+ ispeed = ospeed = getattr(TERMIOS, 'B38400')
+ custom_baud = int(self._baudrate) # store for later
+
+ #setup char len
+ cflag &= ~TERMIOS.CSIZE
+ if self._bytesize == 8:
+ cflag |= TERMIOS.CS8
+ elif self._bytesize == 7:
+ cflag |= TERMIOS.CS7
+ elif self._bytesize == 6:
+ cflag |= TERMIOS.CS6
+ elif self._bytesize == 5:
+ cflag |= TERMIOS.CS5
+ else:
+ raise ValueError('Invalid char len: %r' % self._bytesize)
+ #setup stopbits
+ if self._stopbits == STOPBITS_ONE:
+ cflag &= ~(TERMIOS.CSTOPB)
+ elif self._stopbits == STOPBITS_TWO:
+ cflag |= (TERMIOS.CSTOPB)
+ else:
+ raise ValueError('Invalid stopit specification: %r' % self._stopbits)
+ #setup parity
+ iflag &= ~(TERMIOS.INPCK|TERMIOS.ISTRIP)
+ if self._parity == PARITY_NONE:
+ cflag &= ~(TERMIOS.PARENB|TERMIOS.PARODD)
+ elif self._parity == PARITY_EVEN:
+ cflag &= ~(TERMIOS.PARODD)
+ cflag |= (TERMIOS.PARENB)
+ elif self._parity == PARITY_ODD:
+ cflag |= (TERMIOS.PARENB|TERMIOS.PARODD)
+ else:
+ raise ValueError('Invalid parity: %r' % self._parity)
+ #setup flow control
+ #xonxoff
+ if hasattr(TERMIOS, 'IXANY'):
+ if self._xonxoff:
+ iflag |= (TERMIOS.IXON|TERMIOS.IXOFF) #|TERMIOS.IXANY)
+ else:
+ iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF|TERMIOS.IXANY)
+ else:
+ if self._xonxoff:
+ iflag |= (TERMIOS.IXON|TERMIOS.IXOFF)
+ else:
+ iflag &= ~(TERMIOS.IXON|TERMIOS.IXOFF)
+ #rtscts
+ if hasattr(TERMIOS, 'CRTSCTS'):
+ if self._rtscts:
+ cflag |= (TERMIOS.CRTSCTS)
+ else:
+ cflag &= ~(TERMIOS.CRTSCTS)
+ elif hasattr(TERMIOS, 'CNEW_RTSCTS'): #try it with alternate constant name
+ if self._rtscts:
+ cflag |= (TERMIOS.CNEW_RTSCTS)
+ else:
+ cflag &= ~(TERMIOS.CNEW_RTSCTS)
+ #XXX should there be a warning if setting up rtscts (and xonxoff etc) fails??
+
+ #buffer
+ #vmin "minimal number of characters to be read. = for non blocking"
+ if vmin < 0 or vmin > 255:
+ raise ValueError('Invalid vmin: %r ' % vmin)
+ cc[TERMIOS.VMIN] = vmin
+ #vtime
+ if vtime < 0 or vtime > 255:
+ raise ValueError('Invalid vtime: %r' % vtime)
+ cc[TERMIOS.VTIME] = vtime
+ #activate settings
+ termios.tcsetattr(self.fd, TERMIOS.TCSANOW, [iflag, oflag, cflag, lflag, ispeed, ospeed, cc])
+
+ # apply custom baud rate, if any
+ if custom_baud is not None:
+ import array
+ buf = array.array('i', [0] * 32)
+
+ # get serial_struct
+ FCNTL.ioctl(self.fd, TERMIOS.TIOCGSERIAL, buf)
+
+ # set custom divisor
+ buf[6] = buf[7] / custom_baud
+
+ # update flags
+ buf[4] &= ~ASYNC_SPD_MASK
+ buf[4] |= ASYNC_SPD_CUST
+
+ # set serial_struct
+ try:
+ res = FCNTL.ioctl(self.fd, TERMIOS.TIOCSSERIAL, buf)
+ except IOError:
+ raise ValueError('Failed to set custom baud rate: %r' % self._baudrate)
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.fd is not None:
+ os.close(self.fd)
+ self.fd = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ #~ s = fcntl.ioctl(self.fd, TERMIOS.FIONREAD, TIOCM_zero_str)
+ s = fcntl.ioctl(self.fd, TIOCINQ, TIOCM_zero_str)
+ return struct.unpack('I',s)[0]
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if self.fd is None: raise portNotOpenError
+ read = ''
+ inp = None
+ if size > 0:
+ while len(read) < size:
+ #print "\tread(): size",size, "have", len(read) #debug
+ ready,_,_ = select.select([self.fd],[],[], self._timeout)
+ if not ready:
+ break #timeout
+ buf = os.read(self.fd, size-len(read))
+ read = read + buf
+ if (self._timeout >= 0 or self._interCharTimeout > 0) and not buf:
+ break #early abort on timeout
+ return read
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if self.fd is None: raise portNotOpenError
+ if not isinstance(data, str):
+ raise TypeError('expected str, got %s' % type(data))
+ t = len(data)
+ d = data
+ while t > 0:
+ try:
+ if self._writeTimeout is not None and self._writeTimeout > 0:
+ _,ready,_ = select.select([],[self.fd],[], self._writeTimeout)
+ if not ready:
+ raise writeTimeoutError
+ n = os.write(self.fd, d)
+ if self._writeTimeout is not None and self._writeTimeout > 0:
+ _,ready,_ = select.select([],[self.fd],[], self._writeTimeout)
+ if not ready:
+ raise writeTimeoutError
+ d = d[n:]
+ t = t - n
+ except OSError,v:
+ if v.errno != errno.EAGAIN:
+ raise
+
+ def flush(self):
+ """Flush of file like objects. In this case, wait until all data
+ is written."""
+ self.drainOutput()
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcflush(self.fd, TERMIOS.TCIFLUSH)
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcflush(self.fd, TERMIOS.TCOFLUSH)
+
+ def sendBreak(self, duration=0.25):
+ """Send break condition. Timed, returns to idle state after given duration."""
+ if self.fd is None:
+ raise portNotOpenError
+ termios.tcsendbreak(self.fd, int(duration/0.25))
+
+ def setBreak(self, level=1):
+ """Set break: Controls TXD. When active, to transmitting is possible."""
+ if self.fd is None: raise portNotOpenError
+ if level:
+ fcntl.ioctl(self.fd, TIOCSBRK)
+ else:
+ fcntl.ioctl(self.fd, TIOCCBRK)
+
+ def setRTS(self, level=1):
+ """Set terminal status line: Request To Send"""
+ if self.fd is None: raise portNotOpenError
+ if level:
+ fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_RTS_str)
+ else:
+ fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_RTS_str)
+
+ def setDTR(self, level=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if self.fd is None: raise portNotOpenError
+ if level:
+ fcntl.ioctl(self.fd, TIOCMBIS, TIOCM_DTR_str)
+ else:
+ fcntl.ioctl(self.fd, TIOCMBIC, TIOCM_DTR_str)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_CTS != 0
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_DSR != 0
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_RI != 0
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if self.fd is None: raise portNotOpenError
+ s = fcntl.ioctl(self.fd, TIOCMGET, TIOCM_zero_str)
+ return struct.unpack('I',s)[0] & TIOCM_CD != 0
+
+ # - - platform specific - - - -
+
+ def drainOutput(self):
+ """internal - not portable!"""
+ if self.fd is None: raise portNotOpenError
+ termios.tcdrain(self.fd)
+
+ def nonblocking(self):
+ """internal - not portable!"""
+ if self.fd is None:
+ raise portNotOpenError
+ fcntl.fcntl(self.fd, FCNTL.F_SETFL, FCNTL.O_NONBLOCK)
+
+ def fileno(self):
+ """For easier of the serial port instance with select.
+ WARNING: this function is not portable to different platforms!"""
+ if self.fd is None: raise portNotOpenError
+ return self.fd
+
+if __name__ == '__main__':
+ s = Serial(0,
+ baudrate=19200, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_EVEN, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=3, #set a timeout value, None for waiting forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ )
+ s.setRTS(1)
+ s.setDTR(1)
+ s.flushInput()
+ s.flushOutput()
+ s.write('hello')
+ print repr(s.read(5))
+ print s.inWaiting()
+ del s
+
diff --git a/fonera-python/serial/serialutil.py b/fonera-python/serial/serialutil.py
new file mode 100644
index 0000000..fd466f2
--- /dev/null
+++ b/fonera-python/serial/serialutil.py
@@ -0,0 +1,400 @@
+#! python
+# Python Serial Port Extension for Win32, Linux, BSD, Jython
+# see __init__.py
+#
+# (C) 2001-2008 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+
+PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK, PARITY_SPACE = 'N', 'E', 'O', 'M', 'S'
+STOPBITS_ONE, STOPBITS_TWO = (1, 2)
+FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5,6,7,8)
+
+PARITY_NAMES = {
+ PARITY_NONE: 'None',
+ PARITY_EVEN: 'Even',
+ PARITY_ODD: 'Odd',
+ PARITY_MARK: 'Mark',
+ PARITY_SPACE:'Space',
+}
+
+XON = chr(17)
+XOFF = chr(19)
+
+#Python < 2.2.3 compatibility
+try:
+ True
+except:
+ True = 1
+ False = not True
+
+class SerialException(Exception):
+ """Base class for serial port related exceptions."""
+
+portNotOpenError = SerialException('Port not open')
+
+class SerialTimeoutException(SerialException):
+ """Write timeouts give an exception"""
+
+writeTimeoutError = SerialTimeoutException("Write timeout")
+
+class FileLike(object):
+ """An abstract file like class.
+
+ This class implements readline and readlines based on read and
+ writelines based on write.
+ This class is used to provide the above functions for to Serial
+ port objects.
+
+ Note that when the serial port was opened with _NO_ timeout that
+ readline blocks until it sees a newline (or the specified size is
+ reached) and that readlines would never return and therefore
+ refuses to work (it raises an exception in this case)!
+ """
+
+ def read(self, size): raise NotImplementedError
+ def write(self, s): raise NotImplementedError
+
+ def readline(self, size=None, eol='\n'):
+ """read a line which is terminated with end-of-line (eol) character
+ ('\n' by default) or until timeout"""
+ line = ''
+ while 1:
+ c = self.read(1)
+ if c:
+ line += c #not very efficient but lines are usually not that long
+ if c == eol:
+ break
+ if size is not None and len(line) >= size:
+ break
+ else:
+ break
+ return line
+
+ def readlines(self, sizehint=None, eol='\n'):
+ """read a list of lines, until timeout
+ sizehint is ignored"""
+ if self.timeout is None:
+ raise ValueError, "Serial port MUST have enabled timeout for this function!"
+ lines = []
+ while 1:
+ line = self.readline(eol=eol)
+ if line:
+ lines.append(line)
+ if line[-1] != eol: #was the line received with a timeout?
+ break
+ else:
+ break
+ return lines
+
+ def xreadlines(self, sizehint=None):
+ """just call readlines - here for compatibility"""
+ return self.readlines()
+
+ def writelines(self, sequence):
+ for line in sequence:
+ self.write(line)
+
+ def flush(self):
+ """flush of file like objects"""
+ pass
+
+ # iterator for e.g. "for line in Serial(0): ..." usage
+ def next(self):
+ line = self.readline()
+ if not line: raise StopIteration
+ return line
+
+ def __iter__(self):
+ return self
+
+
+class SerialBase(FileLike):
+ """Serial port base class. Provides __init__ function and properties to
+ get/set port settings."""
+
+ #default values, may be overriden in subclasses that do not support all values
+ BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
+ 19200,38400,57600,115200,230400,460800,500000,576000,921600,
+ 1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000)
+ BYTESIZES = (FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS)
+ PARITIES = (PARITY_NONE, PARITY_EVEN, PARITY_ODD)
+ STOPBITS = (STOPBITS_ONE, STOPBITS_TWO)
+
+ def __init__(self,
+ port = None, #number of device, numbering starts at
+ #zero. if everything fails, the user
+ #can specify a device string, note
+ #that this isn't portable anymore
+ #port will be opened if one is specified
+ baudrate=9600, #baudrate
+ bytesize=EIGHTBITS, #number of databits
+ parity=PARITY_NONE, #enable parity checking
+ stopbits=STOPBITS_ONE, #number of stopbits
+ timeout=None, #set a timeout value, None to wait forever
+ xonxoff=0, #enable software flow control
+ rtscts=0, #enable RTS/CTS flow control
+ writeTimeout=None, #set a timeout for writes
+ dsrdtr=None, #None: use rtscts setting, dsrdtr override if true or false
+ interCharTimeout=None #Inter-character timeout, None to disable
+ ):
+ """Initialize comm port object. If a port is given, then the port will be
+ opened immediately. Otherwise a Serial port object in closed state
+ is returned."""
+
+ self._isOpen = False
+ self._port = None #correct value is assigned below trough properties
+ self._baudrate = None #correct value is assigned below trough properties
+ self._bytesize = None #correct value is assigned below trough properties
+ self._parity = None #correct value is assigned below trough properties
+ self._stopbits = None #correct value is assigned below trough properties
+ self._timeout = None #correct value is assigned below trough properties
+ self._writeTimeout = None #correct value is assigned below trough properties
+ self._xonxoff = None #correct value is assigned below trough properties
+ self._rtscts = None #correct value is assigned below trough properties
+ self._dsrdtr = None #correct value is assigned below trough properties
+ self._interCharTimeout = None #correct value is assigned below trough properties
+
+ #assign values using get/set methods using the properties feature
+ self.port = port
+ self.baudrate = baudrate
+ self.bytesize = bytesize
+ self.parity = parity
+ self.stopbits = stopbits
+ self.timeout = timeout
+ self.writeTimeout = writeTimeout
+ self.xonxoff = xonxoff
+ self.rtscts = rtscts
+ self.dsrdtr = dsrdtr
+ self.interCharTimeout = interCharTimeout
+
+ if port is not None:
+ self.open()
+
+ def isOpen(self):
+ """Check if the port is opened."""
+ return self._isOpen
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ #TODO: these are not realy needed as the is the BAUDRATES etc attribute...
+ #maybe i remove them before the final release...
+
+ def getSupportedBaudrates(self):
+ return [(str(b), b) for b in self.BAUDRATES]
+
+ def getSupportedByteSizes(self):
+ return [(str(b), b) for b in self.BYTESIZES]
+
+ def getSupportedStopbits(self):
+ return [(str(b), b) for b in self.STOPBITS]
+
+ def getSupportedParities(self):
+ return [(PARITY_NAMES[b], b) for b in self.PARITIES]
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def setPort(self, port):
+ """Change the port. The attribute portstr is set to a string that
+ contains the name of the port."""
+
+ was_open = self._isOpen
+ if was_open: self.close()
+ if port is not None:
+ if type(port) in [type(''), type(u'')]: #strings are taken directly
+ self.portstr = port
+ else:
+ self.portstr = self.makeDeviceName(port)
+ else:
+ self.portstr = None
+ self._port = port
+ if was_open: self.open()
+
+ def getPort(self):
+ """Get the current port setting. The value that was passed on init or using
+ setPort() is passed back. See also the attribute portstr which contains
+ the name of the port as a string."""
+ return self._port
+
+ port = property(getPort, setPort, doc="Port setting")
+
+
+ def setBaudrate(self, baudrate):
+ """Change baudrate. It raises a ValueError if the port is open and the
+ baudrate is not possible. If the port is closed, then tha value is
+ accepted and the exception is raised when the port is opened."""
+ #~ if baudrate not in self.BAUDRATES: raise ValueError("Not a valid baudrate: %r" % baudrate)
+ try:
+ self._baudrate = int(baudrate)
+ except TypeError:
+ raise ValueError("Not a valid baudrate: %r" % (baudrate,))
+ else:
+ if self._isOpen: self._reconfigurePort()
+
+ def getBaudrate(self):
+ """Get the current baudrate setting."""
+ return self._baudrate
+
+ baudrate = property(getBaudrate, setBaudrate, doc="Baudrate setting")
+
+
+ def setByteSize(self, bytesize):
+ """Change byte size."""
+ if bytesize not in self.BYTESIZES: raise ValueError("Not a valid byte size: %r" % (bytesize,))
+ self._bytesize = bytesize
+ if self._isOpen: self._reconfigurePort()
+
+ def getByteSize(self):
+ """Get the current byte size setting."""
+ return self._bytesize
+
+ bytesize = property(getByteSize, setByteSize, doc="Byte size setting")
+
+
+ def setParity(self, parity):
+ """Change parity setting."""
+ if parity not in self.PARITIES: raise ValueError("Not a valid parity: %r" % (parity,))
+ self._parity = parity
+ if self._isOpen: self._reconfigurePort()
+
+ def getParity(self):
+ """Get the current parity setting."""
+ return self._parity
+
+ parity = property(getParity, setParity, doc="Parity setting")
+
+
+ def setStopbits(self, stopbits):
+ """Change stopbits size."""
+ if stopbits not in self.STOPBITS: raise ValueError("Not a valid stopbit size: %r" % (stopbits,))
+ self._stopbits = stopbits
+ if self._isOpen: self._reconfigurePort()
+
+ def getStopbits(self):
+ """Get the current stopbits setting."""
+ return self._stopbits
+
+ stopbits = property(getStopbits, setStopbits, doc="Stopbits setting")
+
+
+ def setTimeout(self, timeout):
+ """Change timeout setting."""
+ if timeout is not None:
+ if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
+ try:
+ timeout + 1 #test if it's a number, will throw a TypeError if not...
+ except TypeError:
+ raise ValueError("Not a valid timeout: %r" % (timeout,))
+
+ self._timeout = timeout
+ if self._isOpen: self._reconfigurePort()
+
+ def getTimeout(self):
+ """Get the current timeout setting."""
+ return self._timeout
+
+ timeout = property(getTimeout, setTimeout, doc="Timeout setting for read()")
+
+
+ def setWriteTimeout(self, timeout):
+ """Change timeout setting."""
+ if timeout is not None:
+ if timeout < 0: raise ValueError("Not a valid timeout: %r" % (timeout,))
+ try:
+ timeout + 1 #test if it's a number, will throw a TypeError if not...
+ except TypeError:
+ raise ValueError("Not a valid timeout: %r" % timeout)
+
+ self._writeTimeout = timeout
+ if self._isOpen: self._reconfigurePort()
+
+ def getWriteTimeout(self):
+ """Get the current timeout setting."""
+ return self._writeTimeout
+
+ writeTimeout = property(getWriteTimeout, setWriteTimeout, doc="Timeout setting for write()")
+
+
+ def setXonXoff(self, xonxoff):
+ """Change XonXoff setting."""
+ self._xonxoff = xonxoff
+ if self._isOpen: self._reconfigurePort()
+
+ def getXonXoff(self):
+ """Get the current XonXoff setting."""
+ return self._xonxoff
+
+ xonxoff = property(getXonXoff, setXonXoff, doc="Xon/Xoff setting")
+
+ def setRtsCts(self, rtscts):
+ """Change RtsCts flow control setting."""
+ self._rtscts = rtscts
+ if self._isOpen: self._reconfigurePort()
+
+ def getRtsCts(self):
+ """Get the current RtsCts flow control setting."""
+ return self._rtscts
+
+ rtscts = property(getRtsCts, setRtsCts, doc="RTS/CTS flow control setting")
+
+ def setDsrDtr(self, dsrdtr=None):
+ """Change DsrDtr flow control setting."""
+ if dsrdtr is None:
+ #if not set, keep backwards compatibility and follow rtscts setting
+ self._dsrdtr = self._rtscts
+ else:
+ #if defined independently, follow its value
+ self._dsrdtr = dsrdtr
+ if self._isOpen: self._reconfigurePort()
+
+ def getDsrDtr(self):
+ """Get the current DsrDtr flow control setting."""
+ return self._dsrdtr
+
+ dsrdtr = property(getDsrDtr, setDsrDtr, "DSR/DTR flow control setting")
+
+ def setInterCharTimeout(self, interCharTimeout):
+ """Change inter-character timeout setting."""
+ if interCharTimeout is not None:
+ if interCharTimeout < 0: raise ValueError("Not a valid timeout: %r" % interCharTimeout)
+ try:
+ interCharTimeout + 1 #test if it's a number, will throw a TypeError if not...
+ except TypeError:
+ raise ValueError("Not a valid timeout: %r" % interCharTimeout)
+
+ self._interCharTimeout = interCharTimeout
+ if self._isOpen: self._reconfigurePort()
+
+ def getInterCharTimeout(self):
+ """Get the current inter-character timeout setting."""
+ return self._interCharTimeout
+
+ interCharTimeout = property(getInterCharTimeout, setInterCharTimeout, doc="Inter-character timeout setting for read()")
+
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def __repr__(self):
+ """String representation of the current port settings and its state."""
+ return "%s<id=0x%x, open=%s>(port=%r, baudrate=%r, bytesize=%r, parity=%r, stopbits=%r, timeout=%r, xonxoff=%r, rtscts=%r, dsrdtr=%r)" % (
+ self.__class__.__name__,
+ id(self),
+ self._isOpen,
+ self.portstr,
+ self.baudrate,
+ self.bytesize,
+ self.parity,
+ self.stopbits,
+ self.timeout,
+ self.xonxoff,
+ self.rtscts,
+ self.dsrdtr,
+ )
+
+if __name__ == '__main__':
+ s = SerialBase()
+ print s.portstr
+ print s.getSupportedBaudrates()
+ print s.getSupportedByteSizes()
+ print s.getSupportedParities()
+ print s.getSupportedStopbits()
+ print s
diff --git a/fonera-python/serial/serialwin32.py b/fonera-python/serial/serialwin32.py
new file mode 100644
index 0000000..f5e8961
--- /dev/null
+++ b/fonera-python/serial/serialwin32.py
@@ -0,0 +1,336 @@
+#! python
+# Python Serial Port Extension for Win32, Linux, BSD, Jython
+# serial driver for win32
+# see __init__.py
+#
+# (C) 2001-2008 Chris Liechti <[email protected]>
+# this is distributed under a free software license, see license.txt
+
+import win32file # The base COM port and file IO functions.
+import win32event # We use events and the WaitFor[Single|Multiple]Objects functions.
+import win32con # constants.
+from serialutil import *
+
+#from winbase.h. these should realy be in win32con
+MS_CTS_ON = 16
+MS_DSR_ON = 32
+MS_RING_ON = 64
+MS_RLSD_ON = 128
+
+def device(portnum):
+ """Turn a port number into a device name"""
+ return 'COM%d' % (portnum+1) #numbers are transformed to a string
+
+class Serial(SerialBase):
+ """Serial port implemenation for Win32. This implemenatation requires a
+ win32all installation."""
+
+ BAUDRATES = (50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,
+ 19200,38400,57600,115200)
+
+ def open(self):
+ """Open port with current settings. This may throw a SerialException
+ if the port cannot be opened."""
+ if self._port is None:
+ raise SerialException("Port must be configured before it can be used.")
+ self.hComPort = None
+ # the "\\.\COMx" format is required for devices other than COM1-COM8
+ # not all versions of windows seem to support this properly
+ # so that the first few ports are used with the DOS device name
+ port = self.portstr
+ if port.upper().startswith('COM') and int(port[3:]) > 8:
+ port = '\\\\.\\' + port
+ try:
+ self.hComPort = win32file.CreateFile(port,
+ win32con.GENERIC_READ | win32con.GENERIC_WRITE,
+ 0, # exclusive access
+ None, # no security
+ win32con.OPEN_EXISTING,
+ win32con.FILE_FLAG_OVERLAPPED,
+ None)
+ except Exception, msg:
+ self.hComPort = None #'cause __del__ is called anyway
+ raise SerialException("could not open port %s: %s" % (self.portstr, msg))
+ # Setup a 4k buffer
+ win32file.SetupComm(self.hComPort, 4096, 4096)
+
+ #Save original timeout values:
+ self._orgTimeouts = win32file.GetCommTimeouts(self.hComPort)
+
+ self._rtsState = win32file.RTS_CONTROL_ENABLE
+ self._dtrState = win32file.DTR_CONTROL_ENABLE
+
+ self._reconfigurePort()
+
+ # Clear buffers:
+ # Remove anything that was there
+ win32file.PurgeComm(self.hComPort,
+ win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT |
+ win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
+
+ self._overlappedRead = win32file.OVERLAPPED()
+ self._overlappedRead.hEvent = win32event.CreateEvent(None, 1, 0, None)
+ self._overlappedWrite = win32file.OVERLAPPED()
+ #~ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 1, 0, None)
+ self._overlappedWrite.hEvent = win32event.CreateEvent(None, 0, 0, None)
+ self._isOpen = True
+
+ def _reconfigurePort(self):
+ """Set communication parameters on opened port."""
+ if not self.hComPort:
+ raise SerialException("Can only operate on a valid port handle")
+
+ #Set Windows timeout values
+ #timeouts is a tuple with the following items:
+ #(ReadIntervalTimeout,ReadTotalTimeoutMultiplier,
+ # ReadTotalTimeoutConstant,WriteTotalTimeoutMultiplier,
+ # WriteTotalTimeoutConstant)
+ if self._timeout is None:
+ timeouts = (0, 0, 0, 0, 0)
+ elif self._timeout == 0:
+ timeouts = (win32con.MAXDWORD, 0, 0, 0, 0)
+ else:
+ timeouts = (0, 0, int(self._timeout*1000), 0, 0)
+ if self._timeout != 0 and self._interCharTimeout is not None:
+ timeouts = (int(self._interCharTimeout * 1000),) + timeouts[1:]
+
+ if self._writeTimeout is None:
+ pass
+ elif self._writeTimeout == 0:
+ timeouts = timeouts[:-2] + (0, win32con.MAXDWORD)
+ else:
+ timeouts = timeouts[:-2] + (0, int(self._writeTimeout*1000))
+ win32file.SetCommTimeouts(self.hComPort, timeouts)
+
+ win32file.SetCommMask(self.hComPort, win32file.EV_ERR)
+
+ # Setup the connection info.
+ # Get state and modify it:
+ comDCB = win32file.GetCommState(self.hComPort)
+ comDCB.BaudRate = self._baudrate
+
+ if self._bytesize == FIVEBITS:
+ comDCB.ByteSize = 5
+ elif self._bytesize == SIXBITS:
+ comDCB.ByteSize = 6
+ elif self._bytesize == SEVENBITS:
+ comDCB.ByteSize = 7
+ elif self._bytesize == EIGHTBITS:
+ comDCB.ByteSize = 8
+ else:
+ raise ValueError("Unsupported number of data bits: %r" % self._bytesize)
+
+ if self._parity == PARITY_NONE:
+ comDCB.Parity = win32file.NOPARITY
+ comDCB.fParity = 0 # Dis/Enable Parity Check
+ elif self._parity == PARITY_EVEN:
+ comDCB.Parity = win32file.EVENPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ elif self._parity == PARITY_ODD:
+ comDCB.Parity = win32file.ODDPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ elif self._parity == PARITY_MARK:
+ comDCB.Parity = win32file.MARKPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ elif self._parity == PARITY_SPACE:
+ comDCB.Parity = win32file.SPACEPARITY
+ comDCB.fParity = 1 # Dis/Enable Parity Check
+ else:
+ raise ValueError("Unsupported parity mode: %r" % self._parity)
+
+ if self._stopbits == STOPBITS_ONE:
+ comDCB.StopBits = win32file.ONESTOPBIT
+ elif self._stopbits == STOPBITS_TWO:
+ comDCB.StopBits = win32file.TWOSTOPBITS
+ else:
+ raise ValueError("Unsupported number of stop bits: %r" % self._stopbits)
+
+ comDCB.fBinary = 1 # Enable Binary Transmission
+ # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE)
+ if self._rtscts:
+ comDCB.fRtsControl = win32file.RTS_CONTROL_HANDSHAKE
+ else:
+ comDCB.fRtsControl = self._rtsState
+ if self._dsrdtr:
+ comDCB.fDtrControl = win32file.DTR_CONTROL_HANDSHAKE
+ else:
+ comDCB.fDtrControl = self._dtrState
+ comDCB.fOutxCtsFlow = self._rtscts
+ comDCB.fOutxDsrFlow = self._dsrdtr
+ comDCB.fOutX = self._xonxoff
+ comDCB.fInX = self._xonxoff
+ comDCB.fNull = 0
+ comDCB.fErrorChar = 0
+ comDCB.fAbortOnError = 0
+ comDCB.XonChar = XON
+ comDCB.XoffChar = XOFF
+
+ try:
+ win32file.SetCommState(self.hComPort, comDCB)
+ except win32file.error, e:
+ raise ValueError("Cannot configure port, some setting was wrong. Original message: %s" % e)
+
+ #~ def __del__(self):
+ #~ self.close()
+
+ def close(self):
+ """Close port"""
+ if self._isOpen:
+ if self.hComPort:
+ try:
+ # Restore original timeout values:
+ win32file.SetCommTimeouts(self.hComPort, self._orgTimeouts)
+ except win32file.error:
+ # ignore errors. can happen for unplugged USB serial devices
+ pass
+ # Close COM-Port:
+ win32file.CloseHandle(self.hComPort)
+ win32file.CloseHandle(self._overlappedRead.hEvent)
+ win32file.CloseHandle(self._overlappedWrite.hEvent)
+ self.hComPort = None
+ self._isOpen = False
+
+ def makeDeviceName(self, port):
+ return device(port)
+
+ # - - - - - - - - - - - - - - - - - - - - - - - -
+
+ def inWaiting(self):
+ """Return the number of characters currently in the input buffer."""
+ flags, comstat = win32file.ClearCommError(self.hComPort)
+ return comstat.cbInQue
+
+ def read(self, size=1):
+ """Read size bytes from the serial port. If a timeout is set it may
+ return less characters as requested. With no timeout it will block
+ until the requested number of bytes is read."""
+ if not self.hComPort: raise portNotOpenError
+ if size > 0:
+ win32event.ResetEvent(self._overlappedRead.hEvent)
+ flags, comstat = win32file.ClearCommError(self.hComPort)
+ if self.timeout == 0:
+ n = min(comstat.cbInQue, size)
+ if n > 0:
+ rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(n), self._overlappedRead)
+ win32event.WaitForSingleObject(self._overlappedRead.hEvent, win32event.INFINITE)
+ read = str(buf)
+ else:
+ read = ''
+ else:
+ rc, buf = win32file.ReadFile(self.hComPort, win32file.AllocateReadBuffer(size), self._overlappedRead)
+ n = win32file.GetOverlappedResult(self.hComPort, self._overlappedRead, 1)
+ read = str(buf[:n])
+ else:
+ read = ''
+ return read
+
+ def write(self, data):
+ """Output the given string over the serial port."""
+ if not self.hComPort: raise portNotOpenError
+ if not isinstance(data, str):
+ raise TypeError('expected str, got %s' % type(data))
+ #print repr(s),
+ if data:
+ #~ win32event.ResetEvent(self._overlappedWrite.hEvent)
+ err, n = win32file.WriteFile(self.hComPort, data, self._overlappedWrite)
+ if err: #will be ERROR_IO_PENDING:
+ # Wait for the write to complete.
+ #~ win32event.WaitForSingleObject(self._overlappedWrite.hEvent, win32event.INFINITE)
+ n = win32file.GetOverlappedResult(self.hComPort, self._overlappedWrite, 1)
+ if n != len(data):
+ raise writeTimeoutError
+
+
+ def flushInput(self):
+ """Clear input buffer, discarding all that is in the buffer."""
+ if not self.hComPort: raise portNotOpenError
+ win32file.PurgeComm(self.hComPort, win32file.PURGE_RXCLEAR | win32file.PURGE_RXABORT)
+
+ def flushOutput(self):
+ """Clear output buffer, aborting the current output and
+ discarding all that is in the buffer."""
+ if not self.hComPort: raise portNotOpenError
+ win32file.PurgeComm(self.hComPort, win32file.PURGE_TXCLEAR | win32file.PURGE_TXABORT)
+
+ def sendBreak(self, duration=0.25):
+ """Send break condition. Timed, returns to idle state after given duration."""
+ if not self.hComPort: raise portNotOpenError
+ import time
+ win32file.SetCommBreak(self.hComPort)
+ time.sleep(duration)
+ win32file.ClearCommBreak(self.hComPort)
+
+ def setBreak(self, level=1):
+ """Set break: Controls TXD. When active, to transmitting is possible."""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ win32file.SetCommBreak(self.hComPort)
+ else:
+ win32file.ClearCommBreak(self.hComPort)
+
+ def setRTS(self, level=1):
+ """Set terminal status line: Request To Send"""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ self._rtsState = win32file.RTS_CONTROL_ENABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETRTS)
+ else:
+ self._rtsState = win32file.RTS_CONTROL_DISABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.CLRRTS)
+
+ def setDTR(self, level=1):
+ """Set terminal status line: Data Terminal Ready"""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ self._dtrState = win32file.DTR_CONTROL_ENABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETDTR)
+ else:
+ self._dtrState = win32file.DTR_CONTROL_DISABLE
+ win32file.EscapeCommFunction(self.hComPort, win32file.CLRDTR)
+
+ def getCTS(self):
+ """Read terminal status line: Clear To Send"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_CTS_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getDSR(self):
+ """Read terminal status line: Data Set Ready"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_DSR_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getRI(self):
+ """Read terminal status line: Ring Indicator"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_RING_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ def getCD(self):
+ """Read terminal status line: Carrier Detect"""
+ if not self.hComPort: raise portNotOpenError
+ return MS_RLSD_ON & win32file.GetCommModemStatus(self.hComPort) != 0
+
+ # - - platform specific - - - -
+
+ def setXON(self, level=True):
+ """Platform specific - set flow state."""
+ if not self.hComPort: raise portNotOpenError
+ if level:
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETXON)
+ else:
+ win32file.EscapeCommFunction(self.hComPort, win32file.SETXOFF)
+
+#Nur Testfunktion!!
+if __name__ == '__main__':
+ s = Serial(0)
+ print s
+
+ s = Serial()
+ print s
+
+
+ s.baudrate = 19200
+ s.databits = 7
+ s.close()
+ s.port = 0
+ s.open()
+ print s
+
diff --git a/fonera-python/serial/sermsdos.py b/fonera-python/serial/sermsdos.py
new file mode 100644
index 0000000..a516118
--- /dev/null
+++ b/fonera-python/serial/sermsdos.py
@@ -0,0 +1,215 @@
+# sermsdos.py
+#
+# History:
+#
+# 3rd September 2002 Dave Haynes
+# 1. First defined
+#
+# Although this code should run under the latest versions of
+# Python, on DOS-based platforms such as Windows 95 and 98,
+# it has been specifically written to be compatible with
+# PyDOS, available at:
+# http://www.python.org/ftp/python/wpy/dos.html
+#
+# PyDOS is a stripped-down version of Python 1.5.2 for
+# DOS machines. Therefore, in making changes to this file,
+# please respect Python 1.5.2 syntax. In addition, please
+# limit the width of this file to 60 characters.
+#
+# Note also that the modules in PyDOS contain fewer members
+# than other versions, so we are restricted to using the
+# following:
+#
+# In module os:
+# -------------
+# environ, chdir, getcwd, getpid, umask, fdopen, close,
+# dup, dup2, fstat, lseek, open, read, write, O_RDONLY,
+# O_WRONLY, O_RDWR, O_APPEND, O_CREAT, O_EXCL, O_TRUNC,
+# access, F_OK, R_OK, W_OK, X_OK, chmod, listdir, mkdir,
+# remove, rename, renames, rmdir, stat, unlink, utime,
+# execl, execle, execlp, execlpe, execvp, execvpe, _exit,
+# system.
+#
+# In module os.path:
+# ------------------
+# curdir, pardir, sep, altsep, pathsep, defpath, linesep.
+#
+
+import os
+import sys
+import string
+import serialutil
+
+BAUD_RATES = {
+ 110: "11",
+ 150: "15",
+ 300: "30",
+ 600: "60",
+ 1200: "12",
+ 2400: "24",
+ 4800: "48",
+ 9600: "96",
+ 19200: "19"}
+
+(PARITY_NONE, PARITY_EVEN, PARITY_ODD, PARITY_MARK,
+PARITY_SPACE) = range(5)
+(STOPBITS_ONE, STOPBITS_ONEANDAHALF,
+STOPBITS_TWO) = (1, 1.5, 2)
+FIVEBITS, SIXBITS, SEVENBITS, EIGHTBITS = (5,6,7,8)
+(RETURN_ERROR, RETURN_BUSY, RETURN_RETRY, RETURN_READY,
+RETURN_NONE) = ('E', 'B', 'P', 'R', 'N')
+portNotOpenError = ValueError('port not open')
+
+def device(portnum):
+ return 'COM%d' % (portnum+1)
+
+class Serial(serialutil.FileLike):
+ """
+ port: number of device; numbering starts at
+ zero. if everything fails, the user can
+ specify a device string, note that this
+ isn't portable any more
+ baudrate: baud rate
+ bytesize: number of databits
+ parity: enable parity checking
+ stopbits: number of stopbits
+ timeout: set a timeout (None for waiting forever)
+ xonxoff: enable software flow control
+ rtscts: enable RTS/CTS flow control
+ retry: DOS retry mode
+ """
+ def __init__(self,
+ port,
+ baudrate = 9600,
+ bytesize = EIGHTBITS,
+ parity = PARITY_NONE,
+ stopbits = STOPBITS_ONE,
+ timeout = None,
+ xonxoff = 0,
+ rtscts = 0,
+ retry = RETURN_RETRY
+ ):
+
+ if type(port) == type(''):
+ #strings are taken directly
+ self.portstr = port
+ else:
+ #numbers are transformed to a string
+ self.portstr = device(port+1)
+
+ self.baud = BAUD_RATES[baudrate]
+ self.bytesize = str(bytesize)
+
+ if parity == PARITY_NONE:
+ self.parity = 'N'
+ elif parity == PARITY_EVEN:
+ self.parity = 'E'
+ elif parity == PARITY_ODD:
+ self.parity = 'O'
+ elif parity == PARITY_MARK:
+ self.parity = 'M'
+ elif parity == PARITY_SPACE:
+ self.parity = 'S'
+
+ self.stop = str(stopbits)
+ self.retry = retry
+ self.filename = "sermsdos.tmp"
+
+ self._config(self.portstr, self.baud, self.parity,
+ self.bytesize, self.stop, self.retry, self.filename)
+
+ def __del__(self):
+ self.close()
+
+ def close(self):
+ pass
+
+ def _config(self, port, baud, parity, data, stop, retry,
+ filename):
+ comString = string.join(("MODE ", port, ":"
+ , " BAUD= ", baud, " PARITY= ", parity
+ , " DATA= ", data, " STOP= ", stop, " RETRY= ",
+ retry, " > ", filename ), '')
+ os.system(comString)
+
+ def setBaudrate(self, baudrate):
+ self._config(self.portstr, BAUD_RATES[baudrate],
+ self.parity, self.bytesize, self.stop, self.retry,
+ self.filename)
+
+ def inWaiting(self):
+ """returns the number of bytes waiting to be read"""
+ raise NotImplementedError
+
+ def read(self, num = 1):
+ """Read num bytes from serial port"""
+ handle = os.open(self.portstr,
+ os.O_RDONLY | os.O_BINARY)
+ # print os.fstat(handle)
+ rv = os.read(handle, num)
+ os.close(handle)
+ return rv
+
+ def write(self, s):
+ """Write string to serial port"""
+ handle = os.open(self.portstr,
+ os.O_WRONLY | os.O_BINARY)
+ rv = os.write(handle, s)
+ os.close(handle)
+ return rv
+
+ def flushInput(self):
+ raise NotImplementedError
+
+ def flushOutput(self):
+ raise NotImplementedError
+
+ def sendBreak(self):
+ raise NotImplementedError
+
+ def setRTS(self,level=1):
+ """Set terminal status line"""
+ raise NotImplementedError
+
+ def setDTR(self,level=1):
+ """Set terminal status line"""
+ raise NotImplementedError
+
+ def getCTS(self):
+ """Eead terminal status line"""
+ raise NotImplementedError
+
+ def getDSR(self):
+ """Eead terminal status line"""
+ raise NotImplementedError
+
+ def getRI(self):
+ """Eead terminal status line"""
+ raise NotImplementedError
+
+ def getCD(self):
+ """Eead terminal status line"""
+ raise NotImplementedError
+
+ def __repr__(self):
+ return string.join(( "<Serial>: ", self.portstr
+ , self.baud, self.parity, self.bytesize, self.stop,
+ self.retry , self.filename), ' ')
+
+if __name__ == '__main__':
+ print __name__
+ s = Serial(0)
+ print s
+
+
+
+
+
+
+
+
+
+
+
+
+
|
sbma44/artomatic
|
61fc7d0d9a896276ba3d5186795d3000456af376
|
actually adding _socket code this time. whoops!
|
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
index 54b051b..454ee0c 100644
--- a/scripts/bellserver.py
+++ b/scripts/bellserver.py
@@ -1,95 +1,99 @@
# Echo server program
-import socket
+try:
+ import socket
+except Exception, e:
+ import _socket as socket
import time
+import settings
class BellServer(object):
"""
Handles listening for and responding to network and serial events within the Ring For Service project
"""
- HOST = ''
- RECIPIENTS = ['127.0.0.1']
- PORT = 50008
-
def __init__(self):
super(BellServer, self).__init__()
+ self.HOST = settings.HOST
+ self.RECIPIENTS = settings.RECIPIENTS
+ self.PORT = settings.PORT
+
# create a nonblocking socket to handle server responsibilities
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(0)
s.bind((self.HOST, self.PORT))
self.socket = s
def close(self):
"""
Close socket to free it up for server restart or other uses.
"""
self.socket.close()
def bell_strike_detected(self):
"""
Checks the serial connection for notice of a bell strike from the Arduino.
"""
# TODO: everything
return False
def transmit_bell_strike(self):
"""
Send a bell strike notification across the network
"""
for recipient in self.RECIPIENTS:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((recipient, self.PORT))
s.send('[X]')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
def strike_bell(self):
"""
Send a bell strike notification to the Arduino over the serial link
"""
pass
def loop(self):
"""
Main server loop
"""
self.socket.listen(1)
while 1:
# check serial input for bell strike notification
if self.bell_strike_detected():
self.send_bell()
# listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
data_received = False
try:
conn, addr = self.socket.accept()
data_received = True
except Exception, e:
data_received = False
if data_received:
print 'Connected by', addr
while 1:
data = False
try:
data = conn.recv(1024)
except Exception, e:
pass
if not data: break
# TODO: replace echo with write to serial output to initiate bell strike
self.strike_bell()
conn.send(data.upper())
if __name__ == '__main__':
B = BellServer()
try:
B.loop()
finally:
# shutdown socket
B.close()
\ No newline at end of file
|
sbma44/artomatic
|
3dbcb812f8464a8d7c1892f45f70ffce5b78acdb
|
breaking settings out into a separate file. accounting for _socket module naming in fonera environment.
|
diff --git a/scripts/settings.py b/scripts/settings.py
new file mode 100644
index 0000000..43414b1
--- /dev/null
+++ b/scripts/settings.py
@@ -0,0 +1,3 @@
+HOST = ''
+RECIPIENTS = ['127.0.0.1']
+PORT = 50008
|
sbma44/artomatic
|
04ba824fa67e2c8e684421d7a553d3b1a9730507
|
adding python-fonera resources and first pass at bellserver script
|
diff --git a/fonera-python/UserDict.py b/fonera-python/UserDict.py
new file mode 100644
index 0000000..5e97817
--- /dev/null
+++ b/fonera-python/UserDict.py
@@ -0,0 +1,175 @@
+"""A more or less complete user-defined wrapper around dictionary objects."""
+
+class UserDict:
+ def __init__(self, dict=None, **kwargs):
+ self.data = {}
+ if dict is not None:
+ self.update(dict)
+ if len(kwargs):
+ self.update(kwargs)
+ def __repr__(self): return repr(self.data)
+ def __cmp__(self, dict):
+ if isinstance(dict, UserDict):
+ return cmp(self.data, dict.data)
+ else:
+ return cmp(self.data, dict)
+ def __len__(self): return len(self.data)
+ def __getitem__(self, key):
+ if key in self.data:
+ return self.data[key]
+ if hasattr(self.__class__, "__missing__"):
+ return self.__class__.__missing__(self, key)
+ raise KeyError(key)
+ def __setitem__(self, key, item): self.data[key] = item
+ def __delitem__(self, key): del self.data[key]
+ def clear(self): self.data.clear()
+ def copy(self):
+ if self.__class__ is UserDict:
+ return UserDict(self.data.copy())
+ import copy
+ data = self.data
+ try:
+ self.data = {}
+ c = copy.copy(self)
+ finally:
+ self.data = data
+ c.update(self)
+ return c
+ def keys(self): return self.data.keys()
+ def items(self): return self.data.items()
+ def iteritems(self): return self.data.iteritems()
+ def iterkeys(self): return self.data.iterkeys()
+ def itervalues(self): return self.data.itervalues()
+ def values(self): return self.data.values()
+ def has_key(self, key): return self.data.has_key(key)
+ def update(self, dict=None, **kwargs):
+ if dict is None:
+ pass
+ elif isinstance(dict, UserDict):
+ self.data.update(dict.data)
+ elif isinstance(dict, type({})) or not hasattr(dict, 'items'):
+ self.data.update(dict)
+ else:
+ for k, v in dict.items():
+ self[k] = v
+ if len(kwargs):
+ self.data.update(kwargs)
+ def get(self, key, failobj=None):
+ if not self.has_key(key):
+ return failobj
+ return self[key]
+ def setdefault(self, key, failobj=None):
+ if not self.has_key(key):
+ self[key] = failobj
+ return self[key]
+ def pop(self, key, *args):
+ return self.data.pop(key, *args)
+ def popitem(self):
+ return self.data.popitem()
+ def __contains__(self, key):
+ return key in self.data
+ @classmethod
+ def fromkeys(cls, iterable, value=None):
+ d = cls()
+ for key in iterable:
+ d[key] = value
+ return d
+
+class IterableUserDict(UserDict):
+ def __iter__(self):
+ return iter(self.data)
+
+class DictMixin:
+ # Mixin defining all dictionary methods for classes that already have
+ # a minimum dictionary interface including getitem, setitem, delitem,
+ # and keys. Without knowledge of the subclass constructor, the mixin
+ # does not define __init__() or copy(). In addition to the four base
+ # methods, progressively more efficiency comes with defining
+ # __contains__(), __iter__(), and iteritems().
+
+ # second level definitions support higher levels
+ def __iter__(self):
+ for k in self.keys():
+ yield k
+ def has_key(self, key):
+ try:
+ value = self[key]
+ except KeyError:
+ return False
+ return True
+ def __contains__(self, key):
+ return self.has_key(key)
+
+ # third level takes advantage of second level definitions
+ def iteritems(self):
+ for k in self:
+ yield (k, self[k])
+ def iterkeys(self):
+ return self.__iter__()
+
+ # fourth level uses definitions from lower levels
+ def itervalues(self):
+ for _, v in self.iteritems():
+ yield v
+ def values(self):
+ return [v for _, v in self.iteritems()]
+ def items(self):
+ return list(self.iteritems())
+ def clear(self):
+ for key in self.keys():
+ del self[key]
+ def setdefault(self, key, default=None):
+ try:
+ return self[key]
+ except KeyError:
+ self[key] = default
+ return default
+ def pop(self, key, *args):
+ if len(args) > 1:
+ raise TypeError, "pop expected at most 2 arguments, got "\
+ + repr(1 + len(args))
+ try:
+ value = self[key]
+ except KeyError:
+ if args:
+ return args[0]
+ raise
+ del self[key]
+ return value
+ def popitem(self):
+ try:
+ k, v = self.iteritems().next()
+ except StopIteration:
+ raise KeyError, 'container is empty'
+ del self[k]
+ return (k, v)
+ def update(self, other=None, **kwargs):
+ # Make progressively weaker assumptions about "other"
+ if other is None:
+ pass
+ elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
+ for k, v in other.iteritems():
+ self[k] = v
+ elif hasattr(other, 'keys'):
+ for k in other.keys():
+ self[k] = other[k]
+ else:
+ for k, v in other:
+ self[k] = v
+ if kwargs:
+ self.update(kwargs)
+ def get(self, key, default=None):
+ try:
+ return self[key]
+ except KeyError:
+ return default
+ def __repr__(self):
+ return repr(dict(self.iteritems()))
+ def __cmp__(self, other):
+ if other is None:
+ return 1
+ if isinstance(other, DictMixin):
+ other = dict(other.iteritems())
+ return cmp(dict(self.iteritems()), other)
+ def __len__(self):
+ return len(self.keys())
diff --git a/fonera-python/python-mini_2.5.1-2_mips.ipk b/fonera-python/python-mini_2.5.1-2_mips.ipk
new file mode 100644
index 0000000..391e5b6
Binary files /dev/null and b/fonera-python/python-mini_2.5.1-2_mips.ipk differ
diff --git a/fonera-python/termios.so b/fonera-python/termios.so
new file mode 100644
index 0000000..4ce8d9e
Binary files /dev/null and b/fonera-python/termios.so differ
diff --git a/scripts/bellserver.py b/scripts/bellserver.py
new file mode 100644
index 0000000..54b051b
--- /dev/null
+++ b/scripts/bellserver.py
@@ -0,0 +1,95 @@
+# Echo server program
+import socket
+import time
+
+class BellServer(object):
+ """
+ Handles listening for and responding to network and serial events within the Ring For Service project
+ """
+
+ HOST = ''
+ RECIPIENTS = ['127.0.0.1']
+ PORT = 50008
+
+ def __init__(self):
+ super(BellServer, self).__init__()
+
+ # create a nonblocking socket to handle server responsibilities
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.setblocking(0)
+ s.bind((self.HOST, self.PORT))
+ self.socket = s
+
+ def close(self):
+ """
+ Close socket to free it up for server restart or other uses.
+ """
+ self.socket.close()
+
+ def bell_strike_detected(self):
+ """
+ Checks the serial connection for notice of a bell strike from the Arduino.
+ """
+ # TODO: everything
+ return False
+
+ def transmit_bell_strike(self):
+ """
+ Send a bell strike notification across the network
+ """
+ for recipient in self.RECIPIENTS:
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ s.connect((recipient, self.PORT))
+ s.send('[X]')
+ data = s.recv(1024)
+ s.close()
+ print 'Received', repr(data)
+
+ def strike_bell(self):
+ """
+ Send a bell strike notification to the Arduino over the serial link
+ """
+ pass
+
+ def loop(self):
+ """
+ Main server loop
+ """
+
+ self.socket.listen(1)
+ while 1:
+ # check serial input for bell strike notification
+ if self.bell_strike_detected():
+ self.send_bell()
+
+ # listen for incoming network data signalling bell strikes (in a non-blocking-compatible manner)
+ data_received = False
+ try:
+ conn, addr = self.socket.accept()
+ data_received = True
+ except Exception, e:
+ data_received = False
+
+ if data_received:
+ print 'Connected by', addr
+ while 1:
+ data = False
+ try:
+ data = conn.recv(1024)
+ except Exception, e:
+ pass
+
+ if not data: break
+
+ # TODO: replace echo with write to serial output to initiate bell strike
+ self.strike_bell()
+ conn.send(data.upper())
+
+
+if __name__ == '__main__':
+ B = BellServer()
+ try:
+ B.loop()
+ finally:
+ # shutdown socket
+ B.close()
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
e5e968a7db53c726669b561e06984b1d31443969
|
Increasing number of feed items as max.
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 26e2608..9caea90 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,146 +1,146 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def Feed.random_feed
Feed.all[rand(Feed.count)]
end
def Feed.update_some
- 5.times do
+ 3.times do
Feed.random_feed.update_feed
end
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating(perform_update = true)
return read_attribute(:rating) if !perform_update
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
- if (result.entries.size() > 200)
+ if (result.entries.size() > 300)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
e6878de330071d0d60c6ae17778448c22c7a7f8f
|
Increasing the feed count
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 3d9eaca..26e2608 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,146 +1,146 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def Feed.random_feed
Feed.all[rand(Feed.count)]
end
def Feed.update_some
5.times do
Feed.random_feed.update_feed
end
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating(perform_update = true)
return read_attribute(:rating) if !perform_update
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
- if (result.entries.size() > 55)
+ if (result.entries.size() > 200)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
4ea789371702437585f0f0981533734f09c2a434
|
Fixing the feed admin page
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 99be46d..3d9eaca 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,145 +1,146 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def Feed.random_feed
Feed.all[rand(Feed.count)]
end
def Feed.update_some
5.times do
Feed.random_feed.update_feed
end
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating(perform_update = true)
+ return read_attribute(:rating) if !perform_update
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 55)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
a4345eafccd70c832e79c7e22d5e8e9c26818406
|
Improving the feed admin page.
|
diff --git a/app/controllers/feed_controller.rb b/app/controllers/feed_controller.rb
index a4413ba..d4c2d0d 100644
--- a/app/controllers/feed_controller.rb
+++ b/app/controllers/feed_controller.rb
@@ -1,61 +1,74 @@
class FeedController < ApplicationController
before_filter :admin_authorized?, :only => [:remove_feed]
def index
@feeds = Feed.find(:all)
end
def new
@feed = Feed.new
end
def create
@feed = Feed.new(params[:feed])
puts @feed.url
@feed.update_feed
if @feed.save
flash[:notice] = "Feed was successfully created."
redirect_to(@feed)
else
render :action => "new"
end
end
def show
@feed = Feed.find(params[:id])
@feed_items = FeedItem.paginate(:page => params[:page], :per_page => 15,
:conditions => ['feed_id = ?', params[:id]], :order => 'created_at desc')
end
def update
@feeds = Feed.find(:all)
@feeds.each { |feed| feed.update_feed }
end
def remove_feed
feed = Feed.find(params[:id])
if feed.destroy
flash[:notice] = "The feed has been sucessfully deleted."
else
flash[:error] = "Unable to delete feed"
end
redirect_to :controller => 'feed', :action => 'index'
end
def admin
- @feeds = Feed.find(:all)
+ @feeds = Feed.find(:all, :order => 'rating desc')
render :layout => 'admin'
end
+ def enable_feed
+ @feed = Feed.find(params[:id])
+ @feed.update_attributes(:disabled => 0, :disabled_reason => nil)
+
+ render :layout => false
+ end
+
+ def admin_row
+ @feed = Feed.find(params[:id])
+
+ render :layout => false
+ end
+
def admin_parse_logs
@logs = FeedParseLog.find(:all, :limit => 30, :conditions => ['feed_id = ?', params[:id]], :order => 'parse_start desc')
@feed_id = params[:id]
render :layout => 'admin'
end
end
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 56d738d..99be46d 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,145 +1,145 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def Feed.random_feed
Feed.all[rand(Feed.count)]
end
def Feed.update_some
5.times do
Feed.random_feed.update_feed
end
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
- def rating
+ def rating(perform_update = true)
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 55)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
diff --git a/app/views/feed/_admin_row.html.erb b/app/views/feed/_admin_row.html.erb
new file mode 100644
index 0000000..3ab3d70
--- /dev/null
+++ b/app/views/feed/_admin_row.html.erb
@@ -0,0 +1,19 @@
+<td>
+ <%= link_to it.id, :controller => "feed", :action => "admin_parse_logs", :id => it.id %>
+</td>
+<td title="<%= it.title %>"><%= truncate(it.title, 15, '...') %></td>
+<td title="<%= it.image_url %>"><%= truncate(it.image_url, 15, '...') || " " %></td>
+<td title="<%= it.feed_url %>"><%= truncate(it.feed_url, 15, '...') %></td>
+<td title="<%= it.description %>"><%= truncate(it.description, 20, '...') || " " %></td>
+<td><%= it.created_at.pretty() %></td>
+<td><%= it.updated_at.pretty() %></td>
+<td title="<% it.url %>"><%= truncate(it.url, 15, '...') %></td>
+<td><%= it.clicks %></td>
+<td><%= it.rating(false) %></td>
+<td><%= it.disabled %></td>
+<td><%= it.disabled_reason || " " %></td>
+<td>
+ <% if it.disabled %>
+ <a href="javascript:tpf.enableFeed(<%= it.id %>)">Enable</a>
+ <% else %> <% end %>
+</td>
\ No newline at end of file
diff --git a/app/views/feed/admin.html.erb b/app/views/feed/admin.html.erb
index eb2750a..dc0e063 100644
--- a/app/views/feed/admin.html.erb
+++ b/app/views/feed/admin.html.erb
@@ -1,38 +1,26 @@
<div class="adminFeedsPage">
<table border="1px">
<tr>
<th>ID</th>
<th>Title</th>
<th>Image</th>
<th>Feed Url</th>
<th>Description</th>
<th>Created At</th>
<th>Updated At</th>
<th>Url</th>
<th>Clicks</th>
<th>Rating</th>
<th>Disabled</th>
<th>Disabled Reason</th>
+ <th>Actions</th>
</tr>
<% @feeds.each { |it| %>
- <tr>
- <td>
- <%= link_to it.id, :controller => "feed", :action => "admin_parse_logs", :id => it.id %>
- </td>
- <td title="<%= it.title %>"><%= truncate(it.title, 15, '...') %></td>
- <td title="<%= it.image_url %>"><%= truncate(it.image_url, 15, '...') %></td>
- <td title="<%= it.feed_url %>"><%= truncate(it.feed_url, 15, '...') %></td>
- <td title="<%= it.description %>"><%= truncate(it.description, 20, '...') %></td>
- <td><%= it.created_at.pretty() %></td>
- <td><%= it.updated_at.pretty() %></td>
- <td title="<% it.url %>"><%= truncate(it.url, 15, '...') %></td>
- <td><%= it.clicks %></td>
- <td><%= it.rating %></td>
- <td><%= it.disabled %></td>
- <td><%= it.disabled_reason %></td>
+ <tr id="feedRow<%= it.id %>">
+ <%= render :partial => 'admin_row', :locals => { :it => it } %>
</tr>
<% } %>
</table>
</div>
\ No newline at end of file
diff --git a/app/views/feed/admin_row.html.erb b/app/views/feed/admin_row.html.erb
new file mode 100644
index 0000000..78c97fd
--- /dev/null
+++ b/app/views/feed/admin_row.html.erb
@@ -0,0 +1 @@
+<%= render :partial => 'admin_row', :locals => {:it => @feed } %>
\ No newline at end of file
diff --git a/app/views/feed/enable_feed.html.erb b/app/views/feed/enable_feed.html.erb
new file mode 100644
index 0000000..f6b3c0d
--- /dev/null
+++ b/app/views/feed/enable_feed.html.erb
@@ -0,0 +1 @@
+$('#feedRow<%= @feed.id %>').load('/feed/admin_row?id=<%= @feed.id %>');
\ No newline at end of file
diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb
index 8c2482c..db436a0 100644
--- a/app/views/layouts/admin.html.erb
+++ b/app/views/layouts/admin.html.erb
@@ -1,8 +1,14 @@
<html>
<head>
-
+ <%= javascript_include_tag "jquery-1.3.2.min.js" %>
+ <%= javascript_include_tag "jquery.bgiframe.js" %>
+ <%= javascript_include_tag "jquery.delegate.js" %>
+ <%= javascript_include_tag "jquery.tooltip.min.js" %>
+ <%= javascript_include_tag "jquery.dimensions.js"%>
+ <%= javascript_include_tag "jquery.pngFix.js"%>
+ <%= javascript_include_tag "main.js" %>
</head>
<body>
<%= yield %>
</body>
</html>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 513b218..559cc65 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,88 +1,90 @@
ActionController::Routing::Routes.draw do |map|
map.resources :models
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.resource :user_preference
map.resource :session, :collection => { :send_forgot_password => :post }
map.resources :users, :collection => { :login_submit => :post }
map.connect 'login', :controller => 'users', :action => 'login'
map.connect 'logout', :controller => 'users', :action => 'logout'
map.connect 'feed/admin_parse_logs', :controller => 'feed', :action => 'admin_parse_logs'
map.connect 'feed/admin', :controller => 'feed', :action => 'admin'
+ map.connect 'feed/admin_row', :controller => 'feed', :action => 'admin_row'
+ map.connect 'feed/enable_feed', :controller => 'feed', :action => 'enable_feed'
map.resources :feed
map.resources :feed_comment
map.connect 'feed_item/media', :controller => 'feed_item', :action => 'media'
map.resources :feed_item
map.resources :feed_item_category
map.resources :category
map.resources :category_comment
map.resources :homepage
map.resources :feed_item_comment
map.resources :category_organizer
map.resources :comments
map.resources :blog_posts
map.resources :email_subscriptions
map.resources :email_a_friend_messages
map.connect 'blog', :controller => 'blog_posts'
map.connect 'blog.xml', :controller => 'blog_posts', :format => 'xml'
map.connect 'privacy-policy', :controller => 'static_pages', :action => 'privacy_policy'
map.connect 'sitemap', :controller => 'static_pages', :action => 'sitemap'
map.connect 'contact-us', :controller => 'static_pages', :action => 'contact_us'
map.connect 'contribute', :controller => 'static_pages', :action => 'contribute'
map.connect 'how-it-works', :controller => 'static_pages', :action => 'how_it_works'
map.connect 'search', :controller => 'static_pages', :action => 'search'
map.connect 'open-source', :controller => 'static_pages', :action => 'open_source'
map.connect 'sitemap.xml', :controller => 'sitemap', :action => 'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.homepage '', :controller => 'homepage'
map.connect 'update', :controller => 'feed', :action => 'update'
map.root :controller => "homepage"
map.connect '*', :controller => 'application', :action => 'rescue_404'
end
diff --git a/public/javascripts/main.js b/public/javascripts/main.js
index 9ae35c4..bdd49ed 100644
--- a/public/javascripts/main.js
+++ b/public/javascripts/main.js
@@ -1,56 +1,64 @@
// Logic that needs to be performed when the page loads.
jQuery(document).ready(function() {
jQuery(".tooltip").tooltip({showURL: false, fade: 250, track: true });
// Ajax submit methods
jQuery(".deleteComment").linkWithAjax();
jQuery(document).pngFix();
});
// Define the variable tpf if it isn't defined
if (typeof tpf == 'undefined') {
tpf = {}
}
// Hide show the comments section of the participate block.
tpf.hideShowCommentSection = function() {
hiddenElements = jQuery('#commentSection:hidden');
jQuery('#commentSection:visible').hide();
jQuery('#emailAFriendSection').hide();
hiddenElements.show();
}
// Hide show the email a friend section of the participate block
tpf.hideShowEmailAFriendSection = function() {
hiddenElements = jQuery('#emailAFriendSection:hidden');
jQuery('#emailAFriendSection:visible').hide();
jQuery('#commentSection').hide();
hiddenElements.show();
}
+// Enables a particular feed
+tpf.enableFeed = function(id) {
+ jQuery.ajax({
+ dataType: 'script',
+ url: '/feed/enable_feed?id=' + id
+ });
+}
+
// Ensure that jQuery sends all javascript files with a text/javascript header
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
// Hide the flash messages after 6 seconds
setTimeout("jQuery('.flashes').slideUp('slow')", 6000);
// jQuery function extension that will allow you to submit a form using ajax.
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
jQuery.post(this.action, jQuery(this).serialize(), null, "script");
return false;
})
return this;
};
// jQuery function extension that will allow you to click a link with ajax.
jQuery.fn.linkWithAjax = function() {
jQuery(this).click(function() {
jQuery.get(jQuery(this).attr('href'), null, null, "script");
return false;
});
return this;
};
|
jenglert/The-Peoples--Feed
|
bcc61c3e9c9f40be5f90612a09adace2bde725c6
|
increasing the rails version
|
diff --git a/config/environment.rb b/config/environment.rb
index bc675ef..9e2f3f3 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,59 +1,59 @@
# Be sure to restart your server when you modify this file
# Specifies gem version of Rails to use when vendor/rails is not present
-RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION
+RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Specify gems that this application depends on and have them installed with rake gems:install
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "sqlite3-ruby", :lib => "sqlite3"
# config.gem "aws-s3", :lib => "aws/s3"
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Skip frameworks you're not going to use. To use Rails without a database,
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names.
config.active_record.default_timezone = :utc
# Use the file store cache
config.cache_store = :file_store, "#{RAILS_ROOT}/tmp/cache"
config.gem 'javan-whenever', :lib => false, :source => 'http://gems.github.com'
config.action_mailer.smtp_settings = {
:address => 'mail.thepeoplesfeed.com',
:port => 26,
:domain => 'www.thepeoplesfeed.com',
:authentication => :login,
:user_name => '[email protected]',
:password => 'thepeoplesfeed'
}
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
# config.i18n.default_locale = :de
end
require 'extensions/all'
require "will_paginate"
require 'cgi'
|
jenglert/The-Peoples--Feed
|
cd8b0fbcd4070068e9177b7e8859e555642e09eb
|
Reducing the amount of feeds updated with update_some
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index a5b667f..56d738d 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,145 +1,145 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def Feed.random_feed
Feed.all[rand(Feed.count)]
end
def Feed.update_some
- 15.times do
+ 5.times do
Feed.random_feed.update_feed
end
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 55)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
bf380c0a8cdedbd642c84fdea45bbdc755bd5325
|
Adding the update some feed command
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 4d2242e..a5b667f 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,135 +1,145 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
+ def Feed.random_feed
+ Feed.all[rand(Feed.count)]
+ end
+
+ def Feed.update_some
+ 15.times do
+ Feed.random_feed.update_feed
+ end
+ end
+
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 55)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
15e4b6ecd5437b5711e221474388cec04d81ae95
|
code cleanup
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 1341889..296306a 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,63 +1,60 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
- # Be sure to include AuthenticationSystem in Application Controller instead
- include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
# Always drop the logged in cookie.
- cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => Time.new + 360.days }
+ cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => 360.days.from_now }
default = '/'
-
- puts "referrer:" + request.referrer
+
# Attempt to determine if we came from the login page, if so, do nothing. If not, go to the page we used to be at
default = request.referrer if !request.referrer.include?('sessions')
redirect_back_or_default(default)
flash[:notice] = "Logged in successfully"
else
flash[:error] = "Username/Password not recognized. Please try again."
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
def forgot_password
end
def send_forgot_password
users = User.find_all_by_email(params[:email])
if users.length <= 0
# This is potential security whole since users could find all the emails in our database.
# At this point, the added user flexibility is better than the added security.
flash[:error] = "Unable to find a user with that email."
render :action => 'forgot_password'
return
end
new_password = User.random_password
users[0].password = new_password
users[0].password_confirmation = new_password
users[0].save!
flash[:notice] = "We are emailing you a replacement password."
ConsumerMailer.deliver_forgot_password(users[0].email, new_password)
redirect_back_or_default('/')
end
end
|
jenglert/The-Peoples--Feed
|
82a85b59b8e82dcbb8923d4bd524dd0658ed3982
|
cleaning up script
|
diff --git a/script/clearCaches.sh b/script/clearCaches.sh
index c7a18ad..9a94760 100755
--- a/script/clearCaches.sh
+++ b/script/clearCaches.sh
@@ -1,8 +1,3 @@
-#!/bin/sh
+#!/bin/bash
rm ~/Documents/thepeoplesfeed/public/sitemap.xml
rm -rf ~/Documents/thepeoplesfeed/tmp/cache/*
-wget --spider http://localhost:9000/sitemap.xml
-wget --spider http://localhost:9000/contribute
-wget --spider http://localhost:9000/feed/new
-wget --spider http://localhost:9000/category/2291
-wget --spider http://localhost:9000/feed/25
|
jenglert/The-Peoples--Feed
|
f5c8891f85bb1be72d8bba4e8c310725a6b1367a
|
Removing a potential NPE
|
diff --git a/app/views/feed/show.html.erb b/app/views/feed/show.html.erb
index 9bce24d..bfe7dfb 100644
--- a/app/views/feed/show.html.erb
+++ b/app/views/feed/show.html.erb
@@ -1,44 +1,44 @@
<% meta_description "RSS feeds provided by '#{@feed.title}'"%>
<div class="feedShow">
<table class="feedInfo">
<tr>
<td colspan="2" class="title">
<%= image_tag @feed.image_url if @feed.image_url %>
- <%= page_title @feed.title + " RSS Feed" %>
+ <%= page_title (@feed.title || "" ) + " RSS Feed" %>
</td>
</tr>
<tr>
<td class="leftColumn"><b>Last Updated:</b> <%= @feed.updated_at.pretty%></td>
<td><h2><%= @feed.description %></h2></td>
</tr>
<tr>
<td class="leftColumn"><%= @feed.feed_items.count.to_s + ' ' + 'Articles'.pluralize %></td>
<td>
<a class="tooltip" title="The People's Feed uses a rating system to help determine which feeds are the most popular in the overal scheme of things. Rather than using a closed, proprietary system like Google, we use an open ratings system. This allows the community at large to have input on the most effective ratings.">
<b>Rating: </b> <%= sprintf('%.1f', @feed.rating) unless @feed.rating.nil? %>
<span class="whatIsThis">(what is this)</span>
</td>
</tr>
</table>
<div class="adminControls">
<% if admin_logged_in? %>
<%= link_to 'Delete', :controller => 'feed', :action => 'remove_feed', :id => @feed.id %>
<% end %>
</div>
<%= render :partial => 'shared/participate', :locals => { :post_location => '/feed_comment', :item => @feed }%>
<h2>Articles From This Feed</h2>
<ul>
<% @feed_items.each { |item| %>
<li>
<%= link_to h(item.title.fix_html), item %>
</li>
<% } %>
</ul>
<div class="pagination">
<%= will_paginate @feed_items %>
</div>
-</div>
\ No newline at end of file
+</div>
|
jenglert/The-Peoples--Feed
|
4ddce9e9b0678f97faae29bfa2ad459e03a00664
|
Adding the clear caches file.
|
diff --git a/script/clearCaches.sh b/script/clearCaches.sh
new file mode 100755
index 0000000..c7a18ad
--- /dev/null
+++ b/script/clearCaches.sh
@@ -0,0 +1,8 @@
+#!/bin/sh
+rm ~/Documents/thepeoplesfeed/public/sitemap.xml
+rm -rf ~/Documents/thepeoplesfeed/tmp/cache/*
+wget --spider http://localhost:9000/sitemap.xml
+wget --spider http://localhost:9000/contribute
+wget --spider http://localhost:9000/feed/new
+wget --spider http://localhost:9000/category/2291
+wget --spider http://localhost:9000/feed/25
|
jenglert/The-Peoples--Feed
|
ac29876d2e81ec913a1d38d422901ac9d79924cb
|
Increasing the timeout for a broken feed
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 9cb4007..4d2242e 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,135 +1,135 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
- # Ensure that the operation took less than 30 seconds. If it took more, set the feed to disabled.
- if(Time.now - startTime > 30)
+ # Ensure that the operation took less than 60 seconds. If it took more, set the feed to disabled.
+ if(Time.now - startTime > 60)
update_attribute(:disabled_reason, "Took too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
- if (result.entries.size() > 45)
+ if (result.entries.size() > 55)
update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
535cfba09535e83a41b20c923c297d6fddc6b902
|
Making category names unique
|
diff --git a/app/models/category.rb b/app/models/category.rb
index c4a6c1f..ccb9753 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -1,12 +1,12 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Category < ActiveRecord::Base
- has_many :feed_item_categories
+ has_many :feed_item_categories, :dependent => :destroy
has_many :feed_items, :through => :feed_item_categories
has_many :user_preferences
validates_presence_of :name
acts_as_commentable
end
\ No newline at end of file
diff --git a/db/migrate/20100929041215_make_category_name_unique.rb b/db/migrate/20100929041215_make_category_name_unique.rb
new file mode 100644
index 0000000..4a08a71
--- /dev/null
+++ b/db/migrate/20100929041215_make_category_name_unique.rb
@@ -0,0 +1,17 @@
+class MakeCategoryNameUnique < ActiveRecord::Migration
+ def self.up
+
+ categories = Category.find_by_sql("select * from categories where name in (select name from categories group by name having count(*) > 1)")
+ categories_by_name = {}
+ puts categories.count
+ categories.each do |category|
+ category.destroy if !categories_by_name.include? category.name
+ categories_by_name[category.name] = category
+ end
+
+ execute "create unique index category_name_uidx on categories(name)"
+ end
+
+ def self.down
+ end
+end
|
jenglert/The-Peoples--Feed
|
8274942314d9aa63bffc921102a3fcae4a22bd77
|
Enhancing incremental
|
diff --git a/db/migrate/20100929034845_make_guid_unique.rb b/db/migrate/20100929034845_make_guid_unique.rb
index 19ece98..83f7e04 100644
--- a/db/migrate/20100929034845_make_guid_unique.rb
+++ b/db/migrate/20100929034845_make_guid_unique.rb
@@ -1,19 +1,20 @@
class MakeGuidUnique < ActiveRecord::Migration
def self.up
execute "create index feed_item_guid_idx on feed_items(guid)"
FeedItem.all.each do |fi|
+ puts fi.id if fi.id % 1000 == 0
FeedItem.find_all_by_guid(fi.guid).each do |found_feed_item|
if found_feed_item.id != fi.id
found_feed_item.destroy
end
end
end
execute "drop index feed_item_guid_idx on feed_items"
execute "create unique index feed_item_guid_uidx on feed_items(guid)"
end
def self.down
end
end
|
jenglert/The-Peoples--Feed
|
df26ce0e4d538ff6e1370cba737b0398d2b441fd
|
Enhancing incremental
|
diff --git a/db/migrate/20100929034845_make_guid_unique.rb b/db/migrate/20100929034845_make_guid_unique.rb
index 588f37c..19ece98 100644
--- a/db/migrate/20100929034845_make_guid_unique.rb
+++ b/db/migrate/20100929034845_make_guid_unique.rb
@@ -1,16 +1,19 @@
class MakeGuidUnique < ActiveRecord::Migration
def self.up
+
+ execute "create index feed_item_guid_idx on feed_items(guid)"
+
FeedItem.all.each do |fi|
FeedItem.find_all_by_guid(fi.guid).each do |found_feed_item|
if found_feed_item.id != fi.id
found_feed_item.destroy
end
end
end
-
+ execute "drop index feed_item_guid_idx on feed_items"
execute "create unique index feed_item_guid_uidx on feed_items(guid)"
end
def self.down
end
end
|
jenglert/The-Peoples--Feed
|
f53b0aa0fe4653a398b7d888843b37f5824e4fb7
|
adding incremental to make guid on feed items have a unique index
|
diff --git a/db/migrate/20100929034845_make_guid_unique.rb b/db/migrate/20100929034845_make_guid_unique.rb
new file mode 100644
index 0000000..588f37c
--- /dev/null
+++ b/db/migrate/20100929034845_make_guid_unique.rb
@@ -0,0 +1,16 @@
+class MakeGuidUnique < ActiveRecord::Migration
+ def self.up
+ FeedItem.all.each do |fi|
+ FeedItem.find_all_by_guid(fi.guid).each do |found_feed_item|
+ if found_feed_item.id != fi.id
+ found_feed_item.destroy
+ end
+ end
+ end
+
+ execute "create unique index feed_item_guid_uidx on feed_items(guid)"
+ end
+
+ def self.down
+ end
+end
|
jenglert/The-Peoples--Feed
|
5f14746b260893b959b97893d75925baf96b2c38
|
Updating readme file.
|
diff --git a/README b/README
index 37ec8ea..b3104c8 100644
--- a/README
+++ b/README
@@ -1,243 +1,4 @@
-== Welcome to Rails
+The Peoples Feed
+================
-Rails is a web-application framework that includes everything needed to create
-database-backed web applications according to the Model-View-Control pattern.
-
-This pattern splits the view (also called the presentation) into "dumb" templates
-that are primarily responsible for inserting pre-built data in between HTML tags.
-The model contains the "smart" domain objects (such as Account, Product, Person,
-Post) that holds all the business logic and knows how to persist themselves to
-a database. The controller handles the incoming requests (such as Save New Account,
-Update Product, Show Post) by manipulating the model and directing data to the view.
-
-In Rails, the model is handled by what's called an object-relational mapping
-layer entitled Active Record. This layer allows you to present the data from
-database rows as objects and embellish these data objects with business logic
-methods. You can read more about Active Record in
-link:files/vendor/rails/activerecord/README.html.
-
-The controller and view are handled by the Action Pack, which handles both
-layers by its two parts: Action View and Action Controller. These two layers
-are bundled in a single package due to their heavy interdependence. This is
-unlike the relationship between the Active Record and Action Pack that is much
-more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
-link:files/vendor/rails/actionpack/README.html.
-
-
-== Getting Started
-
-1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
- and your application name. Ex: rails myapp
-2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
-3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
-4. Follow the guidelines to start developing your application
-
-
-== Web Servers
-
-By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
-with a variety of other web servers.
-
-Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
-suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
-getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
-More info at: http://mongrel.rubyforge.org
-
-Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
-Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
-FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
-
-== Apache .htaccess example for FCGI/CGI
-
-# General Apache options
-AddHandler fastcgi-script .fcgi
-AddHandler cgi-script .cgi
-Options +FollowSymLinks +ExecCGI
-
-# If you don't want Rails to look in certain directories,
-# use the following rewrite rules so that Apache won't rewrite certain requests
-#
-# Example:
-# RewriteCond %{REQUEST_URI} ^/notrails.*
-# RewriteRule .* - [L]
-
-# Redirect all requests not available on the filesystem to Rails
-# By default the cgi dispatcher is used which is very slow
-#
-# For better performance replace the dispatcher with the fastcgi one
-#
-# Example:
-# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-RewriteEngine On
-
-# If your Rails application is accessed via an Alias directive,
-# then you MUST also set the RewriteBase in this htaccess file.
-#
-# Example:
-# Alias /myrailsapp /path/to/myrailsapp/public
-# RewriteBase /myrailsapp
-
-RewriteRule ^$ index.html [QSA]
-RewriteRule ^([^.]+)$ $1.html [QSA]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
-# In case Rails experiences terminal errors
-# Instead of displaying this message you can supply a file here which will be rendered instead
-#
-# Example:
-# ErrorDocument 500 /500.html
-
-ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
-
-
-== Debugging Rails
-
-Sometimes your application goes wrong. Fortunately there are a lot of tools that
-will help you debug it and get it back on the rails.
-
-First area to check is the application log files. Have "tail -f" commands running
-on the server.log and development.log. Rails will automatically display debugging
-and runtime information to these files. Debugging info will also be shown in the
-browser on requests from 127.0.0.1.
-
-You can also log your own messages directly into the log file from your code using
-the Ruby logger class from inside your controllers. Example:
-
- class WeblogController < ActionController::Base
- def destroy
- @weblog = Weblog.find(params[:id])
- @weblog.destroy
- logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
- end
- end
-
-The result will be a message in your log file along the lines of:
-
- Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
-
-More information on how to use the logger is at http://www.ruby-doc.org/core/
-
-Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
-
-* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
-* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
-
-These two online (and free) books will bring you up to speed on the Ruby language
-and also on programming in general.
-
-
-== Debugger
-
-Debugger support is available through the debugger command when you start your Mongrel or
-Webrick server with --debugger. This means that you can break out of execution at any point
-in the code, investigate and change the model, AND then resume execution!
-You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
-Example:
-
- class WeblogController < ActionController::Base
- def index
- @posts = Post.find(:all)
- debugger
- end
- end
-
-So the controller will accept the action, run the first line, then present you
-with a IRB prompt in the server window. Here you can do things like:
-
- >> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
- >> @posts.first.title = "hello from a debugger"
- => "hello from a debugger"
-
-...and even better is that you can examine how your runtime objects actually work:
-
- >> f = @posts.first
- => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
- >> f.
- Display all 152 possibilities? (y or n)
-
-Finally, when you're ready to resume execution, you enter "cont"
-
-
-== Console
-
-You can interact with the domain model by starting the console through <tt>script/console</tt>.
-Here you'll have all parts of the application configured, just like it is when the
-application is running. You can inspect domain models, change values, and save to the
-database. Starting the script without arguments will launch it in the development environment.
-Passing an argument will specify a different environment, like <tt>script/console production</tt>.
-
-To reload your controllers and models after launching the console run <tt>reload!</tt>
-
-== dbconsole
-
-You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
-You would be connected to the database with the credentials defined in database.yml.
-Starting the script without arguments will connect you to the development database. Passing an
-argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
-Currently works for mysql, postgresql and sqlite.
-
-== Description of Contents
-
-app
- Holds all the code that's specific to this particular application.
-
-app/controllers
- Holds controllers that should be named like weblogs_controller.rb for
- automated URL mapping. All controllers should descend from ApplicationController
- which itself descends from ActionController::Base.
-
-app/models
- Holds models that should be named like post.rb.
- Most models will descend from ActiveRecord::Base.
-
-app/views
- Holds the template files for the view that should be named like
- weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
- syntax.
-
-app/views/layouts
- Holds the template files for layouts to be used with views. This models the common
- header/footer method of wrapping views. In your views, define a layout using the
- <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
- call <% yield %> to render the view using this layout.
-
-app/helpers
- Holds view helpers that should be named like weblogs_helper.rb. These are generated
- for you automatically when using script/generate for controllers. Helpers can be used to
- wrap functionality for your views into methods.
-
-config
- Configuration files for the Rails environment, the routing map, the database, and other dependencies.
-
-db
- Contains the database schema in schema.rb. db/migrate contains all
- the sequence of Migrations for your schema.
-
-doc
- This directory is where your application documentation will be stored when generated
- using <tt>rake doc:app</tt>
-
-lib
- Application specific libraries. Basically, any kind of custom code that doesn't
- belong under controllers, models, or helpers. This directory is in the load path.
-
-public
- The directory available for the web server. Contains subdirectories for images, stylesheets,
- and javascripts. Also contains the dispatchers and the default HTML files. This should be
- set as the DOCUMENT_ROOT of your web server.
-
-script
- Helper scripts for automation and generation.
-
-test
- Unit and functional tests along with fixtures. When using the script/generate scripts, template
- test files will be generated for you and placed in this directory.
-
-vendor
- External libraries that the application depends on. Also includes the plugins subdirectory.
- If the app has frozen rails, those gems also go here, under vendor/rails/.
- This directory is in the load path.
+This Ruby on Rails project provides a framework for parsing and downloading RSS feeds as a website. This project could easily be transformed into something much more interesting than http://www.thepeoplesfeed.com. For example, you could use this as the base for a site that pulls from the twitter accounts and blogs of professional athletes.
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
0207c31bacb19d4ce7c7a0e5de2ebbc857766a9e
|
Adding comment
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index a4af25f..47cd8dc 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,141 +1,142 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
@feedItems = FeedItem.find(:all, :limit => 50, :order => 'rating desc')
- feedPenalty = {}
+ # Ensure that the list of feed items pulls from a variety of different feeds.
+ feedPenalty = {}
@feedItems.each{ |feedItem|
if (feedPenalty[feedItem.feed])
feedItem.rating -= feedPenalty[feedItem.feed]
feedPenalty[feedItem.feed] = feedPenalty[feedItem.feed] * 1.5
else
feedPenalty[feedItem.feed] = 1
end
}
@feedItems.sort(){ |a, b| b.rating <=> a.rating }
@feedItems.slice(0,25)
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new(:name => category_name).save!
end
self.categories << category unless self.categories.include? category
end
end
rescue => ex
logger.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 3 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
jenglert/The-Peoples--Feed
|
e3c6d04e81901fadc9884d9f3b7ab54e77302fae
|
Altering feed items to provide a larger range of feed providers in the list of feeds.
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index e28d9e1..a4af25f 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,128 +1,141 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
- FeedItem.find(:all, :limit => 20, :order => 'rating desc')
+ @feedItems = FeedItem.find(:all, :limit => 50, :order => 'rating desc')
+ feedPenalty = {}
+
+ @feedItems.each{ |feedItem|
+ if (feedPenalty[feedItem.feed])
+ feedItem.rating -= feedPenalty[feedItem.feed]
+ feedPenalty[feedItem.feed] = feedPenalty[feedItem.feed] * 1.5
+ else
+ feedPenalty[feedItem.feed] = 1
+ end
+ }
+ @feedItems.sort(){ |a, b| b.rating <=> a.rating }
+
+ @feedItems.slice(0,25)
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new(:name => category_name).save!
end
self.categories << category unless self.categories.include? category
end
end
rescue => ex
logger.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 3 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
jenglert/The-Peoples--Feed
|
b878fda20779a7457064b06f00e7a58026453d90
|
Preventing errors if the system cannot find a feed item, likely because it has been deleted.
|
diff --git a/app/controllers/feed_item_controller.rb b/app/controllers/feed_item_controller.rb
index bc74f3c..77f4e80 100644
--- a/app/controllers/feed_item_controller.rb
+++ b/app/controllers/feed_item_controller.rb
@@ -1,32 +1,38 @@
class FeedItemController < ApplicationController
def show
- @feed_item = FeedItem.find(params[:id])
+ begin
+ @feed_item = FeedItem.find(params[:id])
+ rescue ActiveRecord::RecordNotFound => rnf
+ flash[:error] = "Unable to find feed item"
+ redirect_to '/'
+ return
+ end
if @feed_item.clicks.nil?
@feed_item.clicks = 0
end
@feed_item.clicks = @feed_item.clicks + 1
@feed_item.save
end
def redir
@feed_item = FeedItem.find(params[:id])
if @feed_item.clicks.nil?
@feed_item.clicks = 0
end
@feed_item.clicks = @feed_item.clicks + 1
@feed_item.save
redirect_to @feed_item.item_url
end
def media
@feed_items = FeedItem.paginate(:all, :conditions => "updated_at > DATE_SUB(curdate(), INTERVAL 20 DAY) and image_url is not null",
:order => 'updated_at desc', :page => params[:page], :per_page => 24)
end
end
|
jenglert/The-Peoples--Feed
|
82cf7fc11252acb915301373242c9e1eba50c1e0
|
Enhancing the admin pages. Adding a new admin layout. Ability to see the feed parse logs.
|
diff --git a/app/controllers/feed_controller.rb b/app/controllers/feed_controller.rb
index 5d31331..a4413ba 100644
--- a/app/controllers/feed_controller.rb
+++ b/app/controllers/feed_controller.rb
@@ -1,55 +1,61 @@
class FeedController < ApplicationController
before_filter :admin_authorized?, :only => [:remove_feed]
def index
@feeds = Feed.find(:all)
end
def new
@feed = Feed.new
end
def create
@feed = Feed.new(params[:feed])
puts @feed.url
@feed.update_feed
if @feed.save
flash[:notice] = "Feed was successfully created."
redirect_to(@feed)
else
render :action => "new"
end
end
def show
@feed = Feed.find(params[:id])
@feed_items = FeedItem.paginate(:page => params[:page], :per_page => 15,
:conditions => ['feed_id = ?', params[:id]], :order => 'created_at desc')
end
def update
@feeds = Feed.find(:all)
@feeds.each { |feed| feed.update_feed }
end
def remove_feed
feed = Feed.find(params[:id])
if feed.destroy
flash[:notice] = "The feed has been sucessfully deleted."
else
flash[:error] = "Unable to delete feed"
end
redirect_to :controller => 'feed', :action => 'index'
end
def admin
@feeds = Feed.find(:all)
- render :layout => 'search'
+ render :layout => 'admin'
+ end
+
+ def admin_parse_logs
+ @logs = FeedParseLog.find(:all, :limit => 30, :conditions => ['feed_id = ?', params[:id]], :order => 'parse_start desc')
+ @feed_id = params[:id]
+ render :layout => 'admin'
end
end
diff --git a/app/views/feed/admin.html.erb b/app/views/feed/admin.html.erb
index 95aa331..eb2750a 100644
--- a/app/views/feed/admin.html.erb
+++ b/app/views/feed/admin.html.erb
@@ -1,36 +1,38 @@
<div class="adminFeedsPage">
-<table>
+<table border="1px">
<tr>
<th>ID</th>
<th>Title</th>
<th>Image</th>
<th>Feed Url</th>
<th>Description</th>
<th>Created At</th>
<th>Updated At</th>
<th>Url</th>
<th>Clicks</th>
<th>Rating</th>
<th>Disabled</th>
<th>Disabled Reason</th>
</tr>
<% @feeds.each { |it| %>
<tr>
- <td><%= it.id %></td>
- <td><%= it.title %></td>
- <td><%= it.image_url %></td>
- <td><%= it.feed_url %></td>
- <td><%= it.description %></td>
- <td><%= it.created_at %></td>
- <td><%= it.updated_at %></td>
- <td><%= it.url %></td>
+ <td>
+ <%= link_to it.id, :controller => "feed", :action => "admin_parse_logs", :id => it.id %>
+ </td>
+ <td title="<%= it.title %>"><%= truncate(it.title, 15, '...') %></td>
+ <td title="<%= it.image_url %>"><%= truncate(it.image_url, 15, '...') %></td>
+ <td title="<%= it.feed_url %>"><%= truncate(it.feed_url, 15, '...') %></td>
+ <td title="<%= it.description %>"><%= truncate(it.description, 20, '...') %></td>
+ <td><%= it.created_at.pretty() %></td>
+ <td><%= it.updated_at.pretty() %></td>
+ <td title="<% it.url %>"><%= truncate(it.url, 15, '...') %></td>
<td><%= it.clicks %></td>
<td><%= it.rating %></td>
<td><%= it.disabled %></td>
<td><%= it.disabled_reason %></td>
</tr>
<% } %>
</table>
</div>
\ No newline at end of file
diff --git a/app/views/feed/admin_parse_logs.html.erb b/app/views/feed/admin_parse_logs.html.erb
new file mode 100644
index 0000000..1b8075e
--- /dev/null
+++ b/app/views/feed/admin_parse_logs.html.erb
@@ -0,0 +1,19 @@
+<h2>Results for <%= @feed_id %></h2>
+<table border="1px">
+ <tr>
+ <th>ID</th>
+ <th>Items Added</th>
+ <th>Start</th>
+ <th>End</th>
+ <th>Time</th>
+ </tr>
+ <% @logs.each{ |it| %>
+ <tr>
+ <td><%= it.id %></td>
+ <td><%= it.feed_items_added %></td>
+ <td><%= it.parse_start ? it.parse_start : " " %></td>
+ <td><%= it.parse_finish ? it.parse_finish : " " %></td>
+ <td><%= (it.parse_finish and it.parse_start) ? (it.parse_finish - it.parse_start) : " " %></td>
+ </tr>
+ <% } %>
+</table>
\ No newline at end of file
diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb
new file mode 100644
index 0000000..8c2482c
--- /dev/null
+++ b/app/views/layouts/admin.html.erb
@@ -0,0 +1,8 @@
+<html>
+ <head>
+
+ </head>
+ <body>
+ <%= yield %>
+ </body>
+</html>
\ No newline at end of file
diff --git a/config/database_example.yml b/config/database_example.yml
deleted file mode 100644
index 33e531b..0000000
--- a/config/database_example.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-development:
- adapter: mysql
- encoding: utf8
- database: peoplesfeed_dev
- username: root
-
-# Warning: The database defined as "test" will be erased and
-# re-generated from your development database when you run "rake".
-# Do not set this db to the same as development or production.
-test:
- adapter: mysql
- encoding: utf8
- database: peoplesfeed_test
- username: root
-
-production:
- adapter: sqlite3
- database: db/production.sqlite3
- pool: 5
- timeout: 5000
diff --git a/config/routes.rb b/config/routes.rb
index e023bf7..513b218 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,87 +1,88 @@
ActionController::Routing::Routes.draw do |map|
map.resources :models
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.resource :user_preference
map.resource :session, :collection => { :send_forgot_password => :post }
map.resources :users, :collection => { :login_submit => :post }
map.connect 'login', :controller => 'users', :action => 'login'
map.connect 'logout', :controller => 'users', :action => 'logout'
+ map.connect 'feed/admin_parse_logs', :controller => 'feed', :action => 'admin_parse_logs'
map.connect 'feed/admin', :controller => 'feed', :action => 'admin'
map.resources :feed
map.resources :feed_comment
map.connect 'feed_item/media', :controller => 'feed_item', :action => 'media'
map.resources :feed_item
map.resources :feed_item_category
map.resources :category
map.resources :category_comment
map.resources :homepage
map.resources :feed_item_comment
map.resources :category_organizer
map.resources :comments
map.resources :blog_posts
map.resources :email_subscriptions
map.resources :email_a_friend_messages
map.connect 'blog', :controller => 'blog_posts'
map.connect 'blog.xml', :controller => 'blog_posts', :format => 'xml'
map.connect 'privacy-policy', :controller => 'static_pages', :action => 'privacy_policy'
map.connect 'sitemap', :controller => 'static_pages', :action => 'sitemap'
map.connect 'contact-us', :controller => 'static_pages', :action => 'contact_us'
map.connect 'contribute', :controller => 'static_pages', :action => 'contribute'
map.connect 'how-it-works', :controller => 'static_pages', :action => 'how_it_works'
map.connect 'search', :controller => 'static_pages', :action => 'search'
map.connect 'open-source', :controller => 'static_pages', :action => 'open_source'
map.connect 'sitemap.xml', :controller => 'sitemap', :action => 'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.homepage '', :controller => 'homepage'
map.connect 'update', :controller => 'feed', :action => 'update'
map.root :controller => "homepage"
map.connect '*', :controller => 'application', :action => 'rescue_404'
end
|
jenglert/The-Peoples--Feed
|
c1bbe931caeb7a5bebff6b9a8eb0038d0c54ef4b
|
Fixing logger.
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index 458ca57..e28d9e1 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,128 +1,128 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new(:name => category_name).save!
end
self.categories << category unless self.categories.include? category
end
end
rescue => ex
- LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
+ logger.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 3 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
jenglert/The-Peoples--Feed
|
8b7d20ec6ac1818e8c704bae74457035d7506a65
|
Adding feed admin page.
|
diff --git a/app/controllers/feed_controller.rb b/app/controllers/feed_controller.rb
index 2f72835..5d31331 100644
--- a/app/controllers/feed_controller.rb
+++ b/app/controllers/feed_controller.rb
@@ -1,50 +1,55 @@
class FeedController < ApplicationController
before_filter :admin_authorized?, :only => [:remove_feed]
def index
@feeds = Feed.find(:all)
end
def new
@feed = Feed.new
end
def create
@feed = Feed.new(params[:feed])
puts @feed.url
@feed.update_feed
if @feed.save
flash[:notice] = "Feed was successfully created."
redirect_to(@feed)
else
render :action => "new"
end
end
def show
@feed = Feed.find(params[:id])
@feed_items = FeedItem.paginate(:page => params[:page], :per_page => 15,
:conditions => ['feed_id = ?', params[:id]], :order => 'created_at desc')
end
def update
@feeds = Feed.find(:all)
@feeds.each { |feed| feed.update_feed }
end
def remove_feed
feed = Feed.find(params[:id])
if feed.destroy
flash[:notice] = "The feed has been sucessfully deleted."
else
flash[:error] = "Unable to delete feed"
end
redirect_to :controller => 'feed', :action => 'index'
end
+ def admin
+ @feeds = Feed.find(:all)
+ render :layout => 'search'
+ end
+
end
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 95cb706..a54518b 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,133 +1,135 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 15 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 15)
+ update_attributes(:disabled_reason, "Too long processing (#{Time.now - startTime})")
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 45)
- self.update_attribute(:disabled, true)
+ update_attribute(:disabled_reason, "Too many entires " + result.entries.size().to_s)
+ update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
diff --git a/app/views/feed/admin.html.erb b/app/views/feed/admin.html.erb
new file mode 100644
index 0000000..95aa331
--- /dev/null
+++ b/app/views/feed/admin.html.erb
@@ -0,0 +1,36 @@
+<div class="adminFeedsPage">
+
+<table>
+ <tr>
+ <th>ID</th>
+ <th>Title</th>
+ <th>Image</th>
+ <th>Feed Url</th>
+ <th>Description</th>
+ <th>Created At</th>
+ <th>Updated At</th>
+ <th>Url</th>
+ <th>Clicks</th>
+ <th>Rating</th>
+ <th>Disabled</th>
+ <th>Disabled Reason</th>
+ </tr>
+ <% @feeds.each { |it| %>
+ <tr>
+ <td><%= it.id %></td>
+ <td><%= it.title %></td>
+ <td><%= it.image_url %></td>
+ <td><%= it.feed_url %></td>
+ <td><%= it.description %></td>
+ <td><%= it.created_at %></td>
+ <td><%= it.updated_at %></td>
+ <td><%= it.url %></td>
+ <td><%= it.clicks %></td>
+ <td><%= it.rating %></td>
+ <td><%= it.disabled %></td>
+ <td><%= it.disabled_reason %></td>
+ </tr>
+ <% } %>
+</table>
+
+</div>
\ No newline at end of file
diff --git a/app/views/layouts/standard.html.erb b/app/views/layouts/standard.html.erb
index 9ddb9e5..06735d1 100644
--- a/app/views/layouts/standard.html.erb
+++ b/app/views/layouts/standard.html.erb
@@ -1,123 +1,136 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<%= stylesheet_link_tag 'main' %>
<meta name="verify-v1" content="qnzsIVoN1EFhSa6I3djN8bQ0o9x+L1NZp/eJ6C6XCao=" ></meta>
<title>
<%= "#@page_title - " if !@page_title.nil? %> The People's Feed
</title>
<% if !@meta_description.nil? %>
<meta name="description" content="<%= @meta_description %>" />
<% end %>
<%= javascript_include_tag "jquery-1.3.2.min.js" %>
<%= javascript_include_tag "jquery.bgiframe.js" %>
<%= javascript_include_tag "jquery.delegate.js" %>
<%= javascript_include_tag "jquery.tooltip.min.js" %>
<%= javascript_include_tag "jquery.dimensions.js"%>
<%= javascript_include_tag "jquery.pngFix.js"%>
<%= javascript_include_tag "main.js" %>
<%= yield(:head)%>
</head>
<body>
<div class="header">
<% link_to '/' do %>
<img src="/images/header_logo.png" alt="The People's Feed" class="logo" />
<% end %>
<div class="motto">The latest news ranked according to its popularity by YOU</div>
<%= render :partial => 'shared/main_menu_insert' %>
</div>
<div class="body">
<div class="centerColumn">
<div class="flashes">
<% if flash.has_key?(:error) %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
<% if flash.has_key?(:notice) %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
</div>
<%= yield %>
</div>
<div class="rightHandList">
+ <div>
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* Peoples' Feed: Top Right Nav */
+ google_ad_slot = "5558791084";
+ google_ad_width = 180;
+ google_ad_height = 150;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ </div>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_feeds') do %>
<h3>Top Feeds</h3>
<%= render :partial => 'shared/feed_narrow', :locals => { :topFeeds => @topFeeds } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_categories') do %>
<h3>Top Categories</h3>
<%= render :partial => 'shared/category_narrow', :locals => { :topCategories => @topCategories } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_media') do %>
<h3>Top Media</h3>
<%= render :partial => 'shared/media_narrow', :locals => { :topMedia => @topMedia } %>
<% end %>
<% if show_ads %>
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 160x600, created 7/7/09 */
google_ad_slot = "8881178843";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<% end %>
</div>
<div class="clearBoth" />
</div>
<div class="footer">
<%= link_to 'sitemap', '/sitemap'%> |
<%= link_to 'privacy', '/privacy-policy' %> |
<%= link_to 'contact us', '/contact-us' %> |
<%= link_to 'contribute', '/contribute' %> |
<%= link_to 'how it works', '/how-it-works' %>
</div>
<% if show_ads %>
<div class="bottomAd">
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 728x90, created 7/30/09 */
google_ad_slot = "3484810864";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<% end %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9105909-1");
pageTracker._trackPageview();
} catch(err) {}</script>
<div class="lastUpdated">
Last Updated: <%=
FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" )[0].created_at.pretty if FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" ).length > 0
%>
</div>
</body>
</html>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index d4365a7..e023bf7 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,86 +1,87 @@
ActionController::Routing::Routes.draw do |map|
map.resources :models
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.resource :user_preference
map.resource :session, :collection => { :send_forgot_password => :post }
map.resources :users, :collection => { :login_submit => :post }
map.connect 'login', :controller => 'users', :action => 'login'
map.connect 'logout', :controller => 'users', :action => 'logout'
+ map.connect 'feed/admin', :controller => 'feed', :action => 'admin'
map.resources :feed
map.resources :feed_comment
map.connect 'feed_item/media', :controller => 'feed_item', :action => 'media'
map.resources :feed_item
map.resources :feed_item_category
map.resources :category
map.resources :category_comment
map.resources :homepage
map.resources :feed_item_comment
map.resources :category_organizer
map.resources :comments
map.resources :blog_posts
map.resources :email_subscriptions
map.resources :email_a_friend_messages
map.connect 'blog', :controller => 'blog_posts'
map.connect 'blog.xml', :controller => 'blog_posts', :format => 'xml'
map.connect 'privacy-policy', :controller => 'static_pages', :action => 'privacy_policy'
map.connect 'sitemap', :controller => 'static_pages', :action => 'sitemap'
map.connect 'contact-us', :controller => 'static_pages', :action => 'contact_us'
map.connect 'contribute', :controller => 'static_pages', :action => 'contribute'
map.connect 'how-it-works', :controller => 'static_pages', :action => 'how_it_works'
map.connect 'search', :controller => 'static_pages', :action => 'search'
map.connect 'open-source', :controller => 'static_pages', :action => 'open_source'
map.connect 'sitemap.xml', :controller => 'sitemap', :action => 'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.homepage '', :controller => 'homepage'
map.connect 'update', :controller => 'feed', :action => 'update'
map.root :controller => "homepage"
map.connect '*', :controller => 'application', :action => 'rescue_404'
end
diff --git a/db/migrate/20100630033030_add_disabled_reason_to_feed.rb b/db/migrate/20100630033030_add_disabled_reason_to_feed.rb
new file mode 100644
index 0000000..2b7e833
--- /dev/null
+++ b/db/migrate/20100630033030_add_disabled_reason_to_feed.rb
@@ -0,0 +1,9 @@
+class AddDisabledReasonToFeed < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :disabled_reason, :string
+ end
+
+ def self.down
+ drop_column :feeds, :disabled_reason, :string
+ end
+end
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 62bc5a0..f57ca08 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,227 +1,232 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
-.rightHandList { width: 175px; }
+.rightHandList { width: 175px; padding-top: 15px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #CCF; color: black;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; font-size: 13.5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
.feedItemShow .relatedArticles { padding-top: 35px; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 500px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 492px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
.addComment TEXTAREA { width: 360px; height: 150px;}
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
.emailAFriend .submit { text-align: right; }
.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
/* Login Screen */
.login { width: 500px; margin: auto; padding: 5px; }
.login .forgotPassword { padding-top: 30px; }
/* Forgot Password Screen */
.forgotPassword FORM { padding-top: 10px; padding-bottom: 15px; }
+
+/* Admin Feed Listing Pages */
+.adminFeedsPage { font-size: 12px; padding-top: 15px; }
+.adminFeedsPage TABLE TD,
+.adminFeedsPage Table TH { border: 1px solid black; }
|
jenglert/The-Peoples--Feed
|
1a26821a6f214ece4e191605f430783da7a91af6
|
Removing unused require
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 4453752..95cb706 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,133 +1,133 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
-require 'ruby-prof'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
belongs_to :site
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
return if (self.disabled)
startTime = Time.now
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
# Ensure that the operation took less than 15 seconds. If it took more, set the feed to disabled.
if(Time.now - startTime > 15)
update_attribute(:disabled, true)
end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
+
# Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
if (result.entries.size() > 45)
self.update_attribute(:disabled, true)
return
end
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
fb585cb9f765b81484dceb00a8d33d2d1524b4cd
|
Adding disabled flag to feeds.
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 53a7ab9..4453752 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,112 +1,133 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
+require 'ruby-prof'
+
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
+ belongs_to :site
+
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
+ return if (self.disabled)
+
+ startTime = Time.now
+
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
+
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
+
+ # Ensure that the operation took less than 15 seconds. If it took more, set the feed to disabled.
+ if(Time.now - startTime > 15)
+ update_attribute(:disabled, true)
+ end
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
+ startTime = Time.now
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
+ # Ensure that the feed doesn't have too many entries. If it does, ignore the feed.
+ if (result.entries.size() > 45)
+ self.update_attribute(:disabled, true)
+ return
+ end
+
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
- self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
+ self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index 7566ab2..458ca57 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,132 +1,128 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
- temp = []
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
- unless temp.include? category_name
- temp << category_name
- category = Category.find_by_name(category_name)
- unless category
- # Try to find a merge category before creating a new category.x
- category_merge = CategoryMerge.find_by_merge_src(category_name)
- if category_merge
- category = Category.find_by_id(category_merge.merge_target)
- end
- end
- if !category
- category = Category.new :name => category_name
- end
- self.categories << category
+ category = Category.find_by_name(category_name)
+ unless category
+ # Try to find a merge category before creating a new category.
+ category_merge = CategoryMerge.find_by_merge_src(category_name)
+ if category_merge
+ category = Category.find_by_id(category_merge.merge_target)
+ end
end
+ if !category
+ category = Category.new(:name => category_name).save!
+ end
+ self.categories << category unless self.categories.include? category
end
end
rescue => ex
LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 3 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
diff --git a/db/migrate/20100627183540_add_disabled_to_feed.rb b/db/migrate/20100627183540_add_disabled_to_feed.rb
new file mode 100644
index 0000000..450d18e
--- /dev/null
+++ b/db/migrate/20100627183540_add_disabled_to_feed.rb
@@ -0,0 +1,9 @@
+class AddDisabledToFeed < ActiveRecord::Migration
+ def self.up
+ add_column :feeds, :disabled, :boolean
+ end
+
+ def self.down
+ drop_column :feeds, :disabled, :boolean
+ end
+end
|
jenglert/The-Peoples--Feed
|
90b5b620fd62b397e37dd94654868983e73fdab9
|
Adding a job for updating the feed
|
diff --git a/config/schedule.rb b/config/schedule.rb
index 667fe60..7cbaf53 100644
--- a/config/schedule.rb
+++ b/config/schedule.rb
@@ -1,22 +1,27 @@
# Learn more: http://github.com/javan/whenever
# Refresh the feed parse stats
every 1.day, :at => "11:30pm" do
runner "FeedParseStat.refresh"
end
#############################################
# Production CRON jobs
#############################################
# Refresh the production caches
every 4.hours do
command "/home/jamesro/thepeoplesfeed/script/clearCaches.sh > /home/jamesro/cron.log"
end
# Fetch new issue emails
every 10.minutes do
command "/home/jamesro/thepeoplesfeed/script/getIssues.sh > /home/jamesro/cron.log"
+end
+
+# Fetch new feeds
+every 30.minutes do
+ runner "Feed.find(:all).each {|feed| feed.update_feed}"
end
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
83e162eceeb1e41f8b71272eccb843097230f7fc
|
Updating the people's feed logo so that the word people is larger!
|
diff --git a/public/images/header_logo.png b/public/images/header_logo.png
index 0387a3c..ccaeb6a 100644
Binary files a/public/images/header_logo.png and b/public/images/header_logo.png differ
diff --git a/public/images/header_logo.psd b/public/images/header_logo.psd
index 89c6617..e87ef6f 100644
Binary files a/public/images/header_logo.psd and b/public/images/header_logo.psd differ
|
jenglert/The-Peoples--Feed
|
a7bea4a81a8d86d1cc9af61bf47da352e0eea09b
|
Fixing ads
|
diff --git a/public/personal/halloween-09/index.html b/public/personal/halloween-09/index.html
index e57849f..4f43d4d 100644
--- a/public/personal/halloween-09/index.html
+++ b/public/personal/halloween-09/index.html
@@ -1,82 +1,118 @@
<html>
<head>
<title>Lee's Halloween Eve Adventure</title>
<style>
* { color: white; }
IMG { padding-bottom: 30px; }
- TD { text-align: top; }
+ TD { vertical-align: top; }
</style>
</head>
<body style="background-color: black;">
<table><tr><td>
<h1>Lee's Halloween Eve Adventure</h1>
<h2>Step 1: Preparty Posing</h2>
<img src="lee-posing.jpg" />
<h2>Step 2: A Little Rockband</h2>
<img src="lee-guitar.jpg" />
<h2>Step 3: Strutting to the Party</h2>
<img src="lee-strutting.jpg" />
<h2>Step 4: Enjoying the Party!!</h2>
<img src="lee-posing.jpg" />
<h2>Step 5: Potentially Enjoyed the Party too Much</h2>
<img src="lee-bed.jpg" />
</td>
<td>
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* graphite ad */
google_ad_slot = "1711140014";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* graphite ad */
google_ad_slot = "1711140014";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* graphite ad */
google_ad_slot = "1711140014";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* graphite ad */
google_ad_slot = "1711140014";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
</td></tr></table>
</body>
</html>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
0bf5f89bbd6b9829c17b7f33c9f5d804783d078e
|
Adding personal page w/ lee as faerie
|
diff --git a/public/personal/halloween-09/index.html b/public/personal/halloween-09/index.html
new file mode 100644
index 0000000..e57849f
--- /dev/null
+++ b/public/personal/halloween-09/index.html
@@ -0,0 +1,82 @@
+<html>
+<head>
+ <title>Lee's Halloween Eve Adventure</title>
+ <style>
+ * { color: white; }
+ IMG { padding-bottom: 30px; }
+ TD { text-align: top; }
+ </style>
+</head>
+<body style="background-color: black;">
+ <table><tr><td>
+ <h1>Lee's Halloween Eve Adventure</h1>
+
+ <h2>Step 1: Preparty Posing</h2>
+ <img src="lee-posing.jpg" />
+
+ <h2>Step 2: A Little Rockband</h2>
+ <img src="lee-guitar.jpg" />
+
+ <h2>Step 3: Strutting to the Party</h2>
+ <img src="lee-strutting.jpg" />
+
+ <h2>Step 4: Enjoying the Party!!</h2>
+ <img src="lee-posing.jpg" />
+
+ <h2>Step 5: Potentially Enjoyed the Party too Much</h2>
+ <img src="lee-bed.jpg" />
+ </td>
+
+ <td>
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+ <script type="text/javascript"><!--
+ google_ad_client = "pub-7279077462237001";
+ /* graphite ad */
+ google_ad_slot = "1711140014";
+ google_ad_width = 160;
+ google_ad_height = 600;
+ //-->
+ </script>
+ <script type="text/javascript"
+ src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
+ </script>
+ <br />
+
+ </td></tr></table>
+</body>
+</html>
\ No newline at end of file
diff --git a/public/personal/halloween-09/lee-bar.jpg b/public/personal/halloween-09/lee-bar.jpg
new file mode 100644
index 0000000..f615f25
Binary files /dev/null and b/public/personal/halloween-09/lee-bar.jpg differ
diff --git a/public/personal/halloween-09/lee-bed.jpg b/public/personal/halloween-09/lee-bed.jpg
new file mode 100644
index 0000000..ff400bb
Binary files /dev/null and b/public/personal/halloween-09/lee-bed.jpg differ
diff --git a/public/personal/halloween-09/lee-guitar.jpg b/public/personal/halloween-09/lee-guitar.jpg
new file mode 100644
index 0000000..597f83d
Binary files /dev/null and b/public/personal/halloween-09/lee-guitar.jpg differ
diff --git a/public/personal/halloween-09/lee-posing.jpg b/public/personal/halloween-09/lee-posing.jpg
new file mode 100644
index 0000000..2dfbd39
Binary files /dev/null and b/public/personal/halloween-09/lee-posing.jpg differ
diff --git a/public/personal/halloween-09/lee-strutting.jpg b/public/personal/halloween-09/lee-strutting.jpg
new file mode 100644
index 0000000..3a0755a
Binary files /dev/null and b/public/personal/halloween-09/lee-strutting.jpg differ
|
jenglert/The-Peoples--Feed
|
d205e7e1e64d44f4658a49263e35950bd3673851
|
Increasing the delay between updates.
|
diff --git a/lib/daemons/update.rb b/lib/daemons/update.rb
index 53c9869..c969b3e 100755
--- a/lib/daemons/update.rb
+++ b/lib/daemons/update.rb
@@ -1,22 +1,22 @@
#!/usr/bin/env ruby
# You might want to change this
ENV["RAILS_ENV"] ||= "production"
require File.dirname(__FILE__) + "/../../config/environment"
$running = true
Signal.trap("TERM") do
$running = false
end
while($running) do
# Replace this with your code
ActiveRecord::Base.logger.info "This daemon is still running at #{Time.now}.\n"
Feed.find(:all).each {|feed| feed.update_feed}
# Updating all the feeds usually takes pretty long so it's not necessary to sleep for that long.
- sleep 150
+ sleep 500
end
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
b32fb6970437aec3a58b5abad41292cd5b27bcec
|
Reducing the value of an image by one point.
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index e723ab5..7566ab2 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,132 +1,132 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
temp = []
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
unless temp.include? category_name
temp << category_name
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.x
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new :name => category_name
end
self.categories << category
end
end
end
rescue => ex
LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
- image_url ? 4 : 0
+ image_url ? 3 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
jenglert/The-Peoples--Feed
|
a51e1783a887af5dc82c9c35200ce247996b281f
|
Fixing typo
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index e4d6b71..53a7ab9 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,112 +1,112 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
- before_remove :destroy_feed_parse_logs
+ before_destroy :destroy_feed_parse_logs
# Removes all the feed parse logs before destroying the
def destroy_feed_parse_logs
FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
end
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
|
jenglert/The-Peoples--Feed
|
1f52cf28c8d63b8e98f3b82fef408002293a3260
|
reducing the frequency of the update job allow feeds to remove feed parse logs
|
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 218f3e0..e4d6b71 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,105 +1,112 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
has_many :feed_items, :dependent => :destroy
has_many :user_preferences
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
+ before_remove :destroy_feed_parse_logs
+
+ # Removes all the feed parse logs before destroying the
+ def destroy_feed_parse_logs
+ FeedParseLog.find_all_by_feed_id(self.id).each { |fpl| fpl.destroy }
+ end
+
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
diff --git a/lib/daemons/update.rb b/lib/daemons/update.rb
index a1d70d2..53c9869 100755
--- a/lib/daemons/update.rb
+++ b/lib/daemons/update.rb
@@ -1,22 +1,22 @@
#!/usr/bin/env ruby
# You might want to change this
ENV["RAILS_ENV"] ||= "production"
require File.dirname(__FILE__) + "/../../config/environment"
$running = true
Signal.trap("TERM") do
$running = false
end
while($running) do
# Replace this with your code
ActiveRecord::Base.logger.info "This daemon is still running at #{Time.now}.\n"
Feed.find(:all).each {|feed| feed.update_feed}
# Updating all the feeds usually takes pretty long so it's not necessary to sleep for that long.
- sleep 5
+ sleep 150
end
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
1acba8ff77de1b0841bfd4403d0afe36aab85f7e
|
Adding the ability to delete feeds.
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index 5bc3f91..e723ab5 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,132 +1,132 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
- has_many :feed_item_categories
+ has_many :feed_item_categories, :dependent => :destroy
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
:limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
temp = []
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
unless temp.include? category_name
temp << category_name
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.x
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new :name => category_name
end
self.categories << category
end
end
end
rescue => ex
LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 4 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
|
jenglert/The-Peoples--Feed
|
99d239ec85a35a2da1e03f646b5458cf7e392022
|
Adding the ability to delete feeds.
|
diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb
index 1281157..7b5c0ba 100644
--- a/app/controllers/comments_controller.rb
+++ b/app/controllers/comments_controller.rb
@@ -1,19 +1,21 @@
class CommentsController < ApplicationController
+ before_filter :admin_authorized?, :only => [:remove]
+
def index
@comments = Comment.paginate(:all, :per_page => 40, :page => params[:page])
end
# Removes a comment. This is specificially not the 'delete' method that is provided with rails. I don't want to have to deal
# with the delete syntax that comes with rails.
def remove
@id = params[:id]
Comment.find_by_id(@id).destroy
respond_to do |format|
format.html { redirect_to :controller => 'comments' }
format.js
end
end
end
\ No newline at end of file
diff --git a/app/controllers/feed_controller.rb b/app/controllers/feed_controller.rb
index 4000e03..2f72835 100644
--- a/app/controllers/feed_controller.rb
+++ b/app/controllers/feed_controller.rb
@@ -1,36 +1,50 @@
class FeedController < ApplicationController
+ before_filter :admin_authorized?, :only => [:remove_feed]
+
def index
@feeds = Feed.find(:all)
end
def new
@feed = Feed.new
end
def create
@feed = Feed.new(params[:feed])
puts @feed.url
@feed.update_feed
if @feed.save
flash[:notice] = "Feed was successfully created."
redirect_to(@feed)
else
render :action => "new"
end
end
def show
@feed = Feed.find(params[:id])
@feed_items = FeedItem.paginate(:page => params[:page], :per_page => 15,
:conditions => ['feed_id = ?', params[:id]], :order => 'created_at desc')
end
def update
@feeds = Feed.find(:all)
@feeds.each { |feed| feed.update_feed }
end
+ def remove_feed
+ feed = Feed.find(params[:id])
+
+ if feed.destroy
+ flash[:notice] = "The feed has been sucessfully deleted."
+ else
+ flash[:error] = "Unable to delete feed"
+ end
+
+ redirect_to :controller => 'feed', :action => 'index'
+ end
+
end
diff --git a/app/models/feed.rb b/app/models/feed.rb
index 8578221..218f3e0 100644
--- a/app/models/feed.rb
+++ b/app/models/feed.rb
@@ -1,105 +1,105 @@
require 'rss/2.0'
require 'open-uri'
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class Feed < ActiveRecord::Base
- has_many :feed_items
+ has_many :feed_items, :dependent => :destroy
has_many :user_preferences
acts_as_commentable
validates_presence_of :feed_url
validates_uniqueness_of :feed_url
named_scope :top_feeds, :order => 'rating desc', :limit => 5
def validate
if feed_items.length == 0
errors.add_to_base 'Sorry, we were unable to parse the feed you provided. Please double check the URL you have provided.'
end
end
# Determines the rating for
def rating
return 0 if new_record?
return 0 if self.feed_items.count.zero?
calculated_rating = 0
# This query can return nil if there are no feed items that match the conditions.
result = FeedItem.find(
:all,
:select => 'sum(rating) as feed_rating',
:conditions => ["created_at > ? and feed_id = ?", 3.days.ago, self.id])[0]
calculated_rating = result.feed_rating.to_d unless result.nil? or result.feed_rating.nil?
self.update_attributes :rating => calculated_rating
calculated_rating
end
# Updates the feed
def update_feed
result = Feedzirra::Feed.fetch_and_parse(feed_url, :compress => true, :timeout => 5)
save_from_result(result)
# Update the ratings for all the feed items created with 3 days.
FeedItem.recent.for_feed(self.id).each { |feed_item| feed_item.update_rating }
# Force the feed's rating to be updated
self.rating
end
def feed_items_sorted
feed_items.find(:all, :order => 'pub_date DESC')
end
private
def add_entries(entries, feed_parse_log)
#begin
entries.each do |item|
new_feed_item = FeedItem.initialize_from_entry(item)
unless FeedItem.exists?(:guid => new_feed_item.guid)
new_feed_item.save!
add_feed_item(new_feed_item, feed_parse_log)
end
end #each
rescue => ex
logger.error "Unable to parse feed #{self.id}. #{ex.class}: #{ex.message} : #{ex.backtrace}"
end
def add_feed_item(new_feed_item, feed_parse_log)
self.feed_items << new_feed_item
feed_parse_log.increase_items
end
# Save the result of the Feedzirra request into the database.
def save_from_result(result)
feed_parse_log = FeedParseLog.create!(
:feed_id => self.id,
:feed_url => self.feed_url,
:parse_start => Time.now,
:feed_items_added => 0
)
# We need to check whether the result will respond to certain methods. Depending
# on the type of feed that was parsed, all of these parameters may or may not
# be present.
return false unless result && result.respond_to?('title') && result.title
self.title = result.title.strip
# The SAX machine may or may not have added description
self.description = result.respond_to?('description') && result.description ? result.description.strip.remove_html : ""
self.url = result.url.strip if result.url
# Bug: Fix image url parsing
self.image_url = result.image.url.strip if result.respond_to?('image') && result.image && result.image.url
add_entries(result.entries, feed_parse_log)
feed_parse_log.parse_finish = Time.new
feed_parse_log.save
return self.save
end
end
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index 878debb..5bc3f91 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,132 +1,132 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
# Finds feed items related to the current feed item we are looking at.
def related_feed_items
FeedItem.find(:all, :include => 'feed_item_categories',
:conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
- :limit => 10, :order => "created_at desc")
+ :limit => 10, :order => "created_at desc") - [self]
end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
temp = []
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
unless temp.include? category_name
temp << category_name
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.x
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new :name => category_name
end
self.categories << category
end
end
end
rescue => ex
LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 4 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
diff --git a/app/views/feed/show.html.erb b/app/views/feed/show.html.erb
index 04c59bb..9bce24d 100644
--- a/app/views/feed/show.html.erb
+++ b/app/views/feed/show.html.erb
@@ -1,38 +1,44 @@
<% meta_description "RSS feeds provided by '#{@feed.title}'"%>
<div class="feedShow">
<table class="feedInfo">
<tr>
<td colspan="2" class="title">
<%= image_tag @feed.image_url if @feed.image_url %>
<%= page_title @feed.title + " RSS Feed" %>
</td>
</tr>
<tr>
<td class="leftColumn"><b>Last Updated:</b> <%= @feed.updated_at.pretty%></td>
<td><h2><%= @feed.description %></h2></td>
</tr>
<tr>
<td class="leftColumn"><%= @feed.feed_items.count.to_s + ' ' + 'Articles'.pluralize %></td>
<td>
<a class="tooltip" title="The People's Feed uses a rating system to help determine which feeds are the most popular in the overal scheme of things. Rather than using a closed, proprietary system like Google, we use an open ratings system. This allows the community at large to have input on the most effective ratings.">
<b>Rating: </b> <%= sprintf('%.1f', @feed.rating) unless @feed.rating.nil? %>
<span class="whatIsThis">(what is this)</span>
</td>
</tr>
</table>
+
+ <div class="adminControls">
+ <% if admin_logged_in? %>
+ <%= link_to 'Delete', :controller => 'feed', :action => 'remove_feed', :id => @feed.id %>
+ <% end %>
+ </div>
<%= render :partial => 'shared/participate', :locals => { :post_location => '/feed_comment', :item => @feed }%>
<h2>Articles From This Feed</h2>
<ul>
<% @feed_items.each { |item| %>
<li>
<%= link_to h(item.title.fix_html), item %>
</li>
<% } %>
</ul>
<div class="pagination">
<%= will_paginate @feed_items %>
</div>
</div>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
0b19b81474e3c2e25d27e1f1c1bbfe6d60241739
|
Fixing the last updated timestamp so that it will work no feed items.
|
diff --git a/app/views/layouts/standard.html.erb b/app/views/layouts/standard.html.erb
index a4bb1bb..9ddb9e5 100644
--- a/app/views/layouts/standard.html.erb
+++ b/app/views/layouts/standard.html.erb
@@ -1,121 +1,123 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<%= stylesheet_link_tag 'main' %>
<meta name="verify-v1" content="qnzsIVoN1EFhSa6I3djN8bQ0o9x+L1NZp/eJ6C6XCao=" ></meta>
<title>
<%= "#@page_title - " if !@page_title.nil? %> The People's Feed
</title>
<% if !@meta_description.nil? %>
<meta name="description" content="<%= @meta_description %>" />
<% end %>
<%= javascript_include_tag "jquery-1.3.2.min.js" %>
<%= javascript_include_tag "jquery.bgiframe.js" %>
<%= javascript_include_tag "jquery.delegate.js" %>
<%= javascript_include_tag "jquery.tooltip.min.js" %>
<%= javascript_include_tag "jquery.dimensions.js"%>
<%= javascript_include_tag "jquery.pngFix.js"%>
<%= javascript_include_tag "main.js" %>
<%= yield(:head)%>
</head>
<body>
<div class="header">
<% link_to '/' do %>
<img src="/images/header_logo.png" alt="The People's Feed" class="logo" />
<% end %>
<div class="motto">The latest news ranked according to its popularity by YOU</div>
<%= render :partial => 'shared/main_menu_insert' %>
</div>
<div class="body">
<div class="centerColumn">
<div class="flashes">
<% if flash.has_key?(:error) %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
<% if flash.has_key?(:notice) %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
</div>
<%= yield %>
</div>
<div class="rightHandList">
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_feeds') do %>
<h3>Top Feeds</h3>
<%= render :partial => 'shared/feed_narrow', :locals => { :topFeeds => @topFeeds } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_categories') do %>
<h3>Top Categories</h3>
<%= render :partial => 'shared/category_narrow', :locals => { :topCategories => @topCategories } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_media') do %>
<h3>Top Media</h3>
<%= render :partial => 'shared/media_narrow', :locals => { :topMedia => @topMedia } %>
<% end %>
<% if show_ads %>
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 160x600, created 7/7/09 */
google_ad_slot = "8881178843";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<% end %>
</div>
<div class="clearBoth" />
</div>
<div class="footer">
<%= link_to 'sitemap', '/sitemap'%> |
<%= link_to 'privacy', '/privacy-policy' %> |
<%= link_to 'contact us', '/contact-us' %> |
<%= link_to 'contribute', '/contribute' %> |
<%= link_to 'how it works', '/how-it-works' %>
</div>
<% if show_ads %>
<div class="bottomAd">
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 728x90, created 7/30/09 */
google_ad_slot = "3484810864";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<% end %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9105909-1");
pageTracker._trackPageview();
} catch(err) {}</script>
<div class="lastUpdated">
- Last Updated: <%= FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" )[0].created_at.pretty %>
+ Last Updated: <%=
+ FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" )[0].created_at.pretty if FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" ).length > 0
+ %>
</div>
</body>
</html>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
59d364ef4d7b8ac4dc895413837db9322510c80b
|
simplifying the ascii code.
|
diff --git a/app/models/user.rb b/app/models/user.rb
index e8d8949..fd4f680 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,87 +1,87 @@
require 'digest/sha1'
class User < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
validates_presence_of :login, :email
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_length_of :password, :within => 4..40, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :login, :within => 3..40
validates_length_of :email, :within => 3..100
validates_uniqueness_of :login, :email, :case_sensitive => false
before_save :encrypt_password
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :password, :password_confirmation
def self.random_password
- Array.new(8) { (rand(122-97) + 97).chr }.join
+ Array.new(8) { (rand(?z-?a) + ?a).chr }.join
end
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = find_by_login(login) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
remember_me_for 2.weeks
end
def remember_me_for(time)
remember_me_until time.from_now.utc
end
def remember_me_until(time)
self.remember_token_expires_at = time
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
end
|
jenglert/The-Peoples--Feed
|
c7c41c97b3a6b89587117e9647eff8825f7dc560
|
Fixing forgot password issue
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 7ff37c6..1341889 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,65 +1,63 @@
-require 'active_support/secure_random'
-
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
# Always drop the logged in cookie.
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => Time.new + 360.days }
default = '/'
puts "referrer:" + request.referrer
# Attempt to determine if we came from the login page, if so, do nothing. If not, go to the page we used to be at
default = request.referrer if !request.referrer.include?('sessions')
redirect_back_or_default(default)
flash[:notice] = "Logged in successfully"
else
flash[:error] = "Username/Password not recognized. Please try again."
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
def forgot_password
end
def send_forgot_password
users = User.find_all_by_email(params[:email])
if users.length <= 0
# This is potential security whole since users could find all the emails in our database.
# At this point, the added user flexibility is better than the added security.
flash[:error] = "Unable to find a user with that email."
render :action => 'forgot_password'
return
end
new_password = User.random_password
users[0].password = new_password
users[0].password_confirmation = new_password
users[0].save!
flash[:notice] = "We are emailing you a replacement password."
ConsumerMailer.deliver_forgot_password(users[0].email, new_password)
redirect_back_or_default('/')
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 6afeb95..e8d8949 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,87 +1,87 @@
require 'digest/sha1'
class User < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
validates_presence_of :login, :email
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_length_of :password, :within => 4..40, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :login, :within => 3..40
validates_length_of :email, :within => 3..100
validates_uniqueness_of :login, :email, :case_sensitive => false
before_save :encrypt_password
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :password, :password_confirmation
def self.random_password
- SecureRandom.base64(5)
+ Array.new(8) { (rand(122-97) + 97).chr }.join
end
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = find_by_login(login) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
remember_me_for 2.weeks
end
def remember_me_for(time)
remember_me_until time.from_now.utc
end
def remember_me_until(time)
self.remember_token_expires_at = time
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
end
|
jenglert/The-Peoples--Feed
|
26e9d36703600f53753cc8ad7d3a2841d90e7c84
|
Fixing forgotpassword
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 943d27e..7ff37c6 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,65 +1,65 @@
require 'active_support/secure_random'
-
+
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
# Always drop the logged in cookie.
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => Time.new + 360.days }
default = '/'
puts "referrer:" + request.referrer
# Attempt to determine if we came from the login page, if so, do nothing. If not, go to the page we used to be at
default = request.referrer if !request.referrer.include?('sessions')
redirect_back_or_default(default)
flash[:notice] = "Logged in successfully"
else
flash[:error] = "Username/Password not recognized. Please try again."
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
def forgot_password
end
def send_forgot_password
users = User.find_all_by_email(params[:email])
if users.length <= 0
# This is potential security whole since users could find all the emails in our database.
# At this point, the added user flexibility is better than the added security.
flash[:error] = "Unable to find a user with that email."
render :action => 'forgot_password'
return
end
- new_password = SecureRandom.base64(5)
+ new_password = User.random_password
users[0].password = new_password
users[0].password_confirmation = new_password
users[0].save!
flash[:notice] = "We are emailing you a replacement password."
ConsumerMailer.deliver_forgot_password(users[0].email, new_password)
redirect_back_or_default('/')
end
end
diff --git a/app/models/user.rb b/app/models/user.rb
index 1dc9ada..6afeb95 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -1,83 +1,87 @@
require 'digest/sha1'
class User < ActiveRecord::Base
# Virtual attribute for the unencrypted password
attr_accessor :password
validates_presence_of :login, :email
validates_presence_of :password, :if => :password_required?
validates_presence_of :password_confirmation, :if => :password_required?
validates_length_of :password, :within => 4..40, :if => :password_required?
validates_confirmation_of :password, :if => :password_required?
validates_length_of :login, :within => 3..40
validates_length_of :email, :within => 3..100
validates_uniqueness_of :login, :email, :case_sensitive => false
before_save :encrypt_password
# prevents a user from submitting a crafted form that bypasses activation
# anything else you want your user to change should be added here.
attr_accessible :login, :email, :password, :password_confirmation
+
+ def self.random_password
+ SecureRandom.base64(5)
+ end
# Authenticates a user by their login name and unencrypted password. Returns the user or nil.
def self.authenticate(login, password)
u = find_by_login(login) # need to get the salt
u && u.authenticated?(password) ? u : nil
end
# Encrypts some data with the salt.
def self.encrypt(password, salt)
Digest::SHA1.hexdigest("--#{salt}--#{password}--")
end
# Encrypts the password with the user salt
def encrypt(password)
self.class.encrypt(password, salt)
end
def authenticated?(password)
crypted_password == encrypt(password)
end
def remember_token?
remember_token_expires_at && Time.now.utc < remember_token_expires_at
end
# These create and unset the fields required for remembering users between browser closes
def remember_me
remember_me_for 2.weeks
end
def remember_me_for(time)
remember_me_until time.from_now.utc
end
def remember_me_until(time)
self.remember_token_expires_at = time
self.remember_token = encrypt("#{email}--#{remember_token_expires_at}")
save(false)
end
def forget_me
self.remember_token_expires_at = nil
self.remember_token = nil
save(false)
end
# Returns true if the user has just been activated.
def recently_activated?
@activated
end
protected
# before filter
def encrypt_password
return if password.blank?
self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--") if new_record?
self.crypted_password = encrypt(password)
end
def password_required?
crypted_password.blank? || !password.blank?
end
end
|
jenglert/The-Peoples--Feed
|
faf3bf1b8c33742fe90f7264943fcee05ae6d5da
|
Fixing the forgot password screen. Making the participate links wider.
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 5b0aa0f..943d27e 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,63 +1,65 @@
+require 'active_support/secure_random'
+
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
# Always drop the logged in cookie.
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => Time.new + 360.days }
default = '/'
puts "referrer:" + request.referrer
# Attempt to determine if we came from the login page, if so, do nothing. If not, go to the page we used to be at
default = request.referrer if !request.referrer.include?('sessions')
redirect_back_or_default(default)
flash[:notice] = "Logged in successfully"
else
flash[:error] = "Username/Password not recognized. Please try again."
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
def forgot_password
end
def send_forgot_password
users = User.find_all_by_email(params[:email])
if users.length <= 0
# This is potential security whole since users could find all the emails in our database.
# At this point, the added user flexibility is better than the added security.
flash[:error] = "Unable to find a user with that email."
render :action => 'forgot_password'
return
end
new_password = SecureRandom.base64(5)
users[0].password = new_password
users[0].password_confirmation = new_password
users[0].save!
flash[:notice] = "We are emailing you a replacement password."
ConsumerMailer.deliver_forgot_password(users[0].email, new_password)
redirect_back_or_default('/')
end
end
diff --git a/app/views/category/show.html.erb b/app/views/category/show.html.erb
index 02b992c..eb5d238 100644
--- a/app/views/category/show.html.erb
+++ b/app/views/category/show.html.erb
@@ -1,21 +1,20 @@
<% meta_description "RSS Feed articles related to '#{@category.name.capitalize_each_word}'"%>
<div class="categoryShow">
<div class="sectionHeading">
<%= page_title "Articles related to '#{@category.name.capitalize_each_word}'"%>
</div>
<div class="moreInformation">
</div>
<div class="feedItems">
<% @feed_items.each{ |feedItem| %>
<%= render :partial => 'shared/feed_item_wide', :locals => {:feedItem => feedItem} %>
<% } %>
</div>
<div class="pagination">
<%= will_paginate @feed_items %>
</div>
- <%= render :partial => 'shared/show_comments', :locals => { :comments => @category.comments } %>
- <%= render :partial => 'shared/create_comment', :locals => { :post_location => '/category_comment', :commented_item => @category }%>
+ <%= render :partial => 'shared/participate', :locals => { :post_location => '/category_comment', :item => @category }%>
</div>
\ No newline at end of file
diff --git a/app/views/consumer_mailer/forgot_password.html.erb b/app/views/consumer_mailer/forgot_password.html.erb
index 4af3e8a..90100fe 100644
--- a/app/views/consumer_mailer/forgot_password.html.erb
+++ b/app/views/consumer_mailer/forgot_password.html.erb
@@ -1,5 +1,4 @@
-<%= page_title "Forgot Password" %>
Thank you for visiting The People's Feed. Your password has been reset.
Your new password is: <%= @password %>
diff --git a/app/views/feed/show.html.erb b/app/views/feed/show.html.erb
index e197002..04c59bb 100644
--- a/app/views/feed/show.html.erb
+++ b/app/views/feed/show.html.erb
@@ -1,39 +1,38 @@
<% meta_description "RSS feeds provided by '#{@feed.title}'"%>
<div class="feedShow">
<table class="feedInfo">
<tr>
<td colspan="2" class="title">
<%= image_tag @feed.image_url if @feed.image_url %>
<%= page_title @feed.title + " RSS Feed" %>
</td>
</tr>
<tr>
<td class="leftColumn"><b>Last Updated:</b> <%= @feed.updated_at.pretty%></td>
<td><h2><%= @feed.description %></h2></td>
</tr>
<tr>
<td class="leftColumn"><%= @feed.feed_items.count.to_s + ' ' + 'Articles'.pluralize %></td>
<td>
<a class="tooltip" title="The People's Feed uses a rating system to help determine which feeds are the most popular in the overal scheme of things. Rather than using a closed, proprietary system like Google, we use an open ratings system. This allows the community at large to have input on the most effective ratings.">
<b>Rating: </b> <%= sprintf('%.1f', @feed.rating) unless @feed.rating.nil? %>
<span class="whatIsThis">(what is this)</span>
</td>
</tr>
</table>
- <%= render :partial => 'shared/show_comments', :locals => { :comments => @feed.comments } %>
- <%= render :partial => 'shared/create_comment', :locals => { :post_location => '/feed_comment', :commented_item => @feed }%>
+ <%= render :partial => 'shared/participate', :locals => { :post_location => '/feed_comment', :item => @feed }%>
<h2>Articles From This Feed</h2>
<ul>
<% @feed_items.each { |item| %>
<li>
<%= link_to h(item.title.fix_html), item %>
</li>
<% } %>
</ul>
<div class="pagination">
<%= will_paginate @feed_items %>
</div>
</div>
\ No newline at end of file
diff --git a/app/views/sessions/forgot_password.html.erb b/app/views/sessions/forgot_password.html.erb
index 3daae20..878b9b1 100644
--- a/app/views/sessions/forgot_password.html.erb
+++ b/app/views/sessions/forgot_password.html.erb
@@ -1,11 +1,11 @@
<div class="forgotPassword whiteBackground">
- <%= page_title 'Forgot Password'%>
+ <%= page_title 'Forgot Password' %>
Forgot your password? Just enter your email below and we will email you a new password.
<% form_tag '/session/send_forgot_password' do -%>
<%= text_field_tag :email %>
<%= submit_tag "Email me a new password"%>
<% end -%>
</div>
\ No newline at end of file
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
index 95809ce..d752808 100644
--- a/app/views/shared/_participate.html.erb
+++ b/app/views/shared/_participate.html.erb
@@ -1,94 +1,94 @@
<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
<div class="addComment">
<h3>
<a href="#" onclick="tpf.hideShowCommentSection(); return false;">
Add a Comment <img src="/images/expand.png" width="14" height="14">
</a>
|
<a href="#" onclick="tpf.hideShowEmailAFriendSection(); return false;">
Email A Friend <img src="/images/expand.png" width="14" height="14">
</a>
</h3>
<div class="body">
<% if logged_in? %>
<div style="display: none;" id="commentSection">
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', item.id%>
<%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
- <%= f.text_area :comment, :size => "30x7" %>
+ <%= f.text_area :comment %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
</div>
<div style="display: none;" id="emailAFriendSection">
- <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}#{":" + request.port if request.port != 80}#{request.path}") do |f| %>
+ <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}#{":" + request.port.to_s if request.port != 80}#{request.path}") do |f| %>
<%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
- <td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
+ <td><%= f.text_area :message %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
</div>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
diff --git a/lib/email_validation_helper.rb b/lib/email_validation_helper.rb
index 4f114ec..46c8f1b 100644
--- a/lib/email_validation_helper.rb
+++ b/lib/email_validation_helper.rb
@@ -1,53 +1,56 @@
# Module that can be included for some extra email validation functions
require 'resolv'
module EmailValidationHelper
# A constant regex for the desired email address.
EMAIL_ADDRESS_FORMAT = begin
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
'\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
quoted_pair = '\\x5c[\\x00-\\x7f]'
domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
domain_ref = atom
sub_domain = "(?:#{domain_ref}|#{domain_literal})"
word = "(?:#{atom}|#{quoted_string})"
domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
local_part = "#{word}(?:\\x2e#{word})*"
addr_spec = "#{local_part}\\x40#{domain}"
pattern = /\A#{addr_spec}\z/
end
# Performs email validation. Returns an array of issues with the email
def self.validate_email(email, email_field_name = 'email')
errors = []
if !(email)
errors << "Please enter your #{email_field_name} address."
elsif !(EMAIL_ADDRESS_FORMAT =~ email)
errors << "Please check the format of your #{email_field_name} address."
elsif !domain_exists?(email)
errors << "The #{email_field_name} address does not appear to be valid."
end
errors
end
private
def self.domain_exists?(email)
result = email.match(/\@(.+)/)
return if result.nil?
domain = result[1]
mx = -1
Resolv::DNS.open do |dns|
mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
end
mx.size > 0 ? true : false
+
+ rescue
+ return true
end
end
\ No newline at end of file
diff --git a/public/images/expand.psd b/public/images/expand.psd
index e0ea7a8..e8b6fd6 100644
Binary files a/public/images/expand.psd and b/public/images/expand.psd differ
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 5e2fa96..62bc5a0 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,226 +1,227 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #CCF; color: black;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; font-size: 13.5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
.feedItemShow .relatedArticles { padding-top: 35px; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
-.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
+.addComment { text-align: left; background-color: #3D3DC3; width: 500px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
-.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
+.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 492px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
+.addComment TEXTAREA { width: 360px; height: 150px;}
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
.emailAFriend .submit { text-align: right; }
.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
/* Login Screen */
.login { width: 500px; margin: auto; padding: 5px; }
.login .forgotPassword { padding-top: 30px; }
/* Forgot Password Screen */
.forgotPassword FORM { padding-top: 10px; padding-bottom: 15px; }
|
jenglert/The-Peoples--Feed
|
33a453a2dc464d14a95e30c874f908ebb355242d
|
Enhancing the styles for the forgot password functionality on TPF
|
diff --git a/app/views/consumer_mailer/forgot_password.html.erb b/app/views/consumer_mailer/forgot_password.html.erb
index 0d4e6ea..4af3e8a 100644
--- a/app/views/consumer_mailer/forgot_password.html.erb
+++ b/app/views/consumer_mailer/forgot_password.html.erb
@@ -1,3 +1,5 @@
-Your password has been reset.
+<%= page_title "Forgot Password" %>
+Thank you for visiting The People's Feed. Your password has been reset.
+
+Your new password is: <%= @password %>
-Your new password is: <%= @password %>
\ No newline at end of file
diff --git a/app/views/sessions/forgot_password.html.erb b/app/views/sessions/forgot_password.html.erb
index ddc2c67..3daae20 100644
--- a/app/views/sessions/forgot_password.html.erb
+++ b/app/views/sessions/forgot_password.html.erb
@@ -1,10 +1,11 @@
<div class="forgotPassword whiteBackground">
+ <%= page_title 'Forgot Password'%>
Forgot your password? Just enter your email below and we will email you a new password.
<% form_tag '/session/send_forgot_password' do -%>
<%= text_field_tag :email %>
<%= submit_tag "Email me a new password"%>
<% end -%>
</div>
\ No newline at end of file
diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb
index 17c7773..b67d2fa 100644
--- a/app/views/sessions/new.html.erb
+++ b/app/views/sessions/new.html.erb
@@ -1,16 +1,18 @@
<div class="login whiteBackground">
<%= page_title 'Login'%>
<% form_tag session_path do -%>
- <p><label for="login">Login</label><br/>
+ <p><label for="login">Username</label>
<%= text_field_tag 'login' %></p>
- <p><label for="password">Password</label><br/>
+ <p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
-
- <%= link_to "Forgot Password", :controller => 'sessions', :action => 'forgot_password' %>
+
+ <div class="forgotPassword">
+ <%= link_to "Forgot Password", :controller => 'sessions', :action => 'forgot_password' %>
+ </div>
</div>
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 021c6fe..5e2fa96 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,219 +1,226 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #CCF; color: black;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; font-size: 13.5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
.feedItemShow .relatedArticles { padding-top: 35px; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
.emailAFriend .submit { text-align: right; }
.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
+
+/* Login Screen */
+.login { width: 500px; margin: auto; padding: 5px; }
+.login .forgotPassword { padding-top: 30px; }
+
+/* Forgot Password Screen */
+.forgotPassword FORM { padding-top: 10px; padding-bottom: 15px; }
|
jenglert/The-Peoples--Feed
|
fe41d53f17da8e6d04d8ccce2342e75d6982cd69
|
Forgot password functionality.
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 0266cdf..5b0aa0f 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,38 +1,63 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
# render new.rhtml
def new
end
def create
self.current_user = User.authenticate(params[:login], params[:password])
if logged_in?
# Always drop the logged in cookie.
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => Time.new + 360.days }
default = '/'
puts "referrer:" + request.referrer
# Attempt to determine if we came from the login page, if so, do nothing. If not, go to the page we used to be at
default = request.referrer if !request.referrer.include?('sessions')
redirect_back_or_default(default)
flash[:notice] = "Logged in successfully"
else
flash[:error] = "Username/Password not recognized. Please try again."
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
+
+ def forgot_password
+ end
+
+ def send_forgot_password
+ users = User.find_all_by_email(params[:email])
+
+ if users.length <= 0
+ # This is potential security whole since users could find all the emails in our database.
+ # At this point, the added user flexibility is better than the added security.
+ flash[:error] = "Unable to find a user with that email."
+ render :action => 'forgot_password'
+ return
+ end
+
+ new_password = SecureRandom.base64(5)
+
+ users[0].password = new_password
+ users[0].password_confirmation = new_password
+ users[0].save!
+
+ flash[:notice] = "We are emailing you a replacement password."
+ ConsumerMailer.deliver_forgot_password(users[0].email, new_password)
+ redirect_back_or_default('/')
+ end
end
diff --git a/app/models/consumer_mailer.rb b/app/models/consumer_mailer.rb
index b449ffb..03a76aa 100644
--- a/app/models/consumer_mailer.rb
+++ b/app/models/consumer_mailer.rb
@@ -1,10 +1,17 @@
class ConsumerMailer < ActionMailer::Base
def email_a_friend(email_a_friend_settings)
recipients email_a_friend_settings.recipient_email_address
from "[email protected]"
subject "#{email_a_friend_settings.title} - The People's Feed"
body :email_a_friend_settings => email_a_friend_settings
end
+
+ def forgot_password(email, password)
+ recipients email
+ from "[email protected]"
+ subject "Your password from The People's Feed"
+ body :password => password
+ end
end
diff --git a/app/views/consumer_mailer/forgot_password.html.erb b/app/views/consumer_mailer/forgot_password.html.erb
new file mode 100644
index 0000000..0d4e6ea
--- /dev/null
+++ b/app/views/consumer_mailer/forgot_password.html.erb
@@ -0,0 +1,3 @@
+Your password has been reset.
+
+Your new password is: <%= @password %>
\ No newline at end of file
diff --git a/app/views/sessions/forgot_password.html.erb b/app/views/sessions/forgot_password.html.erb
new file mode 100644
index 0000000..ddc2c67
--- /dev/null
+++ b/app/views/sessions/forgot_password.html.erb
@@ -0,0 +1,10 @@
+<div class="forgotPassword whiteBackground">
+ Forgot your password? Just enter your email below and we will email you a new password.
+
+ <% form_tag '/session/send_forgot_password' do -%>
+ <%= text_field_tag :email %>
+
+ <%= submit_tag "Email me a new password"%>
+ <% end -%>
+
+</div>
\ No newline at end of file
diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb
index 43de396..17c7773 100644
--- a/app/views/sessions/new.html.erb
+++ b/app/views/sessions/new.html.erb
@@ -1,14 +1,16 @@
<div class="login whiteBackground">
<%= page_title 'Login'%>
<% form_tag session_path do -%>
<p><label for="login">Login</label><br/>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label><br/>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
-</div>
\ No newline at end of file
+ <%= link_to "Forgot Password", :controller => 'sessions', :action => 'forgot_password' %>
+</div>
+
diff --git a/config/routes.rb b/config/routes.rb
index e0fd1b0..d4365a7 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,86 +1,86 @@
ActionController::Routing::Routes.draw do |map|
map.resources :models
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.resource :user_preference
- map.resource :session
+ map.resource :session, :collection => { :send_forgot_password => :post }
map.resources :users, :collection => { :login_submit => :post }
map.connect 'login', :controller => 'users', :action => 'login'
map.connect 'logout', :controller => 'users', :action => 'logout'
map.resources :feed
map.resources :feed_comment
map.connect 'feed_item/media', :controller => 'feed_item', :action => 'media'
map.resources :feed_item
map.resources :feed_item_category
map.resources :category
map.resources :category_comment
map.resources :homepage
map.resources :feed_item_comment
map.resources :category_organizer
map.resources :comments
map.resources :blog_posts
map.resources :email_subscriptions
map.resources :email_a_friend_messages
map.connect 'blog', :controller => 'blog_posts'
map.connect 'blog.xml', :controller => 'blog_posts', :format => 'xml'
map.connect 'privacy-policy', :controller => 'static_pages', :action => 'privacy_policy'
map.connect 'sitemap', :controller => 'static_pages', :action => 'sitemap'
map.connect 'contact-us', :controller => 'static_pages', :action => 'contact_us'
map.connect 'contribute', :controller => 'static_pages', :action => 'contribute'
map.connect 'how-it-works', :controller => 'static_pages', :action => 'how_it_works'
map.connect 'search', :controller => 'static_pages', :action => 'search'
map.connect 'open-source', :controller => 'static_pages', :action => 'open_source'
map.connect 'sitemap.xml', :controller => 'sitemap', :action => 'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.homepage '', :controller => 'homepage'
map.connect 'update', :controller => 'feed', :action => 'update'
map.root :controller => "homepage"
map.connect '*', :controller => 'application', :action => 'rescue_404'
end
|
jenglert/The-Peoples--Feed
|
11771ac4cb116fe6eb950c2055945caada91b6ad
|
Updating a couple styles.
|
diff --git a/app/views/shared/_feed_item_wide.html.erb b/app/views/shared/_feed_item_wide.html.erb
index 612ebe9..5b3240f 100644
--- a/app/views/shared/_feed_item_wide.html.erb
+++ b/app/views/shared/_feed_item_wide.html.erb
@@ -1,26 +1,26 @@
<div class="feedItemWide whiteBackground">
<table>
<tr>
<td>
<% link_to({:controller => "feed_item", :action => "redir", :id => feedItem }, :target => '_blank') do %>
<%= image_tag(feedItem.image_url) if feedItem.image_url%>
<% end %>
</td>
<td>
<h4>
<% link_to({:controller => "feed_item", :action => "redir", :id => feedItem }, :target => '_blank') do %>
<%= truncate h(feedItem.title.fix_html), :length => 60, :omission => '...' %>
<% end %>
</h4>
<div class="feedItemCreated">
<%= feedItem.created_at.pretty%>
</div>
<div class="description">
<span class="source"><%= link_to feedItem.feed.title, feedItem.feed %>:</span>
- <%= truncate h(feedItem.description.fix_html), :length => 360, :omission => "..." %>
+ <%= truncate h(feedItem.description.fix_html), :length => 420, :omission => "..." %>
<span class="comment"><%= link_to '(more)', feedItem %></span>
</div>
</td>
</tr>
</table>
</div>
\ No newline at end of file
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 4191ec1..021c6fe 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,219 +1,219 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
- background-color: #CCF; color: #DF6900;}
+ background-color: #CCF; color: black;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
-.feedItemWide .description { clear: both; padding-left: 5px; }
+.feedItemWide .description { clear: both; padding-left: 5px; font-size: 13.5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
.feedItemShow .relatedArticles { padding-top: 35px; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
.emailAFriend .submit { text-align: right; }
.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
|
jenglert/The-Peoples--Feed
|
0962252791e08b2a908ae4058bb03e6f058e30ab
|
Removing an extra colon from the email a friend url.
|
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
index 8bd7bc7..95809ce 100644
--- a/app/views/shared/_participate.html.erb
+++ b/app/views/shared/_participate.html.erb
@@ -1,94 +1,94 @@
<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
<div class="addComment">
<h3>
<a href="#" onclick="tpf.hideShowCommentSection(); return false;">
Add a Comment <img src="/images/expand.png" width="14" height="14">
</a>
|
<a href="#" onclick="tpf.hideShowEmailAFriendSection(); return false;">
Email A Friend <img src="/images/expand.png" width="14" height="14">
</a>
</h3>
<div class="body">
<% if logged_in? %>
<div style="display: none;" id="commentSection">
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', item.id%>
<%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
</div>
<div style="display: none;" id="emailAFriendSection">
- <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
+ <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}#{":" + request.port if request.port != 80}#{request.path}") do |f| %>
<%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
<td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
</div>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
a8f57a814a4d6327a502db590aa7a79286ba2f98
|
Fixing a typo in the email link
|
diff --git a/app/controllers/email_a_friend_messages_controller.rb b/app/controllers/email_a_friend_messages_controller.rb
index a85c9e0..7f6d470 100644
--- a/app/controllers/email_a_friend_messages_controller.rb
+++ b/app/controllers/email_a_friend_messages_controller.rb
@@ -1,28 +1,28 @@
class EmailAFriendMessagesController < ApplicationController
before_filter :login_required
# Unimplemnted at this point. Eventually, we might have functionality where a consumer could email a friend about the
# site in general.
def new
@email_a_friend_message = EmailAFriendMessage.new
- @email_a_friend_message.url = "http://#{request.host}:#{request.port if request.port != 80}/" if @email_a_friend_message.url.nil?
+ @email_a_friend_message.url = "http://#{request.host}#{":" + request.port if request.port != 80}/" if @email_a_friend_message.url.nil?
end
def create
@email_a_friend_message = EmailAFriendMessage.new(params[:email_a_friend_message])
if @email_a_friend_message.save
flash[:notice] = "Your message is currently being sent."
ConsumerMailer.deliver_email_a_friend(@email_a_friend_message)
redirect_to @email_a_friend_message.url
return
end
render :action => 'new'
end
end
|
jenglert/The-Peoples--Feed
|
9e6968ab868c5fcac3e1c2f79cbd5931edbc9b22
|
Adding related articles to the articles page.
|
diff --git a/app/models/feed_item.rb b/app/models/feed_item.rb
index 1dff202..878debb 100644
--- a/app/models/feed_item.rb
+++ b/app/models/feed_item.rb
@@ -1,125 +1,132 @@
require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)
class FeedItem < ActiveRecord::Base
belongs_to :feed
has_many :feed_item_categories
has_many :categories, :through => :feed_item_categories
acts_as_commentable
before_save :calculate_rating
named_scope :recent, :conditions => ["created_at > ?", 3.days.ago]
named_scope :for_feed, lambda { |*args| {:conditions => ["feed_id = ?", args.first]}}
def FeedItem.find_top_feed_items
FeedItem.find(:all, :limit => 20, :order => 'rating desc')
end
+
+ # Finds feed items related to the current feed item we are looking at.
+ def related_feed_items
+ FeedItem.find(:all, :include => 'feed_item_categories',
+ :conditions => ["feed_item_categories.category_id in (?)", categories.collect {|category| category.id}],
+ :limit => 10, :order => "created_at desc")
+ end
# The guid will be either the defined guid (preferrably) or the entry's link
def set_guid_from_entry(entry)
if !entry.id.nil?
self.guid = entry.id.strip
elsif !entry.url.nil?
self.guid = entry.url.strip
elsif !entry.title.nil?
self.guid = entry.title
end
end
def set_image_url_from_entry(entry)
self.image_url = entry.media_content[0].url if entry.media_content \
and entry.media_content.length > 0
end
def FeedItem.initialize_from_entry(entry)
new_feed_item = FeedItem.new(
:title => entry.title.strip.remove_html,
:item_url => entry.url.strip,
:description => entry.summary.strip.remove_html,
:pub_date => Time.parse("#{entry.published}")
)
new_feed_item.set_image_url_from_entry(entry)
new_feed_item.set_guid_from_entry(entry)
new_feed_item.update_categories(entry.categories)
new_feed_item
end
def update_categories(categories)
temp = []
categories.each do |rss_category|
rss_category.strip.split(',').each do |rss_category_split|
# Create the new category is necessary
category_name = rss_category_split.strip
unless temp.include? category_name
temp << category_name
category = Category.find_by_name(category_name)
unless category
# Try to find a merge category before creating a new category.x
category_merge = CategoryMerge.find_by_merge_src(category_name)
if category_merge
category = Category.find_by_id(category_merge.merge_target)
end
end
if !category
category = Category.new :name => category_name
end
self.categories << category
end
end
end
rescue => ex
LOG.error "Failed to update categories: #{ex.message}: #{ex.backtrace}"
end
def update_rating
orig_rating = self.rating
new_rating = calculate_rating
self.update_attributes :rating => new_rating if (new_rating - orig_rating).abs > 0.1
end
# The overall rating for this feed item.
def calculate_rating
self.rating = time_multiplier * (clicks_points + description_points + comments_points + image_points + category_points).to_f
end
def time_multiplier
# Calculates a multiplier from 0 to 1 which serves to indicate how new the feed is.
time = self.created_at || Time.now
time_multiplier = (time - 3.days.ago)/3.days
return 0 if time_multiplier < 0.05
time_multiplier
end
def clicks_points
# Ensure that the number of clicks is always at least 0
self.clicks = 0 if self.clicks.nil?
clicks
end
def image_points
image_url ? 4 : 0
end
def description_points
return 0 if description.nil?
points = self.description.length / 100
points = 2 if points > 2
points
end
def comments_points
self.comments_count * 5
end
def category_points
self.feed_item_categories_count > 3 ? 3 : self.feed_item_categories_count
end
# This method provides a more SEO friendly URL.
def to_param
"#{id}-#{title.gsub(/[^a-z0-9]+/i, '-')}"
end
end
diff --git a/app/views/feed_item/show.html.erb b/app/views/feed_item/show.html.erb
index bd9fbe5..40da5c3 100644
--- a/app/views/feed_item/show.html.erb
+++ b/app/views/feed_item/show.html.erb
@@ -1,107 +1,112 @@
<% meta_description @feed_item.description.fix_html %>
<div class="feedItemShow">
<div class="sectionHeading">
<%= page_title @feed_item.title %>
</div>
<table class="feedItemInfo">
<tr>
<td class="categories">
<span class="heading">Categories</span>
<ul>
<% @feed_item.categories.each { |category| %>
<li><%= link_to category.name, category %></li>
<% } %>
</ul>
</td>
<td class="description" rowspan="2" colspan="3">
<div class="fullArticle">
<%= link_to 'Read the Full Article',@feed_item.item_url %>
</div>
<div>
<%= image_tag @feed_item.image_url if @feed_item.image_url%>
</div>
<span class="heading">Description: </span></b><%= h(@feed_item.description.fix_html) %>
</td>
</tr>
<tr>
<td>
<span class="heading">Rating</span>
<table class="rating">
<tr>
<td>
Recency Mult.
</td>
<td>
<%= sprintf('%.2f%', @feed_item.time_multiplier * 100) %>
</td>
</tr>
<tr>
<td>
Clicks Pts.
</td>
<td>
<%= @feed_item.clicks_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Description Pts.
</td>
<td>
<%= @feed_item.description_points.to_s %>
</td>
</tr>
<tr>
<td>
Image Pts.
</td>
<td>
<%= @feed_item.image_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Category Pts.
</td>
<td>
<%= @feed_item.category_points.to_s %>
</td>
</tr>
<tr>
<td colspan="2" class="total">
Total: <%= sprintf('%.1f', @feed_item.rating) %>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<%= link_to @feed_item.feed.title, @feed_item.feed%>
</td>
<td>
<span class="heading">Published:</span> <%= @feed_item.created_at.pretty %>
</td>
<td>
</td>
</tr>
</table>
<%= render :partial => 'shared/participate', :locals => { :post_location => '/feed_item_comment', :item => @feed_item }%>
+
+ <h2 class="relatedArticles">Related Articles</h2>
+ <% @feed_item.related_feed_items.each { |feedItem| %>
+ <%= render :partial => 'shared/feed_item_wide', :locals => {:feedItem => feedItem} %>
+ <% } %>
</div>
\ No newline at end of file
diff --git a/app/views/static_pages/sitemap.html.erb b/app/views/static_pages/sitemap.html.erb
index da724c3..4dd9992 100644
--- a/app/views/static_pages/sitemap.html.erb
+++ b/app/views/static_pages/sitemap.html.erb
@@ -1,32 +1,33 @@
<div class="siteMap">
<%= page_title "Sitemap - the map to The People's Feed" %>
<h2>Contribute</h2>
<ul>
<li><%= link_to 'Information About Contributing', '/contribute'%></li>
<li><%= link_to 'Open Source Information', '/open-source'%></li>
<li><%= link_to 'Email Updates', '/email_subscriptions/new' %></li>
</ul>
<h2>Use</h2>
<ul>
<li><%= link_to 'The most popular news articles', '/'%></li>
<li><%= link_to 'Categories - Complete list', :controller => 'category', :action => 'index'%></li>
<li><%= link_to 'RSS feeds we consume', :controller => 'feed', :action => 'index' %></li>
<li><%= link_to 'Recent pictures', :controller => 'feed_item', :action => 'media' %></li>
<li><%= link_to 'See all user comments', :controller => 'comment' %></li>
<li><%= link_to 'Privacy policy', '/privacy-policy' %></li>
</ul>
<h2>Promote</h2>
<ul>
<li><%= link_to 'Add your feed to our feeds', :controller=> 'feed', :action => 'new' %></li>
+ <li><%= link_to "Email A Friend about The People's Feed", :controller => 'email_a_friend_messages', :action => 'new' %></li>
</ul>
<br />
<br />
<h2>Service, Technologies, and Friends</h2>
<p>The following is a short list of technologies and services that The People's Feed uses. Feel free to visit them</p>
<ul>
<li><a href="http://www.blogoculars.com/link/the-peoples-feed">Blogoculars Blog Directory</a></li>
</ul>
</div>
\ No newline at end of file
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 93eebc0..4191ec1 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,218 +1,219 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #CCF; color: #DF6900;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
+.feedItemShow .relatedArticles { padding-top: 35px; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
.emailAFriend .submit { text-align: right; }
.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
|
jenglert/The-Peoples--Feed
|
525815025526d2975ceea8934ff3f5846e355476
|
Adding utml source to the email a friend email
|
diff --git a/app/views/consumer_mailer/email_a_friend.rhtml b/app/views/consumer_mailer/email_a_friend.rhtml
index d36a92f..fe0af65 100644
--- a/app/views/consumer_mailer/email_a_friend.rhtml
+++ b/app/views/consumer_mailer/email_a_friend.rhtml
@@ -1,5 +1,5 @@
<%= @email_a_friend_settings.sender_email_address %> wants to let you know about a page on The People's Feed:
-<%= @email_a_friend_settings.url %>
+<%= @email_a_friend_settings.url %>?utm_medium=email&utm_source=emailafriend
<%= @email_a_friend_settings.message %>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
a3356466b93ec20934bcafd826ff8946de5a261c
|
Fixing png transparency
|
diff --git a/app/views/layouts/standard.html.erb b/app/views/layouts/standard.html.erb
index 0d89c4f..a4bb1bb 100644
--- a/app/views/layouts/standard.html.erb
+++ b/app/views/layouts/standard.html.erb
@@ -1,120 +1,121 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<%= stylesheet_link_tag 'main' %>
<meta name="verify-v1" content="qnzsIVoN1EFhSa6I3djN8bQ0o9x+L1NZp/eJ6C6XCao=" ></meta>
<title>
<%= "#@page_title - " if !@page_title.nil? %> The People's Feed
</title>
<% if !@meta_description.nil? %>
<meta name="description" content="<%= @meta_description %>" />
<% end %>
<%= javascript_include_tag "jquery-1.3.2.min.js" %>
<%= javascript_include_tag "jquery.bgiframe.js" %>
<%= javascript_include_tag "jquery.delegate.js" %>
<%= javascript_include_tag "jquery.tooltip.min.js" %>
<%= javascript_include_tag "jquery.dimensions.js"%>
+ <%= javascript_include_tag "jquery.pngFix.js"%>
<%= javascript_include_tag "main.js" %>
<%= yield(:head)%>
</head>
<body>
<div class="header">
<% link_to '/' do %>
<img src="/images/header_logo.png" alt="The People's Feed" class="logo" />
<% end %>
<div class="motto">The latest news ranked according to its popularity by YOU</div>
<%= render :partial => 'shared/main_menu_insert' %>
</div>
<div class="body">
<div class="centerColumn">
<div class="flashes">
<% if flash.has_key?(:error) %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
<% if flash.has_key?(:notice) %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
</div>
<%= yield %>
</div>
<div class="rightHandList">
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_feeds') do %>
<h3>Top Feeds</h3>
<%= render :partial => 'shared/feed_narrow', :locals => { :topFeeds => @topFeeds } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_categories') do %>
<h3>Top Categories</h3>
<%= render :partial => 'shared/category_narrow', :locals => { :topCategories => @topCategories } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_media') do %>
<h3>Top Media</h3>
<%= render :partial => 'shared/media_narrow', :locals => { :topMedia => @topMedia } %>
<% end %>
<% if show_ads %>
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 160x600, created 7/7/09 */
google_ad_slot = "8881178843";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<% end %>
</div>
<div class="clearBoth" />
</div>
<div class="footer">
<%= link_to 'sitemap', '/sitemap'%> |
<%= link_to 'privacy', '/privacy-policy' %> |
<%= link_to 'contact us', '/contact-us' %> |
<%= link_to 'contribute', '/contribute' %> |
<%= link_to 'how it works', '/how-it-works' %>
</div>
<% if show_ads %>
<div class="bottomAd">
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 728x90, created 7/30/09 */
google_ad_slot = "3484810864";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<% end %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9105909-1");
pageTracker._trackPageview();
} catch(err) {}</script>
<div class="lastUpdated">
Last Updated: <%= FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" )[0].created_at.pretty %>
</div>
</body>
</html>
\ No newline at end of file
diff --git a/public/javascripts/jquery.pngFix.js b/public/javascripts/jquery.pngFix.js
new file mode 100755
index 0000000..6adfcc9
--- /dev/null
+++ b/public/javascripts/jquery.pngFix.js
@@ -0,0 +1,113 @@
+/**
+ * --------------------------------------------------------------------
+ * jQuery-Plugin "pngFix"
+ * Version: 1.2, 09.03.2009
+ * by Andreas Eberhard, [email protected]
+ * http://jquery.andreaseberhard.de/
+ *
+ * Copyright (c) 2007 Andreas Eberhard
+ * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
+ *
+ * Changelog:
+ * 09.03.2009 Version 1.2
+ * - Update for jQuery 1.3.x, removed @ from selectors
+ * 11.09.2007 Version 1.1
+ * - removed noConflict
+ * - added png-support for input type=image
+ * - 01.08.2007 CSS background-image support extension added by Scott Jehl, [email protected], http://www.filamentgroup.com
+ * 31.05.2007 initial Version 1.0
+ * --------------------------------------------------------------------
+ * @example $(function(){$(document).pngFix();});
+ * @desc Fixes all PNG's in the document on document.ready
+ *
+ * jQuery(function(){jQuery(document).pngFix();});
+ * @desc Fixes all PNG's in the document on document.ready when using noConflict
+ *
+ * @example $(function(){$('div.examples').pngFix();});
+ * @desc Fixes all PNG's within div with class examples
+ *
+ * @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
+ * @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
+ * --------------------------------------------------------------------
+ */
+
+(function($) {
+
+jQuery.fn.pngFix = function(settings) {
+
+ // Settings
+ settings = jQuery.extend({
+ blankgif: 'blank.gif'
+ }, settings);
+
+ var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
+ var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
+
+ if (jQuery.browser.msie && (ie55 || ie6)) {
+
+ //fix images with png-source
+ jQuery(this).find("img[src$=.png]").each(function() {
+
+ jQuery(this).attr('width',jQuery(this).width());
+ jQuery(this).attr('height',jQuery(this).height());
+
+ var prevStyle = '';
+ var strNewHTML = '';
+ var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
+ var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
+ var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
+ var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
+ var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
+ var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
+ if (this.style.border) {
+ prevStyle += 'border:'+this.style.border+';';
+ this.style.border = '';
+ }
+ if (this.style.padding) {
+ prevStyle += 'padding:'+this.style.padding+';';
+ this.style.padding = '';
+ }
+ if (this.style.margin) {
+ prevStyle += 'margin:'+this.style.margin+';';
+ this.style.margin = '';
+ }
+ var imgStyle = (this.style.cssText);
+
+ strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
+ strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
+ strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
+ strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
+ strNewHTML += imgStyle+'"></span>';
+ if (prevStyle != ''){
+ strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
+ }
+
+ jQuery(this).hide();
+ jQuery(this).after(strNewHTML);
+
+ });
+
+ // fix css background pngs
+ jQuery(this).find("*").each(function(){
+ var bgIMG = jQuery(this).css('background-image');
+ if(bgIMG.indexOf(".png")!=-1){
+ var iebg = bgIMG.split('url("')[1].split('")')[0];
+ jQuery(this).css('background-image', 'none');
+ jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
+ }
+ });
+
+ //fix input with png-source
+ jQuery(this).find("input[src$=.png]").each(function() {
+ var bgIMG = jQuery(this).attr('src');
+ jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
+ jQuery(this).attr('src', settings.blankgif)
+ });
+
+ }
+
+ return jQuery;
+
+};
+
+})(jQuery);
diff --git a/public/javascripts/main.js b/public/javascripts/main.js
index 94f71a5..9ae35c4 100644
--- a/public/javascripts/main.js
+++ b/public/javascripts/main.js
@@ -1,54 +1,56 @@
// Logic that needs to be performed when the page loads.
jQuery(document).ready(function() {
jQuery(".tooltip").tooltip({showURL: false, fade: 250, track: true });
// Ajax submit methods
jQuery(".deleteComment").linkWithAjax();
+
+ jQuery(document).pngFix();
});
// Define the variable tpf if it isn't defined
if (typeof tpf == 'undefined') {
tpf = {}
}
// Hide show the comments section of the participate block.
tpf.hideShowCommentSection = function() {
hiddenElements = jQuery('#commentSection:hidden');
jQuery('#commentSection:visible').hide();
jQuery('#emailAFriendSection').hide();
hiddenElements.show();
}
// Hide show the email a friend section of the participate block
tpf.hideShowEmailAFriendSection = function() {
hiddenElements = jQuery('#emailAFriendSection:hidden');
jQuery('#emailAFriendSection:visible').hide();
jQuery('#commentSection').hide();
hiddenElements.show();
}
// Ensure that jQuery sends all javascript files with a text/javascript header
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
// Hide the flash messages after 6 seconds
setTimeout("jQuery('.flashes').slideUp('slow')", 6000);
// jQuery function extension that will allow you to submit a form using ajax.
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
jQuery.post(this.action, jQuery(this).serialize(), null, "script");
return false;
})
return this;
};
// jQuery function extension that will allow you to click a link with ajax.
jQuery.fn.linkWithAjax = function() {
jQuery(this).click(function() {
jQuery.get(jQuery(this).attr('href'), null, null, "script");
return false;
});
return this;
};
|
jenglert/The-Peoples--Feed
|
da3221c8b8cb7ab16f1246eeafffb0a1db472cb5
|
Enhancing javascript
|
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
index d74c586..8bd7bc7 100644
--- a/app/views/shared/_participate.html.erb
+++ b/app/views/shared/_participate.html.erb
@@ -1,94 +1,94 @@
<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
<div class="addComment">
<h3>
- <a href="#" onclick="javascript:tpf.hideShowCommentSection()">
+ <a href="#" onclick="tpf.hideShowCommentSection(); return false;">
Add a Comment <img src="/images/expand.png" width="14" height="14">
</a>
|
- <a href="#" onclick="javascript:tpf.hideShowEmailAFriendSection()">
+ <a href="#" onclick="tpf.hideShowEmailAFriendSection(); return false;">
Email A Friend <img src="/images/expand.png" width="14" height="14">
</a>
</h3>
<div class="body">
<% if logged_in? %>
<div style="display: none;" id="commentSection">
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', item.id%>
<%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
</div>
<div style="display: none;" id="emailAFriendSection">
<% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
<%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
<td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
</div>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
6babe8074d574ae6e7b7652eb0f2e06085e1e40c
|
Using an alternate link tag style.
|
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
index 5c88d60..d74c586 100644
--- a/app/views/shared/_participate.html.erb
+++ b/app/views/shared/_participate.html.erb
@@ -1,94 +1,94 @@
<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
<div class="addComment">
<h3>
- <a href="javascript:tpf.hideShowCommentSection()">
+ <a href="#" onclick="javascript:tpf.hideShowCommentSection()">
Add a Comment <img src="/images/expand.png" width="14" height="14">
</a>
|
- <a href="javascript:tpf.hideShowEmailAFriendSection()">
+ <a href="#" onclick="javascript:tpf.hideShowEmailAFriendSection()">
Email A Friend <img src="/images/expand.png" width="14" height="14">
</a>
</h3>
<div class="body">
<% if logged_in? %>
<div style="display: none;" id="commentSection">
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', item.id%>
<%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
</div>
<div style="display: none;" id="emailAFriendSection">
<% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
<%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
<td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
</div>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
e06cab45326b45486c1db7973b5503caf0abfaeb
|
Updating some things
|
diff --git a/app/views/shared/_create_comment.html.erb b/app/views/shared/_create_comment.html.erb
index 7c452c9..d10e072 100644
--- a/app/views/shared/_create_comment.html.erb
+++ b/app/views/shared/_create_comment.html.erb
@@ -1,64 +1,57 @@
<div class="addComment">
<h3>Add a Comment</h3>
<div class="body">
<% if logged_in? %>
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', commented_item.id%>
+ <%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
- <tr>
- <td class="label">
- email:
- </td>
- <td>
- <%= f.text_field :email %>
- </td>
- </tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/shared/_email_a_friend.html.erb b/app/views/shared/_email_a_friend.html.erb
index 6f241ba..55e1027 100644
--- a/app/views/shared/_email_a_friend.html.erb
+++ b/app/views/shared/_email_a_friend.html.erb
@@ -1,48 +1,45 @@
<div class="emailAFriend collapseable">
<h3>Email a Friend</h3>
<div class="body to_collapse">
<% if logged_in? %>
<% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
+ <%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
- <tr>
- <td class="label">Your Email:</td>
- <td><%= f.text_field :sender_email_address %></td>
- </tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
<td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
<% else %>
Please login to use this functionality.
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
index 97c7310..5c88d60 100644
--- a/app/views/shared/_participate.html.erb
+++ b/app/views/shared/_participate.html.erb
@@ -1,104 +1,94 @@
<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
<div class="addComment">
<h3>
<a href="javascript:tpf.hideShowCommentSection()">
Add a Comment <img src="/images/expand.png" width="14" height="14">
</a>
|
<a href="javascript:tpf.hideShowEmailAFriendSection()">
Email A Friend <img src="/images/expand.png" width="14" height="14">
</a>
</h3>
<div class="body">
<% if logged_in? %>
<div style="display: none;" id="commentSection">
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', item.id%>
+ <%= f.hidden_field :email, :value => current_user.email %>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
- <tr>
- <td class="label">
- email:
- </td>
- <td>
- <%= f.text_field :email %>
- </td>
- </tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
</div>
<div style="display: none;" id="emailAFriendSection">
<% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
+ <%= f.hidden_field :sender_email_address, :value => current_user.email %>
<table>
<tr>
<td class="label">Friend's Email:</td>
<td><%= f.text_field :recipient_email_address %></td>
</tr>
- <tr>
- <td class="label">Your Email:</td>
- <td><%= f.text_field :sender_email_address %></td>
- </tr>
<tr>
<td class="label">URL:</td>
<td><%= f.text_field :url, :readonly => true %></td>
</tr>
<tr>
<td class="label">Subject:</td>
<td><%= f.text_field :title %></td>
</tr>
<tr>
<td class="label">Message:</td>
<td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
</tr>
<tr>
<td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
</tr>
</table>
<% end %>
</div>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
\ No newline at end of file
diff --git a/lib/email_validation_helper.rb b/lib/email_validation_helper.rb
index 75ecedf..4f114ec 100644
--- a/lib/email_validation_helper.rb
+++ b/lib/email_validation_helper.rb
@@ -1,52 +1,53 @@
# Module that can be included for some extra email validation functions
require 'resolv'
module EmailValidationHelper
# A constant regex for the desired email address.
EMAIL_ADDRESS_FORMAT = begin
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
'\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
quoted_pair = '\\x5c[\\x00-\\x7f]'
domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
domain_ref = atom
sub_domain = "(?:#{domain_ref}|#{domain_literal})"
word = "(?:#{atom}|#{quoted_string})"
domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
local_part = "#{word}(?:\\x2e#{word})*"
addr_spec = "#{local_part}\\x40#{domain}"
pattern = /\A#{addr_spec}\z/
end
# Performs email validation. Returns an array of issues with the email
def self.validate_email(email, email_field_name = 'email')
errors = []
if !(email)
errors << "Please enter your #{email_field_name} address."
elsif !(EMAIL_ADDRESS_FORMAT =~ email)
errors << "Please check the format of your #{email_field_name} address."
elsif !domain_exists?(email)
errors << "The #{email_field_name} address does not appear to be valid."
end
errors
end
private
def self.domain_exists?(email)
result = email.match(/\@(.+)/)
return if result.nil?
domain = result[1]
+ mx = -1
Resolv::DNS.open do |dns|
mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
end
mx.size > 0 ? true : false
end
end
\ No newline at end of file
|
jenglert/The-Peoples--Feed
|
1a901017d2a63e0e9693ef1110d018d565e917ef
|
Making the participate link a bit fancier.
|
diff --git a/.gitignore b/.gitignore
index e3af559..5e30051 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,8 +1,9 @@
log/*.log
config/database.yml
tmp/**/*
.DS_Store
db/*.sqlite3
/.idea
*.rb~
.gitignore~
+public/sitemap.xml
diff --git a/app/views/feed_item/show.html.erb b/app/views/feed_item/show.html.erb
index 3ba77a1..bd9fbe5 100644
--- a/app/views/feed_item/show.html.erb
+++ b/app/views/feed_item/show.html.erb
@@ -1,109 +1,107 @@
<% meta_description @feed_item.description.fix_html %>
<div class="feedItemShow">
<div class="sectionHeading">
<%= page_title @feed_item.title %>
</div>
<table class="feedItemInfo">
<tr>
<td class="categories">
<span class="heading">Categories</span>
<ul>
<% @feed_item.categories.each { |category| %>
<li><%= link_to category.name, category %></li>
<% } %>
</ul>
</td>
<td class="description" rowspan="2" colspan="3">
<div class="fullArticle">
<%= link_to 'Read the Full Article',@feed_item.item_url %>
</div>
<div>
<%= image_tag @feed_item.image_url if @feed_item.image_url%>
</div>
<span class="heading">Description: </span></b><%= h(@feed_item.description.fix_html) %>
</td>
</tr>
<tr>
<td>
<span class="heading">Rating</span>
<table class="rating">
<tr>
<td>
Recency Mult.
</td>
<td>
<%= sprintf('%.2f%', @feed_item.time_multiplier * 100) %>
</td>
</tr>
<tr>
<td>
Clicks Pts.
</td>
<td>
<%= @feed_item.clicks_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Description Pts.
</td>
<td>
<%= @feed_item.description_points.to_s %>
</td>
</tr>
<tr>
<td>
Image Pts.
</td>
<td>
<%= @feed_item.image_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Category Pts.
</td>
<td>
<%= @feed_item.category_points.to_s %>
</td>
</tr>
<tr>
<td colspan="2" class="total">
Total: <%= sprintf('%.1f', @feed_item.rating) %>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<%= link_to @feed_item.feed.title, @feed_item.feed%>
</td>
<td>
<span class="heading">Published:</span> <%= @feed_item.created_at.pretty %>
</td>
<td>
</td>
</tr>
</table>
- <%= render :partial => 'shared/email_a_friend'%>
- <%= render :partial => 'shared/show_comments', :locals => { :comments => @feed_item.comments } %>
- <%= render :partial => 'shared/create_comment', :locals => { :post_location => '/feed_item_comment', :commented_item => @feed_item }%>
+ <%= render :partial => 'shared/participate', :locals => { :post_location => '/feed_item_comment', :item => @feed_item }%>
</div>
\ No newline at end of file
diff --git a/app/views/layouts/search.html.erb b/app/views/layouts/search.html.erb
index c145ff3..027d1a6 100644
--- a/app/views/layouts/search.html.erb
+++ b/app/views/layouts/search.html.erb
@@ -1,63 +1,62 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<%= stylesheet_link_tag 'main' %>
<meta name="verify-v1" content="qnzsIVoN1EFhSa6I3djN8bQ0o9x+L1NZp/eJ6C6XCao=" ></meta>
<title>
<%= "#@page_title - " if !@page_title.nil? %> The People's Feed
</title>
<% if !@meta_description.nil? %>
<meta name="description" content="<%= @meta_description %>" />
<% end %>
</head>
<body>
<div class="header">
<img src="/images/header_logo.png" alt="The People's Feed" class="logo" />
<div class="motto">The latest news ranked by the popularity YOU determine.</div>
<div class="smallMenu">
<ul>
<li><%= link_to 'how it works', '/how-it-works' %></li>
<li><%= link_to 'contribute', '/contribute' %></li>
<li><%= link_to 'open source', '/open-source' %></li>
</ul>
</div>
<div class="search">
<form action="http://www.thepeoplesfeed.com/search" id="cse-search-box">
<div>
<input type="hidden" name="cx" value="partner-pub-7279077462237001:a7h0rp-l74h" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="ISO-8859-1" />
<input type="text" name="q" size="20" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script>
</div>
<%= render :partial => 'shared/main_menu_insert' %>
</div>
<div class="body">
<%= yield %>
</div>
<div class="footer">
<%= link_to 'sitemap', '/sitemap'%> |
<%= link_to 'privacy', '/privacy-policy' %> |
<%= link_to 'contact us', '/contact-us' %> |
- <%= link_to 'advertise', '/advertise' %> |
<%= link_to 'contribute', '/contribute' %> |
<%= link_to 'how it works', '/how-it-works' %>
</div>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9105909-1");
pageTracker._trackPageview();
} catch(err) {}</script>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/layouts/standard.html.erb b/app/views/layouts/standard.html.erb
index 6e6ec48..0d89c4f 100644
--- a/app/views/layouts/standard.html.erb
+++ b/app/views/layouts/standard.html.erb
@@ -1,121 +1,120 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<%= stylesheet_link_tag 'main' %>
<meta name="verify-v1" content="qnzsIVoN1EFhSa6I3djN8bQ0o9x+L1NZp/eJ6C6XCao=" ></meta>
<title>
<%= "#@page_title - " if !@page_title.nil? %> The People's Feed
</title>
<% if !@meta_description.nil? %>
<meta name="description" content="<%= @meta_description %>" />
<% end %>
<%= javascript_include_tag "jquery-1.3.2.min.js" %>
<%= javascript_include_tag "jquery.bgiframe.js" %>
<%= javascript_include_tag "jquery.delegate.js" %>
<%= javascript_include_tag "jquery.tooltip.min.js" %>
<%= javascript_include_tag "jquery.dimensions.js"%>
<%= javascript_include_tag "main.js" %>
<%= yield(:head)%>
</head>
<body>
<div class="header">
<% link_to '/' do %>
<img src="/images/header_logo.png" alt="The People's Feed" class="logo" />
<% end %>
<div class="motto">The latest news ranked according to its popularity by YOU</div>
<%= render :partial => 'shared/main_menu_insert' %>
</div>
<div class="body">
<div class="centerColumn">
<div class="flashes">
<% if flash.has_key?(:error) %>
<div class="error">
<%= flash[:error] %>
</div>
<% end %>
<% if flash.has_key?(:notice) %>
<div class="notice">
<%= flash[:notice] %>
</div>
<% end %>
</div>
<%= yield %>
</div>
<div class="rightHandList">
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_feeds') do %>
<h3>Top Feeds</h3>
<%= render :partial => 'shared/feed_narrow', :locals => { :topFeeds => @topFeeds } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_categories') do %>
<h3>Top Categories</h3>
<%= render :partial => 'shared/category_narrow', :locals => { :topCategories => @topCategories } %>
<% end %>
<% cache(:controller => 'homepage', :action => 'homepage', :left_navigation => 'top_media') do %>
<h3>Top Media</h3>
<%= render :partial => 'shared/media_narrow', :locals => { :topMedia => @topMedia } %>
<% end %>
<% if show_ads %>
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 160x600, created 7/7/09 */
google_ad_slot = "8881178843";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<% end %>
</div>
<div class="clearBoth" />
</div>
<div class="footer">
<%= link_to 'sitemap', '/sitemap'%> |
<%= link_to 'privacy', '/privacy-policy' %> |
<%= link_to 'contact us', '/contact-us' %> |
- <%= link_to 'advertise', '/advertise' %> |
<%= link_to 'contribute', '/contribute' %> |
<%= link_to 'how it works', '/how-it-works' %>
</div>
<% if show_ads %>
<div class="bottomAd">
<script type="text/javascript"><!--
google_ad_client = "pub-7279077462237001";
/* 728x90, created 7/30/09 */
google_ad_slot = "3484810864";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<% end %>
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-9105909-1");
pageTracker._trackPageview();
} catch(err) {}</script>
<div class="lastUpdated">
Last Updated: <%= FeedItem.find(:all, :conditions => "created_at = (select max(created_at) from feed_items)" )[0].created_at.pretty %>
</div>
</body>
</html>
\ No newline at end of file
diff --git a/app/views/shared/_participate.html.erb b/app/views/shared/_participate.html.erb
new file mode 100644
index 0000000..97c7310
--- /dev/null
+++ b/app/views/shared/_participate.html.erb
@@ -0,0 +1,104 @@
+<%= render :partial => 'shared/show_comments', :locals => { :comments => item.comments }%>
+<div class="addComment">
+ <h3>
+ <a href="javascript:tpf.hideShowCommentSection()">
+ Add a Comment <img src="/images/expand.png" width="14" height="14">
+ </a>
+ |
+ <a href="javascript:tpf.hideShowEmailAFriendSection()">
+ Email A Friend <img src="/images/expand.png" width="14" height="14">
+ </a>
+ </h3>
+ <div class="body">
+ <% if logged_in? %>
+ <div style="display: none;" id="commentSection">
+ <% form_for :comment, @comment, :url => post_location do |f| %>
+ <%= f.error_messages %>
+ <%= hidden_field_tag 'commented_item_id', item.id%>
+ <table>
+ <tr>
+ <td class="label">
+ name:
+ </td>
+ <td>
+ <%= f.text_field :name %>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ email:
+ </td>
+ <td>
+ <%= f.text_field :email %>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ title:
+ </td>
+ <td>
+ <%= f.text_field :title %>
+ </td>
+ </tr>
+ <tr>
+ <td class="label">
+ comment:
+ </td>
+ <td>
+ <%= f.text_area :comment, :size => "30x7" %>
+ </td>
+ </tr>
+ <tr>
+ <td colspan="2" class="submit">
+ <%= image_submit_tag 'add_comment.png'%>
+ </td>
+ </tr>
+ </table>
+ <% end %>
+ </div>
+ <div style="display: none;" id="emailAFriendSection">
+ <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
+ <table>
+ <tr>
+ <td class="label">Friend's Email:</td>
+ <td><%= f.text_field :recipient_email_address %></td>
+ </tr>
+ <tr>
+ <td class="label">Your Email:</td>
+ <td><%= f.text_field :sender_email_address %></td>
+ </tr>
+ <tr>
+ <td class="label">URL:</td>
+ <td><%= f.text_field :url, :readonly => true %></td>
+ </tr>
+ <tr>
+ <td class="label">Subject:</td>
+ <td><%= f.text_field :title %></td>
+ </tr>
+ <tr>
+ <td class="label">Message:</td>
+ <td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
+ </tr>
+ <tr>
+ <td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
+ </tr>
+ </table>
+ <% end %>
+ </div>
+ <% else %>
+ <div class="loginInstruction">Please login to use this functionality.</div>
+ <div class="miniLoginBox">
+ <% form_tag session_path do -%>
+ <p><label for="login">Login</label>
+ <%= text_field_tag 'login' %></p>
+
+ <p><label for="password">Password</label>
+ <%= password_field_tag 'password' %></p>
+
+
+ <p><%= submit_tag 'Log in' %></p>
+ <% end -%>
+ </div>
+ <% end %>
+ </div>
+</div>
\ No newline at end of file
diff --git a/app/views/shared/error404.html.erb b/app/views/shared/error404.html.erb
index 57db2e9..dd9a515 100644
--- a/app/views/shared/error404.html.erb
+++ b/app/views/shared/error404.html.erb
@@ -1 +1 @@
-404
\ No newline at end of file
+The page you are looking for does not exist.
\ No newline at end of file
diff --git a/app/views/shared/error500.html.erb b/app/views/shared/error500.html.erb
index eb1f494..28b8059 100644
--- a/app/views/shared/error500.html.erb
+++ b/app/views/shared/error500.html.erb
@@ -1 +1 @@
-500
\ No newline at end of file
+Something went wrong. Sorry.
\ No newline at end of file
diff --git a/app/views/static_pages/advertise.html.erb b/app/views/static_pages/advertise.html.erb
deleted file mode 100644
index 250f0df..0000000
--- a/app/views/static_pages/advertise.html.erb
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class="advertise">
- <%= page_title 'Advertise With Us' %>
-
- thepeoplesfeed.com offers many advertising options that will help you reach your advertising goal. Customers can target their advertising to consumer's who are exploring topics similar to your business. Please email <a href="mailto:[email protected]">the webmaster</a> for more information.
-
-</div>
\ No newline at end of file
diff --git a/app/views/static_pages/sitemap.html.erb b/app/views/static_pages/sitemap.html.erb
index 531fc07..da724c3 100644
--- a/app/views/static_pages/sitemap.html.erb
+++ b/app/views/static_pages/sitemap.html.erb
@@ -1,33 +1,32 @@
<div class="siteMap">
<%= page_title "Sitemap - the map to The People's Feed" %>
<h2>Contribute</h2>
<ul>
<li><%= link_to 'Information About Contributing', '/contribute'%></li>
<li><%= link_to 'Open Source Information', '/open-source'%></li>
<li><%= link_to 'Email Updates', '/email_subscriptions/new' %></li>
</ul>
<h2>Use</h2>
<ul>
<li><%= link_to 'The most popular news articles', '/'%></li>
<li><%= link_to 'Categories - Complete list', :controller => 'category', :action => 'index'%></li>
<li><%= link_to 'RSS feeds we consume', :controller => 'feed', :action => 'index' %></li>
<li><%= link_to 'Recent pictures', :controller => 'feed_item', :action => 'media' %></li>
<li><%= link_to 'See all user comments', :controller => 'comment' %></li>
<li><%= link_to 'Privacy policy', '/privacy-policy' %></li>
</ul>
<h2>Promote</h2>
<ul>
<li><%= link_to 'Add your feed to our feeds', :controller=> 'feed', :action => 'new' %></li>
- <li><%= link_to 'Advertise on TPF', '/advertise' %></li>
</ul>
<br />
<br />
<h2>Service, Technologies, and Friends</h2>
<p>The following is a short list of technologies and services that The People's Feed uses. Feel free to visit them</p>
<ul>
<li><a href="http://www.blogoculars.com/link/the-peoples-feed">Blogoculars Blog Directory</a></li>
</ul>
</div>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index dffd2ff..e0fd1b0 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,87 +1,86 @@
ActionController::Routing::Routes.draw do |map|
map.resources :models
# The priority is based upon order of creation: first created -> highest priority.
# Sample of regular route:
# map.connect 'products/:id', :controller => 'catalog', :action => 'view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# map.resources :products
# Sample resource route with options:
# map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
# Sample resource route with sub-resources:
# map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
# Sample resource route with more complex sub-resources
# map.resources :products do |products|
# products.resources :comments
# products.resources :sales, :collection => { :recent => :get }
# end
# Sample resource route within a namespace:
# map.namespace :admin do |admin|
# # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
# admin.resources :products
# end
# You can have the root of your site routed with map.root -- just remember to delete public/index.html.
# map.root :controller => "welcome"
# See how all your routes lay out with "rake routes"
# Install the default routes as the lowest priority.
# Note: These default routes make all actions in every controller accessible via GET requests. You should
# consider removing the them or commenting them out if you're using named routes and resources.
map.resource :user_preference
map.resource :session
map.resources :users, :collection => { :login_submit => :post }
map.connect 'login', :controller => 'users', :action => 'login'
map.connect 'logout', :controller => 'users', :action => 'logout'
map.resources :feed
map.resources :feed_comment
map.connect 'feed_item/media', :controller => 'feed_item', :action => 'media'
map.resources :feed_item
map.resources :feed_item_category
map.resources :category
map.resources :category_comment
map.resources :homepage
map.resources :feed_item_comment
map.resources :category_organizer
map.resources :comments
map.resources :blog_posts
map.resources :email_subscriptions
map.resources :email_a_friend_messages
map.connect 'blog', :controller => 'blog_posts'
map.connect 'blog.xml', :controller => 'blog_posts', :format => 'xml'
map.connect 'privacy-policy', :controller => 'static_pages', :action => 'privacy_policy'
map.connect 'sitemap', :controller => 'static_pages', :action => 'sitemap'
map.connect 'contact-us', :controller => 'static_pages', :action => 'contact_us'
- map.connect 'advertise', :controller => 'static_pages', :action => 'advertise'
map.connect 'contribute', :controller => 'static_pages', :action => 'contribute'
map.connect 'how-it-works', :controller => 'static_pages', :action => 'how_it_works'
map.connect 'search', :controller => 'static_pages', :action => 'search'
map.connect 'open-source', :controller => 'static_pages', :action => 'open_source'
map.connect 'sitemap.xml', :controller => 'sitemap', :action => 'index'
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.homepage '', :controller => 'homepage'
map.connect 'update', :controller => 'feed', :action => 'update'
map.root :controller => "homepage"
map.connect '*', :controller => 'application', :action => 'rescue_404'
end
diff --git a/lib/email_validation_helper.rb b/lib/email_validation_helper.rb
index ec6b8cb..75ecedf 100644
--- a/lib/email_validation_helper.rb
+++ b/lib/email_validation_helper.rb
@@ -1,52 +1,52 @@
# Module that can be included for some extra email validation functions
require 'resolv'
module EmailValidationHelper
# A constant regex for the desired email address.
EMAIL_ADDRESS_FORMAT = begin
qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]'
dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]'
atom = '[^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-' +
'\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+'
quoted_pair = '\\x5c[\\x00-\\x7f]'
domain_literal = "\\x5b(?:#{dtext}|#{quoted_pair})*\\x5d"
quoted_string = "\\x22(?:#{qtext}|#{quoted_pair})*\\x22"
domain_ref = atom
sub_domain = "(?:#{domain_ref}|#{domain_literal})"
word = "(?:#{atom}|#{quoted_string})"
domain = "#{sub_domain}(?:\\x2e#{sub_domain})*"
local_part = "#{word}(?:\\x2e#{word})*"
addr_spec = "#{local_part}\\x40#{domain}"
pattern = /\A#{addr_spec}\z/
end
# Performs email validation. Returns an array of issues with the email
def self.validate_email(email, email_field_name = 'email')
errors = []
if !(email)
errors << "Please enter your #{email_field_name} address."
elsif !(EMAIL_ADDRESS_FORMAT =~ email)
errors << "Please check the format of your #{email_field_name} address."
elsif !domain_exists?(email)
errors << "The #{email_field_name} address does not appear to be valid."
end
errors
end
private
def self.domain_exists?(email)
result = email.match(/\@(.+)/)
return if result.nil?
domain = result[1]
Resolv::DNS.open do |dns|
- @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
+ mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
end
- @mx.size > 0 ? true : false
+ mx.size > 0 ? true : false
end
end
\ No newline at end of file
diff --git a/public/images/expand.png b/public/images/expand.png
new file mode 100644
index 0000000..9d37f85
Binary files /dev/null and b/public/images/expand.png differ
diff --git a/public/images/expand.psd b/public/images/expand.psd
new file mode 100644
index 0000000..e0ea7a8
Binary files /dev/null and b/public/images/expand.psd differ
diff --git a/public/javascripts/main.js b/public/javascripts/main.js
index b5354b6..94f71a5 100644
--- a/public/javascripts/main.js
+++ b/public/javascripts/main.js
@@ -1,34 +1,54 @@
// Logic that needs to be performed when the page loads.
jQuery(document).ready(function() {
jQuery(".tooltip").tooltip({showURL: false, fade: 250, track: true });
// Ajax submit methods
jQuery(".deleteComment").linkWithAjax();
});
+// Define the variable tpf if it isn't defined
+if (typeof tpf == 'undefined') {
+ tpf = {}
+}
+
+// Hide show the comments section of the participate block.
+tpf.hideShowCommentSection = function() {
+ hiddenElements = jQuery('#commentSection:hidden');
+ jQuery('#commentSection:visible').hide();
+ jQuery('#emailAFriendSection').hide();
+ hiddenElements.show();
+}
+
+// Hide show the email a friend section of the participate block
+tpf.hideShowEmailAFriendSection = function() {
+ hiddenElements = jQuery('#emailAFriendSection:hidden');
+ jQuery('#emailAFriendSection:visible').hide();
+ jQuery('#commentSection').hide();
+ hiddenElements.show();
+}
+
// Ensure that jQuery sends all javascript files with a text/javascript header
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
});
-// Hide the flash messages after 5 seconds
+// Hide the flash messages after 6 seconds
setTimeout("jQuery('.flashes').slideUp('slow')", 6000);
-
// jQuery function extension that will allow you to submit a form using ajax.
jQuery.fn.submitWithAjax = function() {
this.submit(function() {
jQuery.post(this.action, jQuery(this).serialize(), null, "script");
return false;
})
return this;
};
// jQuery function extension that will allow you to click a link with ajax.
jQuery.fn.linkWithAjax = function() {
jQuery(this).click(function() {
jQuery.get(jQuery(this).attr('href'), null, null, "script");
return false;
});
return this;
};
|
jenglert/The-Peoples--Feed
|
e980a855fb1059e95c92d2b9fb0f3aeb1e94bc40
|
Adding stupid image back.
|
diff --git a/public/images/background.jpg b/public/images/background.jpg
new file mode 100644
index 0000000..901f19a
Binary files /dev/null and b/public/images/background.jpg differ
|
jenglert/The-Peoples--Feed
|
f7b9c8b343729571085e5e5fdbef935b03d613c2
|
Updating background
|
diff --git a/public/images/background.psd b/public/images/background.psd
index dfb3fce..7743edc 100644
Binary files a/public/images/background.psd and b/public/images/background.psd differ
|
jenglert/The-Peoples--Feed
|
f45bdd1dc14e608c05a44f0aa46fe48de41c2dd7
|
Updating files.
|
diff --git a/app/views/feed_item/show.html.erb b/app/views/feed_item/show.html.erb
index bc1c283..3ba77a1 100644
--- a/app/views/feed_item/show.html.erb
+++ b/app/views/feed_item/show.html.erb
@@ -1,156 +1,109 @@
<% meta_description @feed_item.description.fix_html %>
<div class="feedItemShow">
<div class="sectionHeading">
- <%= page_title @feed_item.title%>
+ <%= page_title @feed_item.title %>
</div>
<table class="feedItemInfo">
<tr>
<td class="categories">
<span class="heading">Categories</span>
<ul>
<% @feed_item.categories.each { |category| %>
<li><%= link_to category.name, category %></li>
<% } %>
</ul>
</td>
<td class="description" rowspan="2" colspan="3">
<div class="fullArticle">
<%= link_to 'Read the Full Article',@feed_item.item_url %>
</div>
<div>
<%= image_tag @feed_item.image_url if @feed_item.image_url%>
</div>
<span class="heading">Description: </span></b><%= h(@feed_item.description.fix_html) %>
</td>
</tr>
<tr>
<td>
<span class="heading">Rating</span>
<table class="rating">
<tr>
<td>
Recency Mult.
</td>
<td>
<%= sprintf('%.2f%', @feed_item.time_multiplier * 100) %>
</td>
</tr>
<tr>
<td>
Clicks Pts.
</td>
<td>
<%= @feed_item.clicks_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Description Pts.
</td>
<td>
<%= @feed_item.description_points.to_s %>
</td>
</tr>
<tr>
<td>
Image Pts.
</td>
<td>
<%= @feed_item.image_points.to_s %>
</td>
</tr>
<tr>
<td>
Comments Pts.
</td>
<td>
<%= @feed_item.comments_points.to_s %>
</td>
</tr>
<tr>
<td>
Category Pts.
</td>
<td>
<%= @feed_item.category_points.to_s %>
</td>
</tr>
<tr>
<td colspan="2" class="total">
Total: <%= sprintf('%.1f', @feed_item.rating) %>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<%= link_to @feed_item.feed.title, @feed_item.feed%>
</td>
<td>
<span class="heading">Published:</span> <%= @feed_item.created_at.pretty %>
</td>
<td>
</td>
</tr>
</table>
- <div class="emailAFriend collapseable">
- <h3>Email a Friend</h3>
- <div class="body to_collapse">
- <% if logged_in? %>
- <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
- <table>
- <tr>
- <td class="label">Friend's Email:</td>
- <td><%= f.text_field :recipient_email_address %></td>
- </tr>
- <tr>
- <td class="label">Your Email:</td>
- <td><%= f.text_field :sender_email_address %></td>
- </tr>
- <tr>
- <td class="label">URL:</td>
- <td><%= f.text_field :url, :readonly => true %></td>
- </tr>
- <tr>
- <td class="label">Subject:</td>
- <td><%= f.text_field :title %></td>
- </tr>
- <tr>
- <td class="label">Message:</td>
- <td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
- </tr>
- <tr>
- <td colspan="2"><%= submit_tag 'Email A Friend' %></td>
- </tr>
- </table>
- <% end %>
- <% else %>
- Please login to use this functionality.
- <div class="miniLoginBox">
- <% form_tag session_path do -%>
- <p><label for="login">Login</label>
- <%= text_field_tag 'login' %></p>
-
- <p><label for="password">Password</label>
- <%= password_field_tag 'password' %></p>
-
-
- <p><%= submit_tag 'Log in' %></p>
- <% end -%>
- </div>
- <% end %>
- </div>
- </div>
+ <%= render :partial => 'shared/email_a_friend'%>
<%= render :partial => 'shared/show_comments', :locals => { :comments => @feed_item.comments } %>
<%= render :partial => 'shared/create_comment', :locals => { :post_location => '/feed_item_comment', :commented_item => @feed_item }%>
</div>
\ No newline at end of file
diff --git a/app/views/shared/_create_comment.html.erb b/app/views/shared/_create_comment.html.erb
index d8e2474..7c452c9 100644
--- a/app/views/shared/_create_comment.html.erb
+++ b/app/views/shared/_create_comment.html.erb
@@ -1,64 +1,64 @@
<div class="addComment">
- <h3>Create a Comment</h3>
+ <h3>Add a Comment</h3>
<div class="body">
<% if logged_in? %>
<% form_for :comment, @comment, :url => post_location do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'commented_item_id', commented_item.id%>
<table>
<tr>
<td class="label">
name:
</td>
<td>
<%= f.text_field :name %>
</td>
</tr>
<tr>
<td class="label">
email:
</td>
<td>
<%= f.text_field :email %>
</td>
</tr>
<tr>
<td class="label">
title:
</td>
<td>
<%= f.text_field :title %>
</td>
</tr>
<tr>
<td class="label">
comment:
</td>
<td>
<%= f.text_area :comment, :size => "30x7" %>
</td>
</tr>
<tr>
<td colspan="2" class="submit">
<%= image_submit_tag 'add_comment.png'%>
</td>
</tr>
</table>
<% end %>
<% else %>
<div class="loginInstruction">Please login to use this functionality.</div>
<div class="miniLoginBox">
<% form_tag session_path do -%>
<p><label for="login">Login</label>
<%= text_field_tag 'login' %></p>
<p><label for="password">Password</label>
<%= password_field_tag 'password' %></p>
<p><%= submit_tag 'Log in' %></p>
<% end -%>
</div>
<% end %>
</div>
</div>
diff --git a/app/views/shared/_email_a_friend.html.erb b/app/views/shared/_email_a_friend.html.erb
new file mode 100644
index 0000000..6f241ba
--- /dev/null
+++ b/app/views/shared/_email_a_friend.html.erb
@@ -0,0 +1,48 @@
+<div class="emailAFriend collapseable">
+ <h3>Email a Friend</h3>
+ <div class="body to_collapse">
+ <% if logged_in? %>
+ <% form_for EmailAFriendMessage.new(:url => "http://#{request.host}:#{request.port if request.port != 80}#{request.path}") do |f| %>
+ <table>
+ <tr>
+ <td class="label">Friend's Email:</td>
+ <td><%= f.text_field :recipient_email_address %></td>
+ </tr>
+ <tr>
+ <td class="label">Your Email:</td>
+ <td><%= f.text_field :sender_email_address %></td>
+ </tr>
+ <tr>
+ <td class="label">URL:</td>
+ <td><%= f.text_field :url, :readonly => true %></td>
+ </tr>
+ <tr>
+ <td class="label">Subject:</td>
+ <td><%= f.text_field :title %></td>
+ </tr>
+ <tr>
+ <td class="label">Message:</td>
+ <td><%= f.text_area :message, :cols => 25, :rows => 10 %></td>
+ </tr>
+ <tr>
+ <td colspan="2" class="submit"><%= image_submit_tag 'email_a_friend.png'%></td>
+ </tr>
+ </table>
+ <% end %>
+ <% else %>
+ Please login to use this functionality.
+ <div class="miniLoginBox">
+ <% form_tag session_path do -%>
+ <p><label for="login">Login</label>
+ <%= text_field_tag 'login' %></p>
+
+ <p><label for="password">Password</label>
+ <%= password_field_tag 'password' %></p>
+
+
+ <p><%= submit_tag 'Log in' %></p>
+ <% end -%>
+ </div>
+ <% end %>
+ </div>
+</div>
\ No newline at end of file
diff --git a/public/images/add_comment.png b/public/images/add_comment.png
index c2705eb..47c46cb 100644
Binary files a/public/images/add_comment.png and b/public/images/add_comment.png differ
diff --git a/public/images/add_comment.psd b/public/images/add_comment.psd
index 37419e2..466fc53 100644
Binary files a/public/images/add_comment.psd and b/public/images/add_comment.psd differ
diff --git a/public/images/email_a_friend.png b/public/images/email_a_friend.png
new file mode 100644
index 0000000..eaba43d
Binary files /dev/null and b/public/images/email_a_friend.png differ
diff --git a/public/images/email_a_friend.psd b/public/images/email_a_friend.psd
new file mode 100644
index 0000000..ef1faf9
Binary files /dev/null and b/public/images/email_a_friend.psd differ
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index dd1274c..93eebc0 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,216 +1,218 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #CCF; color: #DF6900;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
-.emailAFriend TD { text-align: left; }
-.emailAFriend .body .label { color: #DF6900; text-align: right; }
+.emailAFriend TD { text-align: left; }
+.emailAFriend .body .label { color: #DF6900; text-align: right; }
+.emailAFriend .submit { text-align: right; }
+.emailAFriend .submit INPUT{ height: 24px; width: 126px; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
|
jenglert/The-Peoples--Feed
|
a9d2cc127762ffa3c30a81824940fe2c74c190d6
|
Lightening menu text.
|
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 95c80a2..dd1274c 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,216 +1,216 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
.header .search { position: absolute; left: 682px; top: 70px;}
.smallMenu { position: absolute; left: 520px; font-size: 16px; }
.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
-moz-border-radius: 5px; -webkit-border-radius: 5px; }
.body { margin: auto; width: 950px; }
.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
- background-color: #3D3DC3; color: #DF6900;}
+ background-color: #CCF; color: #DF6900;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
|
jenglert/The-Peoples--Feed
|
ed0a769822c87c60179ee65273cdd45a2676d42e
|
Increasing the width of the website overall. Lightening some colors to improve readability.
|
diff --git a/public/images/background.jpg b/public/images/background.jpg
index 09f2e4c..901f19a 100644
Binary files a/public/images/background.jpg and b/public/images/background.jpg differ
diff --git a/public/images/background.psd b/public/images/background.psd
index c1a2df7..dfb3fce 100644
Binary files a/public/images/background.psd and b/public/images/background.psd differ
diff --git a/public/stylesheets/main.css b/public/stylesheets/main.css
index 882b079..95c80a2 100644
--- a/public/stylesheets/main.css
+++ b/public/stylesheets/main.css
@@ -1,217 +1,216 @@
/* Global styles */
* { margin: 0px; padding: 0px; outline: none; font-family: Arial; }
-BODY { background: url("/images/background.jpg") #DCDCDC 0% 0% repeat-x scroll;}
+BODY { background: url("/images/background.jpg") #DDD 0% 0% repeat-x scroll;}
A IMG { border: 0px; }
A:link { color: #DF6900; text-decoration: none; }
A:visited { color: #DF6900; text-decoration: none; }
.sectionHeading { text-align: center; }
.clearBoth { clear:both; }
H1 { padding-bottom: 5px; }
+INPUT { -moz-border-radius: 5px; -webkit-border-radius: 5px; }
.pagination { padding-top: 8px; padding-right: 20px; text-align: right; }
.pagination A { font-size: 16px; }
.pagination A:visited { font-size: 16px; }
.fieldWithErrors { display:inline; }
-.whiteBackground { background-color: #EFEFEF; border: 1px solid white; }
+.whiteBackground { background-color: #FFF; border: 1px solid white; }
.lastUpdated { font-size: 8px; }
.flashes { margin: auto; }
.flashes .error { background-color: red; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px; }
.flashes .notice { background-color: #00FF99; margin-left: 100px; margin-right: 100px; padding: 10px; margin-bottom: 10px;}
/* Global tooltip CSS */
#tooltip { position: absolute; z-index: 3000; border: 1px solid #111; background-color: #eee; padding: 4px; opacity: 0.85; }
#tooltip h3, #tooltip div { margin: 0; font-size: 15px; width: 400px;}
/* Layout styles */
-.header { margin: auto; width: 830px; height: 120px; position:relative; }
+.header { margin: auto; width: 950px; height: 120px; position:relative; }
.header IMG.logo { position: absolute; left: 19px; }
.header .motto { position: absolute; left: 75px; top: 80px; color: white; font-size: 13px; }
-.header .menu { position: absolute; left: 525px; top: 29px;}
+.header .menu { position: absolute; left: 645px; top: 29px;}
.header .menu IMG { margin-left: -4px; }
-.header .search { position: absolute; left: 562px; top: 70px;}
-.body { margin: auto; width: 900px; }
-.footer { margin: auto; width: 900px; height: 75px; border-top: 1px gray solid;
+.header .search { position: absolute; left: 682px; top: 70px;}
+.smallMenu { position: absolute; left: 520px; font-size: 16px; }
+.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
+ padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
+ -moz-border-radius: 5px; -webkit-border-radius: 5px; }
+.body { margin: auto; width: 950px; }
+.footer { margin: auto; width: 950px; height: 75px; border-top: 1px gray solid;
margin-top: 20px; padding-top: 5px; text-align: center; font-size: 13px; }
.footer A { font-size: 13px; }
.footer A:VISITED { font-size: 13px; }
.centerColumn, .rightHandList { vertical-align: top; text-align: center; float:left; }
-.centerColumn { width: 690px; padding-top: 10px; padding-right: 10px; }
+.centerColumn { width: 740px; padding-top: 10px; padding-right: 10px; }
.rightHandList { width: 175px; }
.rightHandList H3 { padding: 3px 0px; margin-top: 10px; margin-bottom: 5px;
background-color: #3D3DC3; color: #DF6900;}
/* Error Styling */
.errorExplanation { border: 4px red solid; background-color: #F44; margin: 0px 25px;}
/* Feed item listing (WIDE)*/
DIV.feedItemWide { text-align: left; margin: 5px 10px 10px 7px;
padding: 5px 7px 5px 7px; }
.feedItemWide H4 { float:left; font-size: 17px; }
.feedItemWide .feedItemCreated { padding-left: 15px; text-align: right; }
.feedItemWide .description { clear: both; padding-left: 5px; }
.feedItemWide .description .source { font-size: 13px; padding-left: 5px; }
.feedItemWide .description .comment{ font-size: 13px; padding-left: 5px; }
.feedWide { padding-bottom: 10px; }
/* Feed item show page. */
.feedItemShow .leftColumn { width: 150px; }
.feedItemShow .description { padding: 10px 15px 10px 15px; vertical-align: top; }
.feedItemShow .description .fullArticle { padding-bottom: 25px; font-size: 24px; }
.feedItemShow .heading { color: #3D3DC3; font-weight: bold; font-size: 19px; }
.feedItemShow .categories UL { text-align:left; padding-left: 20px; }
.feedItemShow .categories LI A { font-size: 14px; }
.feedItemShow TABLE.feedItemInfo { width: 85%; margin: auto; }
.feedItemShow .feedItemInfo TD { border: 1px solid gray; padding: 1px; }
.feedItemShow TABLE.rating TD { border: 0px; font-size: 12px; text-align: left; }
.feedItemShow TABLE.rating .total { border-top: 4px black double; text-align: center; }
/* Feed show page */
.feedShow .feedInfo { padding: 10px 0px; }
.feedShow .title IMG { padding-top: 2px; }
.feedShow TABLE.feedInfo { width: 95%; margin: auto; }
.feedShow TABLE.feedInfo .leftColumn { width: 125px; }
.feedShow .whatIsThis { font-size: 11px; }
.feedShow .feedInfo TD { border: 1px solid gray; padding: 1px; }
.feedShow UL { text-align:left; padding-left: 30px; }
.feedShow H2 { padding-top: 30px; }
/* Feed index */
.feedIndex H1 { padding-bottom: 10px;}
.feedIndex UL { text-align: left; padding-left: 25px; }
.feedIndex .addAFeed { text-align: right; padding-top: 20px; padding-right: 30px;}
/* Category view */
.categoryShow .feedItems UL { list-style-type: none;}
.categoryShow .feedItems LI { padding-bottom: 4px;}
/* Creating a comment */
.addComment { text-align: left; background-color: #3D3DC3; width: 370px; margin: auto; margin-top: 30px;}
.addComment .label { text-align: right; font-variant: small-caps; color: #DF6900; font-weight:bold; }
.addComment H3 { text-align: center; color: #FFF; background-color: #DFAB7D; padding: 5px 0; border: 3px solid #DF6900;}
.addComment INPUT, .addComment TEXTAREA { margin: 1px 0px;}
.addComment .submit { text-align: right; }
.addComment .submit INPUT { height: 24px; width: 126px;}
.addComment .body { border: 3px solid #3D3DC3; background-color: #7F80FF; width: 364px; }
.addComment .loginInstruction { text-align: center; padding-top: 5px; }
/* Comment Listing */
.showComments { width: 75%; margin: auto; text-align: left; border: 1px solid #000; margin-top: 20px; }
.showComments H3 { text-align: center; color: #FFF; background-color: #DF6900; padding: 5px 0px; }
.showComments .heading { font-variant: small-caps; font-size: 12px; border-top: 1px solid #000; }
.showComments .heading .title { font-size: 20px; font-weight: bold; color: #DF6900; }
.showComments .comment { padding: 0px; background-color: #DF6900; padding: 15px 140px 15px 15px;
border-bottom: 1px solid #000;
background: #DF6900 url('/images/comment_right.gif') right repeat-y; }
.showComments .left { float: left; padding-top: 3px; padding-left: 10px; }
.showComments .right { float: right; background-color: #3D3DC3; padding:8px; color: #FFF; font-weight: bold; width: 104px;
text-align: right;}
.showComments .spacer { height: 5px; background-color: #000;}
/* Add a feed */
.addFeed { background-color: #DF6900; padding: 30px 30px 30px 30px; width: 60%; margin: auto; margin-top: 5px;}
.addFeed P { padding-bottom: 10px;}
/* User signup table */
TABLE.userSignup { margin: auto; margin-top: 10px;}
TABLE.userSignup .rightAlign { text-align: right; }
/* Widgets */
.feedNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed;}
.feedNarrow .noLine { border-bottom: none; }
.categoryNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.categoryNarrow .noLine { border-bottom: none; }
.mediaNarrow H4 { margin-bottom: 4px; padding-bottom: 4px; border-bottom: 2px #3D3DC3 dashed; }
.mediaNarrow .noLine { border-bottom: none; }
/* Category index page */
.categoryIndex { text-align : left; padding-left: 40px; }
/* Join us page */
.joinUs { padding: 0px 10px 10px 10px; text-align: left; }
.joinUs H1 { text-align: center; }
.joinUs UL { padding-left: 45px; padding-bottom: 15px; }
.joinUs H2 { padding-bottom: 3px; padding-left: 25px; }
.joinUs H3 { padding-bottom: 3px; padding-left: 25px; }
.joinUs DIV.whiteBackground { margin: 0px 10px 15px 10px; padding: 3px; }
.joinUs P { padding-left: 35px; padding-right: 20px; }
.joinUs .emailSubscription { padding-left: 50px; padding-top: 16px; }
/* How it all works */
.howItAllWorks { text-align: left; padding: 0px 10px 10px 10px; margin: 0px 10px 10px 10px; }
.howItAllWorks P { padding: 10px; }
/* Media view page */
.feedItemMedia TABLE TD { padding: 5px; }
-
-/* Top small menu */
-.smallMenu { position: absolute; left: 400px; font-size: 16px; }
-.smallMenu LI { display: inline; margin-right: 2px; background: #EFEFEF;
- padding: 2px 2px 1px 2px; border: 2px solid #3D3DC3;
- -moz-border-radius: 5px; -webkit-border-radius: 5px; }
/* Sitemap */
.siteMap { text-align: left; }
.siteMap H2 { padding-left: 20px; }
.siteMap UL { padding-left: 45px; padding-bottom: 10px; }
/* Search Results */
.searchResults { width: 800px; margin-top: 15px;}
/* Blog Posts */
.blogPosts H1 { padding-bottom: 15px; }
.blogPost { text-align: left; margin-left: 10px; margin-right: 10px;
margin-bottom: 15px; }
.blogPost H1 { padding-left: 10px; padding-bottom: 0px; }
.blogPost .byline { font-size: 11px; padding-left: 20px; }
.blogPost .post { padding: 10px; margin: 5px 15px 15px 15px; }
.blogPost UL { padding: 10px 10px 10px 10px; }
.blogPost OL { padding: 10px 10px 10px 10px; }
.blogPost PRE { background: #DDD; border: 1px #BBB solid; padding-left: 15px; }
.blogPosts .rssLinks { text-align: right; padding-right: 11px; }
.blogPosts .rssLinks IMG { vertical-align: text-bottom; }
/* Open source info page */
.openSource { margin: 0px 15px 15px 15px; text-align: left;
padding: 8px 8px 8px 15px; }
.openSource P { padding-bottom: 15px; }
/* Add a feed */
.addFeedGuidlines { text-align: left; padding: 8px; margin: 5px 5px 10px 5px; }
.addFeedGuidlines P { padding-bottom: 10px; }
.addFeedGuidlines H1 { padding-bottom: 10px; }
.addFeedGuidlines DT { padding-left: 8px; font-size: 16px; }
.addFeedGuidlines DL { padding-left: 20px; font-size: 13px; padding-bottom: 5px;}
/* Email Subscription Join */
.emailSubscription { margin: 0px 10px 10px 10px; padding-bottom: 15px; padding-left: 10px; padding-right: 10px; }
.emailSubscription P { padding-bottom: 20px; }
.emailSubscription .errorExplanation { margin: 15px 15px; }
.emailSubscriptionSuccess { margin: 0px 10px 10px 10px; padding-bottom: 15px; }
/* Comments list */
.commentsList .commentBody { text-align: left; padding-left: 40px; }
.commentsList .comment { padding-bottom : 5px; margin: 10px 50px 10px 50px; padding-top: 5px; }
.commentsList .comment .title{ float: left; padding-left: 25px; padding-bottom: 10px; }
.commentsList .comment .date { float: right; padding-right: 10px; }
/* User Preferences Setup */
.userPreferences TABLE { margin: auto;}
.userPreferences TD { text-align: left; padding: 1px 10px 2px 10px; }
.userPreferences TD.label { text-align: right; }
.userPreferences TD.update { text-align: center; }
/* Email A Friend Page */
.emailAFriendForm TABLE { margin: auto; }
.emailAFriendForm TABLE TD { padding: 1px; }
/* Widget */
.emailAFriend { width: 370px; margin: auto; padding-top: 5px; }
.emailAFriend H3 { background-color: #DFAB7D; border: 3px solid #DF6900; color: #FFF; padding: 5px 0; text-align: center; }
.emailAFriend .body { background-color: #7F80FF; border: 3px solid #3D3DC3; width: 364px; padding: 5px 0 0 0; }
.emailAFriend TD { text-align: left; }
.emailAFriend .body .label { color: #DF6900; text-align: right; }
/* Mini login box */
.miniLoginBox { margin: auto; padding: 5px 75px 5px 5px; text-align: right; }
|
jtietema/Fizzy
|
6915cf76e4c00af2a5705fb8ac61a8241e8c063e
|
remove expired personal Akismet API key
|
diff --git a/configs/application.ini b/configs/application.ini
index 953ca76..36f7d3c 100644
--- a/configs/application.ini
+++ b/configs/application.ini
@@ -1,44 +1,44 @@
[production]
bootstrap.path = APPLICATION_PATH "/Bootstrap.php"
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.moduleControllerDirectoryName = "controllers"
resources.session.save_path = "/tmp"
autoloaderNamespaces.fizzy = "Fizzy_"
autoloaderNamespaces.zendl = "ZendL_"
pluginPaths.Fizzy_Resource = APPLICATION_PATH "/../library/Fizzy/Resource/"
phpSettings.display_startup_errors = 0
phpSettings.display_errors = 0
title = "Fizzy"
pages.defaultTemplate = "page.phtml"
pages.defaultLayout = "default"
paths.templatePath = APPLICATION_PATH "/modules/default/views/templates"
paths.layoutPath = APPLICATION_PATH "/modules/default/views/layouts"
backendSwitch = "fizzy"
contact.email = "[email protected]"
; Doctrine resources
resources.doctrine.manager.attributes.attr_model_loading = model_loading_conservative
resources.doctrine.connections.default.dsn = "mysql://root@localhost/fizzy"
resources.doctrine.paths.models_path = APPLICATION_PATH "/models/"
resources.doctrine.paths.yaml_schema_path = ROOT_PATH "/database/schema/"
resources.doctrine.paths.sql_path = ROOT_PATH "/database/sql/"
resources.doctrine.paths.migrations_path = ROOT_PATH "/database/migrations/"
resources.doctrine.paths.data_fixtures_path = ROOT_PATH "/database/fixtures/"
-spam.akismetKey = 6498bcae933b
-spam.siteUrl = http://tietema.net
+spam.akismetKey = 00
+spam.siteUrl = http://example.org
[development : production]
phpSettings.display_startup_errors = 1
phpSettings.display_errors = 1
resources.frontController.throwExceptions = "true"
resources.doctrine.connections.default.dsn = "mysql://root:php-dev@localhost/fizzy"
resources.sabredav.enabled = true
resources.sabredav.browser = true
[test : production]
\ No newline at end of file
|
jtietema/Fizzy
|
c9ae569d449bfac49a3ec7eb745fcb7b0018e21e
|
fixed translation bug
|
diff --git a/library/Fizzy/Controller.php b/library/Fizzy/Controller.php
index d5ad287..87f5091 100644
--- a/library/Fizzy/Controller.php
+++ b/library/Fizzy/Controller.php
@@ -1,142 +1,142 @@
<?php
/**
* Class Fizzy_Controller
* @package Fizzy
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';
/**
* Controller class for Fizzy.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_Controller extends Zend_Controller_Action
{
/**
* Flash messenger helper instance
* @var Zend_View_Helper_FlashMessenger
*/
protected $_flashMessenger = null;
protected $_translate = null;
protected function translate($messageId, $locale = null)
{
- if (null === $this->translate) {
+ if (null === $this->_translate) {
$this->_translate = Zend_Registry::get('Zend_Translate');
}
return $this->_translate->_($messageId, $locale = null);
}
/**
* Disables the view renderer and layout
*/
protected function _disableDisplay()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
}
/**
* Adds a flash message to the session.
* @todo move to controller plugin
* @param string $message
* @param string $type Defaults to 'info'
*/
protected function addMessage($message, $type = 'info')
{
$this->_getFlashMessenger()->addMessage(array(
'message' => $message,
'type' => strtolower($type)
));
}
/**
* Adds a message of type 'info' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addInfoMessage($message)
{
$this->addMessage($message, 'info');
}
/**
* Adds a message of type 'success' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addSuccessMessage($message)
{
$this->addMessage($message, 'success');
}
/**
* Adds a message of type 'warning' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addWarningMessage($message)
{
$this->addMessage($message, 'warning');
}
/**
* Adds a message of type 'error' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addErrorMessage($message)
{
$this->addMessage($message, 'error');
}
/**
* Gets the flash messenger instance for this controller. Initializes the
* helper from the helper broker if no active instance is found.
* @return Zend_View_Helper_FlashMessenger
*/
protected function _getFlashMessenger()
{
if(null === $this->_flashMessenger) {
$this->_flashMessenger = $this->_helper->getHelper('flashMessenger');
}
return $this->_flashMessenger;
}
/**
* Overrides Zend Framework default redirect function to allow redirecting
* to route names. Route names start with an '@'.
* @param string $url the url or route name
* @param array $options the route parameters
*/
protected function _redirect($url, $options = array())
{
if (false !== strpos($url, '@') && 0 === strpos($url, '@')) {
// A routename is specified
$url = trim($url, '@');
$this->_helper->redirector->gotoRoute($options, $url);
}
else {
// Assume an url is passed in
parent::_redirect($url, $options);
}
}
}
|
jtietema/Fizzy
|
82f90c5e91ff98269eaf82376f9e7efc22e29682
|
added default language selection to the login page
|
diff --git a/application/modules/admin/controllers/AuthController.php b/application/modules/admin/controllers/AuthController.php
index 91dd414..a7c2205 100644
--- a/application/modules/admin/controllers/AuthController.php
+++ b/application/modules/admin/controllers/AuthController.php
@@ -1,125 +1,128 @@
<?php
/**
* Class Admin_AuthController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_AuthController extends Fizzy_Controller
{
public function loginAction()
{
$form = $this->_getForm();
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$authAdapter = new Fizzy_Doctrine_AuthAdapter(
$form->username->getValue(), $form->password->getValue()
);
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$result = $auth->authenticate($authAdapter);
if($result->isValid()) {
$this->_redirect('@admin');
}
$messages = $result->getMessages();
$this->addErrorMessage(array_shift($messages));
$this->_redirect('@admin_login');
}
}
$this->view->form = $form;
$this->view->langForm = $this->_getLangForm();
$this->renderScript('login.phtml');
}
public function languageAction()
{
$form = $this->_getLangForm();
if($this->_request->isPost()) {
if ($form->isValid($_POST)){
$session = new Zend_Session_Namespace('Lang');
$session->language = $form->language->getValue();
}
}
$this->_redirect('@login');
}
public function logoutAction()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$auth->clearIdentity();
$this->_redirect('@admin');
}
protected function _getForm()
{
$formConfig = array (
'elements' => array (
'username' => array (
'type' => 'text',
'options' => array (
'label' => 'Username',
'required' => true
)
),
'password' => array (
'type' => 'password',
'options' => array (
'label' => 'Password',
'required' => true
),
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Login',
'ignore' => true
)
)
)
);
return new Fizzy_Form(new Zend_Config($formConfig));
}
protected function _getLangForm()
{
- return new Zend_Form(array(
+ $form = new Zend_Form(array(
'action' => $this->view->url('@admin_login_lang'),
'elements' => array(
'language' => array(
'type' => 'select',
'options' => array(
'label' => 'Language',
'multiOptions' => array(
'nl' => 'Nederlands',
'en' => 'English'
),
'onChange' => 'this.form.submit();'
)
)
)
));
+ $translate = Zend_Registry::get('Zend_Translate');
+ $form->language->setValue($translate->getLocale());
+ return $form;
}
public function postDispatch()
{
$this->_helper->layout->setLayout('login');
}
}
diff --git a/application/modules/admin/views/layouts/default.phtml b/application/modules/admin/views/layouts/default.phtml
index 56bad7d2..ab9c158 100644
--- a/application/modules/admin/views/layouts/default.phtml
+++ b/application/modules/admin/views/layouts/default.phtml
@@ -1,81 +1,81 @@
<?php
/**
* Fizzy layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>Fizzy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy-2.0.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/tables.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/forms.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<?= $this->jQuery()->setVersion('1.4.2')->enable()->addStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css') ?>
<script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/tiny_mce.js'); ?>"></script>
<script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/fizzy.js'); ?>"></script>
</head>
<body>
<div id="container">
<div id="header-panel">
<h1>Fizzy</h1>
<div id="navigation-panel">
<?= $this->action('navigation', 'index', 'admin'); ?>
</div>
</div>
<div id="sub-navigation-panel">
<?= $this->action('subnavigation', 'index', 'admin'); ?>
</div>
<div id="messages-panel">
<?= $this->render('flashMessages.phtml'); ?>
</div>
<div id="main-panel">
<?= $this->layout()->content; ?>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div id="footer-panel">
<div id="copyright-panel">
Fizzy <?= Fizzy_Version::VERSION ?>
<?= $this->translate('running on') ?>
Zend Framework <?= Zend_Version::VERSION ?>
<?= $this->translate('and') ?>
Doctrine <?= Doctrine::VERSION ?>
|
- (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a><br />
+ © 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a><br />
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
diff --git a/application/modules/admin/views/layouts/login.phtml b/application/modules/admin/views/layouts/login.phtml
index a789e7b..7229505 100644
--- a/application/modules/admin/views/layouts/login.phtml
+++ b/application/modules/admin/views/layouts/login.phtml
@@ -1,55 +1,55 @@
<?php
/**
* Fizzy login layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Fizzy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy-2.0.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/tables.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/forms.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<script type="text/javascript" src="<?= $this->baseUrl("/fizzy_assets/js/jquery-1.3.2.min.js"); ?>"></script>
</head>
<body>
<div id="container">
<div id="login-panel">
<h1><?= $this->translate('Fizzy login') ?></h1>
<div id="message-panel">
<?= $this->fizzyMessages(); ?>
</div>
<?= $this->layout()->content; ?>
<div class="clear"></div>
<div id="login-copyright">
- (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a>
+ © 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a>
</div>
</div>
</div>
</body>
</html>
|
jtietema/Fizzy
|
d36b98e2ff8e329d8438cc3b8bb4b29960285dd1
|
added language selection option to the login page
|
diff --git a/application/Bootstrap.php b/application/Bootstrap.php
index 6317300..164ccc8 100644
--- a/application/Bootstrap.php
+++ b/application/Bootstrap.php
@@ -1,143 +1,151 @@
<?php
/**
* Class Bootstrap
* @category Fizzy
* @package Fizzy_Bootstrap
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Description of Bootstrap
*
* @author jeroen
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* Initializes a new view object and loads the view directories into it.
* @return Zend_View
*/
protected function _initView()
{
$view = new Zend_View();
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'Fizzy', 'View', 'Helper')
)), 'Fizzy_View_Helper');
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'ZendX', 'JQuery', 'View', 'Helper')
)), 'ZendX_JQuery_View_Helper');
return $view;
}
/**
* Starts Zend_Layout in MVC mode.
* @todo add custom front controller plugin for layout allow multiple layouts
* @return Zend_Layout
*/
protected function _initLayout()
{
$this->bootstrap('FrontController');
$layout = Zend_Layout::startMvc(array (
'layout' => 'default',
));
$front = $this->getResource('FrontController');
$front->registerPlugin(new Fizzy_Layout_ControllerPlugin());
return $layout;
}
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
return $config;
}
protected function _initRoutes()
{
$this->bootstrap('FrontController');
$options = $this->getOptions();
$backendSwitch = isset($options['backendSwitch']) ? strtolower((string) $options['backendSwitch']) : 'fizzy';
$router = $this->getContainer()->frontcontroller->getRouter();
$config = new Zend_Config_Ini(ROOT_PATH . '/configs/routes.ini');
$routes = $config->{$this->getEnvironment()}->toArray();
// Parse all routes and replace the backend switch
foreach ($routes as &$route) {
if (false !== strpos($route['route'], '{backend}')) {
$route['route'] = str_replace('{backend}', $backendSwitch, $route['route']);
}
}
// Load parsed routes into the router
$router->addConfig(new Zend_Config($routes));
return $router;
}
protected function _initTypes()
{
$config = new ZendL_Config_Yaml(ROOT_PATH . '/configs/types.yml');
$types = Fizzy_Types::initialize($config);
return $types;
}
/**
* @todo make adapter class configurable
*/
protected function _initSpam()
{
$this->bootstrap('Config');
$config = $this->getContainer()->config;
$adapter = new Fizzy_Spam_Adapter_Akismet($config->spam->akismetKey, $config->spam->siteUrl);
Fizzy_Spam::setDefaultAdapter($adapter);
}
protected function _initModuleErrorHandler()
{
$this->bootstrap('FrontController');
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Fizzy_Controller_Plugin_ErrorHandlerModuleSelector());
}
protected function _initTranslate()
{
$translate = new Zend_Translate(
array(
'adapter' => 'array',
'content' => ROOT_PATH . '/languages/admin_nl.php',
'locale' => 'nl'
)
);
+
+ $session = new Zend_Session_Namespace('Lang');
+ if (isset($session->language)){
+ $translate->setLocale($session->language);
+ } else {
+ $session->language = $translate->getLocale();
+ }
+
Zend_Registry::set('Zend_Translate', $translate);
return $translate;
}
}
diff --git a/application/assets/css/fizzy-2.0.css b/application/assets/css/fizzy-2.0.css
index 7f4cfa6..434b6e2 100644
--- a/application/assets/css/fizzy-2.0.css
+++ b/application/assets/css/fizzy-2.0.css
@@ -1,550 +1,556 @@
/**
* Fizzy 2.0 Stylesheet
*
* Scheme: http://colorschemedesigner.com/#3D11TpE--l2br
* Scheme: http://colorschemedesigner.com/#3z21NBR..v5g0
*
* @author Mattijs Hoitink <[email protected]>
*/
/* ********************** */
/* HTML ELEMENTS */
html {
background-color: #F1EFE2;
}
body {
font: 75%/1.2 'Lucida Grande',Arial,Helvetica,sans-serif;
}
em { font-style: italic; }
a {
color: #3581C5;
text-decoration: none;
}
a:hover {
color: #033F75;
text-decoration: underline;
}
h1 { font-size: 150%; }
h2 { font-size: 140%; }
h3 { font-size: 120%; }
h4 { font-size: 110%; }
h5 {}
h6 {}
h1 ,h2, h3, h4, h5, h6, strong {
font-weight:bold;
}
h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
h3 {
margin-bottom: .3em;
padding-bottom: .2em;
border-bottom: 1px solid #E4E4E4;
}
p { margin-bottom: 1em; }
label {
display: block;
margin-bottom: .3em;
font-weight: bold;
}
fieldset {
display: block;
padding: 10px;
border: 1px groove #E4E4E4;
}
legend { color: #918A8A; }
input[type="text"], input[type="password"], input[type="email"], textarea {
width: 300px;
padding: 2px 4px;
border: 1px solid #918A8A;
}
input[type="text"].hasDatepicker {
width: auto;
}
#ui-datepicker-div {
z-index: 1000;
}
/* HTML ELEMENTS */
/* ********************** */
.gray1 {
color: gray;
}
/* ********************** */
/* BUTTONS */
.c3button, a.c3button {
display: inline-block;
padding: 5px 10px;
background: #222 url('../images/button-overlay.png') repeat-x;
-moz-box-shadow: 0 1px 3px 1px rgba(0,0,0,0.2);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px solid rgb(0,0,0,0.25);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
cursor: pointer;
background-color: #EBEBEB;
color: #666666;
}
a.c3button:hover {
text-decoration: none;
}
.c3button.large {
padding: 0.5em 1em;
font-size: 20px;
}
.c3button.orange {
background-color: #FF5C00;
color: #FFFFFF;
}
.c3button.green {
background-color: #20C519;
color: #FFFFFF;
}
.c3button.blue {
background-color: #195CC5;
color: #FFFFFF;
}
.c3button img {
position: relative;
top: 0.3em;
}
/* BUTTONS */
/* ********************** */
/* ********************** */
/* GENERAL CLASSES */
.fleft { float: left; }
.fright { float: right; }
.tleft { text-align: left; }
.tright { text-align: right; }
.tcenter { text-align: center; }
.clr, .clear {
height: 1px;
line-height: 1px;
font-size: 0;
clear: both;
}
#container {
background-color: #FFFFFF;
}
/* GENERAL CLASSES */
/* ********************** */
/* ********************** */
/* PANELS */
#header-panel {
position: relative;
background-color: #0A62B2;
color: #F8F8F8;
height: 5.3em;
margin: 0;
padding: 15px 30px 0 30px;
-moz-box-shadow: inset 0px -8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 -8px 6px -4px rgba(0,0,0,0.2);
}
#navigation-panel {
position: absolute;
bottom: -1px;
}
#main-panel {
position: relative;
min-height: 400px;
}
#messages-panel {
/*width: 400px;
position: absolute;
top: 0;
left: 50%;
margin-left: -200px;*/
min-height: 3em;
}
#content-panel {
margin: 0px 345px 10px 30px;
}
#sidebar-panel {
margin: 0px 30px 0 0;
min-height: 300px;
padding: 0;
position: absolute;
top: 0;
right: 0;
width: 300px;
z-index: 9;
}
#footer-panel {
height: 6em;
padding-top: 20px;
color: #999999;
/*-moz-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);*/
background: #F1EFE2 url(../images/footerbg.png) repeat-x scroll 0 0
}
#copyright-panel {
float: right;
margin: 10px 20px;
}
/* PANELS */
/* ********************** */
/* ********************** */
/* Login */
+#login-copyright {
+ position: absolute;
+ bottom: 7px;
+ right: 10px;
+}
+
#login-panel {
position: absolute;
top: 50px;
left: 50%;
margin-left: -250px;
width: 500px;
padding: 10px;
background-color: #FFFFFF;
border: 1px solid #E9E9E9;
-moz-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
}
#login-panel h1 {
display: block;
padding: 15px 10px;
background-color: #0A62B2;
color: #F8F8F8;
}
/* Login */
/* ********************** */
/* ********************** */
/* NAVIGATION */
#navigation-panel ul li {
float: left;
list-style-type: none;
margin: 0 2px 0 0;
padding: 0;
white-space: nowrap;
}
#navigation-panel ul li a {
color: #FFFFFF;
display: block;
margin: 0;
padding: 4px 10px;
text-decoration: none;
}
#navigation-panel ul li.active a, #navigation-panel ul li.active a:hover {
background-color: #FFFFFF;
color: #555555;
}
#navigation-panel ul li a:hover {
color: #FFFFFF;
background-color: #3581C5;
}
#sub-navigation-panel {
margin-left: 20px;
margin-right: 20px;
margin-top: 10px;
padding-bottom: 5px;
height: 16px;
border-bottom: 1px solid #E4E4E4;
}
#sub-navigation-panel ul li {
display: inline;
list-style-type: none;
padding-right: 20px;
font-weight: bold;
}
#sub-navigation-panel ul li.active a {
text-decoration: underline;
}
/* NAVIGATION */
/* ********************** */
/* ********************** */
/* MESSAGES */
#messages-panel #messages {
padding: 1em 2.5em;
}
#messages-panel .message {
position: relative;
}
#messages-panel .message .message-close {
position: absolute;
right: 10px;
top: 10px;
}
.error, .notice, .success, .info { padding: .8em; border: 1px solid #ddd; }
.error { background: #E22C33; color: #440A09; border-color: #B20A0A; }
.notice { background: #E2CC2C; color: #443E09; border-color: #B28C0A; }
.success { background: #2CE23D; color: #264409; border-color: #22B20A; }
.info { background: #2C88E2; color: #091144; border-color: #0A1AB2; }
.error a { color: #8a1f11; }
.notice a { color: #514721; }
.success a { color: #264409; }
.info a { color: #193D88; }
/* MESSAGES */
/* ********************** */
/* ********************** */
/* CONTENT */
#content-panel h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
#content-panel h2 img {
float: left;
margin-top: 2px;
margin-right: 10px;
}
.details-panel {
margin-bottom: 2em;
padding: 1.5em;
background-color: #ECEEEC;
}
/* CONTENT */
/* ********************** */
/* ********************** */
/* SIDEBAR */
#sidebar-panel .block {
display: block;
margin-bottom: 20px;
}
#sidebar-panel .block h2 {}
#sidebar-panel .block p, #sidebar-panel .block .content {
margin: 1em;
}
#sidebar-panel hr {
margin: 1.5em .5em;
background-color: #E4E4E4;
border: 0;
height: 1px;
}
/* actions */
#sidebar-panel ul.actions {
margin: .5em;
}
#sidebar-panel ul.actions li {
padding: 0.7em 1em;
margin: 0;
background-color: #EFEFEF;
border-collapse: collapse;
border-top: 1px solid #FFFFFF;
border-bottom: 1px solid #D4D4D4;
}
#sidebar-panel ul.actions li.no-bg {
background-color: transparent;
border: 0;
}
#sidebar-panel ul.actions li.last {
border-bottom: 0;
}
#sidebar-panel ul.actions li a,
#sidebar-panel ul.actions li input[type="submit"]
{}
#sidebar-panel ul.actions li a.delete {
color: #8D3134;
text-decoration: underline;
}
#sidebar-panel ul.actions li img {
float: left;
margin-top: -1px;
margin-right: 1em;
}
#sidebar-panel ul.actions li.right {
text-align: right;
}
#sidebar-panel ul.actions li.right img {
float: right;
margin-right: 0;
margin-left: 1em;
}
/* SIDEBAR */
/* ********************** */
/* ********************** */
/* MEDIA */
#media-panel {}
#media-tabs-panel {}
#media-tabs-panel ul {
margin: 0;
padding: 0;
list-style: none;
}
#media-tabs-panel ul li {
display: inline-block;
}
#media-panel .media-container {
overflow: auto;
margin: 0;
padding-bottom: 10px;
height: 390px;
border: 1px solid #DEDEDE;
background-color: #ECEEEC;
/*-moz-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);*/
}
#media-panel .media-container div.thumbnail {
position: relative;
float:left;
margin: 1em 0 0 1em;
padding: 5px 10px;
border: solid 1px black;
background-color: white;
width: 140px;
height: 140px;
}
#media-panel .media-container div.thumbnail div.head {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.head .filename {
float: left;
}
#media-panel .media-container div.thumbnail div.head .remove {
float: right;
}
#media-panel .media-container div.thumbnail div.body {
height: 100px;
line-height: 100px;
background-color: #E9EEF0;
border: solid 1px black;
}
#media-panel .media-container div.thumbnail div.body a,
#media-panel .media-container div.thumbnail div.body a:link,
#media-panel .media-container div.thumbnail div.body a:active,
#media-panel .media-container div.thumbnail div.body a:visited
{
display: block;
vertical-align: middle;
text-align: center;
}
#media-panel .media-container div.thumbnail div.body img {
margin: 0 -4px 0 4px;
}
#media-panel .media-container div.thumbnail img.source {
max-width: 120px;
max-height: 80px;
vertical-align: middle;
}
#media-panel .media-container div.thumbnail img.icon {
vertical-align: middle;
}
#media-panel .media-container div.thumbnail div.foot {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.foot .size {
float: right;
display: block;
}
/* MEDIA */
/* ********************** */
/* ********************** */
/* COMMENTS */
.comments {
margin-top: 10px;
margin-bottom: 10px;
}
.comment {
position: relative;
border: solid 1px #E4E4E4;
margin-bottom:10px;
}
.comment .avatar {
float: left;
padding: 10px;
}
.comment .content {
float:left;
padding: 10px;
}
.comment .content .author-info {
margin-bottom: 5px;
}
.comment .content .actions {
margin-top: 10px;
}
.comment .content .actions li {
display: inline;
list-style-type: none;
padding-right: 20px;
}
\ No newline at end of file
diff --git a/application/modules/admin/controllers/AuthController.php b/application/modules/admin/controllers/AuthController.php
index d9bb2f5..91dd414 100644
--- a/application/modules/admin/controllers/AuthController.php
+++ b/application/modules/admin/controllers/AuthController.php
@@ -1,92 +1,125 @@
<?php
/**
* Class Admin_AuthController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_AuthController extends Fizzy_Controller
{
public function loginAction()
{
$form = $this->_getForm();
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$authAdapter = new Fizzy_Doctrine_AuthAdapter(
$form->username->getValue(), $form->password->getValue()
);
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$result = $auth->authenticate($authAdapter);
if($result->isValid()) {
$this->_redirect('@admin');
}
$messages = $result->getMessages();
$this->addErrorMessage(array_shift($messages));
$this->_redirect('@admin_login');
}
}
$this->view->form = $form;
+ $this->view->langForm = $this->_getLangForm();
$this->renderScript('login.phtml');
}
+ public function languageAction()
+ {
+ $form = $this->_getLangForm();
+ if($this->_request->isPost()) {
+ if ($form->isValid($_POST)){
+ $session = new Zend_Session_Namespace('Lang');
+ $session->language = $form->language->getValue();
+ }
+ }
+ $this->_redirect('@login');
+ }
+
public function logoutAction()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$auth->clearIdentity();
$this->_redirect('@admin');
}
protected function _getForm()
{
$formConfig = array (
'elements' => array (
'username' => array (
'type' => 'text',
'options' => array (
'label' => 'Username',
'required' => true
)
),
'password' => array (
'type' => 'password',
'options' => array (
'label' => 'Password',
'required' => true
),
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Login',
'ignore' => true
)
)
)
);
return new Fizzy_Form(new Zend_Config($formConfig));
}
+ protected function _getLangForm()
+ {
+ return new Zend_Form(array(
+ 'action' => $this->view->url('@admin_login_lang'),
+ 'elements' => array(
+ 'language' => array(
+ 'type' => 'select',
+ 'options' => array(
+ 'label' => 'Language',
+ 'multiOptions' => array(
+ 'nl' => 'Nederlands',
+ 'en' => 'English'
+ ),
+ 'onChange' => 'this.form.submit();'
+ )
+ )
+ )
+ ));
+ }
+
public function postDispatch()
{
$this->_helper->layout->setLayout('login');
}
}
diff --git a/application/modules/admin/views/layouts/login.phtml b/application/modules/admin/views/layouts/login.phtml
index db96206..a789e7b 100644
--- a/application/modules/admin/views/layouts/login.phtml
+++ b/application/modules/admin/views/layouts/login.phtml
@@ -1,57 +1,55 @@
<?php
/**
* Fizzy login layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Fizzy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy-2.0.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/tables.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/forms.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<script type="text/javascript" src="<?= $this->baseUrl("/fizzy_assets/js/jquery-1.3.2.min.js"); ?>"></script>
</head>
<body>
<div id="container">
<div id="login-panel">
<h1><?= $this->translate('Fizzy login') ?></h1>
<div id="message-panel">
<?= $this->fizzyMessages(); ?>
</div>
<?= $this->layout()->content; ?>
<div class="clear"></div>
-
- </div>
-
- <div style="position: absolute; width: 500px; top: 280px; left: 50%; margin-left: -250px; padding: 10px; text-align: right;">
- (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a>
+ <div id="login-copyright">
+ (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a>
+ </div>
</div>
</div>
</body>
</html>
diff --git a/application/modules/admin/views/scripts/login.phtml b/application/modules/admin/views/scripts/login.phtml
index 6a3176d..f32d2ee 100644
--- a/application/modules/admin/views/scripts/login.phtml
+++ b/application/modules/admin/views/scripts/login.phtml
@@ -1,7 +1,9 @@
<div class="form-panel">
<form action="<?= $this->form->getAction(); ?>" id="Loginform" name="LoginForm" method="post">
<?= $this->form->username; ?>
<?= $this->form->password; ?>
<input type="submit" value="<?= $this->translate('Login') ?>" />
</form>
+ <br>
+ <?= $this->langForm ?>
</div>
\ No newline at end of file
diff --git a/configs/routes.ini b/configs/routes.ini
index e510553..cb0beb8 100644
--- a/configs/routes.ini
+++ b/configs/routes.ini
@@ -1,241 +1,246 @@
[development : production]
[test : production]
[production]
;; Catch all for pages slugs
page_by_slug.route = "/:slug"
page_by_slug.defaults.controller = "pages"
page_by_slug.defaults.action = "slug"
page_by_slug.defaults.module = "default"
;; Blog
blog.route = "blog"
blog.defaults.controller = "blog"
blog.defaults.action = "index"
blog.defaults.module = "default"
;; Blog posts
blog_posts.route = "/blog/:blog_slug"
blog_posts.defaults.controller = "blog"
blog_posts.defaults.action = "blog"
blog_posts.defaults.module = "default"
;; Post
blog_post.route = "/blog/:blog_slug/:post_slug"
blog_post.defaults.controller = "blog"
blog_post.defaults.action = "post"
blog_post.defaults.module = "default"
;; Feeds
blog_rss.route = "/blog/rss"
blog_rss.defaults.controller = "blog"
blog_rss.defaults.action = "rss"
blog_rss.defaults.module = "default"
blog_atom.route = "/blog/atom"
blog_atom.defaults.controller = "blog"
blog_atom.defaults.action = "atom"
blog_atom.defaults.module = "default"
;; User posts
user_posts.route = "/blog/author/:username"
user_posts.defaults.controller = "blog"
user_posts.defaults.action = "user"
user_posts.defaults.module = "default"
;; Comments
add_comment.route = "/comment/add/:stream"
add_comment.defaults.controller = "comment"
add_comment.defaults.action = "add"
add_comment.defaults.module = "default"
;; Homepage
homepage.route = "/"
homepage.defaults.controller = "pages"
homepage.defaults.controller = "pages"
homepage.defaults.action = "slug"
homepage.defaults.module = "default"
;; Contact form
;;contact.route = "/contact"
;;contact.defaults.controller = "contact"
;;contact.defaults.action = "index"
;;contact.defaults.module = "default"
;; Admin pages control
admin_blogs.route = "/{backend}/blogs"
admin_blogs.defaults.action = "index"
admin_blogs.defaults.controller = "blogs"
admin_blogs.defaults.module = "admin"
admin_blog.route = "/{backend}/blog/:id"
admin_blog.defaults.action = "blog"
admin_blog.defaults.controller = "blogs"
admin_blog.defaults.module = "admin"
admin_blog_post_add.route = "/{backend}/blog/:blog_id/add"
admin_blog_post_add.defaults.action = "add-post"
admin_blog_post_add.defaults.controller = "blogs"
admin_blog_post_add.defaults.module = "admin"
admin_blog_post_edit.route = "/{backend}/post/:post_id/edit"
admin_blog_post_edit.defaults.action = "edit-post"
admin_blog_post_edit.defaults.controller = "blogs"
admin_blog_post_edit.defaults.module = "admin"
admin_blog_post_delete.route = "/{backend}/post/:post_id/delete"
admin_blog_post_delete.defaults.action = "delete-post"
admin_blog_post_delete.defaults.controller = "blogs"
admin_blog_post_delete.defaults.module = "admin"
admin_comments.route = "/{backend}/comments"
admin_comments.defaults.action = "index"
admin_comments.defaults.controller = "comments"
admin_comments.defaults.module = "admin"
admin_comments_list.route = "/{backend}/comments/list"
admin_comments_list.defaults.action = "list"
admin_comments_list.defaults.controller = "comments"
admin_comments_list.defaults.module = "admin"
admin_comments_topic.route = "/{backend}/comments/topic/:id"
admin_comments_topic.defaults.action = "topic"
admin_comments_topic.defaults.controller = "comments"
admin_comments_topic.defaults.module = "admin"
admin_comments_ham.route = "/{backend}/comment/ham/:id"
admin_comments_ham.defaults.action = "ham"
admin_comments_ham.defaults.controller = "comments"
admin_comments_ham.defaults.module = "admin"
admin_comments_spam.route = "/{backend}/comment/spam/:id"
admin_comments_spam.defaults.action = "spam"
admin_comments_spam.defaults.controller = "comments"
admin_comments_spam.defaults.module = "admin"
admin_comments_delete.route = "/{backend}/comment/delete/:id"
admin_comments_delete.defaults.action = "delete"
admin_comments_delete.defaults.controller = "comments"
admin_comments_delete.defaults.module = "admin"
admin_comments_edit.route = "/{backend}/comment/edit/:id"
admin_comments_edit.defaults.action = "edit"
admin_comments_edit.defaults.controller = "comments"
admin_comments_edit.defaults.module = "admin"
admin_comments_spambox.route = "/{backend}/comments/spam"
admin_comments_spambox.defaults.action = "spambox"
admin_comments_spambox.defaults.controller = "comments"
admin_comments_spambox.defaults.module = "admin"
admin_pages.route = "/{backend}/pages"
admin_pages.defaults.action = "index"
admin_pages.defaults.controller = "pages"
admin_pages.defaults.module = "admin"
admin_pages_add.route = "/{backend}/pages/add"
admin_pages_add.defaults.action = "add"
admin_pages_add.defaults.controller = "pages"
admin_pages_add.defaults.module = "admin"
admin_pages_edit.route = "/{backend}/pages/edit/:id"
admin_pages_edit.defaults.action = "edit"
admin_pages_edit.defaults.controller = "pages"
admin_pages_edit.defaults.module = "admin"
admin_pages_delete.route = "/{backend}/pages/delete/:id"
admin_pages_delete.defaults.action = "delete"
admin_pages_delete.defaults.controller = "pages"
admin_pages_delete.defaults.module = "admin"
admin_media.route = "/{backend}/media"
admin_media.defaults.action = "index"
admin_media.defaults.controller = "media"
admin_media.defaults.module = "admin"
admin_media_delete.route = "/{backend}/media/delete/:name"
admin_media_delete.defaults.action = "delete"
admin_media_delete.defaults.controller = "media"
admin_media_delete.defaults.module = "admin"
admin_media_gallery.route = "/{backend}/media/gallery"
admin_media_gallery.defaults.action = "gallery"
admin_media_gallery.defaults.controller = "media"
admin_media_gallery.defaults.module = "admin"
admin_media_assets.route = "/{backend}/media/assets"
admin_media_assets.defaults.action = "assets"
admin_media_assets.defaults.controller = "media"
admin_media_assets.defaults.module = "admin"
;; Admin contact
admin_contact.route = "/{backend}/contact"
admin_contact.defaults.module = "admin"
admin_contact.defaults.controller = "contact"
admin_contact.defaults.action = "index"
admin_contact_show.route = "/{backend}/contact/show/:id"
admin_contact_show.defaults.module = "admin"
admin_contact_show.defaults.controller = "contact"
admin_contact_show.defaults.action = "show"
admin_contact_delete.route = "/{backend}/contact/delete/:id"
admin_contact_delete.defaults.module = "admin"
admin_contact_delete.defaults.controller = "contact"
admin_contact_delete.defaults.action = "delete"
;; Admin users
admin_users.route = "/{backend}/users"
admin_users.defaults.action = "index"
admin_users.defaults.controller = "user"
admin_users.defaults.module = "admin"
admin_users_add.route = "/{backend}/user/add"
admin_users_add.defaults.action = "add"
admin_users_add.defaults.controller = "user"
admin_users_add.defaults.module = "admin"
admin_users_edit.route = "/{backend}/user/edit/:id"
admin_users_edit.defaults.action = "edit"
admin_users_edit.defaults.controller = "user"
admin_users_edit.defaults.module = "admin"
admin_users_delete.route = "/{backend}/user/delete/:id"
admin_users_delete.defaults.action = "delete"
admin_users_delete.defaults.controller = "user"
admin_users_delete.defaults.module = "admin"
;; Admin settings
admin_settings.route = "/{backend}/settings"
admin_settings.defaults.module = "admin"
admin_settings.defaults.controller = "settings"
admin_settings.defaults.action = "index"
admin_settings_update.route = "/{backend}/settings/update"
admin_settings_update.defaults.module = "admin"
admin_settings_update.defaults.controller = "settings"
admin_settings_update.defaults.action = "ajax-update"
;; Admin WebDAV
admin_webdav.route = "/{backend}/webdav/*"
admin_webdav.defaults.module = "admin"
admin_webdav.defaults.controller = "webdav"
admin_webdav.defaults.action = "request"
;; Auth section
admin_login.route = "/{backend}/login"
admin_login.defaults.action = "login"
admin_login.defaults.controller = "auth"
admin_login.defaults.module = "admin"
+admin_login_lang.route = "/{backend}/login/language"
+admin_login_lang.defaults.action = "language"
+admin_login_lang.defaults.controller = "auth"
+admin_login_lang.defaults.module = "admin"
+
admin_logout.route = "/{backend}/logout"
admin_logout.defaults.action = "logout"
admin_logout.defaults.controller = "auth"
admin_logout.defaults.module = "admin"
admin.route = "/{backend}"
admin.defaults.action = "index"
admin.defaults.controller = "index"
admin.defaults.module = "admin"
|
jtietema/Fizzy
|
665664771891ff050e1f8ac48a276a589bcbdfbf
|
translations of the custom WYSIWYG plugins
|
diff --git a/application/assets/js/fizzy.js b/application/assets/js/fizzy.js
index 97a45e2..27e8543 100644
--- a/application/assets/js/fizzy.js
+++ b/application/assets/js/fizzy.js
@@ -1,39 +1,42 @@
var Fizzy = function(){
var _editors = [];
+ var _language = 'en';
return {
"wysiwyg" : {
- "count" : function(){
+ count : function(){
return _editors.length;
},
- "register" : function(id){
+ register : function(id, language){
_editors.push(id);
+ _language = language;
},
- "editors" : function(){
+ editors : function(){
return _editors;
},
- "init" : function() {
+ init : function() {
// init all the editors
var editors = fizzy.wysiwyg.editors().join(",");
tinyMCE.init({
+ language: _language,
mode : "exact",
elements: editors,
theme : "advanced",
plugins: "fizzymedia,fizzyassets",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_buttons1: "formatselect,fontselect,fontsizeselect,separator,forecolor,backcolor,separator,removeformat,undo,redo",
theme_advanced_buttons2: "bold,italic,underline,sub,sup,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,separator,outdent,indent,blockquote,separator,link,unlink,fizzymedia,fizzyassets,separator,charmap,code,cleanup",
theme_advanced_buttons3: "",
theme_advanced_statusbar_location : "bottom",
theme_advanced_resizing : true,
theme_advanced_resize_horizontal : false,
relative_urls : false
});
}
}
}
}
var fizzy = Fizzy();
window.onload = fizzy.wysiwyg.init;
diff --git a/application/assets/js/tiny_mce/plugins/fizzymedia/editor_plugin.js b/application/assets/js/tiny_mce/plugins/fizzymedia/editor_plugin.js
index 5cb945a..d7ece75 100644
--- a/application/assets/js/tiny_mce/plugins/fizzymedia/editor_plugin.js
+++ b/application/assets/js/tiny_mce/plugins/fizzymedia/editor_plugin.js
@@ -1,92 +1,92 @@
/**
* TinyMCE plugin for the Fizzy Media Library
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @author Jeroen Tietema <[email protected]>
* @copyright Copyright 2009, Voidwalkers, All rights reserved.
*/
(function() {
// Load plugin specific language pack
tinymce.PluginManager.requireLangPack('fizzymedia');
tinymce.create('tinymce.plugins.FizzymediaPlugin', {
/**
* Initializes the plugin, this will be executed after the plugin has been created.
* This call is done before the editor instance has finished it's initialization so use the onInit event
* of the editor instance to intercept that event.
*
* @param {tinymce.Editor} ed Editor instance that the plugin is initialized in.
* @param {string} url Absolute URL to where the plugin is located.
*/
init : function(ed, url) {
// Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample');
ed.addCommand('fizzyMedia', function() {
ed.windowManager.open({
//
file : url + '../../../../../../fizzy/media/gallery',
width : 640 + parseInt(ed.getLang('fizzymedia.delta_width', 0)),
- height : 480 + parseInt(ed.getLang('fizzymedia.delta_height', 0)),
+ height : 550 + parseInt(ed.getLang('fizzymedia.delta_height', 0)),
inline : 1
}, {
plugin_url : url, // Plugin absolute URL
some_custom_arg : 'custom arg' // Custom argument
});
});
// Register example button
ed.addButton('fizzymedia', {
title : 'fizzymedia.desc',
cmd : 'fizzyMedia',
image : url + '/img/media.gif'
});
// Add a node change handler, selects the button in the UI when a image is selected
ed.onNodeChange.add(function(ed, cm, n) {
cm.setActive('fizzymedia', n.nodeName == 'IMG');
});
},
/**
* Creates control instances based in the incomming name. This method is normally not
* needed since the addButton method of the tinymce.Editor class is a more easy way of adding buttons
* but you sometimes need to create more complex controls like listboxes, split buttons etc then this
* method can be used to create those.
*
* @param {String} n Name of the control to create.
* @param {tinymce.ControlManager} cm Control manager to use inorder to create new control.
* @return {tinymce.ui.Control} New control instance or null if no control was created.
*/
createControl : function(n, cm) {
return null;
},
/**
* Returns information about the plugin as a name/value array.
* The current keys are longname, author, authorurl, infourl and version.
*
* @return {Object} Name/value array containing information about the plugin.
*/
getInfo : function() {
return {
longname : 'Fizzy Media plugin',
author : 'Jeroen Tietema',
authorurl : 'http://www.voidwalkers.nl',
infourl : 'http://project.voidwalkers.nl/projects/show/fizzy',
version : "1.0"
};
}
});
// Register plugin
tinymce.PluginManager.add('fizzymedia', tinymce.plugins.FizzymediaPlugin);
})();
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fizzymedia/langs/en_dlg.js b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/en_dlg.js
index dcb23c3..a7e2279 100644
--- a/application/assets/js/tiny_mce/plugins/fizzymedia/langs/en_dlg.js
+++ b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/en_dlg.js
@@ -1,3 +1,19 @@
tinyMCE.addI18n('en.fizzymedia_dlg',{
- title : 'Fizzy Media Library'
+ title: 'Fizzy Media Library',
+ description: 'Description',
+ width: 'Width',
+ height: 'Height',
+ alignment: 'Alignment',
+ none: 'Not set',
+ left: 'Left',
+ right: 'Right',
+ baseline: 'Baseline',
+ top: 'Top',
+ middle: 'Middle',
+ bottom: 'Bottom',
+ text_top: 'Text top',
+ text_bottom: 'Text bottom',
+ border: 'Border',
+ margins: 'Margins',
+ margins_desc: 'You can specify the margins around the picture above.'
});
diff --git a/application/modules/admin/views/scripts/media/gallery.phtml b/application/modules/admin/views/scripts/media/gallery.phtml
index 9be6b70..4816e4b 100644
--- a/application/modules/admin/views/scripts/media/gallery.phtml
+++ b/application/modules/admin/views/scripts/media/gallery.phtml
@@ -1,91 +1,91 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{#fizzymedia_dlg.title}</title>
<link href="<?= $this->assetUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
<script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzymedia/js/dialog.js') ?>"></script>
</head>
<body>
<div id="image-picker" class="files-container">
<?php foreach($this->files as $fileInfo) : ?>
<div class="thumbnail" id="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" onclick="select('<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>', this);">
<img class="thumbnail" src="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" alt="<?= $fileInfo->basename ?>" />
<div class="filename">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</div>
<div class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<form onsubmit="FizzymediaDialog.insert();return false;" action="#">
<div>
<div class="form-left">
- <label>Description:</label>
+ <label>{#fizzymedia_dlg.description}</label>
<input type="text" name="alt" id="alt" />
- <label>Width</label>
+ <label>{#fizzymedia_dlg.width}</label>
<input type="text" name="width" id="width" class="small" /> px
- <label>Height</label>
+ <label>{#fizzymedia_dlg.height}</label>
<input type="text" name="height" id="height" class="small" /> px
- <label>Alignment</label>
+ <label>{#fizzymedia_dlg.alignment}</label>
<select name="position" id="position">
- <option value="none">-- Not Set --</option>
- <option value="left">Left</option>
- <option value="right">Right</option>
- <option value="baseline">Baseline</option>
- <option value="top">Top</option>
- <option value="middle">Middle</option>
- <option value="bottom">Bottom</option>
- <option value="text-top">Text top</option>
- <option value="text-bottom">Text bottom</option>
+ <option value="none">-- {#fizzymedia_dlg.none} --</option>
+ <option value="left">{#fizzymedia_dlg.left}</option>
+ <option value="right">{#fizzymedia_dlg.right}</option>
+ <option value="baseline">{#fizzymedia_dlg.baseline}</option>
+ <option value="top">{#fizzymedia_dlg.top}</option>
+ <option value="middle">{#fizzymedia_dlg.middle}</option>
+ <option value="bottom">{#fizzymedia_dlg.bottom}</option>
+ <option value="text-top">{#fizzymedia_dlg.text_top}</option>
+ <option value="text-bottom">{#fizzymedia_dlg.text_bottom}</option>
</select>
- <label>Border</label>
+ <label>{#fizzymedia_dlg.border}</label>
<input type="text" name="border" id="border" class="small" /> px
</div>
<div class="form-right">
- <label>Margins</label>
+ <label>{#fizzymedia_dlg.margins}</label>
<table>
<tr>
<td></td>
<td> <input type="text" name="marginTop" id="marginTop" /></td>
<td></td>
</tr>
<tr>
<td><input type="text" name="marginLeft" id="marginLeft" /></td>
<td class="center"><img src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzymedia/img/flower.png');?>" alt="flower" /></td>
<td><input type="text" name="marginRight" id="marginRight" /></td>
</tr>
<tr>
<td></td>
<td> <input type="text" name="marginBottom" id="marginBottom" /></td>
<td></td>
</tr>
</table>
- <p>You can specify the margins around the picture above.</p>
+ <p>{#fizzymedia_dlg.margins_desc}</p>
</div>
<div class="clear"></div>
<input type="button" name="insert" value="{#insert}" onclick="FizzymediaDialog.insert();" />
<input type="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</form>
</body>
</html>
diff --git a/library/Fizzy/View/Helper/Wysiwyg.php b/library/Fizzy/View/Helper/Wysiwyg.php
index 3e1e1ef..be635c7 100644
--- a/library/Fizzy/View/Helper/Wysiwyg.php
+++ b/library/Fizzy/View/Helper/Wysiwyg.php
@@ -1,107 +1,107 @@
<?php
/**
* Class Fizzy_View_Helper_Wysiwyg
* @category Fizzy
* @package Fizzy_View
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Abstract class for extension
*/
require_once 'Zend/View/Helper/FormElement.php';
/**
* Helper to generate a wysiwyg textarea element
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_View_Helper_Wysiwyg extends Zend_View_Helper_FormElement
{
/**
* The default number of rows for a textarea.
*
* @access public
*
* @var int
*/
public $rows = 24;
/**
* The default number of columns for a textarea.
*
* @access public
*
* @var int
*/
public $cols = 80;
/**
* Generates a 'textarea' element.
*
* @access public
*
* @param string|array $name If a string, the element name. If an
* array, all other parameters are ignored, and the array elements
* are extracted in place of added parameters.
*
* @param mixed $value The element value.
*
* @param array $attribs Attributes for the element tag.
*
* @param boolean
*
* @return string The element XHTML.
*/
public function wysiwyg($name, $value = null, $attribs = null)
{
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable
// is it disabled?
$disabled = '';
/*
if ($enabled) {
// disabled.
$disabled = ' disabled="disabled"';
}*/
// Make sure that there are 'rows' and 'cols' values
// as required by the spec. noted by Orjan Persson.
if (empty($attribs['rows'])) {
$attribs['rows'] = (int) $this->rows;
}
if (empty($attribs['cols'])) {
$attribs['cols'] = (int) $this->cols;
}
-
+ $language = $this->getTranslator()->getLocale();
// build the element
$xhtml = '<div class="wysiwyg">'
. '<div class="wysiwyg-editor">'
. '<textarea name="' . $this->view->escape($name) . '"'
. ' id="' . $this->view->escape($id) . '"'
. $disabled
. $this->_htmlAttribs($attribs) . '>'
. $this->view->escape($value) . '</textarea>'
. '</div>'
. '<div class="wysiwyg-toggle"></div>'
. '<script type="text/javascript">'
- . 'fizzy.wysiwyg.register("'.$this->view->escape($id).'");'
+ . 'fizzy.wysiwyg.register("'.$this->view->escape($id).'", "'. $language .'");'
. '</script>'
. '</div>';
return $xhtml;
}
}
|
jtietema/Fizzy
|
e6efd62e572c5ffa7e115777e6d77d2b399c6ac9
|
Dutch language pack for TinyMCE
|
diff --git a/application/assets/js/tiny_mce/langs/nl.js b/application/assets/js/tiny_mce/langs/nl.js
new file mode 100644
index 0000000..9901525
--- /dev/null
+++ b/application/assets/js/tiny_mce/langs/nl.js
@@ -0,0 +1,170 @@
+tinyMCE.addI18n({nl:{
+common:{
+edit_confirm:"Weet u zeker dat u tekst in WYSIWYG mode wilt bewerken in dit tekstveld?",
+apply:"Toepassen",
+insert:"Invoegen",
+update:"Bijwerken",
+cancel:"Annuleren",
+close:"Sluiten",
+browse:"Bladeren",
+class_name:"Klasse",
+not_set:"- Standaard -",
+clipboard_msg:"Kopi\u00EBren/knippen/plakken is niet beschikbaar in Mozilla en Firefox.\nWilt u meer informatie over deze beperking?",
+clipboard_no_support:"Kopi\u00EBren/knippen/plakken wordt niet ondersteund door uw browser, gebruik hiervoor de sneltoetsen.",
+popup_blocked:"U zult uw popup-blocker tijdelijk moeten uitschakelen voor deze website om gebruik te kunnen maken van alle functies van deze teksteditor.",
+invalid_data:"Fout: Er zijn ongeldige waardes ingevoerd, deze zijn rood gemarkeerd.",
+more_colors:"Meer kleuren"
+},
+contextmenu:{
+align:"Uitlijning",
+left:"Links",
+center:"Centreren",
+right:"Rechts",
+full:"Uitvullen"
+},
+insertdatetime:{
+date_fmt:"%d-%m-%Y",
+time_fmt:"%H:%M:%S",
+insertdate_desc:"Datum invoegen",
+inserttime_desc:"Tijd invoegen",
+months_long:"Januari,Februari,Maart,April,Mei,Juni,Juli,Augustus,September,Oktober,November,December",
+months_short:"Jan,Feb,Mar,Apr,Mei,Jun,Jul,Aug,Sep,Okt,Nov,Dec",
+day_long:"Zondag,Maandag,Dinsdag,Woensdag,Donderdag,Vrijdag,Zaterdag,Zondag",
+day_short:"zo,ma,di,wo,do,vr,za,zo"
+},
+print:{
+print_desc:"Afdrukken"
+},
+preview:{
+preview_desc:"Voorbeeld"
+},
+directionality:{
+ltr_desc:"Van links naar rechts",
+rtl_desc:"Van rechts naar links"
+},
+layer:{
+insertlayer_desc:"Nieuwe laag invoegen",
+forward_desc:"Volgende laag",
+backward_desc:"Vorige laag",
+absolute_desc:"Absoluut positioneren inschakelen",
+content:"Nieuwe laag..."
+},
+save:{
+save_desc:"Opslaan",
+cancel_desc:"Alle wijzigingen annuleren"
+},
+nonbreaking:{
+nonbreaking_desc:"Open ruimte invoegen"
+},
+iespell:{
+iespell_desc:"Spellingcontrole",
+download:"ieSpell niet gevonden. Wilt u deze nu installeren?"
+},
+advhr:{
+advhr_desc:"Scheidingslijn"
+},
+emotions:{
+emotions_desc:"Emoties"
+},
+searchreplace:{
+search_desc:"Zoeken",
+replace_desc:"Zoeken/Vervangen"
+},
+advimage:{
+image_desc:"Afbeelding invoegen/bewerken"
+},
+advlink:{
+link_desc:"Link invoegen/bewerken"
+},
+xhtmlxtras:{
+cite_desc:"Citaat",
+abbr_desc:"Afkorting",
+acronym_desc:"Synoniem",
+del_desc:"Verwijderd",
+ins_desc:"Ingevoegd",
+attribs_desc:"Attributen invoegen/bewerken"
+},
+style:{
+desc:"CSS Stijl bewerken"
+},
+paste:{
+paste_text_desc:"Als platte tekst plakken",
+paste_word_desc:"Vanuit Word plakken",
+selectall_desc:"Alles selecteren",
+plaintext_mode_sticky:"Plakken is nu in plattetekstmodus. Klik nog een keer om terug te gaan naar normaal plakken. Nadat u iets plakt, keert u terug naar normaal plakken.",
+plaintext_mode:"Plakken is nu in plattetekstmoduse. Klik nog een keer om terug te gaan naar normaal plakken."
+},
+paste_dlg:{
+text_title:"Gebruik Ctrl+V om tekst in het venster te plakken.",
+text_linebreaks:"Regelafbreking bewaren",
+word_title:"Gebruik Ctrl+V om tekst in het venster te plakken."
+},
+table:{
+desc:"Nieuwe tabel invoegen",
+row_before_desc:"Rij boven invoegen",
+row_after_desc:"Rij onder invoegen",
+delete_row_desc:"Rij verwijderen",
+col_before_desc:"Kolom links invoegen",
+col_after_desc:"Kolom rechts invoegen",
+delete_col_desc:"Kolom verwijderen",
+split_cells_desc:"Cellen splitsen",
+merge_cells_desc:"Cellen samenvoegen",
+row_desc:"Rij-eigenschappen",
+cell_desc:"Cel-eigenschappen",
+props_desc:"Tabeleigenschappen",
+paste_row_before_desc:"Rij boven plakken",
+paste_row_after_desc:"Rij onder plakken",
+cut_row_desc:"Rij knippen",
+copy_row_desc:"Rij kopi\u00EBren",
+del:"Tabel verwijderen",
+row:"Rij",
+col:"Kolom",
+cell:"Cel"
+},
+autosave:{
+unload_msg:"De wijzigingen zullen verloren gaan als u nu deze pagina verlaat.",
+restore_content:"Automatisch opgeslagen inhoud laden.",
+warning_message:"Als u de opgeslagen inhoud laadt, verliest u de inhoud die zich momenteel in de editor bevindt.\n\nWeet u zeker dat u de opgeslagen inhoud wilt laden?"
+},
+fullscreen:{
+desc:"Volledig scherm"
+},
+media:{
+desc:"Media invoegen/bewerken",
+edit:"Media bewerken"
+},
+fullpage:{
+desc:"Documenteigenschappen"
+},
+template:{
+desc:"Voorgedefinieerd sjabloon invoegen"
+},
+visualchars:{
+desc:"Zichtbare symbolen"
+},
+spellchecker:{
+desc:"Spellingcontrole",
+menu:"Instellingen spellingcontrole",
+ignore_word:"Woord negeren",
+ignore_words:"Alles negeren",
+langs:"Talen",
+wait:"Een ogenblik geduld\u2026",
+sug:"Suggesties",
+no_sug:"Geen suggesties",
+no_mpell:"Geen spelfouten gevonden."
+},
+pagebreak:{
+desc:"Pagina-einde invoegen"
+},
+advlist:{
+types:"Types",
+def:"Standaard",
+lower_alpha:"Alfa (klein)",
+lower_greek:"Griekse letters (klein)",
+lower_roman:"Romeinse letters (klein)",
+upper_alpha:"Alfa (groot)",
+upper_roman:"Romeinse letters (groot)",
+circle:"Cirkel",
+disc:"Schijf",
+square:"Vierkant"
+}}});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/advhr/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/advhr/langs/nl_dlg.js
new file mode 100644
index 0000000..10bec4e
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/advhr/langs/nl_dlg.js
@@ -0,0 +1,5 @@
+tinyMCE.addI18n('nl.advhr_dlg',{
+width:"Breedte",
+size:"Hoogte",
+noshade:"Geen schaduw"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/advimage/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/advimage/langs/nl_dlg.js
new file mode 100644
index 0000000..b6db1f2
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/advimage/langs/nl_dlg.js
@@ -0,0 +1,43 @@
+tinyMCE.addI18n('nl.advimage_dlg',{
+tab_general:"Algemeen",
+tab_appearance:"Weergave",
+tab_advanced:"Geavanceerd",
+general:"Algemeen",
+title:"Titel",
+preview:"Voorbeeld",
+constrain_proportions:"Verhouding behouden",
+langdir:"Taalrichting",
+langcode:"Taalcode",
+long_desc:"Uitgebreide beschrijving",
+style:"Stijl",
+classes:"Klasses",
+ltr:"Van links naar rechts",
+rtl:"Van rechts naar links",
+id:"Id",
+map:"Afbeeldingsplattegrond",
+swap_image:"Afbeelding wisselen",
+alt_image:"Alternatieve afbeeldingen",
+mouseover:"Bij muis over",
+mouseout:"Bij muis uit",
+misc:"Diversen",
+example_img:"Voorbeeldweergave",
+missing_alt:"Wilt u de afbeelding zonder beschrijving invoegen? De afbeelding wordt dan mogelijk niet opgemerkt door mensen met een visuele handicap, of welke zonder afbeeldingen browsen.",
+dialog_title:"Afbeelding invoegen/bewerken",
+src:"Bestand/URL",
+alt:"Beschrijving",
+list:"Lijst",
+border:"Rand",
+dimensions:"Afmetingen",
+vspace:"Verticale ruimte",
+hspace:"Horizontale ruimte",
+align:"Uitlijning",
+align_baseline:"Basislijn",
+align_top:"Boven",
+align_middle:"Midden",
+align_bottom:"Onder",
+align_texttop:"Bovenkant tekst",
+align_textbottom:"Onderkant tekst",
+align_left:"Links",
+align_right:"Rechts",
+image_list:"Lijst"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/advlink/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/advlink/langs/nl_dlg.js
new file mode 100644
index 0000000..e8f2fd6
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/advlink/langs/nl_dlg.js
@@ -0,0 +1,52 @@
+tinyMCE.addI18n('nl.advlink_dlg',{
+title:"Link invoegen/bewerken",
+url:"URL",
+target:"Doel",
+titlefield:"Titel",
+is_email:"De ingevoerde URL lijkt op een e-mailadres. Wilt u de vereiste mailto: tekst voorvoegen?",
+is_external:"De ingevoerde URL lijkt op een externe link. Wilt u de vereiste http:// tekst voorvoegen?",
+list:"Lijst",
+general_tab:"Algemeen",
+popup_tab:"Popup",
+events_tab:"Gebeurtenissen",
+advanced_tab:"Geavanceerd",
+general_props:"Algemene eigenschappen",
+popup_props:"Popup eigenschappen",
+event_props:"Gebeurtenissen",
+advanced_props:"Geavanceerde eigenschappen",
+popup_opts:"Opties",
+anchor_names:"Ankers",
+target_same:"In dit venster / frame openen",
+target_parent:"In bovenliggend venster / frame openen",
+target_top:"In bovenste frame openen (vervangt gehele pagina)",
+target_blank:"In nieuw venster openen",
+popup:"Javascript popup",
+popup_url:"Popup URL",
+popup_name:"Venstertitel",
+popup_return:"'return false' invoegen",
+popup_scrollbars:"Scrollbalken weergeven",
+popup_statusbar:"Statusbalk weergeven",
+popup_toolbar:"Werkbalk weergeven",
+popup_menubar:"Menubalk weergeven",
+popup_location:"Lokatiebalk weergeven",
+popup_resizable:"Aanpasbaar venster",
+popup_dependent:"Afhankelijk (Alleen Mozilla/Firefox)",
+popup_size:"Grootte",
+popup_position:"Positie (X/Y)",
+id:"Id",
+style:"Stijl",
+classes:"Klassen",
+target_name:"Doel",
+langdir:"Taalrichting",
+target_langcode:"Taal",
+langcode:"Taalcode",
+encoding:"Taalcodering",
+mime:"MIME type",
+rel:"Relatie van pagina tot doel",
+rev:"Relatie van doel tot pagina",
+tabindex:"Tabvolgorde",
+accesskey:"Toegangstoets",
+ltr:"Van links naar rechts",
+rtl:"Van rechts naar links",
+link_list:"Lijst"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/emotions/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/emotions/langs/nl_dlg.js
new file mode 100644
index 0000000..39f797d
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/emotions/langs/nl_dlg.js
@@ -0,0 +1,20 @@
+tinyMCE.addI18n('nl.emotions_dlg',{
+title:"Emotie invoegen",
+desc:"Emoties",
+cool:"Stoer",
+cry:"Huilen",
+embarassed:"Schamen",
+foot_in_mouth:"Verstomd",
+frown:"Wenkbrauw ophalen",
+innocent:"Onschuldig",
+kiss:"Zoenen",
+laughing:"Lachen",
+money_mouth:"Hebberig",
+sealed:"Afgesloten",
+smile:"Lachen",
+surprised:"Verrast",
+tongue_out:"Tong uitsteken",
+undecided:"Onbeslist",
+wink:"Knipogen",
+yell:"Roepen"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl.js b/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl.js
new file mode 100644
index 0000000..c9db398
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl.js
@@ -0,0 +1,3 @@
+tinyMCE.addI18n('nl.fizzyassets',{
+ desc : 'Bestanden invoege van de Fizzy Media bibliotheek'
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl_dlg.js
new file mode 100644
index 0000000..1179e32
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/fizzyassets/langs/nl_dlg.js
@@ -0,0 +1,3 @@
+tinyMCE.addI18n('nl.fizzyassets_dlg',{
+ title : 'Fizzy bestanden bibliotheek'
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl.js b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl.js
new file mode 100644
index 0000000..2deafc1
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl.js
@@ -0,0 +1,3 @@
+tinyMCE.addI18n('nl.fizzymedia',{
+ desc : 'Plaatjes invoegen vanuit de Fizzy Media bibliotheek'
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl_dlg.js
new file mode 100644
index 0000000..6bc18f1
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/fizzymedia/langs/nl_dlg.js
@@ -0,0 +1,19 @@
+tinyMCE.addI18n('nl.fizzymedia_dlg',{
+ title : 'Fizzy Media bibliotheek',
+ description: 'Omschrijving',
+ width: 'Breedte',
+ height: 'Height',
+ alignment: 'Uitlijning',
+ none: 'Geen',
+ left: 'Links',
+ right: 'Rechts',
+ baseline: 'Baseline',
+ top: 'Boven',
+ middle: 'Midden',
+ bottom: 'Beneden',
+ text_top: 'Tekst boven',
+ text_bottom: 'Tekst beneden',
+ border: 'Omlijning',
+ margins: 'Marges',
+ margins_desc: 'U kunt de marges om het plaatje boven invoeren.'
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/fullpage/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/fullpage/langs/nl_dlg.js
new file mode 100644
index 0000000..b90a127
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/fullpage/langs/nl_dlg.js
@@ -0,0 +1,85 @@
+tinyMCE.addI18n('nl.fullpage_dlg',{
+title:"Documenteigenschappen",
+meta_tab:"Algemeen",
+appearance_tab:"Weergave",
+advanced_tab:"Geavanceerd",
+meta_props:"Meta informatie",
+langprops:"Taal en codering",
+meta_title:"Titel",
+meta_keywords:"Sleutelwoorden",
+meta_description:"Beschrijving",
+meta_robots:"Robots",
+doctypes:"Doctype",
+langcode:"Taalcode",
+langdir:"Taalrichting",
+ltr:"Van links naar rechts",
+rtl:"Van rechts naar links",
+xml_pi:"XML toewijzing",
+encoding:"Karaktercodering",
+appearance_bgprops:"Achtergrondeigenschappen",
+appearance_marginprops:"Bodymarge",
+appearance_linkprops:"Linkkleuren",
+appearance_textprops:"Teksteigenschappen",
+bgcolor:"Achtergrondkleur",
+bgimage:"Achtergrondafbeelding",
+left_margin:"Linkermarge",
+right_margin:"Rechtermarge",
+top_margin:"Bovenmarge",
+bottom_margin:"Ondermarge",
+text_color:"Tekstkleur",
+font_size:"Tekengrootte",
+font_face:"Lettertype",
+link_color:"Linkkleur",
+hover_color:"Hoverkleur",
+visited_color:"Bezocht kleur",
+active_color:"Actieve kleur",
+textcolor:"Kleur",
+fontsize:"Tekengrootte",
+fontface:"Lettertype",
+meta_index_follow:"Links indexeren en volgen",
+meta_index_nofollow:"Links indexeren maar niet volgen",
+meta_noindex_follow:"Links volgen maar niet indexeren",
+meta_noindex_nofollow:"Links niet indexeren en niet volgen",
+appearance_style:"Stijlblad en stijleigenschappen",
+stylesheet:"Stijlblad",
+style:"Stijl",
+author:"Auteur",
+copyright:"Copyright",
+add:"Nieuw element toevoegen",
+remove:"Geselecteerde elementen verwijderen",
+moveup:"Geselecteerde elementen omhoog verplaatsen",
+movedown:"Geselecteerde elementen omlaag verplaatsen",
+head_elements:"Kopelementen",
+info:"Informatie",
+add_title:"Titelelement",
+add_meta:"Meta-element",
+add_script:"Scriptelement",
+add_style:"Stijlelement",
+add_link:"Linkelement",
+add_base:"Basiselement",
+add_comment:"Opmerkingknooppunt",
+title_element:"Titelelement",
+script_element:"Scriptelement",
+style_element:"Stijlelement",
+base_element:"Basiselement",
+link_element:"Linkelement",
+meta_element:"Meta-element",
+comment_element:"Opmerking",
+src:"Bron",
+language:"Taal",
+href:"Href",
+target:"Doel",
+type:"Type",
+charset:"Karakterset",
+defer:"Uitstellen",
+media:"Media",
+properties:"Eigenschappen",
+name:"Naam",
+value:"Waarde",
+content:"Inhoud",
+rel:"Rel",
+rev:"Rev",
+hreflang:"Href taal",
+general_props:"Algemeen",
+advanced_props:"Geavanceerd"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/media/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/media/langs/nl_dlg.js
new file mode 100644
index 0000000..b6c7939
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/media/langs/nl_dlg.js
@@ -0,0 +1,103 @@
+tinyMCE.addI18n('nl.media_dlg',{
+title:"Media invoegen/bewerken",
+general:"Algemeen",
+advanced:"Geavanceerd",
+file:"Bestand/URL",
+list:"Lijst",
+size:"Afmetingen",
+preview:"Voorbeeld",
+constrain_proportions:"Verhouding bewaren",
+type:"Type",
+id:"Id",
+name:"Naam",
+class_name:"Klasse",
+vspace:"V-Ruimte",
+hspace:"H-Ruimte",
+play:"Automatisch afspelen",
+loop:"Herhalen",
+menu:"Menu Weergeven",
+quality:"Kwaliteit",
+scale:"Schaal",
+align:"Uitlijning",
+salign:"Schaaluitlijning",
+wmode:"WMode",
+bgcolor:"Achtergrond",
+base:"Basis",
+flashvars:"Variabelen",
+liveconnect:"SWLiveConnect",
+autohref:"AutoHREF",
+cache:"Cache",
+hidden:"Verborgen",
+controller:"Controller",
+kioskmode:"Kioskmodus",
+playeveryframe:"Elk frame afspelen",
+targetcache:"Doelcache",
+correction:"Geen correctie",
+enablejavascript:"JavaScript Inschakelen",
+starttime:"Starttijd",
+endtime:"Eindtijd",
+href:"HREF",
+qtsrcchokespeed:"Chokesnelheid",
+target:"Doel",
+volume:"Volume",
+autostart:"Automatisch afspelen",
+enabled:"Ingeschakeld",
+fullscreen:"Volledig scherm",
+invokeurls:"URLs laden",
+mute:"Geluid dempen",
+stretchtofit:"Passend maken",
+windowlessvideo:"Video zonder venster",
+balance:"Balans",
+baseurl:"BasisURL",
+captioningid:"Ondertiteling id",
+currentmarker:"Huidige markering",
+currentposition:"Huidige positie",
+defaultframe:"Standaard frame",
+playcount:"Afspeelteller",
+rate:"Snelheid",
+uimode:"UI Modus",
+flash_options:"Flash opties",
+qt_options:"Quicktime opties",
+wmp_options:"Windows mediaspeler opties",
+rmp_options:"Real mediaspeler opties",
+shockwave_options:"Shockwave opties",
+autogotourl:"Automatisch naar URL",
+center:"Centreren",
+imagestatus:"Afbeeldingstatus",
+maintainaspect:"Verhouding bewaren",
+nojava:"Geen java",
+prefetch:"Voorladen",
+shuffle:"Willekeurige volgorde",
+console:"Console",
+numloop:"Aantal herhalingen",
+controls:"Bediening",
+scriptcallbacks:"Script callbacks",
+swstretchstyle:"Schaal",
+swstretchhalign:"H-Schaal",
+swstretchvalign:"V-Schaal",
+sound:"Geluid",
+progress:"Voortgang",
+qtsrc:"Quicktime bron",
+qt_stream_warn:"Gestreamde RTSP bronnen dienen op het tabblad geavanceerd bij Quicktime bron te worden opgegeven.\nDe niet-gestreamde versie kan dan bij het tabblad algemeen worden opgegeven.",
+align_top:"Boven",
+align_right:"Rechts",
+align_bottom:"Onder",
+align_left:"Links",
+align_center:"Centreren",
+align_top_left:"Linksboven",
+align_top_right:"Rechtsboven",
+align_bottom_left:"Linksonder",
+align_bottom_right:"Rechtsonder",
+flv_options:"Flash video-opties",
+flv_scalemode:"Schaalmodus",
+flv_buffer:"Buffer",
+flv_startimage:"Startafbeelding",
+flv_starttime:"Starttijd",
+flv_defaultvolume:"Standaard volume",
+flv_hiddengui:"GUI verbergen",
+flv_autostart:"Automatisch afspelen",
+flv_loop:"Herhalen",
+flv_showscalemodes:"Schaalmodus weergeven",
+flv_smoothvideo:"Soepele video",
+flv_jscallback:"JS Callback"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/paste/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/paste/langs/nl_dlg.js
new file mode 100644
index 0000000..99e604f
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/paste/langs/nl_dlg.js
@@ -0,0 +1,5 @@
+tinyMCE.addI18n('nl.paste_dlg',{
+text_title:"Gebruik Ctrl+V om tekst in het venster te plakken.",
+text_linebreaks:"Regelafbreking bewaren",
+word_title:"Gebruik Ctrl+V om tekst in het venster te plakken."
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/searchreplace/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/searchreplace/langs/nl_dlg.js
new file mode 100644
index 0000000..6ad59db
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/searchreplace/langs/nl_dlg.js
@@ -0,0 +1,16 @@
+tinyMCE.addI18n('nl.searchreplace_dlg',{
+searchnext_desc:"Opnieuw zoeken",
+notfound:"Het doorzoeken is voltooid. De zoekterm kon niet meer worden gevonden.",
+search_title:"Zoeken",
+replace_title:"Zoeken/Vervangen",
+allreplaced:"Alle instanties van de zoekterm zijn vervangen.",
+findwhat:"Zoeken naar",
+replacewith:"Vervangen door",
+direction:"Richting",
+up:"Omhoog",
+down:"Omlaag",
+mcase:"Identieke hoofdletters/kleine letters",
+findnext:"Zoeken",
+replace:"Vervangen",
+replaceall:"Alles verv."
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/style/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/style/langs/nl_dlg.js
new file mode 100644
index 0000000..854a0be
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/style/langs/nl_dlg.js
@@ -0,0 +1,63 @@
+tinyMCE.addI18n('nl.style_dlg',{
+title:"CSS Stijl bewerken",
+apply:"Toepassen",
+text_tab:"Tekst",
+background_tab:"Achtergrond",
+block_tab:"Blok",
+box_tab:"Box",
+border_tab:"Rand",
+list_tab:"Lijst",
+positioning_tab:"Positionering",
+text_props:"Tekst",
+text_font:"Lettertype",
+text_size:"Tekengrootte",
+text_weight:"Gewicht",
+text_style:"Stijl",
+text_variant:"Variant",
+text_lineheight:"Lijnhoogte",
+text_case:"Hoofdlettergebruik",
+text_color:"Kleur",
+text_decoration:"Decoratie",
+text_overline:"Overhalen",
+text_underline:"Onderstrepen",
+text_striketrough:"Doorhalen",
+text_blink:"Knipperen",
+text_none:"Niets",
+background_color:"Achtergrondkleur",
+background_image:"Achtergrondafbeelding",
+background_repeat:"Herhalen",
+background_attachment:"Bijlage",
+background_hpos:"Horizontale positie",
+background_vpos:"Verticale positie",
+block_wordspacing:"Woordruimte",
+block_letterspacing:"Letterruimte",
+block_vertical_alignment:"Verticale uitlijning",
+block_text_align:"Tekstuitlijning",
+block_text_indent:"Inspringen",
+block_whitespace:"Witruimte",
+block_display:"Weergave",
+box_width:"Breedte",
+box_height:"Hoogte",
+box_float:"Zweven",
+box_clear:"Vrijhouden",
+padding:"Opening",
+same:"Alles hetzelfde",
+top:"Boven",
+right:"Rechts",
+bottom:"Onder",
+left:"Links",
+margin:"Marge",
+style:"Stijl",
+width:"Breedte",
+height:"Hoogte",
+color:"Kleur",
+list_type:"Type",
+bullet_image:"Opsommingsteken",
+position:"Positie",
+positioning_type:"Type",
+visibility:"Zichtbaarheid",
+zindex:"Z-index",
+overflow:"Overvloeien",
+placement:"Plaatsing",
+clip:"Clip"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/table/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/table/langs/nl_dlg.js
new file mode 100644
index 0000000..0f72b17
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/table/langs/nl_dlg.js
@@ -0,0 +1,74 @@
+tinyMCE.addI18n('nl.table_dlg',{
+general_tab:"Algemeen",
+advanced_tab:"Geavanceerd",
+general_props:"Algemene eigenschappen",
+advanced_props:"Geavanceerde eigenschappen",
+rowtype:"Rijtype",
+title:"Tabel invoegen/bewerken",
+width:"Breedte",
+height:"Hoogte",
+cols:"Kolommen",
+rows:"Rijen",
+cellspacing:"Ruimte om cel",
+cellpadding:"Ruimte in cel",
+border:"Rand",
+align:"Uitlijning",
+align_default:"Standaard",
+align_left:"Links",
+align_right:"Rechts",
+align_middle:"Centreren",
+row_title:"Rij-eigenschappen",
+cell_title:"Celeigenschappen",
+cell_type:"Celtype",
+valign:"Verticale uitlijning",
+align_top:"Boven",
+align_bottom:"Onder",
+bordercolor:"Randkleur",
+bgcolor:"Achtergrondkleur",
+merge_cells_title:"Cellen samenvoegen",
+id:"Id",
+style:"Stijl",
+langdir:"Taalrichting",
+langcode:"Taalcode",
+mime:"Doel MIME type",
+ltr:"Van links naar rechts",
+rtl:"Van rechts naar links",
+bgimage:"Achtergrondafbeelding",
+summary:"Samenvatting",
+td:"Gegevens",
+th:"Kop",
+cell_cell:"Huidige cel bijwerken",
+cell_row:"Alle cellen in rij bijwerken",
+cell_all:"Alle cellen in tabel bijwerken",
+row_row:"Huidige rij bijwerken",
+row_odd:"Oneven rijen bijwerken",
+row_even:"Even rijen bijwerken",
+row_all:"Alle rijen bijwerken",
+thead:"Tabelkop",
+tbody:"Tabellichaam",
+tfoot:"Tabelvoet",
+scope:"Bereik",
+rowgroup:"Rijgroep",
+colgroup:"Kolomgroep",
+col_limit:"U heeft het maximale aantal kolommen van {$cols} overschreden.",
+row_limit:"U heeft hebt het maximale aantal rijen van {$rows} overschreden.",
+cell_limit:"U heeft het maximale aantal cellen van {$cells} overschreden.",
+missing_scope:"Weet u zeker dat u door wilt gaan met het toewijzen van een kop zonder een bereik op te geven? Mensen met een visuele handicap kunnen hierdoor waarschijnlijk slecht bij de gegevens.",
+caption:"Tabelbeschrijving",
+frame:"Frame",
+frame_none:"Geen",
+frame_groups:"Groepen",
+frame_rows:"Rijen",
+frame_cols:"Kolommen",
+frame_all:"Alles",
+rules:"Hulplijnen",
+rules_void:"Geen",
+rules_above:"Boven",
+rules_below:"Onder",
+rules_hsides:"Horizontale zijden",
+rules_lhs:"Linkerzijkant",
+rules_rhs:"Rechterzijkant",
+rules_vsides:"Verticale zijden",
+rules_box:"Box",
+rules_border:"Rand"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/template/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/template/langs/nl_dlg.js
new file mode 100644
index 0000000..bcbbe54
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/template/langs/nl_dlg.js
@@ -0,0 +1,15 @@
+tinyMCE.addI18n('nl.template_dlg',{
+title:"Sjablonen",
+label:"Sjabloon",
+desc_label:"Beschrijving",
+desc:"Voorgedefinieerd sjabloon invoegen",
+select:"Selecteer een sjabloon",
+preview:"Voorbeeld",
+warning:"Waarschuwing: het bijwerken van een sjabloon met een andere kan het verlies van informatie tot gevolg hebben.",
+mdate_format:"%d-%m-%Y %H:%M:%S",
+cdate_format:"%d-%m-%Y %H:%M:%S",
+months_long:"Januari,Februari,Maart,April,Mei,Juni,Juli,Augustus,September,Oktober,November,December",
+months_short:"Jan,Feb,Mar,Apr,Mei,Jun,Jul,Aug,Sep,Okt,Nov,Dec",
+day_long:"Zondag,Maandag,Dinsdag,Woensdag,Donderdag,Vrijdag,Zaterdag,Zondag",
+day_short:"zo,ma,di,wo,do,vr,za,zo"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/plugins/xhtmlxtras/langs/nl_dlg.js b/application/assets/js/tiny_mce/plugins/xhtmlxtras/langs/nl_dlg.js
new file mode 100644
index 0000000..659e763
--- /dev/null
+++ b/application/assets/js/tiny_mce/plugins/xhtmlxtras/langs/nl_dlg.js
@@ -0,0 +1,32 @@
+tinyMCE.addI18n('nl.xhtmlxtras_dlg',{
+attribute_label_title:"Titel",
+attribute_label_id:"ID",
+attribute_label_class:"Klasse",
+attribute_label_style:"Stijl",
+attribute_label_cite:"Citaat",
+attribute_label_datetime:"Datum/Tijd",
+attribute_label_langdir:"Tekstrichting",
+attribute_option_ltr:"Van links naar rechts",
+attribute_option_rtl:"Van rechts naar links",
+attribute_label_langcode:"Taal",
+attribute_label_tabindex:"Tabvolgorde",
+attribute_label_accesskey:"Toegangstoets",
+attribute_events_tab:"Gebeurtenissen",
+attribute_attrib_tab:"Attributen",
+general_tab:"Algemeen",
+attrib_tab:"Attributen",
+events_tab:"Gebeurtenissen",
+fieldset_general_tab:"Algemene instellingen",
+fieldset_attrib_tab:"Elementattributen",
+fieldset_events_tab:"Element Gebeurtenissen",
+title_ins_element:"Invoegingselement",
+title_del_element:"Verwijderingselement",
+title_acronym_element:"Synoniem",
+title_abbr_element:"Afkorting",
+title_cite_element:"Citaat",
+remove:"Verwijderen",
+insert_date:"Huidige datum/tijd invoegen",
+option_ltr:"Van links naar rechts",
+option_rtl:"Van rechts naar links",
+attribs_title:"Attributen Invoegen/bewerken"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/themes/advanced/langs/nl.js b/application/assets/js/tiny_mce/themes/advanced/langs/nl.js
new file mode 100644
index 0000000..1e67ec9
--- /dev/null
+++ b/application/assets/js/tiny_mce/themes/advanced/langs/nl.js
@@ -0,0 +1,62 @@
+tinyMCE.addI18n('nl.advanced',{
+style_select:"Stijlen",
+font_size:"Tekengrootte",
+fontdefault:"Lettertype",
+block:"Opmaak",
+paragraph:"Alinea",
+div:"Div",
+address:"Adres",
+pre:"Vaste opmaak",
+h1:"Kop 1",
+h2:"Kop 2",
+h3:"Kop 3",
+h4:"Kop 4",
+h5:"Kop 5",
+h6:"Kop 6",
+blockquote:"Citaat",
+code:"Code",
+samp:"Codevoorbeeld",
+dt:"Definitieterm",
+dd:"Definitiebeschrijving",
+bold_desc:"Vet (Ctrl+B)",
+italic_desc:"Cursief (Ctrl+I)",
+underline_desc:"Onderstrepen (Ctrl+U)",
+striketrough_desc:"Doorhalen",
+justifyleft_desc:"Links uitlijnen",
+justifycenter_desc:"Centreren",
+justifyright_desc:"Rechts uitlijnen",
+justifyfull_desc:"Uitvullen",
+bullist_desc:"Opsommingstekens",
+numlist_desc:"Nummering",
+outdent_desc:"Inspringing verkleinen",
+indent_desc:"Inspringing vergroten",
+undo_desc:"Ongedaan maken (Ctrl+Z)",
+redo_desc:"Herhalen (Ctrl+Y)",
+link_desc:"Link invoegen/bewerken",
+unlink_desc:"Link verwijderen",
+image_desc:"Afbeelding invoegen/bewerken",
+cleanup_desc:"Code opruimen",
+code_desc:"HTML bron bewerken",
+sub_desc:"Subscript",
+sup_desc:"Superscript",
+hr_desc:"Scheidingslijn invoegen",
+removeformat_desc:"Opmaak verwijderen",
+custom1_desc:"Uw eigen beschrijving hier",
+forecolor_desc:"Tekstkleur",
+backcolor_desc:"Tekstmarkeringskleur",
+charmap_desc:"Symbool invoegen",
+visualaid_desc:"Hulplijnen weergeven",
+anchor_desc:"Anker invoegen/bewerken",
+cut_desc:"Knippen",
+copy_desc:"Kopi\u00EBren",
+paste_desc:"Plakken",
+image_props_desc:"Afbeeldingseigenschappen",
+newdocument_desc:"Nieuw document",
+help_desc:"Help",
+blockquote_desc:"Citaat",
+clipboard_msg:"Kopi\u00EBren/knippen/plakken is niet beschikbaar in Mozilla en Firefox.\nWilt u meer informatie over deze beperking?",
+path:"Pad",
+newdocument:"Weet u zeker dat u alle inhoud wilt wissen?",
+toolbar_focus:"Spring naar werkbalk - Alt+Q, Spring naar tekst - Alt-Z, Spring naar elementpad - Alt-X",
+more_colors:"Meer kleuren"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/themes/advanced/langs/nl_dlg.js b/application/assets/js/tiny_mce/themes/advanced/langs/nl_dlg.js
new file mode 100644
index 0000000..46300ab
--- /dev/null
+++ b/application/assets/js/tiny_mce/themes/advanced/langs/nl_dlg.js
@@ -0,0 +1,51 @@
+tinyMCE.addI18n('nl.advanced_dlg',{
+about_title:"Over TinyMCE",
+about_general:"Info",
+about_help:"Help",
+about_license:"Licentie",
+about_plugins:"Invoegtoepassingen",
+about_plugin:"Invoegtoepassing",
+about_author:"Auteur",
+about_version:"Versie",
+about_loaded:"Geladen Invoegtoepassingen",
+anchor_title:"Anker invoegen/bewerken",
+anchor_name:"Ankernaam",
+code_title:"HTML Bron",
+code_wordwrap:"Automatische terugloop",
+colorpicker_title:"Kleuren",
+colorpicker_picker_tab:"Alle kleuren",
+colorpicker_picker_title:"Alle kleuren",
+colorpicker_palette_tab:"Palet",
+colorpicker_palette_title:"Paletkleuren",
+colorpicker_named_tab:"Benoemd",
+colorpicker_named_title:"Benoemde kleuren",
+colorpicker_color:"Kleur:",
+colorpicker_name:"Naam:",
+charmap_title:"Symbolen",
+image_title:"Afbeelding invoegen/bewerken",
+image_src:"Bestand/URL",
+image_alt:"Beschrijving",
+image_list:"Lijst",
+image_border:"Rand",
+image_dimensions:"Afmetingen",
+image_vspace:"Verticale ruimte",
+image_hspace:"Horizontale ruimte",
+image_align:"Uitlijning",
+image_align_baseline:"Basislijn",
+image_align_top:"Boven",
+image_align_middle:"Midden",
+image_align_bottom:"Onder",
+image_align_texttop:"Bovenkant tekst",
+image_align_textbottom:"Onderkant tekst",
+image_align_left:"Links",
+image_align_right:"Rechts",
+link_title:"Link invoegen/bewerken",
+link_url:"URL",
+link_target:"Doel",
+link_target_same:"Link in hetzelfde venster openen",
+link_target_blank:"Link in een nieuw venster openen",
+link_titlefield:"Titel",
+link_is_email:"De ingevoerde URL lijkt op een e-mailadres. Wilt u de vereiste mailto: tekst voorvoegen?",
+link_is_external:"De ingevoerde URL lijkt op een externe link. Wilt u de vereiste http:// tekst voorvoegen?",
+link_list:"Link lijst"
+});
\ No newline at end of file
diff --git a/application/assets/js/tiny_mce/themes/simple/langs/nl.js b/application/assets/js/tiny_mce/themes/simple/langs/nl.js
new file mode 100644
index 0000000..a28ea63
--- /dev/null
+++ b/application/assets/js/tiny_mce/themes/simple/langs/nl.js
@@ -0,0 +1,11 @@
+tinyMCE.addI18n('nl.simple',{
+bold_desc:"Vet (Ctrl+B)",
+italic_desc:"Cursief (Ctrl+I)",
+underline_desc:"Onderstrepen (Ctrl+U)",
+striketrough_desc:"Doorhalen",
+bullist_desc:"Opsommingstekens",
+numlist_desc:"Nummering",
+undo_desc:"Ongedaan maken (Ctrl+Z)",
+redo_desc:"Herhalen (Ctrl+Y)",
+cleanup_desc:"Code opruimen"
+});
\ No newline at end of file
|
jtietema/Fizzy
|
35bbe81499799b7c6fc2d09bb6965fc96880619e
|
most of the backend is translated
|
diff --git a/application/Bootstrap.php b/application/Bootstrap.php
index f9a5874..6317300 100644
--- a/application/Bootstrap.php
+++ b/application/Bootstrap.php
@@ -1,130 +1,143 @@
<?php
/**
* Class Bootstrap
* @category Fizzy
* @package Fizzy_Bootstrap
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Description of Bootstrap
*
* @author jeroen
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* Initializes a new view object and loads the view directories into it.
* @return Zend_View
*/
protected function _initView()
{
$view = new Zend_View();
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'Fizzy', 'View', 'Helper')
)), 'Fizzy_View_Helper');
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'ZendX', 'JQuery', 'View', 'Helper')
)), 'ZendX_JQuery_View_Helper');
return $view;
}
/**
* Starts Zend_Layout in MVC mode.
* @todo add custom front controller plugin for layout allow multiple layouts
* @return Zend_Layout
*/
protected function _initLayout()
{
$this->bootstrap('FrontController');
$layout = Zend_Layout::startMvc(array (
'layout' => 'default',
));
$front = $this->getResource('FrontController');
$front->registerPlugin(new Fizzy_Layout_ControllerPlugin());
return $layout;
}
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
return $config;
}
protected function _initRoutes()
{
$this->bootstrap('FrontController');
$options = $this->getOptions();
$backendSwitch = isset($options['backendSwitch']) ? strtolower((string) $options['backendSwitch']) : 'fizzy';
$router = $this->getContainer()->frontcontroller->getRouter();
$config = new Zend_Config_Ini(ROOT_PATH . '/configs/routes.ini');
$routes = $config->{$this->getEnvironment()}->toArray();
// Parse all routes and replace the backend switch
foreach ($routes as &$route) {
if (false !== strpos($route['route'], '{backend}')) {
$route['route'] = str_replace('{backend}', $backendSwitch, $route['route']);
}
}
// Load parsed routes into the router
$router->addConfig(new Zend_Config($routes));
return $router;
}
protected function _initTypes()
{
$config = new ZendL_Config_Yaml(ROOT_PATH . '/configs/types.yml');
$types = Fizzy_Types::initialize($config);
return $types;
}
/**
* @todo make adapter class configurable
*/
protected function _initSpam()
{
$this->bootstrap('Config');
$config = $this->getContainer()->config;
$adapter = new Fizzy_Spam_Adapter_Akismet($config->spam->akismetKey, $config->spam->siteUrl);
Fizzy_Spam::setDefaultAdapter($adapter);
}
protected function _initModuleErrorHandler()
{
$this->bootstrap('FrontController');
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Fizzy_Controller_Plugin_ErrorHandlerModuleSelector());
}
+ protected function _initTranslate()
+ {
+ $translate = new Zend_Translate(
+ array(
+ 'adapter' => 'array',
+ 'content' => ROOT_PATH . '/languages/admin_nl.php',
+ 'locale' => 'nl'
+ )
+ );
+ Zend_Registry::set('Zend_Translate', $translate);
+ return $translate;
+ }
+
}
diff --git a/application/modules/admin/controllers/CommentsController.php b/application/modules/admin/controllers/CommentsController.php
index 691cd61..df1daaa 100644
--- a/application/modules/admin/controllers/CommentsController.php
+++ b/application/modules/admin/controllers/CommentsController.php
@@ -1,287 +1,287 @@
<?php
/**
* Class Admin_CommentsController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Controller class for the moderation panel of comments
*
* @author Jeroen Tietema <[email protected]>
*/
class Admin_CommentsController extends Fizzy_SecuredController
{
/**
* Dashboard. Shows latest comments and total numbers of comments, spam, etc.
*/
public function indexAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = 0')->orderBy('id DESC');
$this->view->totalComments = $query->count();
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$spamQuery = Doctrine_Query::create()->from('Comments')->where('spam = 1');
$this->view->spamComments = $spamQuery->count();
$this->view->paginator = $paginator;
}
/**
* List of discussions/topics
*/
public function listAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')
->groupBy('post_id')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
/**
* Shows one discussion/topic/thread.
*/
public function topicAction()
{
$id = $this->_getParam('id', null);
$pageNumber = $this->_getParam('page', 1);
if (null === $id){
return $this->renderScript('comments/topic-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('post_id = ?', $id)->andWhere('spam = 0')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$tempModel = $query->fetchOne();
if (null == $tempModel){
return $this->renderScript('comments/topic-not-found.phtml');
}
$this->view->threadModel = $tempModel->getThreadModel();
$this->view->paginator = $paginator;
}
/**
* Marks given message as spam.
*/
public function spamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = true;
$comment->save();
/**
* @todo pass to the spam backend
*/
$this->_redirectBack($comment);
}
/**
* Unmarks given message as spam.
*/
public function hamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = false;
$comment->save();
/**
* @todo pass to the Spam backend
*/
$this->_redirectBack($comment);
}
/**
* Edit the comment.
*/
public function editAction()
{
$id = $this->_getParam('id', null);
$redirect = $this->_getParam('back', 'dashboard');
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$form = new Zend_Form();
$form->setAction($this->view->url('@admin_comments_edit?id=' . $comment->id) . '&back=' . $redirect);
$form->addElement(new Zend_Form_Element_Text('name', array(
'label' => 'Author name'
)));
$form->addElement(new Zend_Form_Element_Text('email', array(
- 'label' => 'Author E-mail'
+ 'label' => 'Author e-mail'
)));
$form->addElement(new Zend_Form_Element_Text('website', array(
'label' => 'Author website'
)));
$form->addElement(new Zend_Form_Element_Textarea('body', array(
'label' => 'Comment'
)));
$form->addElement(new Zend_Form_Element_Submit('save', array(
'label' => 'Save'
)));
if ($this->_request->isPost() && $form->isValid($_POST)){
$comment->name = $form->name->getValue();
$comment->email = $form->email->getValue();
$comment->website = $form->website->getValue();
$comment->body = $form->body->getValue();
$comment->save();
$this->_redirectBack($comment);
}
$form->name->setValue($comment->name);
$form->email->setValue($comment->email);
$form->website->setValue($comment->website);
$form->body->setValue($comment->body);
$this->view->form = $form;
$this->view->comment = $comment;
$this->view->back = $redirect;
}
/**
* Delete the comment.
*/
public function deleteAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->delete();
$this->_redirectBack($comment);
}
/**
* Approve the comment (when using moderation).
*/
public function approveAction()
{
}
/**
* Unapprove the given comment.
*/
public function unapproveAction()
{
}
/**
* Shows the spambox containing all spam comments
*/
public function spamboxAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = ?', 1);
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
protected function _redirectBack(Comments $comment = null)
{
$redirect = $this->_getParam('back', 'dashboard');
switch($redirect){
case 'topic':
$this->_redirect('@admin_comments_topic', array('id' => $comment->post_id));
break;
case 'spambox':
$this->_redirect('@admin_comments_spam');
break;
case 'post':
$postId = (int) substr($comment->post_id, 5);
$this->_redirect('@admin_blog_post_edit', array('id' => $postId));
default:
$this->_redirect('@admin_comments');
break;
}
}
}
diff --git a/application/modules/admin/controllers/MediaController.php b/application/modules/admin/controllers/MediaController.php
index be03781..c1be1e4 100644
--- a/application/modules/admin/controllers/MediaController.php
+++ b/application/modules/admin/controllers/MediaController.php
@@ -1,215 +1,215 @@
<?php
/**
* Class Admin_MediaController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Description of Media
*
* @author mattijs
*/
class Admin_MediaController extends Fizzy_SecuredController
{
/**
* @todo implement overwrite checkbox
*/
public function indexAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
$form = $this->_getForm($uploadFolder);
if($this->_request->isPost()) {
if($form->isValid($_POST) && $form->file->receive()) {
$this->addSuccessMessage('File was successfully uploaded.');
}
else {
foreach($form->getErrorMessages() as $message) {
$this->addErrorMessage($message);
}
}
$this->_redirect('@admin_media');
}
# Parse all files in the upload directory
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file) {
if($file->isFile()) {
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
# Render the view
$this->view->uploadFolder = $uploadFolder;
$this->view->files = $files;
$this->view->form = $form;
$this->view->type = $this->_request->getParam('type', 'list');
$this->renderScript('media.phtml');
}
public function displayAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file) {
if($file->isFile()) {
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
$type = $this->_getParam('type', 'list');
if($type == 'thumbnail') {
$script = 'media/thumbnails.phtml';
} else {
$script = 'media/list.phtml';
}
$this->renderScript($script);
}
public function deleteAction()
{
$name = $this->_getParam('name');
if(null !== $name)
{
$name = basename(urldecode($name));
$uploadFolder = ROOT_PATH . '/public/uploads/';
$file = $uploadFolder . DIRECTORY_SEPARATOR . $name;
if(is_file($file))
{
unlink($file);
$this->addSuccessMessage('File was successfully deleted.');
}
}
$this->_redirect('@admin_media');
}
/**
* Returns the form for file uploads
* @param string $uploadFolder
* @return Zend_Form
*/
protected function _getForm($uploadFolder)
{
$formConfig = array (
'action' => $this->view->url('@admin_media'),
'enctype' => 'multipart/form-data',
'elements' => array(
'file' => array (
'type' => 'file',
'options' => array (
'label' => 'File',
- 'description' => 'Choose a file to upload. The maximun file size is ' . str_replace(array('K', 'M', 'G'), array(' KB', ' MB', ' GB'), ini_get('upload_max_filesize')) . '.',
+ 'description' => $this->translate('Choose a file to upload. The maximun file size is') . ' ' . str_replace(array('K', 'M', 'G'), array(' KB', ' MB', ' GB'), ini_get('upload_max_filesize')) . '.',
'required' => true,
'destination' => $uploadFolder,
)
),
/*'overwrite' => array (
'type' => 'checkbox',
'options' => array (
'label' => 'Overwrite existing?',
'description' => 'If this is checked any existing file with the same name will be overridden.',
'required' => false,
)
),*/
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Upload',
'ignore' => true,
)
)
),
);
return new Zend_Form(new Zend_Config($formConfig));
}
/**
* Action for the image picker popup
*/
public function galleryAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
// Parse all files in the upload directory
$files = array();
$imageTypes = array('png', 'jpg', 'jpeg', 'bmp', 'gif');
foreach(new DirectoryIterator($uploadFolder) as $file)
{
if($file->isFile())
{
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
if (in_array($fileInfo['type'], $imageTypes)) {
$files[] = (object) $fileInfo;
}
}
}
// Render the view
$this->view->files = $files;
$this->_helper->layout->disableLayout();
}
public function assetsAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
// Parse all files in the upload directory
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file)
{
if($file->isFile())
{
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
// Render the view
$this->view->files = $files;
$this->_helper->layout->disableLayout();
}
}
diff --git a/application/modules/admin/views/layouts/default.phtml b/application/modules/admin/views/layouts/default.phtml
index c99b4f7..56bad7d2 100644
--- a/application/modules/admin/views/layouts/default.phtml
+++ b/application/modules/admin/views/layouts/default.phtml
@@ -1,81 +1,81 @@
<?php
/**
* Fizzy layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<!DOCTYPE html>
<html>
<head>
<title>Fizzy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy-2.0.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/tables.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/forms.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<?= $this->jQuery()->setVersion('1.4.2')->enable()->addStylesheet('http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css') ?>
<script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/tiny_mce.js'); ?>"></script>
<script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/fizzy.js'); ?>"></script>
</head>
<body>
<div id="container">
<div id="header-panel">
<h1>Fizzy</h1>
<div id="navigation-panel">
<?= $this->action('navigation', 'index', 'admin'); ?>
</div>
</div>
<div id="sub-navigation-panel">
<?= $this->action('subnavigation', 'index', 'admin'); ?>
</div>
<div id="messages-panel">
<?= $this->render('flashMessages.phtml'); ?>
</div>
<div id="main-panel">
<?= $this->layout()->content; ?>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div id="footer-panel">
<div id="copyright-panel">
Fizzy <?= Fizzy_Version::VERSION ?>
- running on
+ <?= $this->translate('running on') ?>
Zend Framework <?= Zend_Version::VERSION ?>
- and
+ <?= $this->translate('and') ?>
Doctrine <?= Doctrine::VERSION ?>
|
- (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd">license</a><br />
+ (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a><br />
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
diff --git a/application/modules/admin/views/layouts/login.phtml b/application/modules/admin/views/layouts/login.phtml
index 15421cb..db96206 100644
--- a/application/modules/admin/views/layouts/login.phtml
+++ b/application/modules/admin/views/layouts/login.phtml
@@ -1,57 +1,57 @@
<?php
/**
* Fizzy login layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Fizzy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy-2.0.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/tables.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/forms.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<script type="text/javascript" src="<?= $this->baseUrl("/fizzy_assets/js/jquery-1.3.2.min.js"); ?>"></script>
</head>
<body>
<div id="container">
<div id="login-panel">
- <h1>Fizzy login</h1>
+ <h1><?= $this->translate('Fizzy login') ?></h1>
<div id="message-panel">
<?= $this->fizzyMessages(); ?>
</div>
<?= $this->layout()->content; ?>
<div class="clear"></div>
</div>
<div style="position: absolute; width: 500px; top: 280px; left: 50%; margin-left: -250px; padding: 10px; text-align: right;">
- (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd">license</a>
+ (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd"><?= $this->translate('license') ?></a>
</div>
</div>
</body>
</html>
diff --git a/application/modules/admin/views/scripts/_pagination.phtml b/application/modules/admin/views/scripts/_pagination.phtml
index e88da1a..1ee4374 100644
--- a/application/modules/admin/views/scripts/_pagination.phtml
+++ b/application/modules/admin/views/scripts/_pagination.phtml
@@ -1,21 +1,21 @@
<?php if (isset($this->previous)): ?>
<a href="?page=<?= $this->previous ?>">
- << prev
+ << <?= $this->translate('prev') ?>
</a>
<?php else: ?>
- << prev
+ << <?= $this->translate('prev') ?>
<?php endif; ?>
<?php foreach ($this->pagesInRange as $page): ?>
<a href="?page=<?= $page ?>">
<?= $page; ?>
</a>
<?php endforeach; ?>
<?php if (isset($this->next)): ?>
<a href="?page=<?= $this->next ?>">
- next >>
+ <?= $this->translate('next') ?> >>
</a>
<?php else: ?>
- next >>
+ <?= $this->translate('next') ?> >>
<?php endif; ?>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/blogs/blog.phtml b/application/modules/admin/views/scripts/blogs/blog.phtml
index 9cd7511..82b475b 100644
--- a/application/modules/admin/views/scripts/blogs/blog.phtml
+++ b/application/modules/admin/views/scripts/blogs/blog.phtml
@@ -1,56 +1,56 @@
<div id="content-panel">
<h2><?= $this->blog->name ?></h2>
<div>
<table class="data">
<thead>
<tr>
<td> </td>
- <td>Title</td>
- <td>Date</td>
- <td>Status</td>
- <td>Author</td>
+ <td><?= $this->translate('Title') ?></td>
+ <td><?= $this->translate('Date') ?></td>
+ <td><?= $this->translate('Status') ?></td>
+ <td><?= $this->translate('Author') ?></td>
</tr>
</thead>
<tbody>
<?php $items = $this->paginator->getCurrentItems();
foreach ($items as $post): ?>
<tr>
<td class="controls">
- <?= $this->link('@admin_blog_post_edit?post_id=' . $post->id, $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_edit?post_id=' . $post->id, $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => $this->translate('edit page'), 'escape' => false)); ?>
</td>
<td>
<?= $post->title ?>
</td>
<td>
<?= $post->date ?>
</td>
<td>
<?php if ($post->status == Post::PUBLISHED): ?>
- Published
+ <?= $this->translate('Published') ?>
<?php elseif ($post->status == Post::PENDING_REVIEW): ?>
- Pending review
+ <?= $this->translate('Pending review') ?>
<?php else: ?>
- Draft
+ <?= $this->translate('Draft') ?>
<?php endif; ?>
</td>
<td>
<?= $post->User->displayname ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_blog_post_add?blog_id=' . $this->blog->id, $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' Add post', array('escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_add?blog_id=' . $this->blog->id, $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' '.$this->translate('Add post'), array('escape' => false)); ?>
</li>
</ul>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/blogs/index.phtml b/application/modules/admin/views/scripts/blogs/index.phtml
index f90c179..422cc5f 100644
--- a/application/modules/admin/views/scripts/blogs/index.phtml
+++ b/application/modules/admin/views/scripts/blogs/index.phtml
@@ -1,25 +1,25 @@
<div id="content-panel">
- <h2>Blogs</h2>
+ <h2><?= $this->translate('Blogs') ?></h2>
<div>
<table class="data">
<thead>
<tr>
- <td>Blog name</td>
- <td>Slug</td>
- <td>Group slug</td>
+ <td><?= $this->translate('Blog name') ?></td>
+ <td><?= $this->translate('Slug') ?></td>
+ <td><?= $this->translate('Group slug') ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($this->blogs as $blog) : ?>
<tr>
<td><a href="<?= $this->url('@admin_blog?id=' . $blog->id) ?>"><?= $blog->name ?></a></td>
<td><?= $blog->slug ?></td>
<td><?= $blog->group_slug ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel"></div>
diff --git a/application/modules/admin/views/scripts/blogs/post-form.phtml b/application/modules/admin/views/scripts/blogs/post-form.phtml
index 12d1467..a845505 100644
--- a/application/modules/admin/views/scripts/blogs/post-form.phtml
+++ b/application/modules/admin/views/scripts/blogs/post-form.phtml
@@ -1,73 +1,73 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
<?= $this->image($this->assetUrl('/images/icon/document.png', false)); ?>
- <?= ($this->post->isNew()) ? 'Add post' : 'Edit post'; ?>
+ <?= $this->translate($this->post->isNew() ? 'Add post' : 'Edit post') ?>
</h2>
<div class="form-panel">
<?= $this->form->title; ?>
<?= $this->form->body; ?>
</div>
<h2>
<?= $this->image($this->assetUrl('/images/icon/balloons.png', false)); ?>
- Comments on this post
+ <?= $this->translate('Comments on this post') ?>
</h2>
<div class="comments">
<?= $this->partial('comments/_comments.phtml', array(
'comments' => $this->post->Comments(),
'back' => 'post'
)) ?>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <input type="submit" value="Save" />
+ <input type="submit" value="<?= $this->translate('Save') ?>" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->post->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_blog_post_delete?post_id=' . $this->post->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete page',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' '.$this->translate('delete post'),
array(
'class' => 'delete',
- 'confirm' => 'Are you sure you want to delete this page?',
+ 'confirm' => $this->translate('Are you sure you want to delete this post?'),
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_blog?id=' . $this->post->Blog->id,
- $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to ' . $this->post->Blog->name,
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' '.$this->translate('back to').' ' . $this->post->Blog->name,
array('escape' => false)
); ?>
</li>
</ul>
- <h2>Options</h2>
+ <h2><?= $this->translate('Options') ?></h2>
<div class="form-options-panel">
<?= $this->form->status; ?>
<?= $this->form->author; ?>
<?= $this->form->date; ?>
<?= $this->form->comments; ?>
</div>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/_comments.phtml b/application/modules/admin/views/scripts/comments/_comments.phtml
index 5c3a393..c876487 100644
--- a/application/modules/admin/views/scripts/comments/_comments.phtml
+++ b/application/modules/admin/views/scripts/comments/_comments.phtml
@@ -1,50 +1,50 @@
<?php foreach ($this->comments as $comment): ?>
<?php
$thread = $comment->getThreadModel();
?>
<div class="comment">
<div class="avatar">
<img src="http://www.gravatar.com/avatar/<?= md5(trim(strtolower($comment->email))) ?>?s=80" alt="<?= $comment->name ?>" />
</div>
<div class="content">
<div class="author-info">
- <span class="gray1">From</span> <?= $comment->name ?>
- <?= (!empty($thread)) ? '<span class="gray1">on</span> '.
+ <span class="gray1"><?= $this->translate('From') ?></span> <?= $comment->name ?>
+ <?= (!empty($thread)) ? '<span class="gray1">' . $this->translate('on') . '</span> '.
$this->link('@admin_comments_topic?id=' . $comment->post_id,$thread->label()) : '' ?>
</div>
<div class="comment-body">
<?= $comment->body ?>
</div>
<div class="actions">
<ul>
<li>
- <?= $this->link('@admin_comments_edit?id=' . $comment->id . '&back=' . $this->back, 'Edit', array(
+ <?= $this->link('@admin_comments_edit?id=' . $comment->id . '&back=' . $this->back, $this->translate('Edit'), array(
'class' => 'c3button'
)) ?>
</li>
<li>
<?php if ($comment->isSpam()) : ?>
- <?= $this->link('@admin_comments_ham?id=' . $comment->id . '&back=' . $this->back, 'Not spam', array(
+ <?= $this->link('@admin_comments_ham?id=' . $comment->id . '&back=' . $this->back, $this->translate('Not spam'), array(
'class' => 'c3button'
)) ?>
<?php else: ?>
- <?= $this->link('@admin_comments_spam?id=' . $comment->id . '&back=' . $this->back, 'Spam', array(
+ <?= $this->link('@admin_comments_spam?id=' . $comment->id . '&back=' . $this->back, $this->translate('Spam'), array(
'class' => 'c3button'
)) ?>
<?php endif; ?>
</li>
<li><?= $this->link(
'@admin_comments_delete?id=' . $comment->id . '&back=' . $this->back,
- 'Delete',
+ $this->translate('Delete'),
array(
'class' => 'delete c3button',
- 'confirm' => 'Are you sure you want to delete this comment?',
+ 'confirm' => $this->translate('Are you sure you want to delete this comment?'),
)
); ?>
</li>
</ul>
</div>
</div>
<div class="clear"></div>
</div>
<?php endforeach; ?>
diff --git a/application/modules/admin/views/scripts/comments/edit.phtml b/application/modules/admin/views/scripts/comments/edit.phtml
index 25145a2..ed6c37a 100644
--- a/application/modules/admin/views/scripts/comments/edit.phtml
+++ b/application/modules/admin/views/scripts/comments/edit.phtml
@@ -1,54 +1,54 @@
<form action="<?= $this->form->getAction(); ?>" method="post">
<div id="content-panel">
<h2>
- Edit Comment
+ <?= $this->translate('Edit comment') ?>
</h2>
<div class="form-panel">
<?= $this->form->name; ?>
<?= $this->form->email; ?>
<?= $this->form->website; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <input type="submit" value="Save" />
+ <input type="submit" value="<?= $this->translate('Save') ?>" />
</li>
</ul>
<hr />
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
'@admin_comments_delete?id=' . $this->comment->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete comment',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' '.$this->translate('delete comment'),
array(
'class' => 'delete',
- 'confirm' => 'Are you sure you want to delete this comment?',
+ 'confirm' => $this->translate('Are you sure you want to delete this comment?'),
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
<?= $this->link(
'@admin_comments_topic?id=' . $this->comment->post_id,
- $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to comments',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' '.$this->translate('back to comments'),
array(
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/comments/index.phtml b/application/modules/admin/views/scripts/comments/index.phtml
index 2b99567..bf18e1b 100644
--- a/application/modules/admin/views/scripts/comments/index.phtml
+++ b/application/modules/admin/views/scripts/comments/index.phtml
@@ -1,29 +1,29 @@
<div id="content-panel">
- <h2>Latest comments</h2>
+ <h2><?= $this->translate('Latest comments') ?></h2>
<?= $this->partial('comments/_comments.phtml', array(
'comments' => $this->paginator->getCurrentItems(),
'back' => 'dashboard'
)) ?>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
<div id="sidebar-panel">
- <h2>Comments overview</h2>
+ <h2><?= $this->translate('Comments overview') ?></h2>
<table class="data">
<tbody>
<tr>
- <td><?= $this->link('@admin_comments_list', 'Total comments') ?></td>
+ <td><?= $this->link('@admin_comments_list', $this->translate('Total comments')) ?></td>
<td><?= $this->totalComments ?></td>
</tr>
<tr>
- <td><?= $this->link('@admin_comments_spambox', 'Spam') ?></td>
+ <td><?= $this->link('@admin_comments_spambox', $this->translate('Spam')) ?></td>
<td><?= $this->spamComments ?></td>
</tr>
</tbody>
</table>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/list.phtml b/application/modules/admin/views/scripts/comments/list.phtml
index f68bcb6..e67c7cc 100644
--- a/application/modules/admin/views/scripts/comments/list.phtml
+++ b/application/modules/admin/views/scripts/comments/list.phtml
@@ -1,34 +1,34 @@
<div id="content-panel">
- <h2>Discussions</h2>
+ <h2><?= $this->translate('Discussions') ?></h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
- <td>Title</td>
- <td>Number comments</td>
+ <td><?= $this->translate('Title') ?></td>
+ <td><?= $this->translate('Number comments') ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($this->paginator->getCurrentItems() as $topic): ?>
<tr>
<td class="controls">
</td>
<td><?= $this->link('@admin_comments_topic?id=' . $topic->post_id, $topic->getThreadModel()->label()) ?></td>
<td><?= $topic->getNumberTopicComments() ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
</div>
<div id="sidebar-panel">
</div>
diff --git a/application/modules/admin/views/scripts/contact/index.phtml b/application/modules/admin/views/scripts/contact/index.phtml
index f157cd9..4bc5a31 100644
--- a/application/modules/admin/views/scripts/contact/index.phtml
+++ b/application/modules/admin/views/scripts/contact/index.phtml
@@ -1,37 +1,37 @@
<div id="content-panel">
- <h2>Contact</h2>
+ <h2><?= $this->translate('Contact') ?></h2>
<table class="data" id="contact-table">
<thead>
<tr>
<th> </th>
- <th>Date</th>
- <th>Name</th>
+ <th><?= $this->translate('Date') ?></th>
+ <th><?= $this->translate('Name') ?></th>
</tr>
</thead>
<tbody>
<?php foreach($this->messages as $message) : ?>
<tr>
<td class="controls" style="width: 55px;">
<?= $this->link('@admin_contact_show?id=' . $message->id, $this->image($this->assetUrl('/images/icon/mail-open.png', false)), array('escape' => false)); ?>
<?= $this->link(
'@admin_contact_delete?id=' . $message->id,
$this->image($this->assetUrl('/images/icon/mail--minus.png', false)),
array (
'confirm' => 'Are you sure you want to delete this contact request?',
'escape' => false
)
); ?>
</td>
<td style="width: 150px;"><?= $message->date; ?></td>
<td style="max-width: 300px;"><?= $message->name; ?> <<a href="mailto:<?= $message->email; ?>"><?= $message->email; ?></a>></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/login.phtml b/application/modules/admin/views/scripts/login.phtml
index b2d5926..6a3176d 100644
--- a/application/modules/admin/views/scripts/login.phtml
+++ b/application/modules/admin/views/scripts/login.phtml
@@ -1,7 +1,7 @@
<div class="form-panel">
<form action="<?= $this->form->getAction(); ?>" id="Loginform" name="LoginForm" method="post">
<?= $this->form->username; ?>
<?= $this->form->password; ?>
- <input type="submit" value="Login" />
+ <input type="submit" value="<?= $this->translate('Login') ?>" />
</form>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/media.phtml b/application/modules/admin/views/scripts/media.phtml
index f805d04..dd6d9ce 100644
--- a/application/modules/admin/views/scripts/media.phtml
+++ b/application/modules/admin/views/scripts/media.phtml
@@ -1,47 +1,48 @@
<div id="content-panel">
- <h2>Media</h2>
+ <h2><?= $this->translate('Media') ?></h2>
<div id="media-panel">
<div id="media-tabs-panel">
<?php
$activeTab = isset($_GET['type']) ? $_GET['type'] : null;
?>
<ul>
<li>
- Show as:
+ <?= $this->translate('Show as') ?>:
</li>
- <li><a class="<?= 'thumbnail' != strtolower($_GET['type']) ? 'active' : ''; ?>" href="<?= $this->baseUrl('/admin/media') ?>">List</a></li>
+ <li><a class="<?= 'thumbnail' != strtolower($_GET['type']) ? 'active' : ''; ?>" href="<?= $this->baseUrl('/admin/media') ?>"><?= $this->translate('List') ?></a></li>
<li> | </li>
- <li><a class="<?= 'thumbnail' == strtolower($_GET['type']) ? 'active' : ''; ?>" href="<?= $this->baseUrl('/admin/media?type=thumbnail') ?>">Thumbnail</a></li>
+ <li><a class="<?= 'thumbnail' == strtolower($_GET['type']) ? 'active' : ''; ?>" href="<?= $this->baseUrl('/admin/media?type=thumbnail') ?>"><?= $this->translate('Thumbnail') ?></a></li>
</ul>
<div class="clear"></div>
</div>
<?= $this->action('display', 'media', 'admin', array('type' => $this->type)); ?>
</div>
</div>
<div id="sidebar-panel">
<div id="upload-form" class="form-container">
- <h2 class="header">Upload</h2>
+ <h2 class="header"><?= $this->translate('Upload') ?></h2>
<p>
- Upload a new file by selecting it on your machine. Check the box if
- you want to overwrite a file that already exists with the same name.
+ <?= $this->translate('Upload a new file by selecting it on your ' .
+ 'machine. Check the box if you want to overwrite a file that ' .
+ 'already exists with the same name.') ?>
<br />
</p>
<?php if(is_writable($this->uploadFolder)) : ?>
<?= $this->form; ?>
<?php else : ?>
<div class="message notice">
<p>
- The upload directory found in the Fizzy configuration is not
- writable. Upload functionality will be disabled until it is made
- writable.
+ <?= $this->translate('The upload directory found in the Fizzy ' .
+ 'configuration is not writable. Upload functionality will be ' .
+ 'disabled until it is made writable.') ?>
</p>
</div>
<?php endif; ?>
</div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/navigation.phtml b/application/modules/admin/views/scripts/navigation.phtml
index 7b97fef..d64c4f6 100644
--- a/application/modules/admin/views/scripts/navigation.phtml
+++ b/application/modules/admin/views/scripts/navigation.phtml
@@ -1,8 +1,8 @@
<ul>
<?php foreach($this->items as $page) : ?>
<li<?= ($page->isActive(true)) ? ' class="active"' : ''; ?>>
- <a href="<?= $page->getHref(); ?>"><?= $page->getLabel(); ?></a>
+ <a href="<?= $page->getHref(); ?>"><?= $this->navigation()->getTranslator()->translate($page->getLabel()) ?></a>
</li>
<?php endforeach; ?>
</ul>
<div class="clear"></div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/pages/form.phtml b/application/modules/admin/views/scripts/pages/form.phtml
index 9ef3186..bc17066 100644
--- a/application/modules/admin/views/scripts/pages/form.phtml
+++ b/application/modules/admin/views/scripts/pages/form.phtml
@@ -1,69 +1,69 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
<?= $this->image($this->assetUrl('/images/icon/document.png', false)); ?>
- <?= ($this->page->isNew()) ? 'Add page' : 'Edit page'; ?>
+ <?= $this->translate(($this->page->isNew()) ? 'Add page' : 'Edit page') ?>
</h2>
<div class="form-panel">
<?= $this->form->id; // required for slugunique validator ?>
<?= $this->form->title; ?>
<?= $this->form->slug; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <input type="submit" value="Save" />
+ <input type="submit" value="<?= $this->translate('Save') ?>" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->page->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_pages_delete?id=' . $this->page->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete page',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' '.$this->translate('delete page'),
array(
'class' => 'delete',
- 'confirm' => 'Are you sure you want to delete this page?',
+ 'confirm' => $this->translate('Are you sure you want to delete this page?'),
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_pages',
- $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to pages',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' '.$this->translate('back to pages'),
array('escape' => false)
); ?>
</li>
</ul>
- <h2>Options</h2>
+ <h2><?= $this->translate('Options') ?></h2>
<div class="form-options-panel">
<?= $this->form->template; ?>
<?= $this->form->layout; ?>
<div class="form-row" id="homepage-row">
- <label for="homepage">Homepage</label>
+ <label for="homepage"><?= $this->translate('Homepage') ?></label>
<?= $this->form->homepage->setDecorators(array('ViewHelper', 'Errors')); ?>
- <?= $this->form->homepage->getDescription(); ?>
+ <?= $this->translate($this->form->homepage->getDescription()) ?>
</div>
</div>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/pages/index.phtml b/application/modules/admin/views/scripts/pages/index.phtml
index 0d41f68..cf837f2 100644
--- a/application/modules/admin/views/scripts/pages/index.phtml
+++ b/application/modules/admin/views/scripts/pages/index.phtml
@@ -1,48 +1,48 @@
<div id="content-panel">
- <h2>Pages</h2>
+ <h2><?= $this->translate('Pages') ?></h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
- <td>Slug</td>
- <td>Title</td>
+ <td><?= $this->translate('Slug') ?></td>
+ <td><?= $this->translate('Title') ?></td>
</tr>
</thead>
<tbody>
<?php foreach($this->pages as $page) : ?>
<tr>
<td class="controls">
- <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => $this->translate('edit page'), 'escape' => false)); ?>
</td>
<td style="width: 200px;"><?= $page['slug'] ?></td>
<td><?= $page['title'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_pages_add', $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' Add page', array('escape' => false)); ?>
+ <?= $this->link('@admin_pages_add', $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' '.$this->translate('Add page'), array('escape' => false)); ?>
</li>
</ul>
<hr />
<div class="block">
- <h2>About pages</h2>
+ <h2><?= $this->translate('About pages') ?></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet fringilla eros in laoreet. Sed rhoncus aliquam accumsan. Nullam nec massa sed elit faucibus ultricies. Vivamus pharetra volutpat posuere. Aliquam a metus neque, et euismod odio. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget metus lacus, quis rhoncus mauris. In sit amet aliquet felis. Aenean luctus ornare posuere. Fusce egestas, nisi nec mattis pretium, lorem lorem venenatis lectus, id ornare lacus justo in neque. Ut commodo risus eu justo vulputate a fringilla quam rhoncus. Curabitur fermentum neque in tellus adipiscing scelerisque.
</p>
</div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/settings/index.phtml b/application/modules/admin/views/scripts/settings/index.phtml
index 0d04ded..ad5cfcb 100644
--- a/application/modules/admin/views/scripts/settings/index.phtml
+++ b/application/modules/admin/views/scripts/settings/index.phtml
@@ -1,201 +1,201 @@
<div id="content-panel">
<h2>
<?= $this->image('/fizzy_assets/images/icon/gear.png', array('alt' => 'Settings Icon')); ?>
- Settings
+ <?= $this->translate('Settings') ?>
</h2>
<table class="settings" id="settings-table">
<tbody>
<?php foreach($this->settings as $component => $settings) : ?>
<tr>
- <th colspan="2"><?= ucfirst($component); ?></th>
+ <th colspan="2"><?= $this->translate(ucfirst($component)) ?></th>
</tr>
<?php foreach($settings as $setting) : ?>
<tr>
<td class="label">
- <?= $setting->label; ?>
+ <?= $this->translate($setting->label) ?>
</td>
<td class="setting editable">
<div id="<?= $setting->component; ?>:<?= $setting->setting_key; ?>" class="value text"><?= $setting->value; ?></div>
- <small><?= $setting->description; ?></small>
+ <small><?= $this->translate($setting->description) ?></small>
</td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>
<?php $this->jQuery()->uiEnable(); ?>
<script type="text/javascript">
(function($) {
$.fn.inlineEdit = function(options) {
options = $.extend({
hoverClass: 'hover-edit',
savingClass: 'saving',
successClass: 'settings-success',
errorClass: 'settings-error',
value: '',
save: ''
}, options);
return $.each(this, function() {
$.inlineEdit(this, options);
});
}
$.inlineEdit = function(object, options) {
// Define self, this is the table cell
var self = $(object);
// Register the container with the setting value
self.valueContainer = self.children('.value');
// Get the initial value
self.value = $.trim(self.valueContainer.text()) || options.value;
// Get the component and key for the setting
var parts = self.valueContainer.attr('id').split(':');
self.settingKey = parts.pop();
self.settingComponent = parts.pop();
/**
* Save function. Executes an AJAX function to save the setting
* if it changed.
* @param newValue
*/
self.save = function(newValue) {
var oldValue = self.value;
// Save new value
self.value = newValue;
// Reset the input
self.reset();
// Only save if new value was different from the old value
if (newValue != oldValue) {
self.removeClass('editing')
.removeClass(options.successClass)
.removeClass(options.errorClass)
.addClass(options.savingClass);
var settingData = {
'component': self.settingComponent,
'settingKey': self.settingKey,
'value': self.value
};
$.ajax({
url: '<?= $this->url('@admin_settings_update'); ?>',
type: 'POST',
processData: false,
data: JSON.stringify(settingData),
contentType: 'application/json',
error: function(data, textStatus, XMLHttpRequest) {
self.value = oldValue;
self.error();
},
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
self.success();
}
});
}
}
/**
* Renders the success class over the table cell.
* This is called after the ajax callback ended successfully.
*/
self.success = function() {
self.removeClass(options.savingClass)
.addClass(options.successClass);
self.delay(5000).animate({ backgroundColor: "#FFFFFF" }, 2500, function() {
$(this).removeClass(options.successClass).attr('style', '');
});
}
/**
* Renders the error class over the table cell.
* This is called after the ajax callback ended successfully.
*/
self.error = function() {
self.removeClass(options.savingClass)
.addClass(options.errorClass);
self.delay(5000).animate({ backgroundColor: "#FFFFFF" }, 2500, function() {
$(this).removeClass(options.errorClass).attr('style', '');
});
}
/**
* Reset the table cell
*/
self.reset = function() {
self.removeClass('editing').addClass('editable');
self.valueContainer.removeClass('form').addClass('value');
self.valueContainer.html(self.value);
}
/**
* Update the table cell class on hover
*/
self.hover(function() {
if (!self.hasClass('editing') && !self.hasClass(options.savingClass)) {
self.addClass(options.hoverClass);
}
}, function() {
self.removeClass(options.hoverClass);
});
/**
* OnClick convert the value container to a form.
*/
self.click(function(event) {
var target = $(event.target);
self.removeClass(options.hoverClass);
if (target.is(self[0].tagName) || target.parent().is(self[0].tagName)) {
if (null != $.inlineEdit.lastOpened) {
$.inlineEdit.lastOpened.reset();
}
$.inlineEdit.lastOpened = self;
self.removeClass('editable').addClass('editing');
self.valueContainer.removeClass('value').addClass('form');
// Input field
var tinput = $(document.createElement('input'))
.attr('type', 'text')
.val(self.value);
// Save button
var saveBtn = $(document.createElement('button'))
.attr('id', 'editable-save')
.html('Save')
.click(function() {
self.save($(this).parent().find('input').val());
});
// Cancel button
var cancelBtn = $(document.createElement('button'))
.attr('id', 'editable-cancel')
.html('Cancel')
.click(function() {
self.reset();
});
// Replace container contents
self.valueContainer.html(tinput)
.append(saveBtn)
.append(cancelBtn)
.find('input')
.focus();
}
});
}
$.inlineEdit.lastOpened = null;
})(jQuery);
$(document).ready(function() {
$('.editable').inlineEdit();
});
</script>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/subnavigation.phtml b/application/modules/admin/views/scripts/subnavigation.phtml
index 8649f17..ca18e01 100644
--- a/application/modules/admin/views/scripts/subnavigation.phtml
+++ b/application/modules/admin/views/scripts/subnavigation.phtml
@@ -1,11 +1,11 @@
<ul>
<?php foreach($this->items as $page) : ?>
<?php $label = $page->getLabel();
if (!empty($label)): ?>
<li<?= ($page->isActive(true)) ? ' class="active"' : ''; ?>>
- <a href="<?= $page->getHref(); ?>"><?= $page->getLabel(); ?></a>
+ <a href="<?= $page->getHref(); ?>"><?= $this->navigation()->getTranslator()->translate($page->getLabel()) ?></a>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
<div class="clear"></div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/form.phtml b/application/modules/admin/views/scripts/user/form.phtml
index 4cecb3a..1340a58 100644
--- a/application/modules/admin/views/scripts/user/form.phtml
+++ b/application/modules/admin/views/scripts/user/form.phtml
@@ -1,57 +1,57 @@
<form action="<?= $this->form->getAction(); ?>" name="UserForm" id="UserForm" method="post">
<div id="content-panel">
<h2>
- <?= $this->user->isNew() ? 'Add user' : 'Edit user'; ?>
+ <?= $this->translate($this->user->isNew() ? 'Add user' : 'Edit user') ?>
</h2>
<div class="form-panel">
<?= $this->form->id; ?>
<?= $this->form->username; ?>
<?= $this->form->displayname; ?>
<?= $this->form->password; ?>
<?= $this->form->password_confirm; ?>
</div>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <input type="submit" value="Save" />
+ <input type="submit" value="<?= $this->translate('Save') ?>" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if (!$this->user->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_users_delete?id=' . $this->user->id,
- $this->image($this->assetUrl('/images/icon/user--minus.png', false)) . ' delete user',
+ $this->image($this->assetUrl('/images/icon/user--minus.png', false)) . ' '.$this->translate('delete user'),
array(
'class' => 'delete',
- 'confirm' => 'Are you sure you want to delete this user?',
+ 'confirm' => $this->translate('Are you sure you want to delete this user?'),
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_users',
- $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to users',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' '.$this->translate('back to users'),
array (
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/list.phtml b/application/modules/admin/views/scripts/user/list.phtml
index 3f05bd6..1d40511 100644
--- a/application/modules/admin/views/scripts/user/list.phtml
+++ b/application/modules/admin/views/scripts/user/list.phtml
@@ -1,41 +1,41 @@
<div id="content-panel">
- <h2>Users</h2>
+ <h2><?= $this->translate('Users') ?></h2>
<table class="data">
<thead>
<tr>
<td> </td>
- <td>Username</td>
+ <td><?= $this->translate('Username') ?></td>
</tr>
</thead>
<tbody>
<?php foreach($this->users as $user) : ?>
<tr>
<td class="controls">
<?= $this->link(
'@admin_users_edit?id=' . $user['id'],
$this->image($this->assetUrl('/images/icon/user--pencil.png', false), array('alt' => 'edit icon')),
array (
'escape' => false
)
); ?>
</td>
<td><?= $user['username'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
- <h2>Actions</h2>
+ <h2><?= $this->translate('Actions') ?></h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_users_add', $this->image($this->assetUrl('/images/icon/user--plus.png', false)) . ' Add user', array('escape' => false)); ?>
+ <?= $this->link('@admin_users_add', $this->image($this->assetUrl('/images/icon/user--plus.png', false)) . ' '.$this->translate('Add user'), array('escape' => false)); ?>
</li>
</ul>
</div>
diff --git a/languages/admin_nl.php b/languages/admin_nl.php
new file mode 100644
index 0000000..9e9f468
--- /dev/null
+++ b/languages/admin_nl.php
@@ -0,0 +1,92 @@
+<?php
+return array(
+ 'Actions' => 'Acties',
+ 'Add page' => 'Pagina toevoegen',
+ 'Add post' => 'Post toevoegen',
+ 'Add user' => 'Gebruiker toevoegen',
+ 'and' => 'en',
+ 'Application' => 'Applicatie',
+ 'Are visitors allowed to comment on this post?'
+ => 'Mogen bezoekers reageren op deze post?',
+ 'Are you sure you want to delete this comment?'
+ => 'Weet u zeker dat u deze reactie wilt verwijderen?',
+ 'Are you sure you want to delete this page?'
+ => 'Weet u zeker dat u deze pagina wilt verwijderen?',
+ 'Are you sure you want to delete this post?'
+ => 'Weet u zeker dat u deze post wilt verwijderen?',
+ 'Are you sure you want to delete this user?'
+ => 'Weet u zeker dat u deze gebruiker wilt verwijderen?',
+ 'Author' => 'Auteur',
+ 'Author e-mail' => 'E-mail auteur',
+ 'Author name' => 'Naam auteur',
+ 'Author website' => 'Website auteur',
+ 'back to' => 'terug naar',
+ 'back to comments' => 'terug naar reactie overzicht',
+ 'back to pages' => 'terug naar pagina overzicht',
+ 'back to users' => 'terug naar gebruikers overzicht',
+ 'Blog name' => 'Blog naam',
+ 'Check this box to make this page the default.'
+ => 'Vink dit veld aan om van deze pagina de Home pagina te maken.',
+ 'Choose a file to upload. The maximun file size is'
+ => 'Kies een bestand om up te loaden. De maximale grootte is',
+ 'Comment' => 'Reactie',
+ 'Comments' => 'Reacties',
+ 'Comments on this post' => 'Reacties op deze post',
+ 'Comments overview' => 'Reactie statistieken',
+ 'Confirm password' => 'Wachtwoord bevestigen',
+ 'Date' => 'Datum',
+ 'Discussions' => 'Discussies',
+ 'Display name' => 'Weergave naam',
+ 'Delete' => 'Verwijderen',
+ 'delete comment' => 'reactie verwijderen',
+ 'delete page' => 'pagina verwijderen',
+ 'delete post' => 'post verwijderen',
+ 'delete user' => 'gebruiker verwijderen',
+ 'Draft' => 'Concept',
+ 'Edit' => 'Bewerken',
+ 'Edit comment' => 'Reactie bewerken',
+ 'edit page' => 'pagina bewerken',
+ 'Edit page' => 'Pagina bewerken',
+ 'Edit post' => 'Post bewerken',
+ 'Edit user' => 'Gebruiker bewerken',
+ 'Fizzy login' => 'Fizzy inloggen',
+ 'From' => 'Door',
+ 'Group slug' => 'Groeps slug',
+ 'Latest comments' => 'Laatste reacties',
+ 'license' => 'licentie',
+ 'List' => 'Lijst',
+ 'Login' => 'Inloggen',
+ 'Logout' => 'Uitloggen',
+ 'Name' => 'Naam',
+ 'next' => 'volgende',
+ 'Not spam' => 'Geen spam',
+ 'on' => 'op',
+ 'Only published posts will show up on the website.'
+ => 'Alleen gepubliceerde posts verschijnen op de website.',
+ 'Options' => 'Opties',
+ 'Page' => 'Pagina',
+ 'Pages' => 'Pagina\'s',
+ 'Password' => 'Wachtwoord',
+ 'prev' => 'vorige',
+ 'Published' => 'Gepubliceerd',
+ 'running on' => 'draaiend op',
+ 'Save' => 'Opslaan',
+ 'Settings' => 'Instellingen',
+ 'Show as' => 'Toon als',
+ 'The author of this post.' => 'De auteur van deze post.',
+ 'The published date of this post.' => 'De datum van publicatie van deze post.',
+ 'The upload directory found in the Fizzy configuration is not writable. Upload functionality will be disabled until it is made writable.'
+ => 'De upload map van Fizzy is niet schrijfbaar voor de webserver. Uploaden is uitgeschakeld tot dit is verholpen.',
+ 'Thread list' => 'Overzicht discussies',
+ 'Thumbnail' => 'Miniatuurweergave',
+ 'Title' => 'Titel',
+ 'Total comments' => 'Totaal aantal reacties',
+ 'Upload a new file by selecting it on your machine. Check the box if you want to overwrite a file that already exists with the same name.'
+ => 'Upload een nieuw bestand door het te selecteren op de computer. Zet het vinkje aan om het bestande bestand te overschrijven met dezelfde naam.',
+ 'Username' => 'Gebruikersnaam',
+ 'Users' => 'Gebruikers',
+ 'You can select a different layout to render the structured text in.'
+ => 'U kunt alternatieve layout kiezen om de gestructureerde tekst in te plaatsen',
+ 'You can select a different template to structure the text.'
+ => 'U kunt een alternatieve template kiezen om de tekst in te structureren.',
+);
\ No newline at end of file
diff --git a/library/Fizzy/Controller.php b/library/Fizzy/Controller.php
index 0c99b43..d5ad287 100644
--- a/library/Fizzy/Controller.php
+++ b/library/Fizzy/Controller.php
@@ -1,132 +1,142 @@
<?php
/**
* Class Fizzy_Controller
* @package Fizzy
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';
/**
* Controller class for Fizzy.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_Controller extends Zend_Controller_Action
{
/**
* Flash messenger helper instance
* @var Zend_View_Helper_FlashMessenger
*/
protected $_flashMessenger = null;
+ protected $_translate = null;
+
+ protected function translate($messageId, $locale = null)
+ {
+ if (null === $this->translate) {
+ $this->_translate = Zend_Registry::get('Zend_Translate');
+ }
+ return $this->_translate->_($messageId, $locale = null);
+ }
+
/**
* Disables the view renderer and layout
*/
protected function _disableDisplay()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
}
/**
* Adds a flash message to the session.
* @todo move to controller plugin
* @param string $message
* @param string $type Defaults to 'info'
*/
protected function addMessage($message, $type = 'info')
{
$this->_getFlashMessenger()->addMessage(array(
'message' => $message,
'type' => strtolower($type)
));
}
/**
* Adds a message of type 'info' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addInfoMessage($message)
{
$this->addMessage($message, 'info');
}
/**
* Adds a message of type 'success' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addSuccessMessage($message)
{
$this->addMessage($message, 'success');
}
/**
* Adds a message of type 'warning' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addWarningMessage($message)
{
$this->addMessage($message, 'warning');
}
/**
* Adds a message of type 'error' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addErrorMessage($message)
{
$this->addMessage($message, 'error');
}
/**
* Gets the flash messenger instance for this controller. Initializes the
* helper from the helper broker if no active instance is found.
* @return Zend_View_Helper_FlashMessenger
*/
protected function _getFlashMessenger()
{
if(null === $this->_flashMessenger) {
$this->_flashMessenger = $this->_helper->getHelper('flashMessenger');
}
return $this->_flashMessenger;
}
/**
* Overrides Zend Framework default redirect function to allow redirecting
* to route names. Route names start with an '@'.
* @param string $url the url or route name
* @param array $options the route parameters
*/
protected function _redirect($url, $options = array())
{
if (false !== strpos($url, '@') && 0 === strpos($url, '@')) {
// A routename is specified
$url = trim($url, '@');
$this->_helper->redirector->gotoRoute($options, $url);
}
else {
// Assume an url is passed in
parent::_redirect($url, $options);
}
}
}
|
jtietema/Fizzy
|
e2aa1072b0a4c2d5418d3c1d1bf4a674cd245f9b
|
Module specific ErrorHandler
|
diff --git a/application/Bootstrap.php b/application/Bootstrap.php
index 0e9a29d..f9a5874 100644
--- a/application/Bootstrap.php
+++ b/application/Bootstrap.php
@@ -1,122 +1,130 @@
<?php
/**
* Class Bootstrap
* @category Fizzy
* @package Fizzy_Bootstrap
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Description of Bootstrap
*
* @author jeroen
*/
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
/**
* Initializes a new view object and loads the view directories into it.
* @return Zend_View
*/
protected function _initView()
{
$view = new Zend_View();
$viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
$viewRenderer->setView($view);
Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'Fizzy', 'View', 'Helper')
)), 'Fizzy_View_Helper');
$view->addHelperPath(
realpath(implode(DIRECTORY_SEPARATOR,
array(ROOT_PATH, 'library', 'ZendX', 'JQuery', 'View', 'Helper')
)), 'ZendX_JQuery_View_Helper');
return $view;
}
/**
* Starts Zend_Layout in MVC mode.
* @todo add custom front controller plugin for layout allow multiple layouts
* @return Zend_Layout
*/
protected function _initLayout()
{
$this->bootstrap('FrontController');
$layout = Zend_Layout::startMvc(array (
'layout' => 'default',
));
$front = $this->getResource('FrontController');
$front->registerPlugin(new Fizzy_Layout_ControllerPlugin());
return $layout;
}
protected function _initConfig()
{
$config = new Zend_Config($this->getOptions());
Zend_Registry::set('config', $config);
return $config;
}
protected function _initRoutes()
{
$this->bootstrap('FrontController');
$options = $this->getOptions();
$backendSwitch = isset($options['backendSwitch']) ? strtolower((string) $options['backendSwitch']) : 'fizzy';
$router = $this->getContainer()->frontcontroller->getRouter();
$config = new Zend_Config_Ini(ROOT_PATH . '/configs/routes.ini');
$routes = $config->{$this->getEnvironment()}->toArray();
// Parse all routes and replace the backend switch
foreach ($routes as &$route) {
if (false !== strpos($route['route'], '{backend}')) {
$route['route'] = str_replace('{backend}', $backendSwitch, $route['route']);
}
}
// Load parsed routes into the router
$router->addConfig(new Zend_Config($routes));
return $router;
}
protected function _initTypes()
{
$config = new ZendL_Config_Yaml(ROOT_PATH . '/configs/types.yml');
$types = Fizzy_Types::initialize($config);
return $types;
}
/**
* @todo make adapter class configurable
*/
protected function _initSpam()
{
$this->bootstrap('Config');
$config = $this->getContainer()->config;
$adapter = new Fizzy_Spam_Adapter_Akismet($config->spam->akismetKey, $config->spam->siteUrl);
Fizzy_Spam::setDefaultAdapter($adapter);
}
+ protected function _initModuleErrorHandler()
+ {
+ $this->bootstrap('FrontController');
+
+ $front = Zend_Controller_Front::getInstance();
+ $front->registerPlugin(new Fizzy_Controller_Plugin_ErrorHandlerModuleSelector());
+ }
+
}
diff --git a/application/modules/admin/controllers/ErrorController.php b/application/modules/admin/controllers/ErrorController.php
new file mode 100644
index 0000000..4520c78
--- /dev/null
+++ b/application/modules/admin/controllers/ErrorController.php
@@ -0,0 +1,52 @@
+<?php
+
+class Admin_ErrorController extends Zend_Controller_Action
+{
+ public function errorAction()
+ {
+
+ $errors = $this->_getParam('error_handler');
+
+ switch ($errors->type) {
+ case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
+ 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()
+ ->setRawHeader('HTTP/1.1 404 Not Found');
+
+ $this->renderScript('error/404.phtml');
+ break;
+ default:
+ // application error; display error page, but don't change
+ // status code
+ //
+ // Mail the exception:
+ $exception = $errors->exception;
+ $body = "Exception log \n"
+ . $exception->getMessage(). "\n"
+ . "in file " . $exception->getFile() . " op regel " . $exception->getLine() . "\n\n"
+ . "Stacktrace: \n"
+ . $exception->getTraceAsString() . "\n\n"
+ . "GET:\n";
+ foreach($_GET as $key => $value) {
+ $body .= $key . ': ' . $value ."\n";
+ }
+ $body .= "POST:\n";
+ foreach($_POST as $key => $value) {
+ $body .= $key . ': ' . $value ."\n";
+ }
+ $body .= "SERVER:\n";
+ foreach($_SERVER as $key => $value) {
+ $body .= $key . ': ' . $value ."\n";
+ }
+ mail("[email protected]", "Fizzy Exception", $body);
+
+ $this->getResponse()
+ ->setRawHeader('HTTP/1.1 500 Server error');
+
+ $this->renderScript('error/500.phtml');
+ break;
+ }
+ }
+}
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/error/404.phtml b/application/modules/admin/views/scripts/error/404.phtml
new file mode 100644
index 0000000..bd104c2
--- /dev/null
+++ b/application/modules/admin/views/scripts/error/404.phtml
@@ -0,0 +1,6 @@
+<div id="content-panel">
+ <h1>Page not found</h1>
+ <p>
+ If you think this is an error, please report it on the contact page
+ </p>
+</div>
diff --git a/application/modules/admin/views/scripts/error/500.phtml b/application/modules/admin/views/scripts/error/500.phtml
new file mode 100644
index 0000000..9f8795c
--- /dev/null
+++ b/application/modules/admin/views/scripts/error/500.phtml
@@ -0,0 +1,9 @@
+<div id="content-panel">
+ <h1>An error occurred</h1>
+ <p>
+ An email has been send to notify the maintainer.
+ </p>
+ <p>
+ Please be patient while we fix this.
+ </p>
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/error/500.phtml b/application/modules/default/views/scripts/error/500.phtml
index 1262c1c..3f9fff3 100644
--- a/application/modules/default/views/scripts/error/500.phtml
+++ b/application/modules/default/views/scripts/error/500.phtml
@@ -1,7 +1,7 @@
-<h1>An error occured</h1>
+<h1>An error occurred</h1>
<p>
An email has been send to notify the maintainer.
</p>
<p>
Please be patient while we fix this.
</p>
diff --git a/library/Fizzy/Controller/Plugin/ErrorHandlerModuleSelector.php b/library/Fizzy/Controller/Plugin/ErrorHandlerModuleSelector.php
new file mode 100644
index 0000000..4c692cb
--- /dev/null
+++ b/library/Fizzy/Controller/Plugin/ErrorHandlerModuleSelector.php
@@ -0,0 +1,38 @@
+<?php
+/**
+ * Class Fizzy_Controller_Plugin_ErrorHandlerModuleSelector
+ * @package Fizzy_Controller
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
+/**
+ * Controller plugin for setting the module specific errorhandler after the
+ * routing took place
+ *
+ * @author Jeroen Tietema <[email protected]>
+ */
+class Fizzy_Controller_Plugin_ErrorHandlerModuleSelector
+ extends Zend_Controller_Plugin_Abstract
+{
+ public function routeShutdown(Zend_Controller_Request_Abstract $request) {
+ $front = Zend_Controller_Front::getInstance();
+
+ $errorHandler = $front->getPlugin('Zend_Controller_Plugin_ErrorHandler');
+
+ if ($errorHandler instanceof Zend_Controller_Plugin_ErrorHandler) {
+ $errorHandler->setErrorHandlerModule($request->getModuleName());
+ }
+ }
+}
|
jtietema/Fizzy
|
f370666737b2fa05c7786ee859b786310ede03b5
|
rss and atom examples for blog frontend
|
diff --git a/application/modules/default/controllers/BlogController.php b/application/modules/default/controllers/BlogController.php
index 7218e9d..d5ae38b 100644
--- a/application/modules/default/controllers/BlogController.php
+++ b/application/modules/default/controllers/BlogController.php
@@ -1,125 +1,182 @@
<?php
/**
* Class BlogController
* @package Fizzy
* @subpackage Controllers
* @category frontend
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright 2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Default blog implementation
*
* @author Mattijs Hoitink <[email protected]>
*/
class BlogController extends Fizzy_Controller
{
/**
* Shows latest posts from all blogs
*/
public function indexAction()
{
$posts = Doctrine_Query::create()
->from('Post')
->where('status = ?', Post::PUBLISHED)
->orderBy('date DESC')
->limit(10)
->execute();
$this->view->posts = $posts;
$this->render('posts');
}
/**
* Shows the posts from a single blog
*/
public function blogAction()
{
$blogSlug = $this->_getParam('blog_slug', null);
if (null === $blogSlug) {
// show 404
}
$blog = Doctrine_Query::create()->from('Blog')->where('slug = ?', $blogSlug)->fetchOne();
if (false === $blog) {
// Show 404
}
$posts = Doctrine_Query::create()
->from('Post')
->where('status = ?', Post::PUBLISHED)
->where('blog_id = ?', $blog->id)
->orderBy('date DESC')
->limit(10)
->execute();
$this->view->blog = $blog;
$this->view->posts = $posts;
$this->render('blog');
}
/**
* Shows all posts by a user
*/
public function userAction()
{
$username = $this->_getParam('username', null);
if (null === $username) {
// Show 404
}
$user = Doctrine_Query::create()
->from('User')
->where('username = ?', $username)
->fetchOne();
if (false === $user) {
// Show 404
}
$posts = Doctrine_Query::create()
->from('Post')
->where('status = ?', Post::PUBLISHED)
->where('author = ?', $user->id)
->orderBy('date DESC')
->limit(10)
->execute();
$this->view->user = $user;
$this->view->posts = $posts;
$this->render('user');
}
/**
* Shows a single post
*/
public function postAction()
{
$slug = $this->_getParam('post_slug', null);
if (null === $slug) {
// Show 404
}
$post = Doctrine_Query::create()->from('Post')->where('slug = ?', $slug)->fetchOne();
if (false === $post) {
// Show 404
}
$this->view->post = $post;
$this->render('post-entry');
}
+
+ public function rssAction()
+ {
+ $feed = $this->_feed();
+ $feed->setFeedLink('http://www.example.com/blog/rss', 'rss');
+
+ $this->view->rss = $feed->export('rss');
+ }
+
+ public function atomAction()
+ {
+ $feed = $this->_feed();
+ $feed->setFeedLink('http://www.example.com/blog/atom', 'atom');
+
+ $this->view->atom = $feed->export('atom');
+
+ }
+
+ protected function _feed()
+ {
+ $this->_helper->layout->disableLayout();
+ $this->_response->setHeader('Content-Type', 'text/xml');
+
+ $feed = new Zend_Feed_Writer_Feed();
+ $feed->setTitle('Fizzy Example Blog');
+ $feed->setLink('http://www.example.com');
+ $feed->setDescription('Example of a Rss feed from the Fizzy Blog module');
+
+ $feed->addAuthor(array(
+ 'name' => 'Paddy',
+ 'email' => '[email protected]',
+ 'uri' => 'http://www.example.com',
+ ));
+ $feed->setDateModified(time());
+
+ $posts = Doctrine_Query::create()
+ ->from('Post')
+ ->where('status = ?', Post::PUBLISHED)
+ ->orderBy('date DESC')
+ ->limit(10)
+ ->execute();
+
+ foreach ($posts as $post){
+ $entry = $feed->createEntry();
+ $entry->setTitle($post->title);
+ $entry->setLink('http://www.example.com/all-your-base-are-belong-to-us');
+ $entry->addAuthor(array(
+ 'name' => $post->User->displayname,
+ ));
+ $entry->setDateModified(new Zend_Date($post->date));
+ $entry->setDateCreated(new Zend_Date($post->date));
+ $entry->setContent($post->body);
+ $feed->addEntry($entry);
+ }
+
+ return $feed;
+ }
}
\ No newline at end of file
diff --git a/application/modules/default/views/layouts/default.phtml b/application/modules/default/views/layouts/default.phtml
index 477f0ab..c143998 100644
--- a/application/modules/default/views/layouts/default.phtml
+++ b/application/modules/default/views/layouts/default.phtml
@@ -1,76 +1,78 @@
<?php
/**
* Default layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<html>
<head>
<?php
$config = Zend_Registry::get('config');
$title = $config->title;
?>
<title><?= $title; ?></title>
<link href="<?= $this->assetUrl("/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
<link href="<?= $this->baseUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
+ <link rel="alternate" type="application/rss+xml" title="RSS" href="<?= $this->url('@blog_rss') ?>">
+ <link rel="alternate" type="application/atom+xml" title="Atom" href="<?= $this->url('@blog_atom') ?>">
</head>
<body>
<div class="container">
<!-- HEADER -->
<div id="header-panel" class="span-24 last">
<h1>Fizzy<span>CMS</span></h1>
<!-- NAVIGATION -->
<div id="navigation-panel">
<ul>
<li><a href="<?= $this->baseUrl('/') ?>" title="Website home">Home</a></li>
<li><a href="<?= $this->baseUrl('/blog') ?>" title="The blog">Blog</a></li>
<li><a href="<?= $this->baseUrl('/about'); ?>" title="About this site">About</a></li>
<li><a href="<?= $this->baseUrl('/configuration'); ?>" title="How to configure Fizzy">Configuration</a></li>
<li><a href="http://project.voidwalkers.nl/projects/show/fizzy" target="_blank" title="Learn more about the fizzy project (opens in a new window)">More</a></li>
</ul>
<div class="clear"></div>
</div>
<!-- NAVIGATION -->
</div>
<!-- CONTENT -->
<div id="main-panel" class="span-24 last">
<div id="content-panel">
<?= $this->layout()->content; ?>
</div>
</div>
<!-- FOOTER -->
<div id="footer-panel" class="span-24 last">
<p>
This site is powered by Fizzy <?= Fizzy_Version::VERSION ?>
running on Zend Framework <?= Zend_Version::VERSION ?>
and Doctrine <?= Doctrine::VERSION ?>
</p>
<p>
(c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd">license</a><br />
</p>
</div>
</div>
</body>
</html>
diff --git a/application/modules/default/views/scripts/blog/atom.phtml b/application/modules/default/views/scripts/blog/atom.phtml
new file mode 100644
index 0000000..193ef67
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/atom.phtml
@@ -0,0 +1 @@
+<?= $this->atom ?>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/rss.phtml b/application/modules/default/views/scripts/blog/rss.phtml
new file mode 100644
index 0000000..3009c5a
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/rss.phtml
@@ -0,0 +1 @@
+<?= $this->rss ?>
\ No newline at end of file
diff --git a/configs/routes.ini b/configs/routes.ini
index 9f7258c..e510553 100644
--- a/configs/routes.ini
+++ b/configs/routes.ini
@@ -1,230 +1,241 @@
[development : production]
[test : production]
[production]
;; Catch all for pages slugs
page_by_slug.route = "/:slug"
page_by_slug.defaults.controller = "pages"
page_by_slug.defaults.action = "slug"
page_by_slug.defaults.module = "default"
;; Blog
blog.route = "blog"
blog.defaults.controller = "blog"
blog.defaults.action = "index"
blog.defaults.module = "default"
;; Blog posts
blog_posts.route = "/blog/:blog_slug"
blog_posts.defaults.controller = "blog"
blog_posts.defaults.action = "blog"
blog_posts.defaults.module = "default"
;; Post
blog_post.route = "/blog/:blog_slug/:post_slug"
blog_post.defaults.controller = "blog"
blog_post.defaults.action = "post"
blog_post.defaults.module = "default"
+;; Feeds
+blog_rss.route = "/blog/rss"
+blog_rss.defaults.controller = "blog"
+blog_rss.defaults.action = "rss"
+blog_rss.defaults.module = "default"
+
+blog_atom.route = "/blog/atom"
+blog_atom.defaults.controller = "blog"
+blog_atom.defaults.action = "atom"
+blog_atom.defaults.module = "default"
+
;; User posts
user_posts.route = "/blog/author/:username"
user_posts.defaults.controller = "blog"
user_posts.defaults.action = "user"
user_posts.defaults.module = "default"
;; Comments
add_comment.route = "/comment/add/:stream"
add_comment.defaults.controller = "comment"
add_comment.defaults.action = "add"
add_comment.defaults.module = "default"
;; Homepage
homepage.route = "/"
homepage.defaults.controller = "pages"
homepage.defaults.controller = "pages"
homepage.defaults.action = "slug"
homepage.defaults.module = "default"
;; Contact form
;;contact.route = "/contact"
;;contact.defaults.controller = "contact"
;;contact.defaults.action = "index"
;;contact.defaults.module = "default"
;; Admin pages control
admin_blogs.route = "/{backend}/blogs"
admin_blogs.defaults.action = "index"
admin_blogs.defaults.controller = "blogs"
admin_blogs.defaults.module = "admin"
admin_blog.route = "/{backend}/blog/:id"
admin_blog.defaults.action = "blog"
admin_blog.defaults.controller = "blogs"
admin_blog.defaults.module = "admin"
admin_blog_post_add.route = "/{backend}/blog/:blog_id/add"
admin_blog_post_add.defaults.action = "add-post"
admin_blog_post_add.defaults.controller = "blogs"
admin_blog_post_add.defaults.module = "admin"
admin_blog_post_edit.route = "/{backend}/post/:post_id/edit"
admin_blog_post_edit.defaults.action = "edit-post"
admin_blog_post_edit.defaults.controller = "blogs"
admin_blog_post_edit.defaults.module = "admin"
admin_blog_post_delete.route = "/{backend}/post/:post_id/delete"
admin_blog_post_delete.defaults.action = "delete-post"
admin_blog_post_delete.defaults.controller = "blogs"
admin_blog_post_delete.defaults.module = "admin"
admin_comments.route = "/{backend}/comments"
admin_comments.defaults.action = "index"
admin_comments.defaults.controller = "comments"
admin_comments.defaults.module = "admin"
admin_comments_list.route = "/{backend}/comments/list"
admin_comments_list.defaults.action = "list"
admin_comments_list.defaults.controller = "comments"
admin_comments_list.defaults.module = "admin"
admin_comments_topic.route = "/{backend}/comments/topic/:id"
admin_comments_topic.defaults.action = "topic"
admin_comments_topic.defaults.controller = "comments"
admin_comments_topic.defaults.module = "admin"
admin_comments_ham.route = "/{backend}/comment/ham/:id"
admin_comments_ham.defaults.action = "ham"
admin_comments_ham.defaults.controller = "comments"
admin_comments_ham.defaults.module = "admin"
admin_comments_spam.route = "/{backend}/comment/spam/:id"
admin_comments_spam.defaults.action = "spam"
admin_comments_spam.defaults.controller = "comments"
admin_comments_spam.defaults.module = "admin"
admin_comments_delete.route = "/{backend}/comment/delete/:id"
admin_comments_delete.defaults.action = "delete"
admin_comments_delete.defaults.controller = "comments"
admin_comments_delete.defaults.module = "admin"
admin_comments_edit.route = "/{backend}/comment/edit/:id"
admin_comments_edit.defaults.action = "edit"
admin_comments_edit.defaults.controller = "comments"
admin_comments_edit.defaults.module = "admin"
admin_comments_spambox.route = "/{backend}/comments/spam"
admin_comments_spambox.defaults.action = "spambox"
admin_comments_spambox.defaults.controller = "comments"
admin_comments_spambox.defaults.module = "admin"
admin_pages.route = "/{backend}/pages"
admin_pages.defaults.action = "index"
admin_pages.defaults.controller = "pages"
admin_pages.defaults.module = "admin"
admin_pages_add.route = "/{backend}/pages/add"
admin_pages_add.defaults.action = "add"
admin_pages_add.defaults.controller = "pages"
admin_pages_add.defaults.module = "admin"
admin_pages_edit.route = "/{backend}/pages/edit/:id"
admin_pages_edit.defaults.action = "edit"
admin_pages_edit.defaults.controller = "pages"
admin_pages_edit.defaults.module = "admin"
admin_pages_delete.route = "/{backend}/pages/delete/:id"
admin_pages_delete.defaults.action = "delete"
admin_pages_delete.defaults.controller = "pages"
admin_pages_delete.defaults.module = "admin"
admin_media.route = "/{backend}/media"
admin_media.defaults.action = "index"
admin_media.defaults.controller = "media"
admin_media.defaults.module = "admin"
admin_media_delete.route = "/{backend}/media/delete/:name"
admin_media_delete.defaults.action = "delete"
admin_media_delete.defaults.controller = "media"
admin_media_delete.defaults.module = "admin"
admin_media_gallery.route = "/{backend}/media/gallery"
admin_media_gallery.defaults.action = "gallery"
admin_media_gallery.defaults.controller = "media"
admin_media_gallery.defaults.module = "admin"
admin_media_assets.route = "/{backend}/media/assets"
admin_media_assets.defaults.action = "assets"
admin_media_assets.defaults.controller = "media"
admin_media_assets.defaults.module = "admin"
;; Admin contact
admin_contact.route = "/{backend}/contact"
admin_contact.defaults.module = "admin"
admin_contact.defaults.controller = "contact"
admin_contact.defaults.action = "index"
admin_contact_show.route = "/{backend}/contact/show/:id"
admin_contact_show.defaults.module = "admin"
admin_contact_show.defaults.controller = "contact"
admin_contact_show.defaults.action = "show"
admin_contact_delete.route = "/{backend}/contact/delete/:id"
admin_contact_delete.defaults.module = "admin"
admin_contact_delete.defaults.controller = "contact"
admin_contact_delete.defaults.action = "delete"
;; Admin users
admin_users.route = "/{backend}/users"
admin_users.defaults.action = "index"
admin_users.defaults.controller = "user"
admin_users.defaults.module = "admin"
admin_users_add.route = "/{backend}/user/add"
admin_users_add.defaults.action = "add"
admin_users_add.defaults.controller = "user"
admin_users_add.defaults.module = "admin"
admin_users_edit.route = "/{backend}/user/edit/:id"
admin_users_edit.defaults.action = "edit"
admin_users_edit.defaults.controller = "user"
admin_users_edit.defaults.module = "admin"
admin_users_delete.route = "/{backend}/user/delete/:id"
admin_users_delete.defaults.action = "delete"
admin_users_delete.defaults.controller = "user"
admin_users_delete.defaults.module = "admin"
;; Admin settings
admin_settings.route = "/{backend}/settings"
admin_settings.defaults.module = "admin"
admin_settings.defaults.controller = "settings"
admin_settings.defaults.action = "index"
admin_settings_update.route = "/{backend}/settings/update"
admin_settings_update.defaults.module = "admin"
admin_settings_update.defaults.controller = "settings"
admin_settings_update.defaults.action = "ajax-update"
;; Admin WebDAV
admin_webdav.route = "/{backend}/webdav/*"
admin_webdav.defaults.module = "admin"
admin_webdav.defaults.controller = "webdav"
admin_webdav.defaults.action = "request"
;; Auth section
admin_login.route = "/{backend}/login"
admin_login.defaults.action = "login"
admin_login.defaults.controller = "auth"
admin_login.defaults.module = "admin"
admin_logout.route = "/{backend}/logout"
admin_logout.defaults.action = "logout"
admin_logout.defaults.controller = "auth"
admin_logout.defaults.module = "admin"
admin.route = "/{backend}"
admin.defaults.action = "index"
admin.defaults.controller = "index"
admin.defaults.module = "admin"
|
jtietema/Fizzy
|
e6ed3a2a9005eaf3b32a9c9d9ca9dcbb6eb48cb0
|
Geocode unit tests and improved UnitTesting.txt
|
diff --git a/UnitTesting.txt b/UnitTesting.txt
index 1d1cf73..e7b0fbe 100644
--- a/UnitTesting.txt
+++ b/UnitTesting.txt
@@ -1,6 +1,19 @@
Running the testsuite
=====================
-run "phpunit ." from the tests directory. (Make sure you have phpunit installed)
+The testsuite requires that you have PHPUnit 3.4 or higher installed.
+
+To run all test:
+run "phpunit ." from the tests directory.
+
+If you want to run only certain tests:
+run "phpunit Validate/"
+This will run all tests in the validate folder.
+
+run "phpunit Validate/YoutubeVideoTest.php"
+to only run the Youtube Video tests.
+
+It is important to always call phpunit from the root of the tests folder because
+otherwise the tests won't find the bootstrap file needed for setting up the
+environment.
-Works with phpunit 3.4.x
\ No newline at end of file
diff --git a/tests/Geocode/AdapterStub.php b/tests/Geocode/AdapterStub.php
new file mode 100644
index 0000000..ce24bb7
--- /dev/null
+++ b/tests/Geocode/AdapterStub.php
@@ -0,0 +1,34 @@
+<?php
+require_once 'Fizzy/Geocode/Adapter/Interface.php';
+require_once 'Fizzy/Geocode/Response.php';
+
+class Geocode_AdapterStub implements Fizzy_Geocode_Adapter_Interface
+{
+ protected $_query;
+
+ public function getQuery()
+ {
+ return $this->_query;
+ }
+
+ public function setQuery($query)
+ {
+ $this->_query = $query;
+ return $this;
+ }
+
+ public function location($query = null)
+ {
+ $response = new Fizzy_Geocode_Response();
+ $location = new Fizzy_Geocode_Location(array(
+ 'address' => 'Marshalllaan 373',
+ 'zipcode' => '3527 TK',
+ 'city' => 'Utrecht',
+ 'country' => 'The Netherlands',
+ 'lat' => '',
+ 'lng' => ''
+ ));
+ $response->addLocation($location);
+ return $response;
+ }
+}
\ No newline at end of file
diff --git a/tests/GeocodeTest.php b/tests/GeocodeTest.php
new file mode 100644
index 0000000..8cca113
--- /dev/null
+++ b/tests/GeocodeTest.php
@@ -0,0 +1,36 @@
+<?php
+require_once 'bootstrap.php';
+require_once 'PHPUnit/Framework.php';
+require_once 'Geocode/AdapterStub.php';
+
+require_once 'Fizzy/Geocode.php';
+
+class GeocodeTest extends PHPUnit_Framework_TestCase
+{
+ function testConstruct()
+ {
+ $geocode = new Fizzy_Geocode();
+ $this->assertNull($geocode->getAdapter());
+
+ $adapter = new Geocode_AdapterStub();
+ $geocode = new Fizzy_Geocode($adapter);
+ $this->assertEquals($adapter, $geocode->getAdapter());
+
+ }
+
+ function testSetAdapter()
+ {
+ $geocode = new Fizzy_Geocode();
+ $this->assertNull($geocode->getAdapter());
+ $adapter = new Geocode_AdapterStub();
+ $this->assertEquals($geocode, $geocode->setAdapter($adapter));
+ $this->assertEquals($adapter, $geocode->getAdapter());
+ }
+
+ function testLocation()
+ {
+ $geocode = new Fizzy_Geocode(new Geocode_AdapterStub());
+ $response = $geocode->location('Something');
+ $this->assertTrue($response instanceof Fizzy_Geocode_Response);
+ }
+}
\ No newline at end of file
|
jtietema/Fizzy
|
4115a3db398f03329f8d37b432f003268cdbc82f
|
improved Youtube filter and validator
|
diff --git a/UnitTesting.txt b/UnitTesting.txt
new file mode 100644
index 0000000..1d1cf73
--- /dev/null
+++ b/UnitTesting.txt
@@ -0,0 +1,6 @@
+Running the testsuite
+=====================
+
+run "phpunit ." from the tests directory. (Make sure you have phpunit installed)
+
+Works with phpunit 3.4.x
\ No newline at end of file
diff --git a/library/Fizzy/Filter/YoutubeId.php b/library/Fizzy/Filter/YoutubeId.php
index 61a1985..25baea4 100644
--- a/library/Fizzy/Filter/YoutubeId.php
+++ b/library/Fizzy/Filter/YoutubeId.php
@@ -1,59 +1,54 @@
<?php
/**
* Class Fizzy_Filter_YoutubeId
* @category Fizzy
* @package Fizzy_Filter
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Filter_Interface */
require_once 'Zend/Filter/Interface.php';
/** Zend_Uri_Http */
require_once 'Zend/Uri/Http.php';
/**
* Filters the id for a YouTube video from a HTTP URI.
*
* @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Filter_YoutubeId implements Zend_Filter_Interface
{
/**
* Filters the YouTube video id from a URL and returns the id. Return an
* empty string on an invalid URL.
+ *
* @param string $value
* @return string
*/
public function filter($value)
{
try {
$uri = Zend_Uri_Http::factory($value);
if($uri->valid()) {
$query = $uri->getQueryAsArray();
if (isset($query['v'])) {
return $query['v'];
- } else {
- return '';
}
}
- else {
- return '';
- }
- } catch (Zend_Uri_Exception $e) {
- return '';
- }
+ } catch (Zend_Uri_Exception $e) {}
+ return '';
}
}
diff --git a/library/Fizzy/Validate/YoutubeVideo.php b/library/Fizzy/Validate/YoutubeVideo.php
index 6bcc483..aa4640c 100644
--- a/library/Fizzy/Validate/YoutubeVideo.php
+++ b/library/Fizzy/Validate/YoutubeVideo.php
@@ -1,105 +1,100 @@
<?php
/**
* Class Fizzy_Validate_YoutubeVideo
* @category Fizzy
* @package Fizzy_Validate
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Validate_Abstract */
require_once 'Zend/Validate/Abstract.php';
/** Zend_Uri_Http */
require_once 'Zend/Uri/Http.php';
/** Zend_Http_Client */
require_once 'Zend/Http/Client.php';
/**
* Validator for YouTube video's. Uses the status code of an HTTP request to
* to the YouTube API to verify a video exists.
*
* API URI: http://gdata.youtube.com/feeds/api/videos/VIDEO_ID
*
* @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Validate_YoutubeVideo extends Zend_Validate_Abstract
{
const API_URL = 'http://gdata.youtube.com/feeds/api/videos/';
- const INVALID_URI = 'invalidUri';
const INVALID_VIDEO = 'notAVideo';
/**
* @see Zend_Validate_Abstract
*/
protected $_messageTemplates = array(
- self::INVALID_URI => "'%value%' is not a valid url",
self::INVALID_VIDEO => "'%value%' is not a valid Youtube video"
);
/**
- * Checks if a YouTube video exists
- * @param string $value
+ * Checks if a YouTube video exists with the given ID
+ *
+ * @param string $value - The Youtube video ID
* @return boolean
*/
public function isValid($value)
{
$value = (string) $value;
$this->_setValue($value);
- try {
- $uri = Zend_Uri_Http::factory($value);
- } catch (Zend_Uri_Exception $e) {
- $this->_error(self::INVALID_URI);
- return false;
- }
-
- $query = $uri->getQueryAsArray();
- if(!isset($query['v'])) {
- $this->_error(self::INVALID_URI);
- return false;
- }
-
- $valid = $this->_checkYoutubeApi($query['v']);
+ $valid = $this->_checkYoutubeApi($value);
if(false === $valid) {
$this->_error(self::INVALID_VIDEO);
return false;
}
return true;
}
/**
* Does a request to the YouTube API.
* @param string|int $id
* @return boolean
*/
protected function _checkYoutubeApi($id)
{
try {
$uri = Zend_Uri_Http::factory(self::API_URL . $id);
+
+ $httpClient = new Zend_Http_Client($uri);
+ $response = $httpClient->request();
} catch (Zend_Uri_Exception $e) {
+ // the id is malformed
return false;
+ } catch (Zend_Http_Client_Adapter_Exception $e){
+ /**
+ * Catch the timeout
+ *
+ * We do not know if the video is valid and are unable to check
+ * so we assume it is OK.
+ */
+ return true;
}
-
- $httpClient = new Zend_Http_Client($uri);
- $response = $httpClient->request();
-
- return ((boolean) $response->getStatus() == '200');
+
+ return $response->getStatus() == '200';
}
}
diff --git a/tests/Filter/YoutubeIdTest.php b/tests/Filter/YoutubeIdTest.php
new file mode 100644
index 0000000..a29e7b9
--- /dev/null
+++ b/tests/Filter/YoutubeIdTest.php
@@ -0,0 +1,24 @@
+<?php
+require_once 'bootstrap.php';
+require_once 'PHPUnit/Framework.php';
+
+require_once 'Fizzy/Filter/YoutubeId.php';
+
+class Filter_YoutubeIdTest extends PHPUnit_Framework_TestCase
+{
+ function testFilter()
+ {
+ $filter = new Fizzy_Filter_YoutubeId();
+
+ $result = $filter->filter('http://www.youtube.com/watch?v=M2eiP12hQQY');
+ $this->assertEquals('M2eiP12hQQY', $result);
+
+ // invalid youtube link
+ $result = $filter->filter('http://www.youtube.com/v/M2eiP12hQQY');
+ $this->assertEquals('', $result);
+
+ // not a url
+ $result = $filter->filter('Some garbage text');
+ $this->assertEquals('', $result);
+ }
+}
diff --git a/tests/Validate/YoutubeVideoTest.php b/tests/Validate/YoutubeVideoTest.php
new file mode 100644
index 0000000..a1089b5
--- /dev/null
+++ b/tests/Validate/YoutubeVideoTest.php
@@ -0,0 +1,19 @@
+<?php
+require_once 'bootstrap.php';
+require_once 'PHPUnit/Framework.php';
+
+require_once 'Fizzy/Validate/YoutubeVideo.php';
+
+class YoutubeVideoTest extends PHPUnit_Framework_TestCase
+{
+ function testIsValid()
+ {
+ $video = new Fizzy_Validate_YoutubeVideo();
+
+ $result = $video->isValid('87D17NrgJxU');
+ $this->assertTrue($result);
+
+ $result = $video->isValid('87D17NrgJxUUUU');
+ $this->assertFalse($result);
+ }
+}
\ No newline at end of file
diff --git a/tests/bootstrap.php b/tests/bootstrap.php
new file mode 100644
index 0000000..b6da9e9
--- /dev/null
+++ b/tests/bootstrap.php
@@ -0,0 +1,3 @@
+<?php
+$lib = realpath(dirname(__FILE__) . '/../library');
+set_include_path($lib . PATH_SEPARATOR . get_include_path());
|
jtietema/Fizzy
|
9e1eb45ebe2410ca3238a1a3b7e04b075e9dc98b
|
small bugfix in comments spam filtering
|
diff --git a/application/models/Comments.php b/application/models/Comments.php
index ab5e47e..1747af2 100644
--- a/application/models/Comments.php
+++ b/application/models/Comments.php
@@ -1,77 +1,77 @@
<?php
/**
* Comments
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package ##PACKAGE##
* @subpackage ##SUBPACKAGE##
* @author ##NAME## <##EMAIL##>
* @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $
*/
class Comments extends BaseComments
{
public function isNew()
{
return empty($this->id);
}
/**
* Returns the model where the comments are attached to.
* It uses the post_id field, which follows the convention <type>:<id>
* The type references a model in the config and the id, well an id.
*
* @return Doctrine_Record|null
*/
public function getThreadModel()
{
if (false === strpos($this->post_id, ':')){
return null;
}
list($type, $id) = explode(':', $this->post_id);
$types = Fizzy_Types::getInstance();
if (!$types->hasType($type) && null === $types->getTypeModel($type)){
return null;
}
$modelName = $types->getTypeModel($type);
$query = Doctrine_Query::create()->from($modelName)
->where('id = ?', $id);
$model = $query->fetchOne();
return $model;
}
public function getNumberTopicComments()
{
$query = Doctrine_Query::create()->from('Comments')
->where('post_id = ?', $this->post_id)->andWhere('spam = 0');
return $query->count();
}
public function isSpam()
{
return (boolean) $this->spam;
}
public function verifyIsSpam()
{
$fizzySpam = new Fizzy_Spam();
- $fizzySpam->isSpam($this->getSpamDocument());
+ return $fizzySpam->isSpam($this->getSpamDocument());
}
public function getSpamDocument()
{
return new Fizzy_Spam_Document(
$this->body,
$this->name,
$this->email,
$this->website,
$this->ip,
$this->user_agent,
$this->referrer
);
}
}
\ No newline at end of file
|
jtietema/Fizzy
|
6866dd5e304bf710274c05453e5895f7227cf35b
|
license headers geocode classes
|
diff --git a/application/library/Fizzy/Geocode/Adapter/Google.php b/application/library/Fizzy/Geocode/Adapter/Google.php
index 5a26496..bf46b50 100644
--- a/application/library/Fizzy/Geocode/Adapter/Google.php
+++ b/application/library/Fizzy/Geocode/Adapter/Google.php
@@ -1,214 +1,232 @@
<?php
+/**
+ * Class Fizzy_Geocode_Adapter_Google
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
require_once 'Zend/Http/Client.php';
require_once 'Zend/Json.php';
require_once 'Zend/Uri.php';
require_once 'Fizzy/Geocode/Adapter/Interface.php';
require_once 'Fizzy/Geocode/Response.php';
require_once 'Fizzy/Geocode/Location.php';
/**
* Adapter voor Google Maps Geocode server V3
*
* @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Geocode_Adapter_Google implements Fizzy_Geocode_Adapter_Interface
{
/**
* Base url for the geocode api
* @var string
*/
protected $_apiUrl = 'http://maps.google.com/maps/api/geocode/';
/**
* Will be configurable in the future when moer output formats are supported.
* @var string
*/
protected $_output = 'json';
/**
* The search query to look up the coordinates for
* @var string
*/
protected $_query = null;
/**
* The country code, specified as a ccTLD ("top-level domain") two-character value.
* {@see http://code.google.com/apis/maps/documentation/geocoding/index.html#CountryCodes}
* @var string
*/
protected $_countryCode = null;
/**
* If Google API's should try to use device specific things to determine the
* location of the device. E.g. a GPS
* @var boolean
*/
protected $_sensor = false;
/**
* The Http client used. Must be an instance of Zend_Http_Client
* @var Zend_Http_Client
*/
protected $_client = null;
/** **/
/**
* Return the Search query
*
* @return string
*/
public function getQuery()
{
return $this->_query;
}
/**
* Set the search query
*
* @param string $query
* @return Fizzy_Geocode_Adapter_Google
*/
public function setQuery($query)
{
$this->_query = str_replace(' ', '+', $query);
return $this;
}
/**
* Set the language code to influence the search results. Language code
* must be a two value TLD style string.
*
* @param string $code
* @return Fizzy_Geocode_Adapter_Google
*/
public function setCountryCode($code)
{
$this->_countryCode = strtoupper($code);
return $this;
}
/**
* Returns the country code that will be used in the search query.
*
* @return null|string
*/
public function getCountryCode()
{
return $this->_countryCode;
}
public function getSensor()
{
return $this->_sensor;
}
/**
* @param boolean $sensor
*/
public function setSensor($sensor)
{
$this->_sensor = (boolean) $sensor;
return $this;
}
/**
* Returns the current client instance if any.
* @return Zend_Http_Client|null
*/
public function getHttpClient()
{
return $this->_client;
}
/**
* Set the Http client to use for making the requests. This is usefull if
* you what Zend_Http_Client to use a specific Zend_Http_Client adapter.
* @param Zend_Http_Client $client
* @return Fizzy_Geocode_Adapter_Google
*/
public function setHttpClient(Zend_Http_Client $client)
{
$this->_client = $client;
return $this;
}
public function location($query = null)
{
if(null !== $query) {
$this->setQuery($query);
}
// Build the request parameters
$parameters = array (
'address' => $this->_query,
'sensor' => ($this->_sensor ? 'true' : 'false')
);
if(null !== $this->_countryCode) {
$parameters['lg'] = $this->_countryCode;
}
// Build the request URI
$uri = Zend_Uri::factory($this->_apiUrl . $this->_output);
$uri->setQuery($parameters);
// Send the request
if ($this->_client === null){
$this->_client = new Zend_Http_Client($uri);
} else {
$this->_client->setUri($uri);
}
$httpResponse = $this->_client->request();
$json = $httpResponse->getBody();
// parse the response into a Fizzy_Geocode_Response
$response = new Fizzy_Geocode_Response();
$responseArray = Zend_Json::decode($json);
if ($responseArray['status'] != 'OK'){
$response->setErrors(array($responseArray['status']));
}
foreach ($responseArray['results'] as $result){
$location = new Fizzy_Geocode_Location();
$location->setLat($result['geometry']['location']['lat']);
$location->setLng($result['geometry']['location']['lng']);
$address = array(
'number' => null,
'street' => null,
'city' => null,
'zipcode' => null,
'country' => null
);
foreach ($result['address_components'] as $component){
if (in_array('street_number', $component['types'])){
$address['number'] = $component['long_name'];
}
if (in_array('route', $component['types'])){
$address['street'] = $component['long_name'];
}
if (in_array('locality', $component['types'])){
$address['city'] = $component['long_name'];
}
if (in_array('country', $component['types'])){
$address['country'] = $component['long_name'];
}
if (in_array('postal_code', $component['types'])){
$address['zipcode'] = $component['long_name'];
}
}
$location->setAddress($address['street'] . ' ' . $address['number']);
$location->setZipcode($address['zipcode']);
$location->setCity($address['city']);
$location->setCountry($address['country']);
$response->addLocation($location);
}
return $response;
}
}
diff --git a/application/library/Fizzy/Geocode/Adapter/Interface.php b/application/library/Fizzy/Geocode/Adapter/Interface.php
index 5759750..938a62e 100644
--- a/application/library/Fizzy/Geocode/Adapter/Interface.php
+++ b/application/library/Fizzy/Geocode/Adapter/Interface.php
@@ -1,8 +1,31 @@
<?php
+/**
+ * Interface Fizzy_Geocode_Adapter_Interface
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
+/**
+ * Interface to be used by all adapters for Fizzy_Geocode
+ *
+ * @author Jeroen Tietema <[email protected]>
+ */
interface Fizzy_Geocode_Adapter_Interface
{
public function getQuery();
public function setQuery($query);
public function location($query = null);
}
\ No newline at end of file
diff --git a/application/library/Fizzy/Geocode/Adapter/Yahoo.php b/application/library/Fizzy/Geocode/Adapter/Yahoo.php
index fe87c23..0d04346 100644
--- a/application/library/Fizzy/Geocode/Adapter/Yahoo.php
+++ b/application/library/Fizzy/Geocode/Adapter/Yahoo.php
@@ -1,124 +1,142 @@
<?php
+/**
+ * Class Fizzy_Geocode_Adapter_Yahoo
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
require_once 'Zend/Uri.php';
require_once 'Zend/Http/Client.php';
require_once 'Fizzy/Geocode/Adapter/Interface.php';
require_once 'Fizzy/Geocode/Exception.php';
require_once 'Fizzy/Geocode/Response.php';
require_once 'Fizzy/Geocode/Location.php';
/**
- * Description of Yahoo
+ * Adapter for the Yahoo Maps Geocode service
*
- * @author jeroen
+ * @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Geocode_Adapter_Yahoo implements Fizzy_Geocode_Adapter_Interface
{
protected $_apiKey = null;
protected $_output = 'php';
protected $_apiUrl = 'http://local.yahooapis.com/MapsService/V1/geocode';
protected $_query = null;
protected $_httpClient = null;
public function __construct($apiKey = null)
{
if (null !== $apiKey){
$this->_apiKey = $apiKey;
}
}
public function getApiKey()
{
return $this->_apiKey;
}
public function setApiKey($apiKey)
{
$this->_apiKey = $apiKey;
return $this;
}
public function getQuery()
{
return $this->_query;
}
public function setQuery($query)
{
$this->_query = $query;
return $this;
}
public function getHttpClient()
{
return $this->_httpClient;
}
public function setHttpClient(Zend_Http_Client $client)
{
$this->_httpClient = $client;
return $this;
}
public function location($query = null)
{
if (null !== $query){
$this->setQuery($query);
}
if (null === $this->_query){
throw new Fizzy_Geocode_Exception('No query passed');
}
$parameters = array(
'appid' => $this->_apiKey,
'location' => $this->_query,
'output' => $this->_output
);
$uri = Zend_Uri::factory($this->_apiUrl);
$uri->setQuery($parameters);
if (null === $this->_httpClient){
$this->_httpClient = new Zend_Http_Client($uri);
} else {
$this->_httpClient->setUri($uri);
}
$httpResponse = $this->_httpClient->request();
$response = new Fizzy_Geocode_Response();
if (200 != $httpResponse->getStatus()){
if (400 == $httpResponse->getStatus()){
$response->setErrors(array('Bad request'));
} elseif (403 == $httpResponse->getStatus()){
$response->setErrors(array('Forbidden'));
} elseif (503 == $httpResponse->getStatus()){
$response->setErrors(array('Service unavailable'));
}
return $response;
}
$php = unserialize($httpResponse->getBody());
var_dump($php);
foreach ($php['ResultSet'] as $result){
$location = new Fizzy_Geocode_Location();
$location->setAddress($result['Address']);
$location->setZipcode($result['Zip']);
$location->setCity($result['City']);
$location->setCountry($result['Country']);
$location->setLat($result['Latitude']);
$location->setLng($result['Longitude']);
$response->addLocation($location);
}
return $response;
}
}
diff --git a/application/library/Fizzy/Geocode/Exception.php b/application/library/Fizzy/Geocode/Exception.php
index 8f218fd..e6615ab 100644
--- a/application/library/Fizzy/Geocode/Exception.php
+++ b/application/library/Fizzy/Geocode/Exception.php
@@ -1,4 +1,22 @@
<?php
+/**
+ * Class Fizzy_Geocode_Exception
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
require_once 'Fizzy/Exception.php';
class Fizzy_Geocode_Exception extends Fizzy_Exception {}
diff --git a/application/library/Fizzy/Geocode/Location.php b/application/library/Fizzy/Geocode/Location.php
index ace3a2a..15c9012 100644
--- a/application/library/Fizzy/Geocode/Location.php
+++ b/application/library/Fizzy/Geocode/Location.php
@@ -1,121 +1,138 @@
<?php
+/**
+ * Class Fizzy_Geocode_Location
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
/**
- * Description of Location
+ * An adapter indepent representation of a location
*
- * @author jeroen
+ * @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Geocode_Location
{
/**
* Array with keys `lat` and `lng`
* @var array|null
*/
protected $_lat = null;
protected $_lng = null;
protected $_address = null;
protected $_zipcode = null;
protected $_city = null;
protected $_country = null;
public function __construct(array $data = null)
{
if (isset($data['address'])){
$this->setAddress($data['address']);
}
if (isset($data['zipcode'])){
$this->setZipcode($data['zipcode']);
}
if (isset($data['city'])){
$this->setCity($data['city']);
}
if (isset($data['country'])){
$this->setCountry($data['country']);
}
if (isset($data['lat'])){
$this->setLat($data['lat']);
}
if (isset($data['lng'])){
$this->setLng($data['lng']);
}
}
public function getCoordinates()
{
return $this->_coordinates;
}
public function setCoordinates($lat, $lng)
{
$this->_lat = $lat;
$this->_lng = $lng;
return $this;
}
public function getLat()
{
return $this->_lat;
}
public function setLat($lat)
{
$this->_lat = $lat;
return $this;
}
public function getLng()
{
return $this->_lng;
}
public function setLng($lng)
{
$this->_lng = $lng;
return $this;
}
public function getAddress()
{
return $this->_address;
}
public function setAddress($address)
{
$this->_address = $address;
return $this;
}
public function getZipcode()
{
return $this->_zipcode;
}
public function setZipcode($zipcode)
{
$this->_zipcode = $zipcode;
return $this;
}
public function getCity()
{
return $this->_city;
}
public function setCity($city)
{
$this->_city = $city;
return $city;
}
public function getCountry()
{
return $this->_country;
}
public function setCountry($country)
{
$this->_country = $country;
return $this;
}
}
diff --git a/application/library/Fizzy/Geocode/Response.php b/application/library/Fizzy/Geocode/Response.php
index 84dc8b5..4b3ad56 100644
--- a/application/library/Fizzy/Geocode/Response.php
+++ b/application/library/Fizzy/Geocode/Response.php
@@ -1,74 +1,92 @@
<?php
+/**
+ * Class Fizzy_Geocode_Response
+ * @package Fizzy_Geocode
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
require_once 'Fizzy/Geocode/Location.php';
/**
- * Description of Response
+ * Adapter indepent response object
*
- * @author jeroen
+ * @author Jeroen Tietema <[email protected]>
*/
class Fizzy_Geocode_Response {
protected $_query = '';
protected $_errors = null;
protected $_locations = array();
/**
* Returns the first location found
*/
public function first()
{
if (count($this->_locations) > 0){
return $this->_locations[0];
}
throw new Fizzy_Geocode_Exception('No locations set');
}
/**
* Returns all locations found
*/
public function all()
{
return $this->_locations;
}
/**
* The number of locations found
*/
public function count()
{
return count($this->_locations);
}
public function isError()
{
return (null !== $this->_errors);
}
public function getLocations()
{
return $this->_locations;
}
public function addLocation(Fizzy_Geocode_Location $location)
{
$this->_locations[] = $location;
}
public function setLocations(array $locations)
{
$this->_locations = $locations;
return $this;
}
public function getErrors()
{
return $this->_errors;
}
public function setErrors(array $errors)
{
$this->_errors = $errors;
return $this;
}
}
|
jtietema/Fizzy
|
adbecfdba3686740b0469cde68f2b6a58dc30684
|
baseUrl's where inserted twice when using nested url viewhelpers
|
diff --git a/application/modules/admin/views/scripts/blogs/blog.phtml b/application/modules/admin/views/scripts/blogs/blog.phtml
index 2304fb9..9cd7511 100644
--- a/application/modules/admin/views/scripts/blogs/blog.phtml
+++ b/application/modules/admin/views/scripts/blogs/blog.phtml
@@ -1,56 +1,56 @@
<div id="content-panel">
<h2><?= $this->blog->name ?></h2>
<div>
<table class="data">
<thead>
<tr>
<td> </td>
<td>Title</td>
<td>Date</td>
<td>Status</td>
<td>Author</td>
</tr>
</thead>
<tbody>
<?php $items = $this->paginator->getCurrentItems();
foreach ($items as $post): ?>
<tr>
<td class="controls">
- <?= $this->link('@admin_blog_post_edit?post_id=' . $post->id, $this->image($this->assetUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_edit?post_id=' . $post->id, $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
</td>
<td>
<?= $post->title ?>
</td>
<td>
<?= $post->date ?>
</td>
<td>
<?php if ($post->status == Post::PUBLISHED): ?>
Published
<?php elseif ($post->status == Post::PENDING_REVIEW): ?>
Pending review
<?php else: ?>
Draft
<?php endif; ?>
</td>
<td>
<?= $post->User->displayname ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_blog_post_add?blog_id=' . $this->blog->id, $this->image($this->assetUrl('/images/icon/document--plus.png')) . ' Add post', array('escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_add?blog_id=' . $this->blog->id, $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' Add post', array('escape' => false)); ?>
</li>
</ul>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/blogs/post-form.phtml b/application/modules/admin/views/scripts/blogs/post-form.phtml
index 16a8478..12d1467 100644
--- a/application/modules/admin/views/scripts/blogs/post-form.phtml
+++ b/application/modules/admin/views/scripts/blogs/post-form.phtml
@@ -1,73 +1,73 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
- <?= $this->image($this->assetUrl('/images/icon/document.png')); ?>
+ <?= $this->image($this->assetUrl('/images/icon/document.png', false)); ?>
<?= ($this->post->isNew()) ? 'Add post' : 'Edit post'; ?>
</h2>
<div class="form-panel">
<?= $this->form->title; ?>
<?= $this->form->body; ?>
</div>
<h2>
- <?= $this->image($this->assetUrl('/images/icon/balloons.png')); ?>
+ <?= $this->image($this->assetUrl('/images/icon/balloons.png', false)); ?>
Comments on this post
</h2>
<div class="comments">
<?= $this->partial('comments/_comments.phtml', array(
'comments' => $this->post->Comments(),
'back' => 'post'
)) ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->post->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_blog_post_delete?post_id=' . $this->post->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete page',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete page',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this page?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_blog?id=' . $this->post->Blog->id,
- $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to ' . $this->post->Blog->name,
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to ' . $this->post->Blog->name,
array('escape' => false)
); ?>
</li>
</ul>
<h2>Options</h2>
<div class="form-options-panel">
<?= $this->form->status; ?>
<?= $this->form->author; ?>
<?= $this->form->date; ?>
<?= $this->form->comments; ?>
</div>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/edit.phtml b/application/modules/admin/views/scripts/comments/edit.phtml
index 115442e..25145a2 100644
--- a/application/modules/admin/views/scripts/comments/edit.phtml
+++ b/application/modules/admin/views/scripts/comments/edit.phtml
@@ -1,54 +1,54 @@
<form action="<?= $this->form->getAction(); ?>" method="post">
<div id="content-panel">
<h2>
Edit Comment
</h2>
<div class="form-panel">
<?= $this->form->name; ?>
<?= $this->form->email; ?>
<?= $this->form->website; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
'@admin_comments_delete?id=' . $this->comment->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete comment',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete comment',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this comment?',
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
<?= $this->link(
'@admin_comments_topic?id=' . $this->comment->post_id,
- $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to comments',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to comments',
array(
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/contact/index.phtml b/application/modules/admin/views/scripts/contact/index.phtml
index e9b4c7d..f157cd9 100644
--- a/application/modules/admin/views/scripts/contact/index.phtml
+++ b/application/modules/admin/views/scripts/contact/index.phtml
@@ -1,37 +1,37 @@
<div id="content-panel">
<h2>Contact</h2>
<table class="data" id="contact-table">
<thead>
<tr>
<th> </th>
<th>Date</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach($this->messages as $message) : ?>
<tr>
<td class="controls" style="width: 55px;">
- <?= $this->link('@admin_contact_show?id=' . $message->id, $this->image($this->assetUrl('/images/icon/mail-open.png')), array('escape' => false)); ?>
+ <?= $this->link('@admin_contact_show?id=' . $message->id, $this->image($this->assetUrl('/images/icon/mail-open.png', false)), array('escape' => false)); ?>
<?= $this->link(
'@admin_contact_delete?id=' . $message->id,
- $this->image($this->assetUrl('/images/icon/mail--minus.png')),
+ $this->image($this->assetUrl('/images/icon/mail--minus.png', false)),
array (
'confirm' => 'Are you sure you want to delete this contact request?',
'escape' => false
)
); ?>
</td>
<td style="width: 150px;"><?= $message->date; ?></td>
<td style="max-width: 300px;"><?= $message->name; ?> <<a href="mailto:<?= $message->email; ?>"><?= $message->email; ?></a>></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/contact/show.phtml b/application/modules/admin/views/scripts/contact/show.phtml
index 90d07f7..2aac55b 100644
--- a/application/modules/admin/views/scripts/contact/show.phtml
+++ b/application/modules/admin/views/scripts/contact/show.phtml
@@ -1,33 +1,33 @@
<div id="content-panel">
<h2>Contact request</h2>
<p>
From: <?= $this->message->name; ?> <<a href="mailto:<?= $this->message->email; ?>"><?= $this->message->email; ?></a>><br />
On: <?= $this->message->date; ?>
</p>
<p>
<?= nl2br($this->message->body); ?>
</p>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
'@admin_contact_delete?id=' . $this->message->id,
- $this->image($this->assetUrl('/images/icon/mail--minus.png')) . 'delete message',
+ $this->image($this->assetUrl('/images/icon/mail--minus.png', false)) . 'delete message',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this message?',
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
- <?= $this->link('@admin_contact', $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' contact list', array('escape' => false)); ?>
+ <?= $this->link('@admin_contact', $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' contact list', array('escape' => false)); ?>
</li>
</ul>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/media/assets.phtml b/application/modules/admin/views/scripts/media/assets.phtml
index 9a33a92..83833c8 100644
--- a/application/modules/admin/views/scripts/media/assets.phtml
+++ b/application/modules/admin/views/scripts/media/assets.phtml
@@ -1,79 +1,79 @@
<?php
$types = array(
- 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
- 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
- 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
- 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
- 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'png' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'bmp' => $this->assetUrl('/images/icon/document-image.png'),
+ 'gif' => $this->assetUrl('/images/icon/document-image.png'),
+ 'doc' => $this->assetUrl('/images/icon/document-word.png'),
+ 'docx' => $this->assetUrl('/images/icon/document-word.png'),
+ 'xls' => $this->assetUrl('/images/icon/document-excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/document-powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/document-pdf.png'),
+ 'flv' => $this->assetUrl('/images/icon/document-flash-movie.png'),
+ 'zip' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'rar' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'txt' => $this->assetUrl('/images/icon/document-text.png'),
);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{#fizzyassets_dlg.title}</title>
<link href="<?= $this->assetUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
<script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzyassets/js/dialog.js') ?>"></script>
</head>
<body>
<div id="image-picker" class="files-container">
<table class="files-table">
<thead>
<tr>
<td colspan="2">Filename</td>
<td>Size</td>
</tr>
</thead>
<tbody>
<?php foreach($this->files as $fileInfo) : ?>
<tr id="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>">
<td class="icon"><img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->assetUrl('/images/icon/page.png'); ?>" alt="" /></td>
<td class="filename">
<a href="#" onclick="select('<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>', this.parentNode.parentNode);">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</a>
</td>
<td class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<form onsubmit="FizzyassetsDialog.insert();return false;" action="#">
<div>
<div class="form-left">
<label>Description:</label>
<input type="text" name="alt" id="alt" />
</div>
<div class="clear"></div>
<input type="button" name="insert" value="{#insert}" onclick="FizzyassetsDialog.insert();" />
<input type="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</form>
</body>
</html>
diff --git a/application/modules/admin/views/scripts/media/list.phtml b/application/modules/admin/views/scripts/media/list.phtml
index 53cd0b7..69c612a 100644
--- a/application/modules/admin/views/scripts/media/list.phtml
+++ b/application/modules/admin/views/scripts/media/list.phtml
@@ -1,67 +1,67 @@
<?php
$types = array(
- 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
- 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
- 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
- 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
- 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'png' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'bmp' => $this->assetUrl('/images/icon/document-image.png'),
+ 'gif' => $this->assetUrl('/images/icon/document-image.png'),
+ 'doc' => $this->assetUrl('/images/icon/document-word.png'),
+ 'docx' => $this->assetUrl('/images/icon/document-word.png'),
+ 'xls' => $this->assetUrl('/images/icon/document-excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/document-powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/document-pdf.png'),
+ 'flv' => $this->assetUrl('/images/icon/document-flash-movie.png'),
+ 'zip' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'rar' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'txt' => $this->assetUrl('/images/icon/document-text.png'),
);
?>
<div class="media-container">
<table class="media">
<?php if(0 < count($this->files)) : ?>
<tbody>
<?php $row = 0; foreach($this->files as $fileInfo) : ?>
<tr class="<?= (++$row % 2) === 0 ? 'even' : 'odd'; ?>">
<td class="icon">
- <img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->baseUrl('/images/icon/page.png'); ?>" alt="" />
+ <img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->assetUrl('/images/icon/document.png'); ?>" alt="" />
</td>
<td class="filename">
<a href="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" target="_blank" title="View file">
<?= $fileInfo->basename; ?>
</a>
</td>
<td class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
<td class="controls">
<?php if(is_writable($this->uploadFolder)) : ?>
<?= $this->link(
'@admin_media_delete?name=' . urlencode($fileInfo->basename),
- $this->image($this->assetUrl('/images/icon/minus-small.png')),
+ $this->image($this->assetUrl('/images/icon/minus-small.png', false)),
array (
'confirm' => "Are you sure you want to delete {$fileInfo->basename}?",
'title' => 'Delete file',
'escape' => false,
)
); ?>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<?php else : ?>
<tr>
<td colspan="4">
No uploaded files were found. Use the form at the bottom to
add new files.
</td>
</tr>
<?php endif; ?>
</table>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/media/thumbnails.phtml b/application/modules/admin/views/scripts/media/thumbnails.phtml
index ae72d04..f53e018 100644
--- a/application/modules/admin/views/scripts/media/thumbnails.phtml
+++ b/application/modules/admin/views/scripts/media/thumbnails.phtml
@@ -1,79 +1,79 @@
<?php
// file type image declarations
$images = array('png', 'jpg', 'jpeg', 'bmp', 'gif');
$types = array(
- 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
- 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
- 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
- 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
- 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
- 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
- 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
- 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'png' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/document-image.png'),
+ 'bmp' => $this->assetUrl('/images/icon/document-image.png'),
+ 'gif' => $this->assetUrl('/images/icon/document-image.png'),
+ 'doc' => $this->assetUrl('/images/icon/document-word.png'),
+ 'docx' => $this->assetUrl('/images/icon/document-word.png'),
+ 'xls' => $this->assetUrl('/images/icon/document-excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/document-powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/document-pdf.png'),
+ 'flv' => $this->assetUrl('/images/icon/document-flash-movie.png'),
+ 'zip' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'rar' => $this->assetUrl('/images/icon/document-zipper.png'),
+ 'txt' => $this->assetUrl('/images/icon/document-text.png'),
);
?>
<div class="media-container">
<?php foreach($this->files as $fileInfo) : ?>
<div class="thumbnail">
<div class="head">
<span class="filename">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</span>
<?php if(is_writable($this->uploadFolder)) : ?>
<span class="remove">
<?= $this->link(
'@admin_media_delete?name=' . urlencode($fileInfo->basename),
- $this->image($this->assetUrl('/images/icon/cross-small.png')),
+ $this->image($this->assetUrl('/images/icon/cross-small.png', false)),
array (
'confirm' => "Are you sure you want to delete {$fileInfo->basename}?",
'title' => 'Delete file',
'escape' => false,
)
); ?>
</span>
<?php endif; ?>
<div class="clear"></div>
</div>
<div class="body">
<a href="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" target="_blank" title="View file">
<?php if (in_array($fileInfo->type, $images)): ?>
<img class="source" src="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" alt="<?= $fileInfo->basename ?>" />
<?php else: ?>
- <img class="icon" width="48px" height="48px" src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->baseUrl('/fizzy_assets/images/icon/page.png'); ?>" alt="" />
+ <img class="icon" width="48px" height="48px" src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->assetUrl('/images/icon/document.png'); ?>" alt="" />
<?php endif; ?>
</a>
</div>
<div class="foot">
<span class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</span>
<div class="clear"></div>
</div>
</div>
<?php endforeach; ?>
<div class="clear"></div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/pages/form.phtml b/application/modules/admin/views/scripts/pages/form.phtml
index c4d9b63..9ef3186 100644
--- a/application/modules/admin/views/scripts/pages/form.phtml
+++ b/application/modules/admin/views/scripts/pages/form.phtml
@@ -1,69 +1,69 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
- <?= $this->image($this->assetUrl('/images/icon/document.png')); ?>
+ <?= $this->image($this->assetUrl('/images/icon/document.png', false)); ?>
<?= ($this->page->isNew()) ? 'Add page' : 'Edit page'; ?>
</h2>
<div class="form-panel">
<?= $this->form->id; // required for slugunique validator ?>
<?= $this->form->title; ?>
<?= $this->form->slug; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->page->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_pages_delete?id=' . $this->page->id,
- $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete page',
+ $this->image($this->assetUrl('/images/icon/document--minus.png', false)) . ' delete page',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this page?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_pages',
- $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to pages',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to pages',
array('escape' => false)
); ?>
</li>
</ul>
<h2>Options</h2>
<div class="form-options-panel">
<?= $this->form->template; ?>
<?= $this->form->layout; ?>
<div class="form-row" id="homepage-row">
<label for="homepage">Homepage</label>
<?= $this->form->homepage->setDecorators(array('ViewHelper', 'Errors')); ?>
<?= $this->form->homepage->getDescription(); ?>
</div>
</div>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/pages/index.phtml b/application/modules/admin/views/scripts/pages/index.phtml
index fc3ec20..0d41f68 100644
--- a/application/modules/admin/views/scripts/pages/index.phtml
+++ b/application/modules/admin/views/scripts/pages/index.phtml
@@ -1,48 +1,48 @@
<div id="content-panel">
<h2>Pages</h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
<td>Slug</td>
<td>Title</td>
</tr>
</thead>
<tbody>
<?php foreach($this->pages as $page) : ?>
<tr>
<td class="controls">
- <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetUrl('/images/icon/document--pencil.png', false), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
</td>
<td style="width: 200px;"><?= $page['slug'] ?></td>
<td><?= $page['title'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_pages_add', $this->image($this->assetUrl('/images/icon/document--plus.png')) . ' Add page', array('escape' => false)); ?>
+ <?= $this->link('@admin_pages_add', $this->image($this->assetUrl('/images/icon/document--plus.png', false)) . ' Add page', array('escape' => false)); ?>
</li>
</ul>
<hr />
<div class="block">
<h2>About pages</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet fringilla eros in laoreet. Sed rhoncus aliquam accumsan. Nullam nec massa sed elit faucibus ultricies. Vivamus pharetra volutpat posuere. Aliquam a metus neque, et euismod odio. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget metus lacus, quis rhoncus mauris. In sit amet aliquet felis. Aenean luctus ornare posuere. Fusce egestas, nisi nec mattis pretium, lorem lorem venenatis lectus, id ornare lacus justo in neque. Ut commodo risus eu justo vulputate a fringilla quam rhoncus. Curabitur fermentum neque in tellus adipiscing scelerisque.
</p>
</div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/form.phtml b/application/modules/admin/views/scripts/user/form.phtml
index 426a593..4cecb3a 100644
--- a/application/modules/admin/views/scripts/user/form.phtml
+++ b/application/modules/admin/views/scripts/user/form.phtml
@@ -1,57 +1,57 @@
<form action="<?= $this->form->getAction(); ?>" name="UserForm" id="UserForm" method="post">
<div id="content-panel">
<h2>
<?= $this->user->isNew() ? 'Add user' : 'Edit user'; ?>
</h2>
<div class="form-panel">
<?= $this->form->id; ?>
<?= $this->form->username; ?>
<?= $this->form->displayname; ?>
<?= $this->form->password; ?>
<?= $this->form->password_confirm; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if (!$this->user->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'@admin_users_delete?id=' . $this->user->id,
- $this->image($this->assetUrl('/images/icon/user--minus.png')) . ' delete user',
+ $this->image($this->assetUrl('/images/icon/user--minus.png', false)) . ' delete user',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this user?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'@admin_users',
- $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to users',
+ $this->image($this->assetUrl('/images/icon/edit-list.png', false)) . ' back to users',
array (
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/list.phtml b/application/modules/admin/views/scripts/user/list.phtml
index 0a99695..3f05bd6 100644
--- a/application/modules/admin/views/scripts/user/list.phtml
+++ b/application/modules/admin/views/scripts/user/list.phtml
@@ -1,41 +1,41 @@
<div id="content-panel">
<h2>Users</h2>
<table class="data">
<thead>
<tr>
<td> </td>
<td>Username</td>
</tr>
</thead>
<tbody>
<?php foreach($this->users as $user) : ?>
<tr>
<td class="controls">
<?= $this->link(
'@admin_users_edit?id=' . $user['id'],
- $this->image($this->assetUrl('/images/icon/user--pencil.png'), array('alt' => 'edit icon')),
+ $this->image($this->assetUrl('/images/icon/user--pencil.png', false), array('alt' => 'edit icon')),
array (
'escape' => false
)
); ?>
</td>
<td><?= $user['username'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_users_add', $this->image($this->assetUrl('/images/icon/user--plus.png')) . ' Add user', array('escape' => false)); ?>
+ <?= $this->link('@admin_users_add', $this->image($this->assetUrl('/images/icon/user--plus.png', false)) . ' Add user', array('escape' => false)); ?>
</li>
</ul>
</div>
|
jtietema/Fizzy
|
08ceac1a8155bd5a3685923446d6363493f792e1
|
Wrong view helper call to assetUrl
|
diff --git a/application/modules/admin/views/scripts/pages/index.phtml b/application/modules/admin/views/scripts/pages/index.phtml
index c78575c..fc3ec20 100644
--- a/application/modules/admin/views/scripts/pages/index.phtml
+++ b/application/modules/admin/views/scripts/pages/index.phtml
@@ -1,48 +1,48 @@
<div id="content-panel">
<h2>Pages</h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
<td>Slug</td>
<td>Title</td>
</tr>
</thead>
<tbody>
<?php foreach($this->pages as $page) : ?>
<tr>
<td class="controls">
- <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetsUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
</td>
<td style="width: 200px;"><?= $page['slug'] ?></td>
<td><?= $page['title'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_pages_add', $this->image($this->assetsUrl('/images/icon/document--plus.png')) . ' Add page', array('escape' => false)); ?>
+ <?= $this->link('@admin_pages_add', $this->image($this->assetUrl('/images/icon/document--plus.png')) . ' Add page', array('escape' => false)); ?>
</li>
</ul>
<hr />
<div class="block">
<h2>About pages</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet fringilla eros in laoreet. Sed rhoncus aliquam accumsan. Nullam nec massa sed elit faucibus ultricies. Vivamus pharetra volutpat posuere. Aliquam a metus neque, et euismod odio. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget metus lacus, quis rhoncus mauris. In sit amet aliquet felis. Aenean luctus ornare posuere. Fusce egestas, nisi nec mattis pretium, lorem lorem venenatis lectus, id ornare lacus justo in neque. Ut commodo risus eu justo vulputate a fringilla quam rhoncus. Curabitur fermentum neque in tellus adipiscing scelerisque.
</p>
</div>
</div>
\ No newline at end of file
|
jtietema/Fizzy
|
3ceb822a3fce730b5fd2ec62fb30ff24e56f3c87
|
Big commit with all static backend urls replaced
|
diff --git a/application/modules/admin/controllers/AuthController.php b/application/modules/admin/controllers/AuthController.php
index b357970..d9bb2f5 100644
--- a/application/modules/admin/controllers/AuthController.php
+++ b/application/modules/admin/controllers/AuthController.php
@@ -1,91 +1,92 @@
<?php
/**
* Class Admin_AuthController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_AuthController extends Fizzy_Controller
{
public function loginAction()
{
$form = $this->_getForm();
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$authAdapter = new Fizzy_Doctrine_AuthAdapter(
$form->username->getValue(), $form->password->getValue()
);
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$result = $auth->authenticate($authAdapter);
+
if($result->isValid()) {
- $this->_redirect('/fizzy', array('prependBase' => true));
+ $this->_redirect('@admin');
}
$messages = $result->getMessages();
$this->addErrorMessage(array_shift($messages));
- $this->_redirect('/fizzy/login', array('prependBase' => true));
+ $this->_redirect('@admin_login');
}
}
$this->view->form = $form;
$this->renderScript('login.phtml');
}
public function logoutAction()
{
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session('fizzy'));
$auth->clearIdentity();
- $this->_redirect('/fizzy', array('prependBase' => true));
+ $this->_redirect('@admin');
}
protected function _getForm()
{
$formConfig = array (
'elements' => array (
'username' => array (
'type' => 'text',
'options' => array (
'label' => 'Username',
'required' => true
)
),
'password' => array (
'type' => 'password',
'options' => array (
'label' => 'Password',
'required' => true
),
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Login',
'ignore' => true
)
)
)
);
return new Fizzy_Form(new Zend_Config($formConfig));
}
public function postDispatch()
{
$this->_helper->layout->setLayout('login');
}
}
diff --git a/application/modules/admin/controllers/BlogsController.php b/application/modules/admin/controllers/BlogsController.php
index 309042f..62c2af9 100644
--- a/application/modules/admin/controllers/BlogsController.php
+++ b/application/modules/admin/controllers/BlogsController.php
@@ -1,219 +1,217 @@
<?php
/**
* Class Admin_BlogsController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_BlogsController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
public function indexAction()
{
$blogs = Doctrine_Query::create()->from('Blog')->execute();
$this->view->blogs = $blogs;
}
public function blogAction()
{
$id = $this->_getParam('id', null);
$pageNumber = $this->_getParam('page', 1);
if (null === $id){
return $this->renderScript('blogs/blogNotFound.phtml');
}
$blog = Doctrine_Query::create()->from('Blog')->where('id = ?', $id)->fetchOne();
if (null == $blog){
return $this->renderScript('blogs/blogNotFound.phtml');
}
$query = Doctrine_Query::create()->from('Post')
->where('blog_id = ?', $id);
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->blog = $blog;
$this->view->paginator = $paginator;
}
public function addPostAction()
{
$blogId = $this->_getParam('blog_id', null);
if (null === $blogId){
return $this->renderScript('blogs/blogNotFound.phtml');
}
$blog = Doctrine_Query::create()->from('Blog')->where('id = ?', $blogId)->fetchOne();
if (null == $blog){
return $this->renderScript('blogs/blogNotFound.phtml');
}
$this->view->blog = $blog;
$this->view->form = $form = $this->_getPostForm();
$form->date->setValue(date('Y-m-d H:i:s'));
$auth = Zend_Auth::getInstance();
$identity = $auth->getIdentity();
$form->author->setValue($identity['id']);
$form->addElement(new Zend_Form_Element_Submit('submit', array(
'label' => 'Add',
'ignore' => true
)));
$this->view->post = $post = new Post();
if ($this->_request->isPost() && $form->isValid($_POST)){
$post->title = $form->title->getValue();
$post->body = $form->body->getValue();
$post->author = $form->author->getValue();
$post->date = $form->date->getValue();
$post->blog_id = $blogId;
$post->save();
- $this->_redirect('/fizzy/blog/' . $blogId);
+ $this->_redirect('@admin_blog', array('id' => $blogId));
}
$this->renderScript('blogs/post-form.phtml');
}
public function editPostAction()
{
$postId = $this->_getParam('post_id', null);
if (null === $postId){
return $this->renderScript('blogs/postNotFound.phtml');
}
$post = Doctrine_Query::create()->from('Post')->where('id = ?', $postId)->fetchOne();
if (null == $post){
return $this->renderScript('blogs/postNotFound.phtml');
}
$form = $this->_getPostForm();
if ($this->_request->isPost() && $form->isValid($_POST)){
$post->title = $form->title->getValue();
$post->body = $form->body->getValue();
$post->author = $form->author->getValue();
$post->date = $form->date->getValue();
$post->comments = $form->comments->getValue();
$post->status = $form->status->getValue();
$post->save();
$this->addSuccessMessage("Post \"<strong>{$post->title}</strong>\" was successfully saved.");
- $this->_redirect('fizzy/post/' . $postId . '/edit');
+ $this->_redirect('@admin_post_edit', array('id' => $postId));
} else {
$form->title->setValue($post->title);
$form->body->setValue($post->body);
$form->author->setValue($post->author);
$form->date->setValue($post->date);
$form->comments->setValue($post->comments);
$form->status->setValue($post->status);
}
$form->addElement(new Zend_Form_Element_Submit('submit', array(
'label' => 'Edit',
'ignore' => true,
)));
$this->view->form = $form;
$this->view->post = $post;
$this->renderScript('blogs/post-form.phtml');
}
public function deletePostAction()
{
$postId = $this->_getParam('post_id', null);
if (null === $postId){
return $this->renderScript('blogs/postNotFound.phtml');
}
$post = Doctrine_Query::create()->from('Post')->where('id = ?', $postId)->fetchOne();
if (null == $post){
return $this->renderScript('blogs/postNotFound.phtml');
}
$post->delete();
- $this->_redirect('fizzy/blog/' . $post->Blog->id);
+ $this->_redirect('@admin_blog', array('id' => $post->Blog->id));
}
protected function _getPostForm()
{
$form = new Zend_Form();
$form->addElement(new Zend_Form_Element_Text('title', array(
'label' => 'Title',
'required' => true,
)));
$form->addElement(new ZendX_JQuery_Form_Element_DatePicker('date', array(
'label' => 'Date',
'required' => true,
'description' => 'The published date of this post.'
)));
$form->date->setJQueryParam('changeMonth', true);
$form->date->setJQueryParam('changeYear', true);
$form->date->setJQueryParam('dateFormat', 'yy-mm-dd');
$form->addElement(new Fizzy_Form_Element_Wysiwyg('body', array(
'label' => 'Body',
'attribs' => array('style' => 'width: 100%;'),
)));
$form->addElement(new Zend_Form_Element_Select('author', array(
'label' => 'Author',
'multiOptions' => $this->_getUsers(),
'description' => 'The author of this post.'
)));
$form->addElement(new Zend_Form_Element_Checkbox('comments', array(
'label' => 'Allow comments',
'value' => true,
'description' => 'Are visitors allowed to comment on this post?'
)));
$form->addElement(new Zend_Form_Element_Select('status', array(
'label' => 'Status',
'multiOptions' => array(
0 => 'Draft',
1 => 'Pending review',
2 => 'Published'
),
'description' => 'Only published posts will show up on the website.'
)));
return $form;
}
protected function _getUsers()
{
$users = Doctrine_Query::create()->from('User')->execute();
$array = array();
foreach ($users as $user){
$array[$user->id] = $user->displayname;
}
return $array;
}
}
diff --git a/application/modules/admin/controllers/CommentsController.php b/application/modules/admin/controllers/CommentsController.php
index 8e98ccb..691cd61 100644
--- a/application/modules/admin/controllers/CommentsController.php
+++ b/application/modules/admin/controllers/CommentsController.php
@@ -1,289 +1,287 @@
<?php
/**
* Class Admin_CommentsController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Controller class for the moderation panel of comments
*
* @author Jeroen Tietema <[email protected]>
*/
class Admin_CommentsController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
/**
* Dashboard. Shows latest comments and total numbers of comments, spam, etc.
*/
public function indexAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = 0')->orderBy('id DESC');
$this->view->totalComments = $query->count();
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$spamQuery = Doctrine_Query::create()->from('Comments')->where('spam = 1');
$this->view->spamComments = $spamQuery->count();
$this->view->paginator = $paginator;
}
/**
* List of discussions/topics
*/
public function listAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')
->groupBy('post_id')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
/**
* Shows one discussion/topic/thread.
*/
public function topicAction()
{
$id = $this->_getParam('id', null);
$pageNumber = $this->_getParam('page', 1);
if (null === $id){
return $this->renderScript('comments/topic-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('post_id = ?', $id)->andWhere('spam = 0')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$tempModel = $query->fetchOne();
if (null == $tempModel){
return $this->renderScript('comments/topic-not-found.phtml');
}
$this->view->threadModel = $tempModel->getThreadModel();
$this->view->paginator = $paginator;
}
/**
* Marks given message as spam.
*/
public function spamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = true;
$comment->save();
/**
* @todo pass to the spam backend
*/
$this->_redirectBack($comment);
}
/**
* Unmarks given message as spam.
*/
public function hamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = false;
$comment->save();
/**
* @todo pass to the Spam backend
*/
$this->_redirectBack($comment);
}
/**
* Edit the comment.
*/
public function editAction()
{
$id = $this->_getParam('id', null);
$redirect = $this->_getParam('back', 'dashboard');
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$form = new Zend_Form();
- $form->setAction($this->view->baseUrl('/fizzy/comment/edit/' . $comment->id . '?back=' . $redirect));
+ $form->setAction($this->view->url('@admin_comments_edit?id=' . $comment->id) . '&back=' . $redirect);
$form->addElement(new Zend_Form_Element_Text('name', array(
'label' => 'Author name'
)));
$form->addElement(new Zend_Form_Element_Text('email', array(
'label' => 'Author E-mail'
)));
$form->addElement(new Zend_Form_Element_Text('website', array(
'label' => 'Author website'
)));
$form->addElement(new Zend_Form_Element_Textarea('body', array(
'label' => 'Comment'
)));
$form->addElement(new Zend_Form_Element_Submit('save', array(
'label' => 'Save'
)));
if ($this->_request->isPost() && $form->isValid($_POST)){
$comment->name = $form->name->getValue();
$comment->email = $form->email->getValue();
$comment->website = $form->website->getValue();
$comment->body = $form->body->getValue();
$comment->save();
$this->_redirectBack($comment);
}
$form->name->setValue($comment->name);
$form->email->setValue($comment->email);
$form->website->setValue($comment->website);
$form->body->setValue($comment->body);
$this->view->form = $form;
$this->view->comment = $comment;
$this->view->back = $redirect;
}
/**
* Delete the comment.
*/
public function deleteAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->delete();
$this->_redirectBack($comment);
}
/**
* Approve the comment (when using moderation).
*/
public function approveAction()
{
}
/**
* Unapprove the given comment.
*/
public function unapproveAction()
{
}
/**
* Shows the spambox containing all spam comments
*/
public function spamboxAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = ?', 1);
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
protected function _redirectBack(Comments $comment = null)
{
$redirect = $this->_getParam('back', 'dashboard');
switch($redirect){
case 'topic':
- $this->_redirect('/fizzy/comments/topic/' . $comment->post_id);
+ $this->_redirect('@admin_comments_topic', array('id' => $comment->post_id));
break;
case 'spambox':
- $this->_redirect('/fizzy/comments/spam');
+ $this->_redirect('@admin_comments_spam');
break;
case 'post':
$postId = (int) substr($comment->post_id, 5);
- $this->_redirect('/fizzy/post/' . $postId . '/edit');
+ $this->_redirect('@admin_blog_post_edit', array('id' => $postId));
default:
- $this->_redirect('/fizzy/comments');
+ $this->_redirect('@admin_comments');
break;
}
}
}
diff --git a/application/modules/admin/controllers/ContactController.php b/application/modules/admin/controllers/ContactController.php
index 81ae265..0b88a04 100644
--- a/application/modules/admin/controllers/ContactController.php
+++ b/application/modules/admin/controllers/ContactController.php
@@ -1,72 +1,69 @@
<?php
/**
* Class Admin_ContactController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_ContactController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
-
public function indexAction()
{
$this->view->messages = Doctrine_Core::getTable('Contact')->findAll();
}
public function showAction()
{
$id = $this->_getParam('id', null);
if(null === $id) {
- $this->_redirect('/fizzy/contact', array('prependBase' => true));
+ $this->_redirect('@admin_contact');
}
$query = Doctrine_Query::create()->from('Contact')->where('id = ?', $id);
$message = $query->fetchOne();
if(null === $message) {
$this->addErrorMessage("Message with ID {$id} could not be found.");
- $this->_redirect('/fizzy/contact', array('prependBase' => true));
+ $this->_redirect('@admin_contact');
}
$this->view->message = $message;
}
public function deleteAction()
{
$id = $this->_getParam('id', null);
if(null === $id) {
- $this->_redirect('/fizzy/contact', array('prependBase' => true));
+ $this->_redirect('@admin_contact');
}
$query = Doctrine_Query::create()->from('Contact')->where('id = ?', $id);
$message = $query->fetchOne();
if(null === $message) {
$this->addErrorMessage("Message with ID {$id} could not be found.");
- $this->_redirect('/fizzy/contact', array('prependBase' => true));
+ $this->_redirect('@admin_contact');
}
$success = $message->delete();
if ($success) {
$this->addSuccessMessage("Message was deleted");
} else {
$this->addErrorMessage("Message with ID {$id} could not be deleted.");
}
- $this->_redirect('/fizzy/contact', array('prependBase' => true));
+ $this->_redirect('@admin_contact');
}
}
\ No newline at end of file
diff --git a/application/modules/admin/controllers/IndexController.php b/application/modules/admin/controllers/IndexController.php
index e3853a8..3875015 100644
--- a/application/modules/admin/controllers/IndexController.php
+++ b/application/modules/admin/controllers/IndexController.php
@@ -1,197 +1,194 @@
<?php
/**
* Class Admin_IndexController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Class Admin_IndexController
*
* @author Mattijs Hoitink <[email protected]>
*/
class Admin_IndexController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
-
protected $_navigation = null;
/**
* Default action redirects to Pages overview.
*/
public function indexAction()
{
- $this->_redirect('/fizzy/pages');
+ $this->_redirect('@admin_pages');
}
public function configurationAction()
{
$this->view->config = Zend_Registry::get('config')->toArray();
$this->renderScript('configuration.phtml');
}
/**
* Renders navigation for the admin section.
*/
public function navigationAction()
{
if (null === $this->_navigation){
$this->_navigation = $this->_createNavigation();
}
$this->view->items = $this->_navigation->getPages();
$this->renderScript('navigation.phtml');
}
public function subnavigationAction()
{
if (null === $this->_navigation){
$this->_navigation = $this->_createNavigation();
}
$this->view->items = array();
foreach ($this->_navigation->getPages() as $page){
if ($page->isActive(true)){
$this->view->items = $page->getPages();
break;
}
}
$this->renderScript('subnavigation.phtml');
}
protected function _createNavigation()
{
$items = array();
// Blog
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Blogs',
'route' => 'admin_blogs',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_blog',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'label' => 'Edit Post',
'route' => 'admin_blog_post_edit',
)),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Add Post',
'route' => 'admin_blog_post_add',
))
)
))
)
));
// Comments
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Comments',
'route' => 'admin_comments',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'label' => 'Dashboard',
'route' => 'admin_comments'
)),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Thread list',
'route' => 'admin_comments_list',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'label' => 'Show thread',
'route' => 'admin_comments_topic',
))
)
)),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Spambox',
'route' => 'admin_comments_spambox',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_comments_edit',
))
)
));
// Pages
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Pages',
'route' => 'admin_pages',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_pages_add',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_pages_edit',
)),
)
));
// Media
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Media',
'route' => 'admin_media',
));
// Contact
$contactLogSetting = Setting::getKey('log', 'contact');
if (null !== $contactLogSetting && 1 == $contactLogSetting->value) {
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Contact',
'route' => 'admin_contact',
'pages' => array (
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_contact_show',
))
)
));
}
// Users
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Users',
'route' => 'admin_users',
'pages' => array (
new Fizzy_Navigation_Page_Route(array(
'label' => 'Add user',
'route' => 'admin_users_add',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_users_edit',
)),
)
));
// Settings
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Settings',
'route' => 'admin_settings',
));
// Logout
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Logout',
'route' => 'admin_logout',
));
return new Zend_Navigation($items);
}
}
diff --git a/application/modules/admin/controllers/MediaController.php b/application/modules/admin/controllers/MediaController.php
index ed9afde..be03781 100644
--- a/application/modules/admin/controllers/MediaController.php
+++ b/application/modules/admin/controllers/MediaController.php
@@ -1,218 +1,215 @@
<?php
/**
* Class Admin_MediaController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Description of Media
*
* @author mattijs
*/
class Admin_MediaController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
-
/**
* @todo implement overwrite checkbox
*/
public function indexAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
$form = $this->_getForm($uploadFolder);
if($this->_request->isPost()) {
if($form->isValid($_POST) && $form->file->receive()) {
$this->addSuccessMessage('File was successfully uploaded.');
}
else {
foreach($form->getErrorMessages() as $message) {
$this->addErrorMessage($message);
}
}
- $this->_redirect('/fizzy/media');
+ $this->_redirect('@admin_media');
}
# Parse all files in the upload directory
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file) {
if($file->isFile()) {
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
# Render the view
$this->view->uploadFolder = $uploadFolder;
$this->view->files = $files;
$this->view->form = $form;
$this->view->type = $this->_request->getParam('type', 'list');
$this->renderScript('media.phtml');
}
public function displayAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file) {
if($file->isFile()) {
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
$type = $this->_getParam('type', 'list');
if($type == 'thumbnail') {
$script = 'media/thumbnails.phtml';
} else {
$script = 'media/list.phtml';
}
$this->renderScript($script);
}
public function deleteAction()
{
$name = $this->_getParam('name');
if(null !== $name)
{
$name = basename(urldecode($name));
$uploadFolder = ROOT_PATH . '/public/uploads/';
$file = $uploadFolder . DIRECTORY_SEPARATOR . $name;
if(is_file($file))
{
unlink($file);
$this->addSuccessMessage('File was successfully deleted.');
}
}
- $this->_redirect($this->view->baseUrl('/fizzy/media'));
+ $this->_redirect('@admin_media');
}
/**
* Returns the form for file uploads
* @param string $uploadFolder
* @return Zend_Form
*/
protected function _getForm($uploadFolder)
{
$formConfig = array (
- 'action' => $this->view->baseUrl('/fizzy/media'),
+ 'action' => $this->view->url('@admin_media'),
'enctype' => 'multipart/form-data',
'elements' => array(
'file' => array (
'type' => 'file',
'options' => array (
'label' => 'File',
'description' => 'Choose a file to upload. The maximun file size is ' . str_replace(array('K', 'M', 'G'), array(' KB', ' MB', ' GB'), ini_get('upload_max_filesize')) . '.',
'required' => true,
'destination' => $uploadFolder,
)
),
/*'overwrite' => array (
'type' => 'checkbox',
'options' => array (
'label' => 'Overwrite existing?',
'description' => 'If this is checked any existing file with the same name will be overridden.',
'required' => false,
)
),*/
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Upload',
'ignore' => true,
)
)
),
);
return new Zend_Form(new Zend_Config($formConfig));
}
/**
* Action for the image picker popup
*/
public function galleryAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
// Parse all files in the upload directory
$files = array();
$imageTypes = array('png', 'jpg', 'jpeg', 'bmp', 'gif');
foreach(new DirectoryIterator($uploadFolder) as $file)
{
if($file->isFile())
{
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
if (in_array($fileInfo['type'], $imageTypes)) {
$files[] = (object) $fileInfo;
}
}
}
// Render the view
$this->view->files = $files;
$this->_helper->layout->disableLayout();
}
public function assetsAction()
{
$uploadFolder = ROOT_PATH . '/public/uploads/';
// Parse all files in the upload directory
$files = array();
foreach(new DirectoryIterator($uploadFolder) as $file)
{
if($file->isFile())
{
$fileInfo = array(
'type' => substr(strrchr($file->getBaseName(), '.'), 1),
'basename' => $file->getBaseName(),
'path' => $file->getPath(),
'size' => $file->getSize(),
);
$files[] = (object) $fileInfo;
}
}
// Render the view
$this->view->files = $files;
$this->_helper->layout->disableLayout();
}
}
diff --git a/application/modules/admin/controllers/PagesController.php b/application/modules/admin/controllers/PagesController.php
index 1851636..dcf5e24 100644
--- a/application/modules/admin/controllers/PagesController.php
+++ b/application/modules/admin/controllers/PagesController.php
@@ -1,232 +1,229 @@
<?php
/**
* Class Admin_PagesController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_PagesController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
-
/**
* Shows a list of pages managed by Fizzy.
*/
public function indexAction()
{
$query = Doctrine_Query::create()->from('Page');
$pages = $query->fetchArray();
$this->view->pages = $pages;
}
/**
* Adds a page.
*/
public function addAction()
{
$page = new Page();
- $form = $this->_getForm($this->view->baseUrl('/fizzy/pages/add'), $page);
+ $form = $this->_getForm($this->view->url('@admin_pages_add'), $page);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$page->populate($form->getValues());
$page->save();
$this->addSuccessMessage("Page {$page->title} was saved successfully.");
- $this->_redirect('/fizzy/pages', array('prependBase' => true));
+ $this->_redirect('@admin_pages');
}
}
$this->view->page = $page;
$this->view->form = $form;
$this->renderScript('pages/form.phtml');
}
public function editAction()
{
$id = $this->_getParam('id', null);
if(null === $id) {
- $this->_redirect('/fizzy/pages', array('prependBase' => true));
+ $this->_redirect('@admin_pages');
}
$query = Doctrine_Query::create()->from('Page')->where('id = ?', $id);
$page = $query->fetchOne();
if(null === $page) {
$this->addErrorMessage("Page with ID {$id} could not be found.");
- $this->_redirect('/fizzy/pages', array('prependBase' => true));
+ $this->_redirect('@admin_pages');
}
- $form = $this->_getForm($this->view->baseUrl('/fizzy/pages/edit/' . $page['id']), $page);
+ $form = $this->_getForm($this->view->url('@admin_pages_edit?id=' . $page['id']), $page);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$page->populate($form->getValues());
$page->save();
$this->addSuccessMessage("Page \"<strong>{$page->title}</strong>\" was successfully saved.");
- $this->_redirect('/fizzy/pages', array('prependBase' => true));
+ $this->_redirect('@admin_pages');
}
}
$this->view->page = $page;
$this->view->form = $form;
$this->renderScript('pages/form.phtml');
}
/**
* Delete a page
*/
public function deleteAction()
{
$id = $this->_getParam('id', null);
if(null !== $id) {
$query = Doctrine_Query::create()->from('Page')->where('id = ?', $id);
$page = $query->fetchOne();
if(null !== $page) {
$page->delete();
$this->addSuccessMessage("Page {$page->title} was successfully deleted.");
}
}
- $this->_redirect('/fizzy/pages', array('prependBase' => true));
+ $this->_redirect('@admin_pages');
}
/**
* Builds the form for adding or editing a page.
* @param string $action
* @param Page $page
* @return Zend_Form
*/
protected function _getForm($action, $page)
{
$config = Zend_Registry::get('config');
$formConfig = array (
'action' => $action,
'elements' => array (
'id' => array (
'type' => 'hidden',
'options' => array (
'required' => false,
'value' => $page['id'],
)
),
'title' => array (
'type' => 'text',
'options' => array (
'label' => 'Title',
'required' => true,
'value' => $page->title,
)
),
'slug' => array (
'type' => 'text',
'options' => array (
'label' => 'Slug',
'required' => true,
'value' => $page->slug,
'filters' => array (
'slugify'
),
'validators' => array (
'slugUnique'
)
)
),
'body' => array (
'type' => 'wysiwyg',
'options' => array (
'label' => 'Body',
'required' => true,
'value' => $page->body,
'attribs' => array('style' => 'width: 100%;'),
)
),
'template' => array (
'type' => 'select',
'options' => array (
'label' => 'Template',
'required' => true,
'multiOptions' => $this->_fetchFiles($config->paths->templatePath),
'value' => $page->getTemplate(),
'description' => 'You can select a different template to structure the text.'
)
),
'layout' => array (
'type' => 'select',
'options' => array (
'label' => 'Layout',
'required' => true,
'multiOptions' => $this->_fetchFiles($config->paths->layoutPath, false),
'value' => $page->getLayout(),
'description' => 'You can select a different layout to render the structured text in.'
)
),
'homepage' => array (
'type' => 'checkbox',
'options' => array (
'label' => 'Is Homepage',
'required' => false,
'value' => (int) $page->homepage,
'checked' => ((boolean) $page->homepage) ? 'checked' : '',
'description' => 'Check this box to make this page the default.'
)
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Save',
'ignore' => true
)
),
),
);
$form = new Fizzy_Form();
$form->setOptions($formConfig);
$form->template->addDecorator('Description');
$form->layout->addDecorator('Description');
return $form;
}
/**
* Fetches a list of files from a given directory
*
* @param string $dir
* @return array
*/
protected function _fetchFiles($dir, $keepExtension = true)
{
$files = array();
$dir = new DirectoryIterator($dir);
foreach ($dir as $file) {
if($file->isDot()) {
continue;
}
$pieces = explode('.', $file->getFilename());
if ($keepExtension) {
$files[$file->getFilename()] = $pieces[0];
} else {
$files[$pieces[0]] = $pieces[0];
}
}
return $files;
}
}
diff --git a/application/modules/admin/controllers/SettingsController.php b/application/modules/admin/controllers/SettingsController.php
index 3696baa..9c1603d 100644
--- a/application/modules/admin/controllers/SettingsController.php
+++ b/application/modules/admin/controllers/SettingsController.php
@@ -1,91 +1,89 @@
<?php
/**
* Class Admin_SettingsController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Class Admin_SettingsController
*
* @author Mattijs Hoitink <[email protected]>
*/
class Admin_SettingsController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
public function indexAction()
{
$settings = Setting::getAll();
$this->view->settings = $settings;
}
/**
* Update setting action called through an ajax request
*/
public function ajaxUpdateAction()
{
// Disable view & layout output
$this->_disableDisplay();
// Alwasy set response type to json
$this->_response->setHeader('Content-Type', 'application/json', true);
// Try to get the data from the request body
try {
$data = Zend_Json::decode($this->_request->getRawBody(), Zend_Json::TYPE_OBJECT);
} catch(Zend_Json_Exception $exception) {
$this->_response->setHttpResponseCode(500);
$this->_response->setBody(Zend_Json::encode(array(
'status' => 'error',
'message' => 'data decoding failed'
)));
return;
}
// Retrieve the setting
$setting = Setting::getKey($data->settingKey, $data->component);
if (null === $setting) {
$this->_response->setHttpResponseCode(404);
$this->_response->setBody(Zend_Json::encode(array(
'status' => 'error',
'message' => 'setting key/component pair not found'
)));
return;
}
// Update the setting
$setting->value = $data->value;
$success = $setting->trySave();
if (false === $success) {
$this->_response->setHttpResponseCode(500);
$this->_response->setBody(Zend_Json::encode(array(
'status' => 'error',
'message' => 'saving failed due to validation errors'
)));
return;
}
// Return success response
$this->_response->setHttpResponseCode(200);
$this->_response->setBody(Zend_Json::encode(array(
'status' => 'success',
'message' => 'setting saved'
)));
}
}
\ No newline at end of file
diff --git a/application/modules/admin/controllers/UserController.php b/application/modules/admin/controllers/UserController.php
index 64ec4ad..4c85d79 100644
--- a/application/modules/admin/controllers/UserController.php
+++ b/application/modules/admin/controllers/UserController.php
@@ -1,165 +1,163 @@
<?php
/**
* Class Admin_UserController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_UserController extends Fizzy_SecuredController
{
- protected $_sessionNamespace = 'fizzy';
- protected $_redirect = '/fizzy/login';
public function indexAction()
{
$query = Doctrine_Query::create()->from('User');
$users = $query->fetchArray();
$this->view->users = $users;
$this->renderScript('/user/list.phtml');
}
public function addAction()
{
$user = new User();
- $form = $this->_getForm($this->view->baseUrl('/fizzy/user/add'), $user);
+ $form = $this->_getForm($this->view->url('@admin_users_add'), $user);
$form->password->setRequired(true);
$form->password_confirm->setRequired(true);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$user->populate($form->getValues());
$user->save();
$this->addSuccessMessage("User {$user->username} was successfully saved.");
- $this->_redirect('/fizzy/users', array('prependBase' => true));
+ $this->_redirect('@admin_users');
}
}
$this->view->user = $user;
$this->view->form = $form;
$this->renderScript('/user/form.phtml');
}
public function editAction()
{
$id = $this->_getParam('id', null);
if(null === $id) {
- $this->_redirect('/fizzy/users', array('prependBase' => true));
+ $this->_redirect('@admin_users');
}
$query = Doctrine_Query::create()->from('User')->where('id = ?', $id);
$user = $query->fetchOne();
if(null === $user) {
$this->addErrorMessage("User with ID {$id} could not be found.");
- $this->_redirect('/fizzy/users', array('prependBase' => true));
+ $this->_redirect('@admin_users');
}
- $form = $this->_getForm($this->view->baseUrl('/fizzy/user/edit/' . $user->id), $user);
+ $form = $this->_getForm($this->view->url('@admin_users_edit?id=' . $user->id), $user);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$user->populate($form->getValues());
$user->save();
$this->addSuccessMessage("User <strong>{$user->username}</strong> was successfully saved.");
- $this->_redirect('/fizzy/users', array('prependBase' => true));
+ $this->_redirect('@admin_users');
}
}
$this->view->user = $user;
$this->view->form = $form;
$this->renderScript('user/form.phtml');
}
public function deleteAction()
{
$id = $this->_getParam('id', null);
if(null !== $id) {
$query = Doctrine_Query::create()->from('User')->where('id = ?', $id);
$user = $query->fetchOne();
if(null !== $user) {
$user->delete();
$this->addSuccessMessage("User {$user->username} was successfully deleted.");
}
- $this->_redirect('/fizzy/users', array('prependBase' => true));
+ $this->_redirect('@admin_users');
}
}
protected function _getForm($action, User $user)
{
$passwordConfirm = new Fizzy_Validate_EqualsField();
$passwordConfirm->setOppositeField('password_confirm');
$passwordConfirm->setFieldName('Password');
$formConfig = array (
'action' => $action,
'elements' => array (
'id' => array (
'type' => 'hidden',
'options' => array (
'required' => false,
'value' => $user->id
)
),
'username' => array (
'type' => 'text',
'options' => array (
'label' => 'Username',
'required' => true,
'value' => $user->username,
'validators' => array (
'usernameUnique'
)
)
),
'displayname' => array(
'type' => 'text',
'options' => array(
'label' => 'Display name',
'required' => true,
'value' => $user->displayname
)
),
'password' => array (
'type' => 'password',
'options' => array (
'label' => 'Password',
'validators' => array (
$passwordConfirm
)
),
),
'password_confirm' => array (
'type' => 'password',
'options' => array (
'label' => 'Confirm password',
'ignore' => true,
)
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Save',
'ignore' => true
)
),
),
);
return new Fizzy_Form(new Zend_Config($formConfig));
}
}
diff --git a/application/modules/admin/controllers/WebdavController.php b/application/modules/admin/controllers/WebdavController.php
index b2cbe5f..850e628 100644
--- a/application/modules/admin/controllers/WebdavController.php
+++ b/application/modules/admin/controllers/WebdavController.php
@@ -1,99 +1,99 @@
<?php
/**
* Class Admin_WebdavController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Controller that handles WebDAV requests.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Admin_WebdavController extends Zend_Controller_Action
{
/**
* Application config
* @var Zend_Config
*/
protected $_config = null;
public function init()
{
// Disable view rendering
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout()->disableLayout();
// Get the application config
$this->_config = Zend_Registry::get('config');
}
/**
* Handles a WebDAV request.
*/
public function requestAction()
{
if (!isset($this->_config->resources->sabredav->enabled) ||
0 == $this->_config->resources->sabredav->enabled) {
// Render 404
$response = $this->getResponse();
$response->clearAllHeaders();
$response->clearBody();
$response->setHttpResponseCode(404);
$response->sendResponse();
return;
}
- $baseUri = '/fizzy/webdav/';
+ $baseUri = $this->view->url('@admin_webdav');
$publicDir = ROOT_PATH . '/public/uploads';
$tmpDir = ROOT_PATH . '/data/tmp';
$auth = new Sabre_HTTP_BasicAuth();
$auth->setRealm('Fizzy');
$authResult = $auth->getUserPass();
if (false === $authResult) {
$auth->requireLogin();
die('Authentication required');
}
list($username, $password) = $authResult;
$authAdapter = new Fizzy_Doctrine_AuthAdapter($username, $password);
$authResult = $authAdapter->authenticate();
if ($authResult->getCode() !== Zend_Auth_Result::SUCCESS) {
$auth->requireLogin();
die('Authentication failed');
}
$publicDirObj = new Sabre_DAV_FS_Directory($publicDir);
$objectTree = new Sabre_DAV_ObjectTree($publicDirObj);
$server = new Sabre_DAV_Server($objectTree);
$server->setBaseUri($baseUri);
if (isset($this->_config->resources->sabredav->browser) &&
false != $this->_config->resources->sabredav->browser) {
$browser = new Sabre_DAV_Browser_Plugin();
$server->addPlugin($browser);
}
$server->exec();
}
}
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/blogs/blog.phtml b/application/modules/admin/views/scripts/blogs/blog.phtml
index f707ca2..2304fb9 100644
--- a/application/modules/admin/views/scripts/blogs/blog.phtml
+++ b/application/modules/admin/views/scripts/blogs/blog.phtml
@@ -1,56 +1,56 @@
<div id="content-panel">
<h2><?= $this->blog->name ?></h2>
<div>
<table class="data">
<thead>
<tr>
<td> </td>
<td>Title</td>
<td>Date</td>
<td>Status</td>
<td>Author</td>
</tr>
</thead>
<tbody>
<?php $items = $this->paginator->getCurrentItems();
foreach ($items as $post): ?>
<tr>
<td class="controls">
- <?= $this->link('/fizzy/post/' . $post->id . '/edit', $this->image('/fizzy_assets/images/icon/document--pencil.png', array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_edit?post_id=' . $post->id, $this->image($this->assetUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
</td>
<td>
<?= $post->title ?>
</td>
<td>
<?= $post->date ?>
</td>
<td>
<?php if ($post->status == Post::PUBLISHED): ?>
Published
<?php elseif ($post->status == Post::PENDING_REVIEW): ?>
Pending review
<?php else: ?>
Draft
<?php endif; ?>
</td>
<td>
<?= $post->User->displayname ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('/fizzy/blog/' . $this->blog->id . '/add', $this->image('/fizzy_assets/images/icon/document--plus.png') . ' Add post', array('escape' => false)); ?>
+ <?= $this->link('@admin_blog_post_add?blog_id=' . $this->blog->id, $this->image($this->assetUrl('/images/icon/document--plus.png')) . ' Add post', array('escape' => false)); ?>
</li>
</ul>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/blogs/index.phtml b/application/modules/admin/views/scripts/blogs/index.phtml
index 4f3fe16..f90c179 100644
--- a/application/modules/admin/views/scripts/blogs/index.phtml
+++ b/application/modules/admin/views/scripts/blogs/index.phtml
@@ -1,25 +1,25 @@
<div id="content-panel">
<h2>Blogs</h2>
<div>
<table class="data">
<thead>
<tr>
<td>Blog name</td>
<td>Slug</td>
<td>Group slug</td>
</tr>
</thead>
<tbody>
<?php foreach ($this->blogs as $blog) : ?>
<tr>
- <td><a href="<?= $this->baseUrl('/fizzy/blog/' . $blog->id) ?>"><?= $blog->name ?></a></td>
+ <td><a href="<?= $this->url('@admin_blog?id=' . $blog->id) ?>"><?= $blog->name ?></a></td>
<td><?= $blog->slug ?></td>
<td><?= $blog->group_slug ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel"></div>
diff --git a/application/modules/admin/views/scripts/blogs/post-form.phtml b/application/modules/admin/views/scripts/blogs/post-form.phtml
index f213de9..16a8478 100644
--- a/application/modules/admin/views/scripts/blogs/post-form.phtml
+++ b/application/modules/admin/views/scripts/blogs/post-form.phtml
@@ -1,73 +1,73 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
- <?= $this->image('/fizzy_assets/images/icon/document.png'); ?>
+ <?= $this->image($this->assetUrl('/images/icon/document.png')); ?>
<?= ($this->post->isNew()) ? 'Add post' : 'Edit post'; ?>
</h2>
<div class="form-panel">
<?= $this->form->title; ?>
<?= $this->form->body; ?>
</div>
<h2>
- <?= $this->image('/fizzy_assets/images/icon/balloons.png'); ?>
+ <?= $this->image($this->assetUrl('/images/icon/balloons.png')); ?>
Comments on this post
</h2>
<div class="comments">
<?= $this->partial('comments/_comments.phtml', array(
'comments' => $this->post->Comments(),
'back' => 'post'
)) ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->post->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
- '/fizzy/post/' . $this->post->id . '/delete',
- $this->image('fizzy_assets/images/icon/document--minus.png') . ' delete page',
+ '@admin_blog_post_delete?post_id=' . $this->post->id,
+ $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete page',
array(
'class' => 'delete',
- 'Are you sure you want to delete this page?',
+ 'confirm' => 'Are you sure you want to delete this page?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
- '/fizzy/blog/' . $this->post->Blog->id,
- $this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to ' . $this->post->Blog->name,
+ '@admin_blog?id=' . $this->post->Blog->id,
+ $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to ' . $this->post->Blog->name,
array('escape' => false)
); ?>
</li>
</ul>
<h2>Options</h2>
<div class="form-options-panel">
<?= $this->form->status; ?>
<?= $this->form->author; ?>
<?= $this->form->date; ?>
<?= $this->form->comments; ?>
</div>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/edit.phtml b/application/modules/admin/views/scripts/comments/edit.phtml
index ba463ed..115442e 100644
--- a/application/modules/admin/views/scripts/comments/edit.phtml
+++ b/application/modules/admin/views/scripts/comments/edit.phtml
@@ -1,54 +1,54 @@
<form action="<?= $this->form->getAction(); ?>" method="post">
<div id="content-panel">
<h2>
Edit Comment
</h2>
<div class="form-panel">
<?= $this->form->name; ?>
<?= $this->form->email; ?>
<?= $this->form->website; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
'@admin_comments_delete?id=' . $this->comment->id,
- $this->image('fizzy_assets/images/icon/document--minus.png') . ' delete comment',
+ $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete comment',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this comment?',
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
<?= $this->link(
'@admin_comments_topic?id=' . $this->comment->post_id,
- $this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to comments',
+ $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to comments',
array(
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/contact/index.phtml b/application/modules/admin/views/scripts/contact/index.phtml
index a6882b6..e9b4c7d 100644
--- a/application/modules/admin/views/scripts/contact/index.phtml
+++ b/application/modules/admin/views/scripts/contact/index.phtml
@@ -1,37 +1,37 @@
<div id="content-panel">
<h2>Contact</h2>
<table class="data" id="contact-table">
<thead>
<tr>
<th> </th>
<th>Date</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<?php foreach($this->messages as $message) : ?>
<tr>
<td class="controls" style="width: 55px;">
- <?= $this->link('/fizzy/contact/show/' . $message->id, $this->image('/fizzy_assets/images/icon/mail-open.png'), array('escape' => false)); ?>
+ <?= $this->link('@admin_contact_show?id=' . $message->id, $this->image($this->assetUrl('/images/icon/mail-open.png')), array('escape' => false)); ?>
<?= $this->link(
- '/fizzy/contact/delete/' . $message->id,
- $this->image('/fizzy_assets/images/icon/mail--minus.png'),
+ '@admin_contact_delete?id=' . $message->id,
+ $this->image($this->assetUrl('/images/icon/mail--minus.png')),
array (
'confirm' => 'Are you sure you want to delete this contact request?',
'escape' => false
)
); ?>
</td>
<td style="width: 150px;"><?= $message->date; ?></td>
<td style="max-width: 300px;"><?= $message->name; ?> <<a href="mailto:<?= $message->email; ?>"><?= $message->email; ?></a>></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/contact/show.phtml b/application/modules/admin/views/scripts/contact/show.phtml
index 86bc92a..90d07f7 100644
--- a/application/modules/admin/views/scripts/contact/show.phtml
+++ b/application/modules/admin/views/scripts/contact/show.phtml
@@ -1,33 +1,33 @@
<div id="content-panel">
<h2>Contact request</h2>
<p>
From: <?= $this->message->name; ?> <<a href="mailto:<?= $this->message->email; ?>"><?= $this->message->email; ?></a>><br />
On: <?= $this->message->date; ?>
</p>
<p>
<?= nl2br($this->message->body); ?>
</p>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
- '/fizzy/contact/delete/' . $this->message->id,
- $this->image('/fizzy_assets/images/icon/mail--minus.png') . 'delete message',
+ '@admin_contact_delete?id=' . $this->message->id,
+ $this->image($this->assetUrl('/images/icon/mail--minus.png')) . 'delete message',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this message?',
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
- <?= $this->link('/fizzy/contact', $this->image('/fizzy_assets/images/icon/edit-list.png') . ' contact list', array('escape' => false)); ?>
+ <?= $this->link('@admin_contact', $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' contact list', array('escape' => false)); ?>
</li>
</ul>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/flashMessages.phtml b/application/modules/admin/views/scripts/flashMessages.phtml
index 4e7201c..07246e2 100644
--- a/application/modules/admin/views/scripts/flashMessages.phtml
+++ b/application/modules/admin/views/scripts/flashMessages.phtml
@@ -1,23 +1,23 @@
<div id="messages" class="span-24 last">
<?= $this->fizzyMessages(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('#messages > .message').each(function(index, element) {
// Create a button
var button = $("<a></a>").attr('href','#').attr('class', 'message-close');
// Add close image to the button
var i = new Image();
- $(i).attr('src', "<?= $this->baseUrl('/fizzy_assets/images/icon/cross.png'); ?>");
+ $(i).attr('src', "<?= $this->assetUrl('/images/icon/cross.png'); ?>");
button.html(i);
// fade on click
button.click(function() {
$(element).slideUp('fast');
});
// Add the button to the container
$(element).append(button);
});
});
</script>
</div>
diff --git a/application/modules/admin/views/scripts/media/assets.phtml b/application/modules/admin/views/scripts/media/assets.phtml
index 4d0888c..9a33a92 100644
--- a/application/modules/admin/views/scripts/media/assets.phtml
+++ b/application/modules/admin/views/scripts/media/assets.phtml
@@ -1,79 +1,79 @@
<?php
$types = array(
- 'png' => $this->baseUrl('/fizzy_assets/images/icon/page_white_picture.png'),
- 'jpg' => $this->baseUrl('/fizzy_assets/images/icon/page_white_picture.png'),
- 'jpeg' => $this->baseUrl('/fizzy_assets/images/icon/page_white_picture.png'),
- 'bmp' => $this->baseUrl('/fizzy_assets/images/icon/page_white_picture.png'),
- 'gif' => $this->baseUrl('/fizzy_assets/images/icon/page_white_picture.png'),
- 'doc' => $this->baseUrl('/fizzy_assets/images/icon/page_white_word.png'),
- 'docx' => $this->baseUrl('/fizzy_assets/images/icon/page_white_word.png'),
- 'xls' => $this->baseUrl('/fizzy_assets/images/icon/page_white_excel.png'),
- 'ppt' => $this->baseUrl('/fizzy_assets/images/icon/page_white_powerpoint.png'),
- 'pdf' => $this->baseUrl('/fizzy_assets/images/icon/page_white_text.png'),
- 'flv' => $this->baseUrl('/fizzy_assets/images/icon/page_white_flash.png'),
- 'zip' => $this->baseUrl('/fizzy_assets/images/icon/page_white_zip.png'),
- 'rar' => $this->baseUrl('/fizzy_assets/images/icon/page_white_zip.png'),
- 'txt' => $this->baseUrl('/fizzy_assets/images/icon/page_white_text.png'),
+ 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
+ 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{#fizzyassets_dlg.title}</title>
- <link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
- <script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
- <script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/plugins/fizzyassets/js/dialog.js') ?>"></script>
+ <link href="<?= $this->assetUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
+ <script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
+ <script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzyassets/js/dialog.js') ?>"></script>
</head>
<body>
<div id="image-picker" class="files-container">
<table class="files-table">
<thead>
<tr>
<td colspan="2">Filename</td>
<td>Size</td>
</tr>
</thead>
<tbody>
<?php foreach($this->files as $fileInfo) : ?>
<tr id="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>">
- <td class="icon"><img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->baseUrl('/images/icon/page.png'); ?>" alt="" /></td>
+ <td class="icon"><img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->assetUrl('/images/icon/page.png'); ?>" alt="" /></td>
<td class="filename">
<a href="#" onclick="select('<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>', this.parentNode.parentNode);">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</a>
</td>
<td class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<form onsubmit="FizzyassetsDialog.insert();return false;" action="#">
<div>
<div class="form-left">
<label>Description:</label>
<input type="text" name="alt" id="alt" />
</div>
<div class="clear"></div>
<input type="button" name="insert" value="{#insert}" onclick="FizzyassetsDialog.insert();" />
<input type="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</form>
</body>
</html>
diff --git a/application/modules/admin/views/scripts/media/gallery.phtml b/application/modules/admin/views/scripts/media/gallery.phtml
index 1dfc0e5..9be6b70 100644
--- a/application/modules/admin/views/scripts/media/gallery.phtml
+++ b/application/modules/admin/views/scripts/media/gallery.phtml
@@ -1,91 +1,91 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{#fizzymedia_dlg.title}</title>
- <link href="<?= $this->baseUrl("/fizzy_assets/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
- <script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
- <script type="text/javascript" src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/plugins/fizzymedia/js/dialog.js') ?>"></script>
+ <link href="<?= $this->assetUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
+ <script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/tiny_mce_popup.js') ?>"></script>
+ <script type="text/javascript" src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzymedia/js/dialog.js') ?>"></script>
</head>
<body>
<div id="image-picker" class="files-container">
<?php foreach($this->files as $fileInfo) : ?>
<div class="thumbnail" id="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" onclick="select('<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>', this);">
<img class="thumbnail" src="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" alt="<?= $fileInfo->basename ?>" />
<div class="filename">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</div>
<div class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
</div>
<form onsubmit="FizzymediaDialog.insert();return false;" action="#">
<div>
<div class="form-left">
<label>Description:</label>
<input type="text" name="alt" id="alt" />
<label>Width</label>
<input type="text" name="width" id="width" class="small" /> px
<label>Height</label>
<input type="text" name="height" id="height" class="small" /> px
<label>Alignment</label>
<select name="position" id="position">
<option value="none">-- Not Set --</option>
<option value="left">Left</option>
<option value="right">Right</option>
<option value="baseline">Baseline</option>
<option value="top">Top</option>
<option value="middle">Middle</option>
<option value="bottom">Bottom</option>
<option value="text-top">Text top</option>
<option value="text-bottom">Text bottom</option>
</select>
<label>Border</label>
<input type="text" name="border" id="border" class="small" /> px
</div>
<div class="form-right">
<label>Margins</label>
<table>
<tr>
<td></td>
<td> <input type="text" name="marginTop" id="marginTop" /></td>
<td></td>
</tr>
<tr>
<td><input type="text" name="marginLeft" id="marginLeft" /></td>
- <td class="center"><img src="<?= $this->baseUrl('/fizzy_assets/js/tiny_mce/plugins/fizzymedia/img/flower.png');?>" alt="flower" /></td>
+ <td class="center"><img src="<?= $this->assetUrl('/js/tiny_mce/plugins/fizzymedia/img/flower.png');?>" alt="flower" /></td>
<td><input type="text" name="marginRight" id="marginRight" /></td>
</tr>
<tr>
<td></td>
<td> <input type="text" name="marginBottom" id="marginBottom" /></td>
<td></td>
</tr>
</table>
<p>You can specify the margins around the picture above.</p>
</div>
<div class="clear"></div>
<input type="button" name="insert" value="{#insert}" onclick="FizzymediaDialog.insert();" />
<input type="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</form>
</body>
</html>
diff --git a/application/modules/admin/views/scripts/media/list.phtml b/application/modules/admin/views/scripts/media/list.phtml
index c67f0f3..53cd0b7 100644
--- a/application/modules/admin/views/scripts/media/list.phtml
+++ b/application/modules/admin/views/scripts/media/list.phtml
@@ -1,67 +1,67 @@
<?php
$types = array(
- 'png' => $this->baseUrl('/fizzy_assets/images/icon/document-image.png'),
- 'jpg' => $this->baseUrl('/fizzy_assets/images/icon/document-image.png'),
- 'jpeg' => $this->baseUrl('/fizzy_assets/images/icon/document-image.png'),
- 'bmp' => $this->baseUrl('/fizzy_assets/images/icon/document-image.png'),
- 'gif' => $this->baseUrl('/fizzy_assets/images/icon/document-image.png'),
- 'doc' => $this->baseUrl('/fizzy_assets/images/icon/document-word.png'),
- 'docx' => $this->baseUrl('/fizzy_assets/images/icon/document-word.png'),
- 'xls' => $this->baseUrl('/fizzy_assets/images/icon/document-excel.png'),
- 'ppt' => $this->baseUrl('/fizzy_assets/images/icon/document-powerpoint.png'),
- 'pdf' => $this->baseUrl('/fizzy_assets/images/icon/document-pdf.png'),
- 'flv' => $this->baseUrl('/fizzy_assets/images/icon/document-flash-movie.png'),
- 'zip' => $this->baseUrl('/fizzy_assets/images/icon/document-zipper.png'),
- 'rar' => $this->baseUrl('/fizzy_assets/images/icon/document-zipper.png'),
- 'txt' => $this->baseUrl('/fizzy_assets/images/icon/document-text.png'),
+ 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
+ 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
);
?>
<div class="media-container">
<table class="media">
<?php if(0 < count($this->files)) : ?>
<tbody>
<?php $row = 0; foreach($this->files as $fileInfo) : ?>
<tr class="<?= (++$row % 2) === 0 ? 'even' : 'odd'; ?>">
<td class="icon">
<img src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->baseUrl('/images/icon/page.png'); ?>" alt="" />
</td>
<td class="filename">
<a href="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" target="_blank" title="View file">
<?= $fileInfo->basename; ?>
</a>
</td>
<td class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
<td class="controls">
<?php if(is_writable($this->uploadFolder)) : ?>
<?= $this->link(
- '/fizzy/media/delete/' . urlencode($fileInfo->basename),
- $this->image('/fizzy_assets/images/icon/minus-small.png'),
+ '@admin_media_delete?name=' . urlencode($fileInfo->basename),
+ $this->image($this->assetUrl('/images/icon/minus-small.png')),
array (
'confirm' => "Are you sure you want to delete {$fileInfo->basename}?",
'title' => 'Delete file',
'escape' => false,
)
); ?>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
<?php else : ?>
<tr>
<td colspan="4">
No uploaded files were found. Use the form at the bottom to
add new files.
</td>
</tr>
<?php endif; ?>
</table>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/media/thumbnails.phtml b/application/modules/admin/views/scripts/media/thumbnails.phtml
index 38e7be3..ae72d04 100644
--- a/application/modules/admin/views/scripts/media/thumbnails.phtml
+++ b/application/modules/admin/views/scripts/media/thumbnails.phtml
@@ -1,79 +1,79 @@
<?php
// file type image declarations
$images = array('png', 'jpg', 'jpeg', 'bmp', 'gif');
$types = array(
- 'png' => $this->baseUrl('/fizzy_assets/images/mimetypes/png.png'),
- 'jpg' => $this->baseUrl('/fizzy_assets/images/mimetypes/jpg.png'),
- 'jpeg' => $this->baseUrl('/fizzy_assets/images/mimetypes/jpg.png'),
- 'bmp' => $this->baseUrl('/fizzy_assets/images/mimetypes/bmp.png'),
- 'gif' => $this->baseUrl('/fizzy_assets/images/mimetypes/gif.png'),
- 'doc' => $this->baseUrl('/fizzy_assets/images/mimetypes/doc.png'),
- 'docx' => $this->baseUrl('/fizzy_assets/images/mimetypes/doc.png'),
- 'xls' => $this->baseUrl('/fizzy_assets/images/mimetypes/xls.png'),
- 'ppt' => $this->baseUrl('/fizzy_assets/images/mimetypes/ppt.png'),
- 'pdf' => $this->baseUrl('/fizzy_assets/images/mimetypes/pdf.png'),
- 'flv' => $this->baseUrl('/fizzy_assets/images/mimetypes/flv.png'),
- 'zip' => $this->baseUrl('/fizzy_assets/images/mimetypes/zip.png'),
- 'rar' => $this->baseUrl('/fizzy_assets/images/mimetypes/rar.png'),
- 'txt' => $this->baseUrl('/fizzy_assets/images/mimetypes/txt.png'),
+ 'png' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'jpeg' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'bmp' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'gif' => $this->assetUrl('/images/icon/page_white_picture.png'),
+ 'doc' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'docx' => $this->assetUrl('/images/icon/page_white_word.png'),
+ 'xls' => $this->assetUrl('/images/icon/page_white_excel.png'),
+ 'ppt' => $this->assetUrl('/images/icon/page_white_powerpoint.png'),
+ 'pdf' => $this->assetUrl('/images/icon/page_white_text.png'),
+ 'flv' => $this->assetUrl('/images/icon/page_white_flash.png'),
+ 'zip' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'rar' => $this->assetUrl('/images/icon/page_white_zip.png'),
+ 'txt' => $this->assetUrl('/images/icon/page_white_text.png'),
);
?>
<div class="media-container">
<?php foreach($this->files as $fileInfo) : ?>
<div class="thumbnail">
<div class="head">
<span class="filename">
<?php if (strlen($fileInfo->basename) > 14):?>
<?= substr($fileInfo->basename, 0, 14); ?>...
<?php else: ?>
<?= $fileInfo->basename ?>
<?php endif; ?>
</span>
<?php if(is_writable($this->uploadFolder)) : ?>
<span class="remove">
<?= $this->link(
- '/fizzy_assets/media/delete/' . urlencode($fileInfo->basename),
- $this->image('/fizzy_assets/images/icon/cross-small.png'),
+ '@admin_media_delete?name=' . urlencode($fileInfo->basename),
+ $this->image($this->assetUrl('/images/icon/cross-small.png')),
array (
'confirm' => "Are you sure you want to delete {$fileInfo->basename}?",
'title' => 'Delete file',
'escape' => false,
)
); ?>
</span>
<?php endif; ?>
<div class="clear"></div>
</div>
<div class="body">
<a href="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" target="_blank" title="View file">
<?php if (in_array($fileInfo->type, $images)): ?>
<img class="source" src="<?= $this->baseUrl('/uploads/' . $fileInfo->basename); ?>" alt="<?= $fileInfo->basename ?>" />
<?php else: ?>
<img class="icon" width="48px" height="48px" src="<?= (array_key_exists($fileInfo->type, $types)) ? $types[$fileInfo->type] : $this->baseUrl('/fizzy_assets/images/icon/page.png'); ?>" alt="" />
<?php endif; ?>
</a>
</div>
<div class="foot">
<span class="size">
<?php if($fileInfo->size < 1024) : ?>
<?= round($fileInfo->size, 2); ?> b
<?php elseif((1024*1024) > $fileInfo->size) : ?>
<?= round($fileInfo->size / 1024, 2); ?> KB
<?php else : ?>
<?= round($fileInfo->size / (1024*1024), 2); ?> MB
<?php endif; ?>
</span>
<div class="clear"></div>
</div>
</div>
<?php endforeach; ?>
<div class="clear"></div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/media/upload.phtml b/application/modules/admin/views/scripts/media/upload.phtml
index 783ecc0..d32e53b 100644
--- a/application/modules/admin/views/scripts/media/upload.phtml
+++ b/application/modules/admin/views/scripts/media/upload.phtml
@@ -1,43 +1,43 @@
<div id="upload-form">
<h2 class="header">Upload</h2>
<p>
Upload a new file by selecting it on your machine. Check the box if
you want to overwrite a file that already exists with the same name.
<br />
</p>
<?php if(is_writable($this->uploadFolder)) : ?>
- <form action="<?= $this->url('/admin/media'); ?>" method="post" enctype="multipart/form-data">
+ <form action="<?= $this->url('@admin_media'); ?>" method="post" enctype="multipart/form-data">
<?php if(isset($this->messages) && !empty($this->messages)) : ?>
<div class="message error">
<ul>
<?php foreach($this->messages as $message) : ?>
<li><?= $message ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<div>
<input name="upload" type="file" /><br />
<small>The maximum size for a file upload is <strong><?= str_replace(array('K', 'M', 'G'), array(' KB', ' MB', ' GB'), $this->upload_max_filesize); ?></strong>.</small>
</div>
<div>
<label for="overwrite">Overwrite existing file?</label>
<input type="checkbox" name="overwrite" value="1" />
</div>
<div>
<input type="submit" value="Upload" />
</div>
</form>
<?php else : ?>
<div class="message notice">
<p>
The upload directory found in the Fizzy configuration is not
writable. Upload functionality will be disabled until it is made
writable.
</p>
</div>
<?php endif; ?>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/pages/form.phtml b/application/modules/admin/views/scripts/pages/form.phtml
index b1cf2cb..c4d9b63 100644
--- a/application/modules/admin/views/scripts/pages/form.phtml
+++ b/application/modules/admin/views/scripts/pages/form.phtml
@@ -1,69 +1,69 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
- <?= $this->image('/fizzy_assets/images/icon/document.png'); ?>
+ <?= $this->image($this->assetUrl('/images/icon/document.png')); ?>
<?= ($this->page->isNew()) ? 'Add page' : 'Edit page'; ?>
</h2>
<div class="form-panel">
<?= $this->form->id; // required for slugunique validator ?>
<?= $this->form->title; ?>
<?= $this->form->slug; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->page->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
- '/fizzy/pages/delete/' . $this->page->id,
- $this->image('fizzy_assets/images/icon/document--minus.png') . ' delete page',
+ '@admin_pages_delete?id=' . $this->page->id,
+ $this->image($this->assetUrl('/images/icon/document--minus.png')) . ' delete page',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this page?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
- '/fizzy/pages',
- $this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to pages',
+ '@admin_pages',
+ $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to pages',
array('escape' => false)
); ?>
</li>
</ul>
<h2>Options</h2>
<div class="form-options-panel">
<?= $this->form->template; ?>
<?= $this->form->layout; ?>
<div class="form-row" id="homepage-row">
<label for="homepage">Homepage</label>
<?= $this->form->homepage->setDecorators(array('ViewHelper', 'Errors')); ?>
<?= $this->form->homepage->getDescription(); ?>
</div>
</div>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/pages/index.phtml b/application/modules/admin/views/scripts/pages/index.phtml
index 85bcb33..c78575c 100644
--- a/application/modules/admin/views/scripts/pages/index.phtml
+++ b/application/modules/admin/views/scripts/pages/index.phtml
@@ -1,48 +1,48 @@
<div id="content-panel">
<h2>Pages</h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
<td>Slug</td>
<td>Title</td>
</tr>
</thead>
<tbody>
<?php foreach($this->pages as $page) : ?>
<tr>
<td class="controls">
- <?= $this->link("@admin_pages_edit?id={$page['id']}", $this->image('/fizzy_assets/images/icon/document--pencil.png', array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
+ <?= $this->link('@admin_pages_edit?id=' . $page['id'], $this->image($this->assetsUrl('/images/icon/document--pencil.png'), array('alt' => 'edit icon')), array('title' => 'edit page', 'escape' => false)); ?>
</td>
<td style="width: 200px;"><?= $page['slug'] ?></td>
<td><?= $page['title'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('@admin_pages_add', $this->image('/fizzy_assets/images/icon/document--plus.png') . ' Add page', array('escape' => false)); ?>
+ <?= $this->link('@admin_pages_add', $this->image($this->assetsUrl('/images/icon/document--plus.png')) . ' Add page', array('escape' => false)); ?>
</li>
</ul>
<hr />
<div class="block">
<h2>About pages</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus laoreet fringilla eros in laoreet. Sed rhoncus aliquam accumsan. Nullam nec massa sed elit faucibus ultricies. Vivamus pharetra volutpat posuere. Aliquam a metus neque, et euismod odio. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aenean eget metus lacus, quis rhoncus mauris. In sit amet aliquet felis. Aenean luctus ornare posuere. Fusce egestas, nisi nec mattis pretium, lorem lorem venenatis lectus, id ornare lacus justo in neque. Ut commodo risus eu justo vulputate a fringilla quam rhoncus. Curabitur fermentum neque in tellus adipiscing scelerisque.
</p>
</div>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/settings/index.phtml b/application/modules/admin/views/scripts/settings/index.phtml
index bc2d08f..0d04ded 100644
--- a/application/modules/admin/views/scripts/settings/index.phtml
+++ b/application/modules/admin/views/scripts/settings/index.phtml
@@ -1,201 +1,201 @@
<div id="content-panel">
<h2>
<?= $this->image('/fizzy_assets/images/icon/gear.png', array('alt' => 'Settings Icon')); ?>
Settings
</h2>
<table class="settings" id="settings-table">
<tbody>
<?php foreach($this->settings as $component => $settings) : ?>
<tr>
<th colspan="2"><?= ucfirst($component); ?></th>
</tr>
<?php foreach($settings as $setting) : ?>
<tr>
<td class="label">
<?= $setting->label; ?>
</td>
<td class="setting editable">
<div id="<?= $setting->component; ?>:<?= $setting->setting_key; ?>" class="value text"><?= $setting->value; ?></div>
<small><?= $setting->description; ?></small>
</td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
</tbody>
</table>
<?php $this->jQuery()->uiEnable(); ?>
<script type="text/javascript">
(function($) {
$.fn.inlineEdit = function(options) {
options = $.extend({
hoverClass: 'hover-edit',
savingClass: 'saving',
successClass: 'settings-success',
errorClass: 'settings-error',
value: '',
save: ''
}, options);
return $.each(this, function() {
$.inlineEdit(this, options);
});
}
$.inlineEdit = function(object, options) {
// Define self, this is the table cell
var self = $(object);
// Register the container with the setting value
self.valueContainer = self.children('.value');
// Get the initial value
self.value = $.trim(self.valueContainer.text()) || options.value;
// Get the component and key for the setting
var parts = self.valueContainer.attr('id').split(':');
self.settingKey = parts.pop();
self.settingComponent = parts.pop();
/**
* Save function. Executes an AJAX function to save the setting
* if it changed.
* @param newValue
*/
self.save = function(newValue) {
var oldValue = self.value;
// Save new value
self.value = newValue;
// Reset the input
self.reset();
// Only save if new value was different from the old value
if (newValue != oldValue) {
self.removeClass('editing')
.removeClass(options.successClass)
.removeClass(options.errorClass)
.addClass(options.savingClass);
var settingData = {
'component': self.settingComponent,
'settingKey': self.settingKey,
'value': self.value
};
$.ajax({
- url: '<?= $this->baseUrl('/fizzy/settings/update'); ?>',
+ url: '<?= $this->url('@admin_settings_update'); ?>',
type: 'POST',
processData: false,
data: JSON.stringify(settingData),
contentType: 'application/json',
error: function(data, textStatus, XMLHttpRequest) {
self.value = oldValue;
self.error();
},
success: function(data, textStatus, XMLHttpRequest) {
console.log(data);
self.success();
}
});
}
}
/**
* Renders the success class over the table cell.
* This is called after the ajax callback ended successfully.
*/
self.success = function() {
self.removeClass(options.savingClass)
.addClass(options.successClass);
self.delay(5000).animate({ backgroundColor: "#FFFFFF" }, 2500, function() {
$(this).removeClass(options.successClass).attr('style', '');
});
}
/**
* Renders the error class over the table cell.
* This is called after the ajax callback ended successfully.
*/
self.error = function() {
self.removeClass(options.savingClass)
.addClass(options.errorClass);
self.delay(5000).animate({ backgroundColor: "#FFFFFF" }, 2500, function() {
$(this).removeClass(options.errorClass).attr('style', '');
});
}
/**
* Reset the table cell
*/
self.reset = function() {
self.removeClass('editing').addClass('editable');
self.valueContainer.removeClass('form').addClass('value');
self.valueContainer.html(self.value);
}
/**
* Update the table cell class on hover
*/
self.hover(function() {
if (!self.hasClass('editing') && !self.hasClass(options.savingClass)) {
self.addClass(options.hoverClass);
}
}, function() {
self.removeClass(options.hoverClass);
});
/**
* OnClick convert the value container to a form.
*/
self.click(function(event) {
var target = $(event.target);
self.removeClass(options.hoverClass);
if (target.is(self[0].tagName) || target.parent().is(self[0].tagName)) {
if (null != $.inlineEdit.lastOpened) {
$.inlineEdit.lastOpened.reset();
}
$.inlineEdit.lastOpened = self;
self.removeClass('editable').addClass('editing');
self.valueContainer.removeClass('value').addClass('form');
// Input field
var tinput = $(document.createElement('input'))
.attr('type', 'text')
.val(self.value);
// Save button
var saveBtn = $(document.createElement('button'))
.attr('id', 'editable-save')
.html('Save')
.click(function() {
self.save($(this).parent().find('input').val());
});
// Cancel button
var cancelBtn = $(document.createElement('button'))
.attr('id', 'editable-cancel')
.html('Cancel')
.click(function() {
self.reset();
});
// Replace container contents
self.valueContainer.html(tinput)
.append(saveBtn)
.append(cancelBtn)
.find('input')
.focus();
}
});
}
$.inlineEdit.lastOpened = null;
})(jQuery);
$(document).ready(function() {
$('.editable').inlineEdit();
});
</script>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/form.phtml b/application/modules/admin/views/scripts/user/form.phtml
index a7a0e9b..426a593 100644
--- a/application/modules/admin/views/scripts/user/form.phtml
+++ b/application/modules/admin/views/scripts/user/form.phtml
@@ -1,57 +1,57 @@
<form action="<?= $this->form->getAction(); ?>" name="UserForm" id="UserForm" method="post">
<div id="content-panel">
<h2>
<?= $this->user->isNew() ? 'Add user' : 'Edit user'; ?>
</h2>
<div class="form-panel">
<?= $this->form->id; ?>
<?= $this->form->username; ?>
<?= $this->form->displayname; ?>
<?= $this->form->password; ?>
<?= $this->form->password_confirm; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if (!$this->user->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
- '/fizzy/user/delete/' . $this->user->id,
- $this->image('fizzy_assets/images/icon/user--minus.png') . ' delete user',
+ '@admin_users_delete?id=' . $this->user->id,
+ $this->image($this->assetUrl('/images/icon/user--minus.png')) . ' delete user',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this user?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
- '/fizzy/users',
- $this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to users',
+ '@admin_users',
+ $this->image($this->assetUrl('/images/icon/edit-list.png')) . ' back to users',
array (
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/user/list.phtml b/application/modules/admin/views/scripts/user/list.phtml
index 441bb56..0a99695 100644
--- a/application/modules/admin/views/scripts/user/list.phtml
+++ b/application/modules/admin/views/scripts/user/list.phtml
@@ -1,41 +1,41 @@
<div id="content-panel">
<h2>Users</h2>
<table class="data">
<thead>
<tr>
<td> </td>
<td>Username</td>
</tr>
</thead>
<tbody>
<?php foreach($this->users as $user) : ?>
<tr>
<td class="controls">
<?= $this->link(
- "/fizzy/user/edit/{$user['id']}",
- $this->image('/fizzy_assets/images/icon/user--pencil.png', array('alt' => 'edit icon')),
+ '@admin_users_edit?id=' . $user['id'],
+ $this->image($this->assetUrl('/images/icon/user--pencil.png'), array('alt' => 'edit icon')),
array (
'escape' => false
)
); ?>
</td>
<td><?= $user['username'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
- <?= $this->link('/fizzy/user/add', $this->image('/fizzy_assets/images/icon/user--plus.png') . ' Add user', array('escape' => false)); ?>
+ <?= $this->link('@admin_users_add', $this->image($this->assetUrl('/images/icon/user--plus.png')) . ' Add user', array('escape' => false)); ?>
</li>
</ul>
</div>
diff --git a/library/Fizzy/Controller.php b/library/Fizzy/Controller.php
index f679204..0c99b43 100644
--- a/library/Fizzy/Controller.php
+++ b/library/Fizzy/Controller.php
@@ -1,113 +1,132 @@
<?php
/**
* Class Fizzy_Controller
* @package Fizzy
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Controller_Action */
require_once 'Zend/Controller/Action.php';
/**
* Controller class for Fizzy.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_Controller extends Zend_Controller_Action
{
/**
* Flash messenger helper instance
* @var Zend_View_Helper_FlashMessenger
*/
protected $_flashMessenger = null;
/**
* Disables the view renderer and layout
*/
protected function _disableDisplay()
{
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
}
/**
* Adds a flash message to the session.
* @todo move to controller plugin
* @param string $message
* @param string $type Defaults to 'info'
*/
protected function addMessage($message, $type = 'info')
{
$this->_getFlashMessenger()->addMessage(array(
'message' => $message,
'type' => strtolower($type)
));
}
/**
* Adds a message of type 'info' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addInfoMessage($message)
{
$this->addMessage($message, 'info');
}
/**
* Adds a message of type 'success' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addSuccessMessage($message)
{
$this->addMessage($message, 'success');
}
/**
* Adds a message of type 'warning' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addWarningMessage($message)
{
$this->addMessage($message, 'warning');
}
/**
* Adds a message of type 'error' to the session's flash messenger.
* @todo move to controller plugin
* @param string $message
*/
protected function addErrorMessage($message)
{
$this->addMessage($message, 'error');
}
/**
* Gets the flash messenger instance for this controller. Initializes the
* helper from the helper broker if no active instance is found.
* @return Zend_View_Helper_FlashMessenger
*/
protected function _getFlashMessenger()
{
if(null === $this->_flashMessenger) {
$this->_flashMessenger = $this->_helper->getHelper('flashMessenger');
}
return $this->_flashMessenger;
}
+ /**
+ * Overrides Zend Framework default redirect function to allow redirecting
+ * to route names. Route names start with an '@'.
+ * @param string $url the url or route name
+ * @param array $options the route parameters
+ */
+ protected function _redirect($url, $options = array())
+ {
+ if (false !== strpos($url, '@') && 0 === strpos($url, '@')) {
+ // A routename is specified
+ $url = trim($url, '@');
+ $this->_helper->redirector->gotoRoute($options, $url);
+ }
+ else {
+ // Assume an url is passed in
+ parent::_redirect($url, $options);
+ }
+ }
+
}
diff --git a/library/Fizzy/SecuredController.php b/library/Fizzy/SecuredController.php
index 71c212f..1020b70 100644
--- a/library/Fizzy/SecuredController.php
+++ b/library/Fizzy/SecuredController.php
@@ -1,69 +1,71 @@
<?php
/**
* Class Fizzy_SecuredController
* @package Fizzy
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Fizzy_Controller */
require_once 'Fizzy/Controller.php';
class Fizzy_SecuredController extends Fizzy_Controller
{
/**
* Identity object for the autheticated user.
* @var mixed
*/
protected $_identity = null;
/**
* The session namespace used for the security credentials
* @var string
*/
- protected $_sessionNamespace = null;
+ protected $_sessionNamespace = 'fizzy';
/**
- * Url to redirect to when not logged in
+ * Route or url to redirect to when not logged in
* @var string
*/
- protected $_redirect = null;
+ protected $_redirect = '@admin_login';
/** **/
/**
* Check for authentication identity
*/
public function preDispatch()
{
if ($this->_sessionNamespace === null || $this->_redirect === null) {
throw new Fizzy_Exception('Please provide a $_sessionNamespace and $_redirect in your Fizzy_SecuredController subclass.');
}
$auth = Zend_Auth::getInstance();
$auth->setStorage(new Zend_Auth_Storage_Session($this->_sessionNamespace));
+
+ // Redirect when no identity is present
if (!$auth->hasIdentity()) {
- $this->_redirect($this->_redirect, array('prependBase' => true));
+ $this->_redirect($this->_redirect);
}
$this->_identity = Zend_Auth::getInstance()->getIdentity();
}
/**
* Returns the identity for the authenticated user.
* @return mixed
*/
public function getIdentity()
{
return $this->_identity;
}
}
\ No newline at end of file
diff --git a/library/Fizzy/View/Helper/Url.php b/library/Fizzy/View/Helper/Url.php
index 5774290..f5f61b7 100644
--- a/library/Fizzy/View/Helper/Url.php
+++ b/library/Fizzy/View/Helper/Url.php
@@ -1,100 +1,103 @@
<?php
/**
* Class Fizzy_View_Helper_Url
* @package Fizzy
* @subpackage View
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* View helper for generating urls
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_View_Helper_Url extends Zend_View_Helper_Abstract
{
/**
* Build an url.
*
* If the url starts with http:// it is assumed this is an external url
* and the url is returned immediately.
*
* If the url starts with '@' followed by a route name the route is fetched
* by that name and build with the parameters provided in a query string
* notation.
*
* The options array can specify prependBase if the generated (internal)
* url should container the base url. Zend_View_Helper_BaseUrl is used
* for this.
*
* @param string $url
* @param array $options
* @return string
*/
public function url($url, $options = array())
{
// If it starts with http:// we assume its an external link
if (0 === strpos($url, 'http://')) {
return $url;
}
$defaults = array('prependBase' => true);
$options += $defaults;
if (null === $this->view) {
$view = new Zend_View();
}
// Check if the url was passed as a route name
if (0 === strpos($url, '@')) {
$routeName = substr($url, 1);
$params = array();
// Check for route parameters
if (false !== strpos($routeName, '?')) {
list($routeName, $paramString) = explode('?', $routeName);
if (empty($paramString)) {
break;
}
$paramPairs = explode('&', $paramString);
foreach ($paramPairs as $pair) {
if (false !== strpos($pair, '=')) {
list($pairKey, $pairValue) = explode('=', $pair);
$params[$pairKey] = $pairValue;
} else {
$params[$pairKey] = null;
}
}
}
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = $router->getRoute($routeName);
// Build the url with route and parameters
$url = $route->assemble($params);
}
// Add base url if prependBase is true
if ((boolean) $options['prependBase']) {
+ if (null === $this->view) {
+ $this->view = new Zend_View();
+ }
$url = $this->view->baseUrl($url);
}
return $url;
}
}
\ No newline at end of file
|
jtietema/Fizzy
|
8394ed38ee9f685cb4e7d5b0b0d685a9f9551b3b
|
Added Url view helper
|
diff --git a/library/Fizzy/View/Helper/Url.php b/library/Fizzy/View/Helper/Url.php
new file mode 100644
index 0000000..5774290
--- /dev/null
+++ b/library/Fizzy/View/Helper/Url.php
@@ -0,0 +1,100 @@
+<?php
+/**
+ * Class Fizzy_View_Helper_Url
+ * @package Fizzy
+ * @subpackage View
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
+/**
+ * View helper for generating urls
+ *
+ * @author Mattijs Hoitink <[email protected]>
+ */
+class Fizzy_View_Helper_Url extends Zend_View_Helper_Abstract
+{
+
+ /**
+ * Build an url.
+ *
+ * If the url starts with http:// it is assumed this is an external url
+ * and the url is returned immediately.
+ *
+ * If the url starts with '@' followed by a route name the route is fetched
+ * by that name and build with the parameters provided in a query string
+ * notation.
+ *
+ * The options array can specify prependBase if the generated (internal)
+ * url should container the base url. Zend_View_Helper_BaseUrl is used
+ * for this.
+ *
+ * @param string $url
+ * @param array $options
+ * @return string
+ */
+ public function url($url, $options = array())
+ {
+ // If it starts with http:// we assume its an external link
+ if (0 === strpos($url, 'http://')) {
+ return $url;
+ }
+
+ $defaults = array('prependBase' => true);
+ $options += $defaults;
+
+ if (null === $this->view) {
+ $view = new Zend_View();
+ }
+
+ // Check if the url was passed as a route name
+ if (0 === strpos($url, '@')) {
+
+ $routeName = substr($url, 1);
+ $params = array();
+
+ // Check for route parameters
+ if (false !== strpos($routeName, '?')) {
+ list($routeName, $paramString) = explode('?', $routeName);
+ if (empty($paramString)) {
+ break;
+ }
+
+ $paramPairs = explode('&', $paramString);
+ foreach ($paramPairs as $pair) {
+ if (false !== strpos($pair, '=')) {
+ list($pairKey, $pairValue) = explode('=', $pair);
+ $params[$pairKey] = $pairValue;
+ } else {
+ $params[$pairKey] = null;
+ }
+ }
+ }
+
+ $router = Zend_Controller_Front::getInstance()->getRouter();
+ $route = $router->getRoute($routeName);
+
+ // Build the url with route and parameters
+ $url = $route->assemble($params);
+ }
+
+ // Add base url if prependBase is true
+ if ((boolean) $options['prependBase']) {
+ $url = $this->view->baseUrl($url);
+ }
+
+ return $url;
+ }
+
+}
\ No newline at end of file
|
jtietema/Fizzy
|
5fbba06297925af6de300fd867652a23bb44d89c
|
Basic version of blog frontend
|
diff --git a/application/models/generated/BasePost.php b/application/models/generated/BasePost.php
index 1a726b0..15e4383 100644
--- a/application/models/generated/BasePost.php
+++ b/application/models/generated/BasePost.php
@@ -1,73 +1,82 @@
<?php
/**
* BasePost
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @property integer $id
* @property string $title
+ * @property string $slug
+ * @property string $intro
* @property string $body
* @property timestamp $date
* @property integer $author
* @property integer $status
* @property boolean $comments
* @property integer $blog_id
* @property User $User
* @property Blog $Blog
*
* @package ##PACKAGE##
* @subpackage ##SUBPACKAGE##
* @author ##NAME## <##EMAIL##>
* @version SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
*/
abstract class BasePost extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('post');
$this->hasColumn('id', 'integer', 4, array(
'type' => 'integer',
'primary' => true,
'autoincrement' => true,
'length' => '4',
));
$this->hasColumn('title', 'string', 255, array(
'type' => 'string',
'length' => '255',
));
+ $this->hasColumn('slug', 'string', 100, array(
+ 'type' => 'string',
+ 'length' => '100',
+ ));
+ $this->hasColumn('intro', 'string', null, array(
+ 'type' => 'string',
+ ));
$this->hasColumn('body', 'string', null, array(
'type' => 'string',
));
$this->hasColumn('date', 'timestamp', null, array(
'type' => 'timestamp',
));
$this->hasColumn('author', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
$this->hasColumn('status', 'integer', 1, array(
'type' => 'integer',
'length' => '1',
));
$this->hasColumn('comments', 'boolean', null, array(
'type' => 'boolean',
));
$this->hasColumn('blog_id', 'integer', 4, array(
'type' => 'integer',
'length' => '4',
));
}
public function setUp()
{
parent::setUp();
$this->hasOne('User', array(
'local' => 'author',
'foreign' => 'id'));
$this->hasOne('Blog', array(
'local' => 'blog_id',
'foreign' => 'id'));
}
}
\ No newline at end of file
diff --git a/application/modules/default/controllers/BlogController.php b/application/modules/default/controllers/BlogController.php
new file mode 100644
index 0000000..7218e9d
--- /dev/null
+++ b/application/modules/default/controllers/BlogController.php
@@ -0,0 +1,125 @@
+<?php
+/**
+ * Class BlogController
+ * @package Fizzy
+ * @subpackage Controllers
+ * @category frontend
+ *
+ * LICENSE
+ *
+ * This source file is subject to the new BSD license that is bundled
+ * with this package in the file LICENSE.txt.
+ * It is also available through the world-wide-web at this URL:
+ * http://www.voidwalkers.nl/license/new-bsd
+ * If you did not receive a copy of the license and are unable to
+ * obtain it through the world-wide-web, please send an email
+ * to [email protected] so we can send you a copy immediately.
+ *
+ * @copyright 2010 Voidwalkers (http://www.voidwalkers.nl)
+ * @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
+ */
+
+/**
+ * Default blog implementation
+ *
+ * @author Mattijs Hoitink <[email protected]>
+ */
+class BlogController extends Fizzy_Controller
+{
+
+ /**
+ * Shows latest posts from all blogs
+ */
+ public function indexAction()
+ {
+ $posts = Doctrine_Query::create()
+ ->from('Post')
+ ->where('status = ?', Post::PUBLISHED)
+ ->orderBy('date DESC')
+ ->limit(10)
+ ->execute();
+
+ $this->view->posts = $posts;
+ $this->render('posts');
+ }
+
+ /**
+ * Shows the posts from a single blog
+ */
+ public function blogAction()
+ {
+ $blogSlug = $this->_getParam('blog_slug', null);
+ if (null === $blogSlug) {
+ // show 404
+ }
+
+ $blog = Doctrine_Query::create()->from('Blog')->where('slug = ?', $blogSlug)->fetchOne();
+ if (false === $blog) {
+ // Show 404
+ }
+
+ $posts = Doctrine_Query::create()
+ ->from('Post')
+ ->where('status = ?', Post::PUBLISHED)
+ ->where('blog_id = ?', $blog->id)
+ ->orderBy('date DESC')
+ ->limit(10)
+ ->execute();
+
+ $this->view->blog = $blog;
+ $this->view->posts = $posts;
+ $this->render('blog');
+ }
+
+ /**
+ * Shows all posts by a user
+ */
+ public function userAction()
+ {
+ $username = $this->_getParam('username', null);
+ if (null === $username) {
+ // Show 404
+ }
+
+ $user = Doctrine_Query::create()
+ ->from('User')
+ ->where('username = ?', $username)
+ ->fetchOne();
+ if (false === $user) {
+ // Show 404
+ }
+
+ $posts = Doctrine_Query::create()
+ ->from('Post')
+ ->where('status = ?', Post::PUBLISHED)
+ ->where('author = ?', $user->id)
+ ->orderBy('date DESC')
+ ->limit(10)
+ ->execute();
+
+ $this->view->user = $user;
+ $this->view->posts = $posts;
+ $this->render('user');
+ }
+
+ /**
+ * Shows a single post
+ */
+ public function postAction()
+ {
+ $slug = $this->_getParam('post_slug', null);
+
+ if (null === $slug) {
+ // Show 404
+ }
+
+ $post = Doctrine_Query::create()->from('Post')->where('slug = ?', $slug)->fetchOne();
+ if (false === $post) {
+ // Show 404
+ }
+
+ $this->view->post = $post;
+ $this->render('post-entry');
+ }
+
+}
\ No newline at end of file
diff --git a/application/modules/default/controllers/CommentController.php b/application/modules/default/controllers/CommentController.php
new file mode 100644
index 0000000..3ab32fc
--- /dev/null
+++ b/application/modules/default/controllers/CommentController.php
@@ -0,0 +1,33 @@
+<?php
+
+class CommentController extends Fizzy_Controller
+{
+
+ public function addAction()
+ {
+ if (!$this->getRequest()->isPost()) {
+ // Deny
+ }
+
+ $stream = $this->_getParam('stream', null);
+ if (null === $stream) {
+ // Deny
+ }
+
+ $comment = new Comments();
+ $comment->post_id = $stream;
+ $comment->name = $_POST['name'];
+ $comment->email = $_POST['email'];
+ $comment->website = $_POST['website'];
+ $comment->body = $_POST['body'];
+ $comment->date = time();
+ $comment->save();
+
+ if (isset($_SERVER['HTTP_REFERER'])) {
+ $this->_redirect($_SERVER['HTTP_REFERER']);
+ }
+ else {
+ $this->render('success.phtml');
+ }
+ }
+}
\ No newline at end of file
diff --git a/application/modules/default/views/layouts/default.phtml b/application/modules/default/views/layouts/default.phtml
index e303adc..477f0ab 100644
--- a/application/modules/default/views/layouts/default.phtml
+++ b/application/modules/default/views/layouts/default.phtml
@@ -1,66 +1,76 @@
<?php
/**
* Default layout
* @package Fizzy
* @subpackage Views
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
?>
<html>
<head>
<?php
$config = Zend_Registry::get('config');
$title = $config->title;
?>
<title><?= $title; ?></title>
- <link href="<?= $this->baseUrl("/css/default.css") ?>" rel="stylesheet" type="text/css" media="screen" />
+ <link href="<?= $this->assetUrl("/css/reset-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
+ <link href="<?= $this->baseUrl("/fizzy_assets/css/fonts-min.css") ?>" rel="stylesheet" type="text/css" media="screen, presentation" />
+ <link href="<?= $this->baseUrl("/css/fizzy.css") ?>" rel="stylesheet" type="text/css" media="screen" />
</head>
<body>
<div class="container">
<!-- HEADER -->
- <div id="header" class="span-24 last">
+ <div id="header-panel" class="span-24 last">
<h1>Fizzy<span>CMS</span></h1>
- </div>
- <!-- NAVIGATION -->
- <div id="navigation" class="span-24 last">
- <ul>
- <li><a href="<?= $this->baseUrl('/') ?>">Home</a></li>
- <li><a href="<?= $this->baseUrl('/about'); ?>">About</a></li>
- <li><a href="<?= $this->baseUrl('/configuration'); ?>">Configuration</a></li>
- <li><a href="http://project.voidwalkers.nl/projects/show/fizzy" target="_blanc">More</a></li>
- </ul>
+ <!-- NAVIGATION -->
+ <div id="navigation-panel">
+ <ul>
+ <li><a href="<?= $this->baseUrl('/') ?>" title="Website home">Home</a></li>
+ <li><a href="<?= $this->baseUrl('/blog') ?>" title="The blog">Blog</a></li>
+ <li><a href="<?= $this->baseUrl('/about'); ?>" title="About this site">About</a></li>
+ <li><a href="<?= $this->baseUrl('/configuration'); ?>" title="How to configure Fizzy">Configuration</a></li>
+ <li><a href="http://project.voidwalkers.nl/projects/show/fizzy" target="_blank" title="Learn more about the fizzy project (opens in a new window)">More</a></li>
+ </ul>
+ <div class="clear"></div>
+ </div>
+ <!-- NAVIGATION -->
</div>
<!-- CONTENT -->
- <div id="main-wrapper" class="span-24 last">
- <div id="content" class="span-24">
- <div class="content-block">
- <?= $this->layout()->content; ?>
- </div>
+ <div id="main-panel" class="span-24 last">
+ <div id="content-panel">
+ <?= $this->layout()->content; ?>
</div>
</div>
<!-- FOOTER -->
- <div id="footer" class="span-24 last">
- (c) 2009 <a href="http://www.voidwalkers.nl" title="The Voidwalkers">Voidwalkers</a> - <a href="http://www.voidwalkers.nl/license/bsd-license" title="Fizzy license">license</a>
+ <div id="footer-panel" class="span-24 last">
+ <p>
+ This site is powered by Fizzy <?= Fizzy_Version::VERSION ?>
+ running on Zend Framework <?= Zend_Version::VERSION ?>
+ and Doctrine <?= Doctrine::VERSION ?>
+ </p>
+ <p>
+ (c) 2009-<?= date('Y'); ?> Voidwalkers - <a href="http://www.voidwalkers.nl/license/new-bsd">license</a><br />
+ </p>
</div>
</div>
</body>
</html>
diff --git a/application/modules/default/views/scripts/blog/blog.phtml b/application/modules/default/views/scripts/blog/blog.phtml
new file mode 100644
index 0000000..e9f6206
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/blog.phtml
@@ -0,0 +1,6 @@
+<div class="blog">
+ <h2>Posts in blog <?= $this->blog->name; ?></h2>
+
+ <?= $this->partial('blog/posts.phtml', array('posts' => $this->posts)); ?>
+
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/comments.phtml b/application/modules/default/views/scripts/blog/comments.phtml
new file mode 100644
index 0000000..3fef921
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/comments.phtml
@@ -0,0 +1,28 @@
+<div class="stream">
+ <?php foreach ($this->comments as $comment) : ?>
+ <div class="comment">
+ <?php if ($this->options['gravatar_enabled']) : ?>
+ <div class="comment-avatar">
+ <img src="http://www.gravatar.com/avatar/<?= md5(trim(strtolower($comment->email))) ?>?s=80" alt="<?= $comment->name ?>" />
+ </div>
+ <?php endif; ?>
+
+ <div class="comment-content">
+ <div class="comment-meta">
+ <?= date('d-m-Y H:i:s', strtotime($comment->date)); ?>
+ by
+ <?php if (!empty($comment->website)) : ?>
+ <?= $this->link($comment->website, $comment->name, array('target' => '_blank')); ?>
+ <?php else : ?>
+ <?= $comment->name ?>
+ <?php endif; ?>
+ </div>
+ <div class="comment-body">
+ <?= $comment->body ?>
+ </div>
+ </div>
+
+ <div class="clear"></div>
+ </div>
+ <?php endforeach; ?>
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/post-entry.phtml b/application/modules/default/views/scripts/blog/post-entry.phtml
new file mode 100644
index 0000000..12cd9b4
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/post-entry.phtml
@@ -0,0 +1,77 @@
+<div class="post">
+ <h2>
+ <?= $this->link(
+ '@blog_post?blog_slug=' . $this->post->Blog->slug . '&post_slug=' . $this->post->slug,
+ $this->post->title
+ ); ?>
+ </h2>
+ <div class="post-meta-top">
+ on <?= date('d-m-Y', strtotime($this->post->date)); ?>
+ by <?= $this->link('@user_posts?username=' . $this->post->User->username,$this->post->User->displayname); ?>
+ in <?= $this->link('@blog_posts?blog_slug=' . $this->post->Blog->slug, $this->post->Blog->name); ?>
+ </div>
+
+ <div class="post-intro">
+ <?= $this->post->intro; ?>
+ </div>
+
+ <div class="post-body">
+ <?= $this->post->body; ?>
+ </div>
+
+</div>
+
+<div class="comments">
+ <a name="comments"></a>
+
+ <h3>Comments</h3>
+ <?php if ($this->post->comments) : ?>
+ <p>
+ There are <?= count($this->post->comments()); ?> comments for this entry.
+ <a href="#comment-form">Leave your own?</a>
+ </p>
+
+ <?= $this->commentStream('post:' . $this->post->id, 'blog/comments.phtml'); ?>
+
+ <div class="comment-form">
+ <h4>Leave a comment</h4>
+ <a name="comment-form"></a>
+ <form action="<?= $this->url('@add_comment?stream=post:' . $this->post->id); ?>" method="post" name="CommentForm">
+ <div class="comment-form-row">
+ <label for="name">Name *</label>
+ <input type="text" name="name" />
+ </div>
+
+ <div class="comment-form-row">
+ <label for="name">Email *</label>
+ <input type="text" name="email" />
+ <br /><small>Your email will not be published</small>
+ </div>
+
+ <div class="comment-form-row">
+ <label for="name">Website</label>
+ <input type="text" name="website" />
+ </div>
+
+ <div class="comment-form-row">
+ <label for="body">Message *</label>
+ <textarea name="body"></textarea>
+ <br /><small>HTML is disabled</small>
+ </div>
+
+ <div class="comment-form-row">
+ <br />
+ <input type="submit" value="Send" />
+ <input type="reset" value="clear" />
+ </div>
+
+ </form>
+ </div>
+
+
+ <?php else : ?>
+ <p class="comments-disabled">
+ Comments for this entry are disabled
+ </p>
+ <?php endif; ?>
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/post-list-entry.phtml b/application/modules/default/views/scripts/blog/post-list-entry.phtml
new file mode 100644
index 0000000..a94110e
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/post-list-entry.phtml
@@ -0,0 +1,39 @@
+<div class="post">
+ <h3>
+ <?= $this->link(
+ '@blog_post?blog_slug=' . $this->post->Blog->slug . '&post_slug=' . $this->post->slug,
+ $this->post->title
+ ); ?>
+ </h3>
+ <div class="post-meta-top">
+ on <?= date('d-m-Y', strtotime($this->post->date)); ?>
+ by <?= $this->link('@user_posts?username=' . $this->post->User->username,$this->post->User->displayname); ?>
+ in <?= $this->link('@blog_posts?blog_slug=' . $this->post->Blog->slug, $this->post->Blog->name); ?>
+ </div>
+
+ <div class="post-intro">
+ <?= $this->post->intro; ?>
+ </div>
+
+ <div class="post-meta-bottom">
+ <span class="post-meta-more">
+ <?= $this->link(
+ '@blog_post?blog_slug=' . $this->post->Blog->slug . '&post_slug=' . $this->post->slug,
+ 'read more »',
+ array(
+ 'escape' => false
+ )
+ ); ?>
+ </span> |
+ <span class="post-meta-comments">
+ <?= count($this->post->comments()) . ' ' . $this->link(
+ '@blog_post?blog_slug=' . $this->post->Blog->slug . '&post_slug=' . $this->post->slug . '#comments',
+ 'comments',
+ array(
+ 'title' => 'View comments for this post'
+ )
+ ); ?>
+ </span>
+ </div>
+
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/posts.phtml b/application/modules/default/views/scripts/blog/posts.phtml
new file mode 100644
index 0000000..d41acf0
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/posts.phtml
@@ -0,0 +1,5 @@
+<div class="posts">
+ <?php foreach ($this->posts as $post) : ?>
+ <?= $this->partial('blog/post-list-entry.phtml', array ('post' => $post)); ?>
+ <?php endforeach; ?>
+</div>
\ No newline at end of file
diff --git a/application/modules/default/views/scripts/blog/user.phtml b/application/modules/default/views/scripts/blog/user.phtml
new file mode 100644
index 0000000..d3fbfb3
--- /dev/null
+++ b/application/modules/default/views/scripts/blog/user.phtml
@@ -0,0 +1,6 @@
+<div class="blog">
+ <h2>Posts by <?= $this->user->displayname; ?></h2>
+
+ <?= $this->partial('blog/posts.phtml', array('posts' => $this->posts)); ?>
+
+</div>
\ No newline at end of file
diff --git a/configs/routes.ini b/configs/routes.ini
index 44bd025..9f7258c 100644
--- a/configs/routes.ini
+++ b/configs/routes.ini
@@ -1,192 +1,230 @@
[development : production]
[test : production]
[production]
;; Catch all for pages slugs
page_by_slug.route = "/:slug"
page_by_slug.defaults.controller = "pages"
page_by_slug.defaults.action = "slug"
page_by_slug.defaults.module = "default"
-contact.route = "/contact"
-contact.defaults.controller = "contact"
-contact.defaults.action = "index"
-contact.defaults.module = "default"
+;; Blog
+blog.route = "blog"
+blog.defaults.controller = "blog"
+blog.defaults.action = "index"
+blog.defaults.module = "default"
+
+;; Blog posts
+blog_posts.route = "/blog/:blog_slug"
+blog_posts.defaults.controller = "blog"
+blog_posts.defaults.action = "blog"
+blog_posts.defaults.module = "default"
+
+;; Post
+blog_post.route = "/blog/:blog_slug/:post_slug"
+blog_post.defaults.controller = "blog"
+blog_post.defaults.action = "post"
+blog_post.defaults.module = "default"
+
+;; User posts
+user_posts.route = "/blog/author/:username"
+user_posts.defaults.controller = "blog"
+user_posts.defaults.action = "user"
+user_posts.defaults.module = "default"
+
+;; Comments
+add_comment.route = "/comment/add/:stream"
+add_comment.defaults.controller = "comment"
+add_comment.defaults.action = "add"
+add_comment.defaults.module = "default"
+
+;; Homepage
+homepage.route = "/"
+homepage.defaults.controller = "pages"
+homepage.defaults.controller = "pages"
+homepage.defaults.action = "slug"
+homepage.defaults.module = "default"
+
+;; Contact form
+;;contact.route = "/contact"
+;;contact.defaults.controller = "contact"
+;;contact.defaults.action = "index"
+;;contact.defaults.module = "default"
;; Admin pages control
admin_blogs.route = "/{backend}/blogs"
admin_blogs.defaults.action = "index"
admin_blogs.defaults.controller = "blogs"
admin_blogs.defaults.module = "admin"
admin_blog.route = "/{backend}/blog/:id"
admin_blog.defaults.action = "blog"
admin_blog.defaults.controller = "blogs"
admin_blog.defaults.module = "admin"
admin_blog_post_add.route = "/{backend}/blog/:blog_id/add"
admin_blog_post_add.defaults.action = "add-post"
admin_blog_post_add.defaults.controller = "blogs"
admin_blog_post_add.defaults.module = "admin"
admin_blog_post_edit.route = "/{backend}/post/:post_id/edit"
admin_blog_post_edit.defaults.action = "edit-post"
admin_blog_post_edit.defaults.controller = "blogs"
admin_blog_post_edit.defaults.module = "admin"
admin_blog_post_delete.route = "/{backend}/post/:post_id/delete"
admin_blog_post_delete.defaults.action = "delete-post"
admin_blog_post_delete.defaults.controller = "blogs"
admin_blog_post_delete.defaults.module = "admin"
admin_comments.route = "/{backend}/comments"
admin_comments.defaults.action = "index"
admin_comments.defaults.controller = "comments"
admin_comments.defaults.module = "admin"
admin_comments_list.route = "/{backend}/comments/list"
admin_comments_list.defaults.action = "list"
admin_comments_list.defaults.controller = "comments"
admin_comments_list.defaults.module = "admin"
admin_comments_topic.route = "/{backend}/comments/topic/:id"
admin_comments_topic.defaults.action = "topic"
admin_comments_topic.defaults.controller = "comments"
admin_comments_topic.defaults.module = "admin"
admin_comments_ham.route = "/{backend}/comment/ham/:id"
admin_comments_ham.defaults.action = "ham"
admin_comments_ham.defaults.controller = "comments"
admin_comments_ham.defaults.module = "admin"
admin_comments_spam.route = "/{backend}/comment/spam/:id"
admin_comments_spam.defaults.action = "spam"
admin_comments_spam.defaults.controller = "comments"
admin_comments_spam.defaults.module = "admin"
admin_comments_delete.route = "/{backend}/comment/delete/:id"
admin_comments_delete.defaults.action = "delete"
admin_comments_delete.defaults.controller = "comments"
admin_comments_delete.defaults.module = "admin"
admin_comments_edit.route = "/{backend}/comment/edit/:id"
admin_comments_edit.defaults.action = "edit"
admin_comments_edit.defaults.controller = "comments"
admin_comments_edit.defaults.module = "admin"
admin_comments_spambox.route = "/{backend}/comments/spam"
admin_comments_spambox.defaults.action = "spambox"
admin_comments_spambox.defaults.controller = "comments"
admin_comments_spambox.defaults.module = "admin"
admin_pages.route = "/{backend}/pages"
admin_pages.defaults.action = "index"
admin_pages.defaults.controller = "pages"
admin_pages.defaults.module = "admin"
admin_pages_add.route = "/{backend}/pages/add"
admin_pages_add.defaults.action = "add"
admin_pages_add.defaults.controller = "pages"
admin_pages_add.defaults.module = "admin"
admin_pages_edit.route = "/{backend}/pages/edit/:id"
admin_pages_edit.defaults.action = "edit"
admin_pages_edit.defaults.controller = "pages"
admin_pages_edit.defaults.module = "admin"
admin_pages_delete.route = "/{backend}/pages/delete/:id"
admin_pages_delete.defaults.action = "delete"
admin_pages_delete.defaults.controller = "pages"
admin_pages_delete.defaults.module = "admin"
admin_media.route = "/{backend}/media"
admin_media.defaults.action = "index"
admin_media.defaults.controller = "media"
admin_media.defaults.module = "admin"
admin_media_delete.route = "/{backend}/media/delete/:name"
admin_media_delete.defaults.action = "delete"
admin_media_delete.defaults.controller = "media"
admin_media_delete.defaults.module = "admin"
admin_media_gallery.route = "/{backend}/media/gallery"
admin_media_gallery.defaults.action = "gallery"
admin_media_gallery.defaults.controller = "media"
admin_media_gallery.defaults.module = "admin"
admin_media_assets.route = "/{backend}/media/assets"
admin_media_assets.defaults.action = "assets"
admin_media_assets.defaults.controller = "media"
admin_media_assets.defaults.module = "admin"
;; Admin contact
admin_contact.route = "/{backend}/contact"
admin_contact.defaults.module = "admin"
admin_contact.defaults.controller = "contact"
admin_contact.defaults.action = "index"
admin_contact_show.route = "/{backend}/contact/show/:id"
admin_contact_show.defaults.module = "admin"
admin_contact_show.defaults.controller = "contact"
admin_contact_show.defaults.action = "show"
admin_contact_delete.route = "/{backend}/contact/delete/:id"
admin_contact_delete.defaults.module = "admin"
admin_contact_delete.defaults.controller = "contact"
admin_contact_delete.defaults.action = "delete"
;; Admin users
admin_users.route = "/{backend}/users"
admin_users.defaults.action = "index"
admin_users.defaults.controller = "user"
admin_users.defaults.module = "admin"
admin_users_add.route = "/{backend}/user/add"
admin_users_add.defaults.action = "add"
admin_users_add.defaults.controller = "user"
admin_users_add.defaults.module = "admin"
admin_users_edit.route = "/{backend}/user/edit/:id"
admin_users_edit.defaults.action = "edit"
admin_users_edit.defaults.controller = "user"
admin_users_edit.defaults.module = "admin"
admin_users_delete.route = "/{backend}/user/delete/:id"
admin_users_delete.defaults.action = "delete"
admin_users_delete.defaults.controller = "user"
admin_users_delete.defaults.module = "admin"
;; Admin settings
admin_settings.route = "/{backend}/settings"
admin_settings.defaults.module = "admin"
admin_settings.defaults.controller = "settings"
admin_settings.defaults.action = "index"
admin_settings_update.route = "/{backend}/settings/update"
admin_settings_update.defaults.module = "admin"
admin_settings_update.defaults.controller = "settings"
admin_settings_update.defaults.action = "ajax-update"
;; Admin WebDAV
admin_webdav.route = "/{backend}/webdav/*"
admin_webdav.defaults.module = "admin"
admin_webdav.defaults.controller = "webdav"
admin_webdav.defaults.action = "request"
;; Auth section
admin_login.route = "/{backend}/login"
admin_login.defaults.action = "login"
admin_login.defaults.controller = "auth"
admin_login.defaults.module = "admin"
admin_logout.route = "/{backend}/logout"
admin_logout.defaults.action = "logout"
admin_logout.defaults.controller = "auth"
admin_logout.defaults.module = "admin"
admin.route = "/{backend}"
admin.defaults.action = "index"
admin.defaults.controller = "index"
admin.defaults.module = "admin"
diff --git a/database/fixtures/blogs.yml b/database/fixtures/blogs.yml
index c60c210..fc335d2 100644
--- a/database/fixtures/blogs.yml
+++ b/database/fixtures/blogs.yml
@@ -1,38 +1,40 @@
Blog:
Default:
name: Default Blog
slug: default
group_slug: default
Post:
Test:
title: Test post
+ slug: "test-post"
+ intro: "Dit is de intro van de test post"
body: dit is een test post
date: now
comments: true
status: 2
author: 1
blog_id: 1
Comments:
test_comment1:
post_id: 'post:1'
body: Some random body
name: Jeroen
email: [email protected]
date: 2010-05-20
about_comment:
post_id: 'page:3'
body: Awesome about page
name: Jeroen
email: [email protected]
about_comment2:
post_id: 'page:3'
body: Awesome about page comment number 2
name: Jeroen
email: [email protected]
about_comment3:
post_id: 'page:3'
body: Awesome about page comment number 3
name: Jeroen
email: [email protected]
\ No newline at end of file
diff --git a/database/schema/schema.yml b/database/schema/schema.yml
index d1ffd54..6498a55 100644
--- a/database/schema/schema.yml
+++ b/database/schema/schema.yml
@@ -1,81 +1,83 @@
User:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
username: string(150)
displayname: string(255)
password: string(150)
encryption: string(10)
Page:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
title: string(255)
slug: string(255)
body: string
homepage: boolean
layout: string(150)
template: string(150)
Blog:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
name: string(255)
slug: string(255)
group_slug: string(255)
Post:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
title: string(255)
+ slug: string(100)
+ intro: string
body: string
date: timestamp
author: integer(4)
status: integer(1)
comments: boolean
blog_id: integer(4)
relations:
User:
local: author
foreign: id
foreignAlias: BlogPosts
Blog:
local: blog_id
foreign: id
foreignAlias: Posts
Comments:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
post_id: string(100)
body: string
name: string(255)
email: string(255)
website: string(255)
date: timestamp
spam:
type: boolean
default: 0
approved: boolean
ip: string(100)
user_agent: string(255)
referrer: string(255)
indexes:
post_id_index:
fields: [post_id]
Setting:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
component: string(50)
setting_key: string(50)
value: string
label: string(255)
description: string
Contact:
columns:
id: { type: integer(4), primary: true, autoincrement: true }
name: string(255)
email: string(255)
body: string
date: datetime
\ No newline at end of file
diff --git a/library/Fizzy/View/Helper/CommentStream.php b/library/Fizzy/View/Helper/CommentStream.php
new file mode 100644
index 0000000..d087de8
--- /dev/null
+++ b/library/Fizzy/View/Helper/CommentStream.php
@@ -0,0 +1,33 @@
+<?php
+
+class Fizzy_View_Helper_CommentStream extends Zend_View_Helper_Abstract
+{
+
+ public function commentStream($streamId, $template, $options = array())
+ {
+ // Update options with defaults
+ $defaults = array (
+ 'gravatar_enabled' => true,
+ 'gravatar_size' => '50',
+ );
+ $options = $options + $defaults;
+
+ // Get the comments for the stream
+ $comments = Doctrine_Query::create()
+ ->from('Comments')
+ ->where('post_id = ?', $streamId)
+ ->limit(10)
+ ->execute();
+
+ if (false === $comments) {
+ return '<p>Could not load comment stream.</p>';
+ }
+
+ if (null === $this->view) {
+ $this->view = new Zend_View();
+ }
+
+ return $this->view->partial($template, array('comments' => $comments, 'options' => $options));
+ }
+
+}
\ No newline at end of file
diff --git a/library/Fizzy/View/Helper/Link.php b/library/Fizzy/View/Helper/Link.php
index fae3497..b83dcd8 100644
--- a/library/Fizzy/View/Helper/Link.php
+++ b/library/Fizzy/View/Helper/Link.php
@@ -1,129 +1,98 @@
<?php
/**
* Class Fizzy_View_Helper_Link
* @package Fizzy
* @subpackage View
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* View helper for generating a link tag.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_View_Helper_Link extends Zend_View_Helper_HtmlElement
{
/**
* Construct a link tag. The passed url is prepended with the base url. This
* can be ignore by setting prependBase to false in the options.
*
* A javascript confirm dialog can be added to the link by specifying the
* confirm key in the options array. This text is converted to a javascript
* confirm dialog.
*
* Output escaping can be turned of by setting the escape options to false
* in the options array.
*
* @param string $url
* @param string $value
* @param array $options
* @return string
*/
public function link($url, $value, $options = array())
{
- $defaults = array('prependBase' => true, 'escape' => true);
- $options += $defaults;
+ $options += array('prependBase' => true, 'escape' => true);
if (null === $this->view) {
$view = new Zend_View();
}
$escape = (boolean) $options['escape'];
// Remove the escape option so it doesn't appear as an html attribute
unset($options['escape']);
- // Check if the url was passed as a route name
- if (0 === strpos($url, '@')) {
+ // Parse the URL with Fizzy_View_Helper_Url
+ $urlHelper = new Fizzy_View_Helper_Url();
+ $urlHelper->setView($this->view);
+ $url = $urlHelper->url($url, $options);
- $routeName = substr($url, 1);
- $params = array();
-
- // Check for route parameters
- if (false !== strpos($routeName, '?')) {
- list($routeName, $paramString) = explode('?', $routeName);
- if (empty($paramString)) {
- break;
- }
-
- $paramPairs = explode('&', $paramString);
- foreach ($paramPairs as $pair) {
- if (false !== strpos($pair, '=')) {
- list($pairKey, $pairValue) = explode('=', $pair);
- $params[$pairKey] = $pairValue;
- } else {
- $params[$pairKey] = null;
- }
- }
- }
-
- $router = Zend_Controller_Front::getInstance()->getRouter();
- $route = $router->getRoute($routeName);
-
- // Build the url with route and parameters
- $url = $route->assemble($params);
- }
-
- // Add base url if prependBase is true
- if ((boolean) $options['prependBase']) {
- $url = $this->view->baseUrl($url);
- }
// Remove the prependBase option so it doesn't appear as an html attribute
unset($options['prependBase']);
// Check for confirm option
if (isset($options['confirm'])) {
$confirmText = $options['confirm'];
$confirm = "return confirm('{$this->view->escape($confirmText)}');";
unset($options['confirm']);
$onclick = '';
if (isset($options['onClick'])) {
$onclick = $options['onClick'];
unset($options['onClick']);
} else if (isset($options['onclick'])) {
$onclick = $options['onclick'];
unset($options['onclick']);
}
if (empty($onclick)) {
$onclick = $confirm;
}
else {
$onclick = $confirm . $onclick;
}
$options['onClick'] = $confirm;
}
// Construct the tag
$xhtml = '<a href="' . $url . '"' . $this->_htmlAttribs($options) . '>';
$xhtml .= ($escape) ? $this->view->escape($value) : $value;
$xhtml .= '</a>';
return $xhtml;
}
}
\ No newline at end of file
diff --git a/library/Fizzy/View/Helper/Uri.php b/library/Fizzy/View/Helper/Uri.php
new file mode 100644
index 0000000..b3d9bbc
--- /dev/null
+++ b/library/Fizzy/View/Helper/Uri.php
@@ -0,0 +1 @@
+<?php
diff --git a/public/css/default.css b/public/css/default.css
index cf46073..ce35ed4 100644
--- a/public/css/default.css
+++ b/public/css/default.css
@@ -1,146 +1,151 @@
@import 'screen.css';
body {
margin: 0;
padding: 0;
background: #e2e6e9;
font-family: Verdana, Arial, Sans-Serif;
}
a:link {
color: #273A4D;
text-decoration: none;
}
a:visited {
color: #273A4D;
text-decoration: none;
}
a:hover, a:active {
color: #ffffff;
background-color: #343838;
}
h1, h2, h3, h4, h5, h6 {
font-weight: normal;
margin: 1em 0;
padding: 0;
}
h1 { font-size: 200%; color: #293138;}
h2 { font-size: 150%; color: #353F47;}
h3 { font-size: 125%; color: #3f4f5c;}
h4 { font-size: 115%; color: #3f4f5c; }
h5 { font-size: 110%; color: #3f4f5c;}
h6 {
font-size: 100%;
text-transform: uppercase;
margin: 5px 0;
font-weight: bold;
}
/* HEADER */
-#header {
-
+#header-panel {
+ position: relative;
+ height: 5.3em;
+ margin: 0;
+ padding: 15px 30px 0;
+ background-color: #0A62B2;
+ -moz-box-shadow: 0 -8px 6px -4px rgba(0, 0, 0, 0.2) inset;
}
-#header h1 {
+#header-panel h1 {
color: #191a1a;
font-weight: bold;
margin-bottom: 0.5em;
}
-#header h1 a {
+#header-panel h1 a {
width:750px;
height: 200px;
background: transparent;
}
-#header h1 a:link,
-#header h1 a:visited {
+#header-panel h1 a:link,
+#header-panel h1 a:visited {
color: #333333;
}
-#header h1 a:hover,
-#header h1 a:active {
+#header-panel h1 a:hover,
+#header-panel h1 a:active {
color: #000000;
background-color: transparent;
}
#header h1 span {color:#5b5c5c;}
/* NAVIGATION */
#navigation {
background-color: #282d2d;
text-transform: uppercase;
font-size: 110%;
}
#navigation ul {
margin: 0 5px;
padding: 0px 0;
list-style-type: none;
}
#navigation li {
float: left;
margin: 0 0 0 5px;
padding: 0;
}
#navigation a:link,
#navigation a:visited {
float: left;
display: block;
color: #c6c6c6;
padding: 0.5em 1em;
}
#navigation ul li.current_page_item a:link,
#navigation ul li.current_page_item a:visited,
#navigation ul li.current_page_item a:hover,
#navigation ul li.current_page_item a:active {
color: #ffffff;
background-color: #414646;
border-left: solid #6b7070 1px;
border-right: solid #6b7070 1px;
}
/* CONTENT */
#main-wrapper {
background-color: #FFFFFF;
}
/* content */
#content {}
.content-block {
margin: 1em 1.5em;
}
/* sidebar */
#sidebar {}
.sidebar-block {
margin: 2em 1em;
}
.sidebar-block h3 {
color:#5b5c5c;
text-transform: uppercase;
border-bottom: solid #5b5c5c 2px;
padding-bottom: 0.3em;
margin: 0;
}
.sidebar-block-content {
background-color: #F3F2F2;
border: solid #E6E4E4 1px;
padding: 0.5em;
}
/* FOOTER */
#footer {
color: #555555;
text-align: center;
padding: 1em 0;
background: #cfcfcf;
}
\ No newline at end of file
diff --git a/public/css/fizzy.css b/public/css/fizzy.css
new file mode 100644
index 0000000..29208a5
--- /dev/null
+++ b/public/css/fizzy.css
@@ -0,0 +1,298 @@
+@import 'screen.css';
+
+/* ********************** */
+/* HTML ELEMENTS */
+
+html {
+ background-color: #F1EFE2;
+}
+body {
+ font: 75%/1.2 'Lucida Grande',Arial,Helvetica,sans-serif;
+ background-color: #F1EFE2;
+}
+
+em { font-style: italic; }
+
+a {
+ color: #3581C5;
+ text-decoration: none;
+}
+a:hover {
+ color: #033F75;
+ text-decoration: underline;
+}
+
+h1 { font-size: 150%; }
+h2 { font-size: 140%; }
+h3 { font-size: 120%; }
+h4 { font-size: 110%; }
+h5 {}
+h6 {}
+
+h1 ,h2, h3, h4, h5, h6, strong {
+ font-weight:bold;
+}
+
+h2 {
+ margin-bottom: 1em;
+ border-bottom: 1px solid #E4E4E4;
+}
+
+h3 {
+ margin-bottom: .3em;
+ padding-bottom: .2em;
+ border-bottom: 1px solid #E4E4E4;
+}
+
+p { margin-bottom: 1em; }
+
+label {
+ display: block;
+ margin-bottom: .3em;
+ font-weight: bold;
+}
+fieldset {
+ display: block;
+ padding: 10px;
+ border: 1px groove #E4E4E4;
+}
+
+legend { color: #918A8A; }
+
+input[type="text"], input[type="password"], input[type="email"], textarea {
+ width: 300px;
+ padding: 2px 4px;
+ border: 1px solid #918A8A;
+}
+
+/* HTML ELEMENTS */
+/* ********************** */
+
+/* ********************** */
+/* GENERAL CLASSES */
+
+.fleft { float: left; }
+.fright { float: right; }
+
+.tleft { text-align: left; }
+.tright { text-align: right; }
+.tcenter { text-align: center; }
+
+.clr, .clear {
+ height: 1px;
+ line-height: 1px;
+ font-size: 0;
+ clear: both;
+}
+
+.container {
+ background-color: #FFFFFF;
+}
+
+/* GENERAL CLASSES */
+/* ********************** */
+
+/* ********************** */
+/* PANELS */
+
+#header-panel {
+ position: relative;
+ background-color: #0A62B2;
+ color: #F8F8F8;
+ height: 5.3em;
+ margin: 0;
+ -moz-box-shadow: inset 0px -8px 6px -4px rgba(0,0,0,0.2);
+ -webkit-box-shadow: inset 0 -8px 6px -4px rgba(0,0,0,0.2);
+}
+
+#navigation-panel {
+ position: absolute;
+ bottom: -1px;
+}
+
+#main-panel {
+ position: relative;
+ min-height: 400px;
+ -moz-box-shadow: 0px 4px 4px -2px rgba(0,0,0,0.2);
+ -webkit-box-shadow: -8px 8px 6px -4px rgba(0,0,0,0.2);
+}
+
+#content-panel {
+ margin: 1em 1.5em;
+}
+
+#footer-panel {
+ height: 6em;
+ padding-top: 20px;
+ color: #999999;
+ background-color: #F1EFE2;
+}
+
+#copyright-panel {
+ float: right;
+ margin: 10px 20px;
+}
+
+/* PANELS */
+/* ********************** */
+
+/* ********************** */
+/* NAVIGATION */
+
+#navigation-panel ul li {
+ float: left;
+ list-style-type: none;
+ margin: 0 2px 0 0;
+ padding: 0;
+ white-space: nowrap;
+}
+
+#navigation-panel ul li a {
+ color: #FFFFFF;
+ display: block;
+ margin: 0;
+ padding: 4px 10px;
+ text-decoration: none;
+}
+
+#navigation-panel ul li.active a, #navigation-panel ul li.active a:hover {
+ background-color: #FFFFFF;
+ color: #555555;
+}
+
+#navigation-panel ul li a:hover {
+ color: #FFFFFF;
+ background-color: #3581C5;
+}
+
+/* NAVIGATION */
+/* ********************** */
+
+#header-panel h1 {
+ margin: 0.8em 1em;
+ color: #FFFFFF;
+}
+#header-panel h1 span {
+
+}
+
+#navigation-panel ul {
+ padding-left: 1.70em;
+}
+
+#footer-panel p {
+ margin: .5em;
+ text-align: right;
+}
+
+/* ********************** */
+/* BLOG */
+
+.post {
+ margin-bottom: 2em;
+}
+.post h2, .post h3 {
+ margin-bottom: .3em;
+}
+
+.post .post-meta-top, .post .post-meta-bottom {
+ font-size: .85em;
+ line-height: 1em;
+ color: #888888;
+}
+
+.post .post-meta-top {
+ margin-bottom: 2em;
+}
+
+.post .post-meta-bottom {
+ margin-top: 1em;
+ padding-top: .4em;
+ border-top: 1px solid #E4E4E4;
+}
+
+.post .post-meta-bottom .post-meta-comments
+{}
+
+.post .post-meta-bottom .post-meta-more
+{}
+
+.post .post-intro {
+ font-style: italic;
+ margin-bottom: 1em;
+}
+
+.posts .post .post-intro {
+ font-style: normal;
+}
+
+.comments
+{}
+
+.comments .comments-disabled {
+ background-color: #E2E2E2;
+ color: #aaa;
+ text-align: center;
+ padding: 2em;
+ margin: 1em 0;
+}
+
+.comments .comment {
+ background-color: #EAEAEA;
+ margin-bottom: .8em;
+ padding: .5em;
+ position: relative;
+ -moz-border-radius: 5px;
+}
+
+.comments .comment .comment-avatar {
+ float: left;
+ display: inline-block;
+ margin-right: 1em;
+}
+.comments .comment .comment-avatar img {
+ border: 1px solid #666666;
+ -moz-border-radius: 5px;
+}
+
+.comments .comment .comment-content {
+ margin-left: 90px;
+}
+
+.comments .comment .comment-meta {
+ padding: .3em 0;
+ font-size: .85em;
+ border-bottom: 1px solid #ccc;
+}
+.comments .comment .comment-body {
+ margin: .5em;
+}
+
+.comments .comment-form {
+ margin-top: 1.5em;
+}
+
+.comments .comment-form form {
+ border-left: 1em solid #EAEAEA;
+ padding: 0.5em 1em;
+}
+
+.comments .comment-form form label {
+ display: inline-block;
+ width: 100px;
+ vertical-align: top;
+ padding-top: .8em;
+}
+.comments .comment-form form small, .comments .comment-form form input[type="submit"] {
+ margin-left: 105px;
+}
+
+.comments .comment-form form input[type="text"] {
+ display: inline-block;
+}
+
+.comments .comment-form form textarea {
+}
+
+/* BLOG */
+/* ********************** */
\ No newline at end of file
|
jtietema/Fizzy
|
f25f2ba566f04d311e8c2ce53a38bec10f1dc613
|
url's gebruiken nu allemaal link view helper in comments module
|
diff --git a/application/modules/admin/controllers/CommentsController.php b/application/modules/admin/controllers/CommentsController.php
index 60c84a8..8e98ccb 100644
--- a/application/modules/admin/controllers/CommentsController.php
+++ b/application/modules/admin/controllers/CommentsController.php
@@ -1,286 +1,289 @@
<?php
/**
* Class Admin_CommentsController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Controller class for the moderation panel of comments
*
* @author Jeroen Tietema <[email protected]>
*/
class Admin_CommentsController extends Fizzy_SecuredController
{
protected $_sessionNamespace = 'fizzy';
protected $_redirect = '/fizzy/login';
/**
* Dashboard. Shows latest comments and total numbers of comments, spam, etc.
*/
public function indexAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = 0')->orderBy('id DESC');
$this->view->totalComments = $query->count();
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$spamQuery = Doctrine_Query::create()->from('Comments')->where('spam = 1');
$this->view->spamComments = $spamQuery->count();
$this->view->paginator = $paginator;
}
/**
* List of discussions/topics
*/
public function listAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')
->groupBy('post_id')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
/**
* Shows one discussion/topic/thread.
*/
public function topicAction()
{
$id = $this->_getParam('id', null);
$pageNumber = $this->_getParam('page', 1);
if (null === $id){
return $this->renderScript('comments/topic-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('post_id = ?', $id)->andWhere('spam = 0')->orderBy('id DESC');
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$tempModel = $query->fetchOne();
+ if (null == $tempModel){
+ return $this->renderScript('comments/topic-not-found.phtml');
+ }
$this->view->threadModel = $tempModel->getThreadModel();
$this->view->paginator = $paginator;
}
/**
* Marks given message as spam.
*/
public function spamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = true;
$comment->save();
/**
* @todo pass to the spam backend
*/
$this->_redirectBack($comment);
}
/**
* Unmarks given message as spam.
*/
public function hamAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->spam = false;
$comment->save();
/**
* @todo pass to the Spam backend
*/
$this->_redirectBack($comment);
}
/**
* Edit the comment.
*/
public function editAction()
{
$id = $this->_getParam('id', null);
$redirect = $this->_getParam('back', 'dashboard');
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$form = new Zend_Form();
$form->setAction($this->view->baseUrl('/fizzy/comment/edit/' . $comment->id . '?back=' . $redirect));
$form->addElement(new Zend_Form_Element_Text('name', array(
'label' => 'Author name'
)));
$form->addElement(new Zend_Form_Element_Text('email', array(
'label' => 'Author E-mail'
)));
$form->addElement(new Zend_Form_Element_Text('website', array(
'label' => 'Author website'
)));
$form->addElement(new Zend_Form_Element_Textarea('body', array(
'label' => 'Comment'
)));
$form->addElement(new Zend_Form_Element_Submit('save', array(
'label' => 'Save'
)));
if ($this->_request->isPost() && $form->isValid($_POST)){
$comment->name = $form->name->getValue();
$comment->email = $form->email->getValue();
$comment->website = $form->website->getValue();
$comment->body = $form->body->getValue();
$comment->save();
$this->_redirectBack($comment);
}
$form->name->setValue($comment->name);
$form->email->setValue($comment->email);
$form->website->setValue($comment->website);
$form->body->setValue($comment->body);
$this->view->form = $form;
$this->view->comment = $comment;
$this->view->back = $redirect;
}
/**
* Delete the comment.
*/
public function deleteAction()
{
$id = $this->_getParam('id', null);
if (null === $id){
return $this->renderScript('comments/comment-not-found.phtml');
}
$query = Doctrine_Query::create()->from('Comments')
->where('id = ?', $id);
$comment = $query->fetchOne();
if (null == $comment){
return $this->renderScript('comments/comment-not-found.phtml');
}
$comment->delete();
$this->_redirectBack($comment);
}
/**
* Approve the comment (when using moderation).
*/
public function approveAction()
{
}
/**
* Unapprove the given comment.
*/
public function unapproveAction()
{
}
/**
* Shows the spambox containing all spam comments
*/
public function spamboxAction()
{
$pageNumber = $this->_getParam('page', 1);
$query = Doctrine_Query::create()->from('Comments')->where('spam = ?', 1);
$paginator = new Zend_Paginator(new Fizzy_Paginator_Adapter_DoctrineQuery($query));
$paginator->setItemCountPerPage(10);
$paginator->setCurrentPageNumber($pageNumber);
$this->view->paginator = $paginator;
}
protected function _redirectBack(Comments $comment = null)
{
$redirect = $this->_getParam('back', 'dashboard');
switch($redirect){
case 'topic':
$this->_redirect('/fizzy/comments/topic/' . $comment->post_id);
break;
case 'spambox':
$this->_redirect('/fizzy/comments/spam');
break;
case 'post':
$postId = (int) substr($comment->post_id, 5);
$this->_redirect('/fizzy/post/' . $postId . '/edit');
default:
$this->_redirect('/fizzy/comments');
break;
}
}
}
diff --git a/application/modules/admin/views/scripts/comments/_comments.phtml b/application/modules/admin/views/scripts/comments/_comments.phtml
index 4f7da42..5c3a393 100644
--- a/application/modules/admin/views/scripts/comments/_comments.phtml
+++ b/application/modules/admin/views/scripts/comments/_comments.phtml
@@ -1,50 +1,50 @@
<?php foreach ($this->comments as $comment): ?>
<?php
$thread = $comment->getThreadModel();
?>
<div class="comment">
<div class="avatar">
<img src="http://www.gravatar.com/avatar/<?= md5(trim(strtolower($comment->email))) ?>?s=80" alt="<?= $comment->name ?>" />
</div>
<div class="content">
<div class="author-info">
<span class="gray1">From</span> <?= $comment->name ?>
<?= (!empty($thread)) ? '<span class="gray1">on</span> '.
$this->link('@admin_comments_topic?id=' . $comment->post_id,$thread->label()) : '' ?>
</div>
<div class="comment-body">
<?= $comment->body ?>
</div>
<div class="actions">
<ul>
<li>
- <?= $this->link('/fizzy/comment/edit/' . $comment->id . '?back=' . $this->back, 'Edit', array(
+ <?= $this->link('@admin_comments_edit?id=' . $comment->id . '&back=' . $this->back, 'Edit', array(
'class' => 'c3button'
)) ?>
</li>
<li>
<?php if ($comment->isSpam()) : ?>
- <?= $this->link('/fizzy/comment/ham/' . $comment->id . '?back=' . $this->back, 'Not spam', array(
+ <?= $this->link('@admin_comments_ham?id=' . $comment->id . '&back=' . $this->back, 'Not spam', array(
'class' => 'c3button'
)) ?>
<?php else: ?>
- <?= $this->link('/fizzy/comment/spam/' . $comment->id . '?back=' . $this->back, 'Spam', array(
+ <?= $this->link('@admin_comments_spam?id=' . $comment->id . '&back=' . $this->back, 'Spam', array(
'class' => 'c3button'
)) ?>
<?php endif; ?>
</li>
<li><?= $this->link(
- '/fizzy/comment/delete/' . $comment->id . '?back=' . $this->back,
+ '@admin_comments_delete?id=' . $comment->id . '&back=' . $this->back,
'Delete',
array(
'class' => 'delete c3button',
'confirm' => 'Are you sure you want to delete this comment?',
)
); ?>
</li>
</ul>
</div>
</div>
<div class="clear"></div>
</div>
<?php endforeach; ?>
diff --git a/application/modules/admin/views/scripts/comments/comment-not-found.phtml b/application/modules/admin/views/scripts/comments/comment-not-found.phtml
index e303127..bec1a44 100644
--- a/application/modules/admin/views/scripts/comments/comment-not-found.phtml
+++ b/application/modules/admin/views/scripts/comments/comment-not-found.phtml
@@ -1,2 +1,2 @@
<h2>Comment not found.</h2>
-<a href="<?= $this->baseUrl('/fizzy/comments/list') ?>">Back to discussion list</a>
+<?= $this->link('@admin_comments_list', 'Back to discussion list') ?>
diff --git a/application/modules/admin/views/scripts/comments/edit.phtml b/application/modules/admin/views/scripts/comments/edit.phtml
index 2b8045f..ba463ed 100644
--- a/application/modules/admin/views/scripts/comments/edit.phtml
+++ b/application/modules/admin/views/scripts/comments/edit.phtml
@@ -1,54 +1,54 @@
<form action="<?= $this->form->getAction(); ?>" method="post">
<div id="content-panel">
<h2>
Edit Comment
</h2>
<div class="form-panel">
<?= $this->form->name; ?>
<?= $this->form->email; ?>
<?= $this->form->website; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<li class="no-bg right">
<?= $this->link(
- '/fizzy/comment/delete/' . $this->comment->id,
+ '@admin_comments_delete?id=' . $this->comment->id,
$this->image('fizzy_assets/images/icon/document--minus.png') . ' delete comment',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this comment?',
'escape' => false
)
); ?>
</li>
<li class="no-bg right last">
<?= $this->link(
- '/fizzy/comments/topic/' . $this->comment->post_id,
+ '@admin_comments_topic?id=' . $this->comment->post_id,
$this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to comments',
array(
'escape' => false
)
); ?>
</li>
</ul>
</div>
</form>
diff --git a/application/modules/admin/views/scripts/comments/index.phtml b/application/modules/admin/views/scripts/comments/index.phtml
index b58cc62..2b99567 100644
--- a/application/modules/admin/views/scripts/comments/index.phtml
+++ b/application/modules/admin/views/scripts/comments/index.phtml
@@ -1,29 +1,29 @@
<div id="content-panel">
<h2>Latest comments</h2>
<?= $this->partial('comments/_comments.phtml', array(
'comments' => $this->paginator->getCurrentItems(),
'back' => 'dashboard'
)) ?>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
<div id="sidebar-panel">
<h2>Comments overview</h2>
<table class="data">
<tbody>
<tr>
- <td><a href="<?= $this->baseUrl('/fizzy/comments/list') ?>">Total comments</a></td>
+ <td><?= $this->link('@admin_comments_list', 'Total comments') ?></td>
<td><?= $this->totalComments ?></td>
</tr>
<tr>
- <td><a href="<?= $this->baseUrl('/fizzy/comments/spam') ?>">Spam</a></td>
+ <td><?= $this->link('@admin_comments_spambox', 'Spam') ?></td>
<td><?= $this->spamComments ?></td>
</tr>
</tbody>
</table>
</div>
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/topic-not-found.phtml b/application/modules/admin/views/scripts/comments/topic-not-found.phtml
index 0bda8ae..c9ea6ad 100644
--- a/application/modules/admin/views/scripts/comments/topic-not-found.phtml
+++ b/application/modules/admin/views/scripts/comments/topic-not-found.phtml
@@ -1,2 +1,2 @@
<h2>Topic not found.</h2>
-<a href="<?= $this->baseUrl('/fizzy/comments/list') ?>">Back to discussion list</a>
+<?= $this->link('@admin_comments_list', 'Back to discussion list') ?>
|
jtietema/Fizzy
|
50b7222465b0444c189fffd82ba71ebe18027811
|
styling comments
|
diff --git a/application/assets/css/fizzy-2.0.css b/application/assets/css/fizzy-2.0.css
index 4244fbc..7f4cfa6 100644
--- a/application/assets/css/fizzy-2.0.css
+++ b/application/assets/css/fizzy-2.0.css
@@ -1,545 +1,550 @@
/**
* Fizzy 2.0 Stylesheet
*
* Scheme: http://colorschemedesigner.com/#3D11TpE--l2br
* Scheme: http://colorschemedesigner.com/#3z21NBR..v5g0
*
* @author Mattijs Hoitink <[email protected]>
*/
/* ********************** */
/* HTML ELEMENTS */
html {
background-color: #F1EFE2;
}
body {
font: 75%/1.2 'Lucida Grande',Arial,Helvetica,sans-serif;
}
em { font-style: italic; }
a {
color: #3581C5;
text-decoration: none;
}
a:hover {
color: #033F75;
text-decoration: underline;
}
h1 { font-size: 150%; }
h2 { font-size: 140%; }
h3 { font-size: 120%; }
h4 { font-size: 110%; }
h5 {}
h6 {}
h1 ,h2, h3, h4, h5, h6, strong {
font-weight:bold;
}
h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
h3 {
margin-bottom: .3em;
padding-bottom: .2em;
border-bottom: 1px solid #E4E4E4;
}
p { margin-bottom: 1em; }
label {
display: block;
margin-bottom: .3em;
font-weight: bold;
}
fieldset {
display: block;
padding: 10px;
border: 1px groove #E4E4E4;
}
legend { color: #918A8A; }
input[type="text"], input[type="password"], input[type="email"], textarea {
width: 300px;
padding: 2px 4px;
border: 1px solid #918A8A;
}
input[type="text"].hasDatepicker {
width: auto;
}
#ui-datepicker-div {
z-index: 1000;
}
/* HTML ELEMENTS */
/* ********************** */
+.gray1 {
+ color: gray;
+}
+
+
/* ********************** */
/* BUTTONS */
.c3button, a.c3button {
display: inline-block;
padding: 5px 10px;
background: #222 url('../images/button-overlay.png') repeat-x;
-moz-box-shadow: 0 1px 3px 1px rgba(0,0,0,0.2);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px solid rgb(0,0,0,0.25);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
cursor: pointer;
background-color: #EBEBEB;
color: #666666;
}
a.c3button:hover {
text-decoration: none;
}
.c3button.large {
padding: 0.5em 1em;
font-size: 20px;
}
.c3button.orange {
background-color: #FF5C00;
color: #FFFFFF;
}
.c3button.green {
background-color: #20C519;
color: #FFFFFF;
}
.c3button.blue {
background-color: #195CC5;
color: #FFFFFF;
}
.c3button img {
position: relative;
top: 0.3em;
}
/* BUTTONS */
/* ********************** */
/* ********************** */
/* GENERAL CLASSES */
.fleft { float: left; }
.fright { float: right; }
.tleft { text-align: left; }
.tright { text-align: right; }
.tcenter { text-align: center; }
.clr, .clear {
height: 1px;
line-height: 1px;
font-size: 0;
clear: both;
}
#container {
background-color: #FFFFFF;
}
/* GENERAL CLASSES */
/* ********************** */
/* ********************** */
/* PANELS */
#header-panel {
position: relative;
background-color: #0A62B2;
color: #F8F8F8;
height: 5.3em;
margin: 0;
padding: 15px 30px 0 30px;
-moz-box-shadow: inset 0px -8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 -8px 6px -4px rgba(0,0,0,0.2);
}
#navigation-panel {
position: absolute;
bottom: -1px;
}
#main-panel {
position: relative;
min-height: 400px;
}
#messages-panel {
/*width: 400px;
position: absolute;
top: 0;
left: 50%;
margin-left: -200px;*/
min-height: 3em;
}
#content-panel {
margin: 0px 345px 10px 30px;
}
#sidebar-panel {
margin: 0px 30px 0 0;
min-height: 300px;
padding: 0;
position: absolute;
top: 0;
right: 0;
width: 300px;
z-index: 9;
}
#footer-panel {
height: 6em;
padding-top: 20px;
color: #999999;
/*-moz-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);*/
background: #F1EFE2 url(../images/footerbg.png) repeat-x scroll 0 0
}
#copyright-panel {
float: right;
margin: 10px 20px;
}
/* PANELS */
/* ********************** */
/* ********************** */
/* Login */
#login-panel {
position: absolute;
top: 50px;
left: 50%;
margin-left: -250px;
width: 500px;
padding: 10px;
background-color: #FFFFFF;
border: 1px solid #E9E9E9;
-moz-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
}
#login-panel h1 {
display: block;
padding: 15px 10px;
background-color: #0A62B2;
color: #F8F8F8;
}
/* Login */
/* ********************** */
/* ********************** */
/* NAVIGATION */
#navigation-panel ul li {
float: left;
list-style-type: none;
margin: 0 2px 0 0;
padding: 0;
white-space: nowrap;
}
#navigation-panel ul li a {
color: #FFFFFF;
display: block;
margin: 0;
padding: 4px 10px;
text-decoration: none;
}
#navigation-panel ul li.active a, #navigation-panel ul li.active a:hover {
background-color: #FFFFFF;
color: #555555;
}
#navigation-panel ul li a:hover {
color: #FFFFFF;
background-color: #3581C5;
}
#sub-navigation-panel {
margin-left: 20px;
margin-right: 20px;
margin-top: 10px;
padding-bottom: 5px;
height: 16px;
border-bottom: 1px solid #E4E4E4;
}
#sub-navigation-panel ul li {
display: inline;
list-style-type: none;
padding-right: 20px;
font-weight: bold;
}
#sub-navigation-panel ul li.active a {
text-decoration: underline;
}
/* NAVIGATION */
/* ********************** */
/* ********************** */
/* MESSAGES */
#messages-panel #messages {
padding: 1em 2.5em;
}
#messages-panel .message {
position: relative;
}
#messages-panel .message .message-close {
position: absolute;
right: 10px;
top: 10px;
}
.error, .notice, .success, .info { padding: .8em; border: 1px solid #ddd; }
.error { background: #E22C33; color: #440A09; border-color: #B20A0A; }
.notice { background: #E2CC2C; color: #443E09; border-color: #B28C0A; }
.success { background: #2CE23D; color: #264409; border-color: #22B20A; }
.info { background: #2C88E2; color: #091144; border-color: #0A1AB2; }
.error a { color: #8a1f11; }
.notice a { color: #514721; }
.success a { color: #264409; }
.info a { color: #193D88; }
/* MESSAGES */
/* ********************** */
/* ********************** */
/* CONTENT */
#content-panel h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
#content-panel h2 img {
float: left;
margin-top: 2px;
margin-right: 10px;
}
.details-panel {
margin-bottom: 2em;
padding: 1.5em;
background-color: #ECEEEC;
}
/* CONTENT */
/* ********************** */
/* ********************** */
/* SIDEBAR */
#sidebar-panel .block {
display: block;
margin-bottom: 20px;
}
#sidebar-panel .block h2 {}
#sidebar-panel .block p, #sidebar-panel .block .content {
margin: 1em;
}
#sidebar-panel hr {
margin: 1.5em .5em;
background-color: #E4E4E4;
border: 0;
height: 1px;
}
/* actions */
#sidebar-panel ul.actions {
margin: .5em;
}
#sidebar-panel ul.actions li {
padding: 0.7em 1em;
margin: 0;
background-color: #EFEFEF;
border-collapse: collapse;
border-top: 1px solid #FFFFFF;
border-bottom: 1px solid #D4D4D4;
}
#sidebar-panel ul.actions li.no-bg {
background-color: transparent;
border: 0;
}
#sidebar-panel ul.actions li.last {
border-bottom: 0;
}
#sidebar-panel ul.actions li a,
#sidebar-panel ul.actions li input[type="submit"]
{}
#sidebar-panel ul.actions li a.delete {
color: #8D3134;
text-decoration: underline;
}
#sidebar-panel ul.actions li img {
float: left;
margin-top: -1px;
margin-right: 1em;
}
#sidebar-panel ul.actions li.right {
text-align: right;
}
#sidebar-panel ul.actions li.right img {
float: right;
margin-right: 0;
margin-left: 1em;
}
/* SIDEBAR */
/* ********************** */
/* ********************** */
/* MEDIA */
#media-panel {}
#media-tabs-panel {}
#media-tabs-panel ul {
margin: 0;
padding: 0;
list-style: none;
}
#media-tabs-panel ul li {
display: inline-block;
}
#media-panel .media-container {
overflow: auto;
margin: 0;
padding-bottom: 10px;
height: 390px;
border: 1px solid #DEDEDE;
background-color: #ECEEEC;
/*-moz-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);*/
}
#media-panel .media-container div.thumbnail {
position: relative;
float:left;
margin: 1em 0 0 1em;
padding: 5px 10px;
border: solid 1px black;
background-color: white;
width: 140px;
height: 140px;
}
#media-panel .media-container div.thumbnail div.head {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.head .filename {
float: left;
}
#media-panel .media-container div.thumbnail div.head .remove {
float: right;
}
#media-panel .media-container div.thumbnail div.body {
height: 100px;
line-height: 100px;
background-color: #E9EEF0;
border: solid 1px black;
}
#media-panel .media-container div.thumbnail div.body a,
#media-panel .media-container div.thumbnail div.body a:link,
#media-panel .media-container div.thumbnail div.body a:active,
#media-panel .media-container div.thumbnail div.body a:visited
{
display: block;
vertical-align: middle;
text-align: center;
}
#media-panel .media-container div.thumbnail div.body img {
margin: 0 -4px 0 4px;
}
#media-panel .media-container div.thumbnail img.source {
max-width: 120px;
max-height: 80px;
vertical-align: middle;
}
#media-panel .media-container div.thumbnail img.icon {
vertical-align: middle;
}
#media-panel .media-container div.thumbnail div.foot {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.foot .size {
float: right;
display: block;
}
/* MEDIA */
/* ********************** */
/* ********************** */
/* COMMENTS */
.comments {
margin-top: 10px;
margin-bottom: 10px;
}
.comment {
position: relative;
- border: solid 1px gray;
+ border: solid 1px #E4E4E4;
margin-bottom:10px;
}
.comment .avatar {
float: left;
padding: 10px;
}
.comment .content {
float:left;
padding: 10px;
}
.comment .content .author-info {
margin-bottom: 5px;
}
.comment .content .actions {
margin-top: 10px;
}
.comment .content .actions li {
display: inline;
list-style-type: none;
padding-right: 20px;
}
\ No newline at end of file
diff --git a/application/modules/admin/views/scripts/comments/_comments.phtml b/application/modules/admin/views/scripts/comments/_comments.phtml
index 787bffd..4f7da42 100644
--- a/application/modules/admin/views/scripts/comments/_comments.phtml
+++ b/application/modules/admin/views/scripts/comments/_comments.phtml
@@ -1,48 +1,50 @@
<?php foreach ($this->comments as $comment): ?>
<?php
$thread = $comment->getThreadModel();
?>
<div class="comment">
<div class="avatar">
<img src="http://www.gravatar.com/avatar/<?= md5(trim(strtolower($comment->email))) ?>?s=80" alt="<?= $comment->name ?>" />
</div>
<div class="content">
<div class="author-info">
- From <?= $comment->name ?> <?= (!empty($thread)) ? 'on '.$thread->label() : '' ?>
+ <span class="gray1">From</span> <?= $comment->name ?>
+ <?= (!empty($thread)) ? '<span class="gray1">on</span> '.
+ $this->link('@admin_comments_topic?id=' . $comment->post_id,$thread->label()) : '' ?>
</div>
<div class="comment-body">
<?= $comment->body ?>
</div>
<div class="actions">
<ul>
<li>
<?= $this->link('/fizzy/comment/edit/' . $comment->id . '?back=' . $this->back, 'Edit', array(
'class' => 'c3button'
)) ?>
</li>
<li>
<?php if ($comment->isSpam()) : ?>
<?= $this->link('/fizzy/comment/ham/' . $comment->id . '?back=' . $this->back, 'Not spam', array(
'class' => 'c3button'
)) ?>
<?php else: ?>
<?= $this->link('/fizzy/comment/spam/' . $comment->id . '?back=' . $this->back, 'Spam', array(
'class' => 'c3button'
)) ?>
<?php endif; ?>
</li>
<li><?= $this->link(
'/fizzy/comment/delete/' . $comment->id . '?back=' . $this->back,
'Delete',
array(
'class' => 'delete c3button',
'confirm' => 'Are you sure you want to delete this comment?',
)
); ?>
</li>
</ul>
</div>
</div>
<div class="clear"></div>
</div>
<?php endforeach; ?>
diff --git a/application/modules/admin/views/scripts/comments/list.phtml b/application/modules/admin/views/scripts/comments/list.phtml
index 72f1f6c..f68bcb6 100644
--- a/application/modules/admin/views/scripts/comments/list.phtml
+++ b/application/modules/admin/views/scripts/comments/list.phtml
@@ -1,34 +1,34 @@
<div id="content-panel">
<h2>Discussions</h2>
<div>
<table class="data" id="pages-table">
<thead>
<tr>
<td> </td>
<td>Title</td>
<td>Number comments</td>
</tr>
</thead>
<tbody>
<?php foreach ($this->paginator->getCurrentItems() as $topic): ?>
<tr>
<td class="controls">
</td>
- <td><a href="<?= $this->baseUrl('/fizzy/comments/topic/' . $topic->post_id) ?>"><?= $topic->getThreadModel()->label() ?></a></td>
+ <td><?= $this->link('@admin_comments_topic?id=' . $topic->post_id, $topic->getThreadModel()->label()) ?></td>
<td><?= $topic->getNumberTopicComments() ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?= $this->paginationControl($this->paginator, 'All', '_pagination.phtml') ?>
</div>
</div>
<div id="sidebar-panel">
</div>
|
jtietema/Fizzy
|
70c954444756c403243747ac5b59cf6df7fea58f
|
improvements in sub-navigation
|
diff --git a/application/assets/css/fizzy-2.0.css b/application/assets/css/fizzy-2.0.css
index a1364dd..4244fbc 100644
--- a/application/assets/css/fizzy-2.0.css
+++ b/application/assets/css/fizzy-2.0.css
@@ -1,539 +1,545 @@
/**
* Fizzy 2.0 Stylesheet
*
* Scheme: http://colorschemedesigner.com/#3D11TpE--l2br
* Scheme: http://colorschemedesigner.com/#3z21NBR..v5g0
*
* @author Mattijs Hoitink <[email protected]>
*/
/* ********************** */
/* HTML ELEMENTS */
html {
background-color: #F1EFE2;
}
body {
font: 75%/1.2 'Lucida Grande',Arial,Helvetica,sans-serif;
}
em { font-style: italic; }
a {
color: #3581C5;
text-decoration: none;
}
a:hover {
color: #033F75;
text-decoration: underline;
}
h1 { font-size: 150%; }
h2 { font-size: 140%; }
h3 { font-size: 120%; }
h4 { font-size: 110%; }
h5 {}
h6 {}
h1 ,h2, h3, h4, h5, h6, strong {
font-weight:bold;
}
h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
h3 {
margin-bottom: .3em;
padding-bottom: .2em;
border-bottom: 1px solid #E4E4E4;
}
p { margin-bottom: 1em; }
label {
display: block;
margin-bottom: .3em;
font-weight: bold;
}
fieldset {
display: block;
padding: 10px;
border: 1px groove #E4E4E4;
}
legend { color: #918A8A; }
input[type="text"], input[type="password"], input[type="email"], textarea {
width: 300px;
padding: 2px 4px;
border: 1px solid #918A8A;
}
input[type="text"].hasDatepicker {
width: auto;
}
#ui-datepicker-div {
z-index: 1000;
}
/* HTML ELEMENTS */
/* ********************** */
/* ********************** */
/* BUTTONS */
.c3button, a.c3button {
display: inline-block;
padding: 5px 10px;
background: #222 url('../images/button-overlay.png') repeat-x;
-moz-box-shadow: 0 1px 3px 1px rgba(0,0,0,0.2);
-webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.2);
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border: 1px solid rgb(0,0,0,0.25);
text-shadow: 0 -1px 1px rgba(0,0,0,0.25);
cursor: pointer;
background-color: #EBEBEB;
color: #666666;
}
a.c3button:hover {
text-decoration: none;
}
.c3button.large {
padding: 0.5em 1em;
font-size: 20px;
}
.c3button.orange {
background-color: #FF5C00;
color: #FFFFFF;
}
.c3button.green {
background-color: #20C519;
color: #FFFFFF;
}
.c3button.blue {
background-color: #195CC5;
color: #FFFFFF;
}
.c3button img {
position: relative;
top: 0.3em;
}
/* BUTTONS */
/* ********************** */
/* ********************** */
/* GENERAL CLASSES */
.fleft { float: left; }
.fright { float: right; }
.tleft { text-align: left; }
.tright { text-align: right; }
.tcenter { text-align: center; }
.clr, .clear {
height: 1px;
line-height: 1px;
font-size: 0;
clear: both;
}
#container {
background-color: #FFFFFF;
}
/* GENERAL CLASSES */
/* ********************** */
/* ********************** */
/* PANELS */
#header-panel {
position: relative;
background-color: #0A62B2;
color: #F8F8F8;
height: 5.3em;
margin: 0;
padding: 15px 30px 0 30px;
-moz-box-shadow: inset 0px -8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0 -8px 6px -4px rgba(0,0,0,0.2);
}
#navigation-panel {
position: absolute;
bottom: -1px;
}
#main-panel {
position: relative;
min-height: 400px;
}
#messages-panel {
/*width: 400px;
position: absolute;
top: 0;
left: 50%;
margin-left: -200px;*/
min-height: 3em;
}
#content-panel {
margin: 0px 345px 10px 30px;
}
#sidebar-panel {
margin: 0px 30px 0 0;
min-height: 300px;
padding: 0;
position: absolute;
top: 0;
right: 0;
width: 300px;
z-index: 9;
}
#footer-panel {
height: 6em;
padding-top: 20px;
color: #999999;
/*-moz-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 0px 8px 6px -4px rgba(0,0,0,0.2);*/
background: #F1EFE2 url(../images/footerbg.png) repeat-x scroll 0 0
}
#copyright-panel {
float: right;
margin: 10px 20px;
}
/* PANELS */
/* ********************** */
/* ********************** */
/* Login */
#login-panel {
position: absolute;
top: 50px;
left: 50%;
margin-left: -250px;
width: 500px;
padding: 10px;
background-color: #FFFFFF;
border: 1px solid #E9E9E9;
-moz-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
-webkit-box-shadow: 4px 4px 6px -4px rgba(0,0,0,0.2);
}
#login-panel h1 {
display: block;
padding: 15px 10px;
background-color: #0A62B2;
color: #F8F8F8;
}
/* Login */
/* ********************** */
/* ********************** */
/* NAVIGATION */
#navigation-panel ul li {
float: left;
list-style-type: none;
margin: 0 2px 0 0;
padding: 0;
white-space: nowrap;
}
#navigation-panel ul li a {
color: #FFFFFF;
display: block;
margin: 0;
padding: 4px 10px;
text-decoration: none;
}
#navigation-panel ul li.active a, #navigation-panel ul li.active a:hover {
background-color: #FFFFFF;
color: #555555;
}
#navigation-panel ul li a:hover {
color: #FFFFFF;
background-color: #3581C5;
}
-#sub-navigation-panel ul {
+#sub-navigation-panel {
margin-left: 20px;
+ margin-right: 20px;
margin-top: 10px;
padding-bottom: 5px;
+ height: 16px;
border-bottom: 1px solid #E4E4E4;
}
#sub-navigation-panel ul li {
display: inline;
list-style-type: none;
padding-right: 20px;
font-weight: bold;
}
+#sub-navigation-panel ul li.active a {
+ text-decoration: underline;
+}
+
/* NAVIGATION */
/* ********************** */
/* ********************** */
/* MESSAGES */
#messages-panel #messages {
padding: 1em 2.5em;
}
#messages-panel .message {
position: relative;
}
#messages-panel .message .message-close {
position: absolute;
right: 10px;
top: 10px;
}
.error, .notice, .success, .info { padding: .8em; border: 1px solid #ddd; }
.error { background: #E22C33; color: #440A09; border-color: #B20A0A; }
.notice { background: #E2CC2C; color: #443E09; border-color: #B28C0A; }
.success { background: #2CE23D; color: #264409; border-color: #22B20A; }
.info { background: #2C88E2; color: #091144; border-color: #0A1AB2; }
.error a { color: #8a1f11; }
.notice a { color: #514721; }
.success a { color: #264409; }
.info a { color: #193D88; }
/* MESSAGES */
/* ********************** */
/* ********************** */
/* CONTENT */
#content-panel h2 {
margin-bottom: 1em;
border-bottom: 1px solid #E4E4E4;
}
#content-panel h2 img {
float: left;
margin-top: 2px;
margin-right: 10px;
}
.details-panel {
margin-bottom: 2em;
padding: 1.5em;
background-color: #ECEEEC;
}
/* CONTENT */
/* ********************** */
/* ********************** */
/* SIDEBAR */
#sidebar-panel .block {
display: block;
margin-bottom: 20px;
}
#sidebar-panel .block h2 {}
#sidebar-panel .block p, #sidebar-panel .block .content {
margin: 1em;
}
#sidebar-panel hr {
margin: 1.5em .5em;
background-color: #E4E4E4;
border: 0;
height: 1px;
}
/* actions */
#sidebar-panel ul.actions {
margin: .5em;
}
#sidebar-panel ul.actions li {
padding: 0.7em 1em;
margin: 0;
background-color: #EFEFEF;
border-collapse: collapse;
border-top: 1px solid #FFFFFF;
border-bottom: 1px solid #D4D4D4;
}
#sidebar-panel ul.actions li.no-bg {
background-color: transparent;
border: 0;
}
#sidebar-panel ul.actions li.last {
border-bottom: 0;
}
#sidebar-panel ul.actions li a,
#sidebar-panel ul.actions li input[type="submit"]
{}
#sidebar-panel ul.actions li a.delete {
color: #8D3134;
text-decoration: underline;
}
#sidebar-panel ul.actions li img {
float: left;
margin-top: -1px;
margin-right: 1em;
}
#sidebar-panel ul.actions li.right {
text-align: right;
}
#sidebar-panel ul.actions li.right img {
float: right;
margin-right: 0;
margin-left: 1em;
}
/* SIDEBAR */
/* ********************** */
/* ********************** */
/* MEDIA */
#media-panel {}
#media-tabs-panel {}
#media-tabs-panel ul {
margin: 0;
padding: 0;
list-style: none;
}
#media-tabs-panel ul li {
display: inline-block;
}
#media-panel .media-container {
overflow: auto;
margin: 0;
padding-bottom: 10px;
height: 390px;
border: 1px solid #DEDEDE;
background-color: #ECEEEC;
/*-moz-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);
-webkit-box-shadow: inset 2px 4px 4px -1px rgba(0,0,0,0.2);*/
}
#media-panel .media-container div.thumbnail {
position: relative;
float:left;
margin: 1em 0 0 1em;
padding: 5px 10px;
border: solid 1px black;
background-color: white;
width: 140px;
height: 140px;
}
#media-panel .media-container div.thumbnail div.head {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.head .filename {
float: left;
}
#media-panel .media-container div.thumbnail div.head .remove {
float: right;
}
#media-panel .media-container div.thumbnail div.body {
height: 100px;
line-height: 100px;
background-color: #E9EEF0;
border: solid 1px black;
}
#media-panel .media-container div.thumbnail div.body a,
#media-panel .media-container div.thumbnail div.body a:link,
#media-panel .media-container div.thumbnail div.body a:active,
#media-panel .media-container div.thumbnail div.body a:visited
{
display: block;
vertical-align: middle;
text-align: center;
}
#media-panel .media-container div.thumbnail div.body img {
margin: 0 -4px 0 4px;
}
#media-panel .media-container div.thumbnail img.source {
max-width: 120px;
max-height: 80px;
vertical-align: middle;
}
#media-panel .media-container div.thumbnail img.icon {
vertical-align: middle;
}
#media-panel .media-container div.thumbnail div.foot {
height: 20px;
line-height: 20px;
}
#media-panel .media-container div.thumbnail div.foot .size {
float: right;
display: block;
}
/* MEDIA */
/* ********************** */
/* ********************** */
/* COMMENTS */
.comments {
margin-top: 10px;
margin-bottom: 10px;
}
.comment {
position: relative;
border: solid 1px gray;
margin-bottom:10px;
}
.comment .avatar {
float: left;
padding: 10px;
}
.comment .content {
float:left;
padding: 10px;
}
.comment .content .author-info {
margin-bottom: 5px;
}
.comment .content .actions {
margin-top: 10px;
}
.comment .content .actions li {
display: inline;
list-style-type: none;
padding-right: 20px;
}
\ No newline at end of file
diff --git a/application/modules/admin/controllers/IndexController.php b/application/modules/admin/controllers/IndexController.php
index 7ee1f17..e3853a8 100644
--- a/application/modules/admin/controllers/IndexController.php
+++ b/application/modules/admin/controllers/IndexController.php
@@ -1,194 +1,197 @@
<?php
/**
* Class Admin_IndexController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/**
* Class Admin_IndexController
*
* @author Mattijs Hoitink <[email protected]>
*/
class Admin_IndexController extends Fizzy_SecuredController
{
protected $_sessionNamespace = 'fizzy';
protected $_redirect = '/fizzy/login';
protected $_navigation = null;
/**
* Default action redirects to Pages overview.
*/
public function indexAction()
{
$this->_redirect('/fizzy/pages');
}
public function configurationAction()
{
$this->view->config = Zend_Registry::get('config')->toArray();
$this->renderScript('configuration.phtml');
}
/**
* Renders navigation for the admin section.
*/
public function navigationAction()
{
if (null === $this->_navigation){
$this->_navigation = $this->_createNavigation();
}
$this->view->items = $this->_navigation->getPages();
$this->renderScript('navigation.phtml');
}
public function subnavigationAction()
{
if (null === $this->_navigation){
$this->_navigation = $this->_createNavigation();
}
$this->view->items = array();
foreach ($this->_navigation->getPages() as $page){
if ($page->isActive(true)){
$this->view->items = $page->getPages();
break;
}
}
$this->renderScript('subnavigation.phtml');
}
protected function _createNavigation()
{
$items = array();
// Blog
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Blogs',
'route' => 'admin_blogs',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_blog',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'label' => 'Edit Post',
'route' => 'admin_blog_post_edit',
)),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Add Post',
'route' => 'admin_blog_post_add',
))
)
))
)
));
// Comments
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Comments',
'route' => 'admin_comments',
'pages' => array(
+ new Fizzy_Navigation_Page_Route(array(
+ 'label' => 'Dashboard',
+ 'route' => 'admin_comments'
+ )),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Thread list',
'route' => 'admin_comments_list',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
'label' => 'Show thread',
'route' => 'admin_comments_topic',
))
)
)),
new Fizzy_Navigation_Page_Route(array(
'label' => 'Spambox',
'route' => 'admin_comments_spambox',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_comments_edit',
))
)
));
// Pages
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Pages',
'route' => 'admin_pages',
'pages' => array(
new Fizzy_Navigation_Page_Route(array(
- 'label' => 'Add page',
'route' => 'admin_pages_add',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_pages_edit',
)),
)
));
// Media
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Media',
'route' => 'admin_media',
));
// Contact
$contactLogSetting = Setting::getKey('log', 'contact');
if (null !== $contactLogSetting && 1 == $contactLogSetting->value) {
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Contact',
'route' => 'admin_contact',
'pages' => array (
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_contact_show',
))
)
));
}
// Users
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Users',
'route' => 'admin_users',
'pages' => array (
new Fizzy_Navigation_Page_Route(array(
'label' => 'Add user',
'route' => 'admin_users_add',
)),
new Fizzy_Navigation_Page_Route(array(
'route' => 'admin_users_edit',
)),
)
));
// Settings
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Settings',
'route' => 'admin_settings',
));
// Logout
$items[] = new Fizzy_Navigation_Page_Route(array(
'label' => 'Logout',
'route' => 'admin_logout',
));
return new Zend_Navigation($items);
}
}
diff --git a/library/Fizzy/Validate/SlugUnique.php b/library/Fizzy/Validate/SlugUnique.php
index c9498ca..45ce859 100644
--- a/library/Fizzy/Validate/SlugUnique.php
+++ b/library/Fizzy/Validate/SlugUnique.php
@@ -1,67 +1,67 @@
<?php
/**
* Class Fizzy_Validate_SlugUnique
* @category Fizzy
* @package Fizzy_Validate
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
/** Zend_Validate_Abstract */
require_once 'Zend/Validate/Abstract.php';
/**
- * Form validator to check if a page slug is unique. Advises the Fizzy_Storage
- * to check this.
+ * Form validator to check if a page slug is unique.
*
* @author Mattijs Hoitink <[email protected]>
*/
class Fizzy_Validate_SlugUnique extends Zend_Validate_Abstract
{
const NOT_UNIQUE = 'notUnique';
protected $_messageTemplates = array (
self::NOT_UNIQUE => 'Slug is not unique.'
);
/** **/
/**
- * Check if a username is valid (unique).
+ * Check if a slug is unique.
+ *
* @param string $value
* @return boolean
*/
public function isValid($value, $context = null)
{
$value = (string) $value;
$this->_setValue($value);
$query = Doctrine_Query::create()->from('Page')->where('slug = ?', $value);
$pages = $query->fetchArray();
// we already have multiple items with this slug (should never occur).
if (count($pages) > 1){
$this->_error(self::NOT_UNIQUE);
return false;
}
-
+
// check if the found slug belongs to the current document. If not return false.
if (count($pages) === 1 && $context['id'] !== $pages[0]['id']) {
$this->_error(self::NOT_UNIQUE);
return false;
}
return true;
}
}
|
jtietema/Fizzy
|
67bb795f4c8f95de41f4b5d1c914d8c2349d1e83
|
bug fix in saving pages
|
diff --git a/application/modules/admin/views/scripts/pages/form.phtml b/application/modules/admin/views/scripts/pages/form.phtml
index a25dce2..b1cf2cb 100644
--- a/application/modules/admin/views/scripts/pages/form.phtml
+++ b/application/modules/admin/views/scripts/pages/form.phtml
@@ -1,68 +1,69 @@
<form action="<?= $this->form->getAction(); ?>" method="post" id="PageForm" name="PageForm">
<div id="content-panel">
<h2>
<?= $this->image('/fizzy_assets/images/icon/document.png'); ?>
<?= ($this->page->isNew()) ? 'Add page' : 'Edit page'; ?>
</h2>
<div class="form-panel">
+ <?= $this->form->id; // required for slugunique validator ?>
<?= $this->form->title; ?>
<?= $this->form->slug; ?>
<?= $this->form->body; ?>
</div>
</div>
<div id="sidebar-panel">
<h2>Actions</h2>
<ul class="actions">
<li class="last">
<input type="submit" value="Save" />
</li>
</ul>
<hr />
<ul class="actions">
<?php if(!$this->page->isNew()) : ?>
<li class="no-bg right">
<?= $this->link(
'/fizzy/pages/delete/' . $this->page->id,
$this->image('fizzy_assets/images/icon/document--minus.png') . ' delete page',
array(
'class' => 'delete',
'confirm' => 'Are you sure you want to delete this page?',
'escape' => false
)
); ?>
</li>
<?php endif; ?>
<li class="no-bg right last">
<?= $this->link(
'/fizzy/pages',
$this->image('/fizzy_assets/images/icon/edit-list.png') . ' back to pages',
array('escape' => false)
); ?>
</li>
</ul>
<h2>Options</h2>
<div class="form-options-panel">
<?= $this->form->template; ?>
<?= $this->form->layout; ?>
<div class="form-row" id="homepage-row">
<label for="homepage">Homepage</label>
<?= $this->form->homepage->setDecorators(array('ViewHelper', 'Errors')); ?>
<?= $this->form->homepage->getDescription(); ?>
</div>
</div>
</div>
</form>
|
jtietema/Fizzy
|
f8bd1a0a3471c18bec32f50507b1f401fe90bc94
|
editing a user doesn't require re-entry of password
|
diff --git a/application/models/User.php b/application/models/User.php
index 2b9d1a4..d810fa5 100644
--- a/application/models/User.php
+++ b/application/models/User.php
@@ -1,28 +1,30 @@
<?php
/**
* User
*
* This class has been auto-generated by the Doctrine ORM Framework
*
* @package ##PACKAGE##
* @subpackage ##SUBPACKAGE##
* @author ##NAME## <##EMAIL##>
* @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $
*/
class User extends BaseUser
{
public function populate($array)
{
$this->username = $array['username'];
- $this->password = $array['password'];
+ if (!empty($array['password'])){
+ $this->password = $array['password'];
+ }
$this->displayname = $array['displayname'];
$this->encryption = $array['encryption'];
return $this;
}
public function isNew()
{
return empty($this->id);
}
}
diff --git a/application/modules/admin/controllers/UserController.php b/application/modules/admin/controllers/UserController.php
index c6f1c99..64ec4ad 100644
--- a/application/modules/admin/controllers/UserController.php
+++ b/application/modules/admin/controllers/UserController.php
@@ -1,165 +1,165 @@
<?php
/**
* Class Admin_UserController
* @category Fizzy
* @package Admin
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://www.voidwalkers.nl/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @copyright Copyright (c) 2009-2010 Voidwalkers (http://www.voidwalkers.nl)
* @license http://www.voidwalkers.nl/license/new-bsd The New BSD License
*/
class Admin_UserController extends Fizzy_SecuredController
{
protected $_sessionNamespace = 'fizzy';
protected $_redirect = '/fizzy/login';
public function indexAction()
{
$query = Doctrine_Query::create()->from('User');
$users = $query->fetchArray();
$this->view->users = $users;
$this->renderScript('/user/list.phtml');
}
public function addAction()
{
$user = new User();
$form = $this->_getForm($this->view->baseUrl('/fizzy/user/add'), $user);
+ $form->password->setRequired(true);
+ $form->password_confirm->setRequired(true);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$user->populate($form->getValues());
$user->save();
$this->addSuccessMessage("User {$user->username} was successfully saved.");
$this->_redirect('/fizzy/users', array('prependBase' => true));
}
}
$this->view->user = $user;
$this->view->form = $form;
$this->renderScript('/user/form.phtml');
}
public function editAction()
{
$id = $this->_getParam('id', null);
if(null === $id) {
$this->_redirect('/fizzy/users', array('prependBase' => true));
}
$query = Doctrine_Query::create()->from('User')->where('id = ?', $id);
$user = $query->fetchOne();
if(null === $user) {
$this->addErrorMessage("User with ID {$id} could not be found.");
$this->_redirect('/fizzy/users', array('prependBase' => true));
}
$form = $this->_getForm($this->view->baseUrl('/fizzy/user/edit/' . $user->id), $user);
if($this->_request->isPost()) {
if($form->isValid($_POST)) {
$user->populate($form->getValues());
$user->save();
$this->addSuccessMessage("User <strong>{$user->username}</strong> was successfully saved.");
$this->_redirect('/fizzy/users', array('prependBase' => true));
}
}
$this->view->user = $user;
$this->view->form = $form;
$this->renderScript('user/form.phtml');
}
public function deleteAction()
{
$id = $this->_getParam('id', null);
if(null !== $id) {
$query = Doctrine_Query::create()->from('User')->where('id = ?', $id);
$user = $query->fetchOne();
if(null !== $user) {
$user->delete();
$this->addSuccessMessage("User {$user->username} was successfully deleted.");
}
$this->_redirect('/fizzy/users', array('prependBase' => true));
}
}
protected function _getForm($action, User $user)
{
$passwordConfirm = new Fizzy_Validate_EqualsField();
$passwordConfirm->setOppositeField('password_confirm');
$passwordConfirm->setFieldName('Password');
$formConfig = array (
'action' => $action,
'elements' => array (
'id' => array (
'type' => 'hidden',
'options' => array (
'required' => false,
'value' => $user->id
)
),
'username' => array (
'type' => 'text',
'options' => array (
'label' => 'Username',
'required' => true,
'value' => $user->username,
'validators' => array (
'usernameUnique'
)
)
),
'displayname' => array(
'type' => 'text',
'options' => array(
'label' => 'Display name',
'required' => true,
'value' => $user->displayname
)
),
'password' => array (
'type' => 'password',
'options' => array (
'label' => 'Password',
- 'required' => true,
'validators' => array (
$passwordConfirm
)
),
),
'password_confirm' => array (
'type' => 'password',
'options' => array (
'label' => 'Confirm password',
- 'required' => true,
'ignore' => true,
)
),
'submit' => array (
'type' => 'submit',
'options' => array (
'label' => 'Save',
'ignore' => true
)
),
),
);
return new Fizzy_Form(new Zend_Config($formConfig));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.