repo
string
commit
string
message
string
diff
string
numpy/numpy.org
c313a1e715890bf69002ec88511b5f6cd5f46ae1
Use new grid syntax (#733)
diff --git a/content/en/_index.md b/content/en/_index.md index 55bbace..8f69427 100644 --- a/content/en/_index.md +++ b/content/en/_index.md @@ -1,49 +1,49 @@ --- title: --- -{{< grid columns="1 2 2 3" >}} +{{< grid1 columns="1 2 2 3" >}} -{{< card >}} +[[item]] +type = 'card' title = 'Powerful N-dimensional arrays' body = ''' Fast and versatile, the NumPy vectorization, indexing, and broadcasting concepts are the de-facto standards of array computing today. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Numerical computing tools' body = ''' NumPy offers comprehensive mathematical functions, random number generators, linear algebra routines, Fourier transforms, and more. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Open source' body = ''' Distributed under a liberal [BSD license](https://github.com/numpy/numpy/blob/main/LICENSE.txt), NumPy is developed and maintained [publicly on GitHub](https://github.com/numpy/numpy) by a vibrant, responsive, and diverse [community](/community). ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Interoperable' body = ''' NumPy supports a wide range of hardware and computing platforms, and plays well with distributed, GPU, and sparse array libraries. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Performant' body = ''' The core of NumPy is well-optimized C code. Enjoy the flexibility of Python with the speed of compiled code. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Easy to use' body = ''' NumPy's high level syntax makes it accessible and productive for programmers from any background or experience level. ''' -{{< /card >}} -{{< /grid >}} +{{< /grid1>}} diff --git a/content/ja/_index.md b/content/ja/_index.md index 38abb8c..192989e 100644 --- a/content/ja/_index.md +++ b/content/ja/_index.md @@ -1,52 +1,52 @@ --- title: --- -{{< grid columns="1 2 2 3" >}} +{{< grid1 columns="1 2 2 3" >}} -{{< card >}} +[[item]] +type = 'card' title = '強力な多次元配列' body = ''' NumPyの高速で多機能なベクトル化計算、インデックス処理、ブロードキャストの考え方は、現在の配列計算におけるデファクト・スタ>ンダードです。 ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = '数値計算ツール群' body = ''' NumPyは、様々な数学関数、乱数生成器、線形代数ルーチン、フーリエ変換などを提供しています。 ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = '相互運用性' body = ''' NumPyは、幅広いハードウェアとコンピューティング・プラットフォームをサポートしており、分散処理、GPU、疎行列ライブラリにも対 応しています。 ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = '高パフォーマンス' body = ''' NumPyの大部分は最適化されたC言語のコードで構成されています。これによりPythonの柔軟性とコンパイルされたコードの高速性の両方 を享受できます。 ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = '使いやすさ' body = ''' NumPyの高水準なシンタックスは、どんなバックグラウンドや経験を持つのプログラマーでも簡単に利用することができ、生産性を高め>ることができます。 ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'オープンソース' body = ''' NumPyは、寛容な[BSDライセンス](https://github.com/numpy/numpy/blob/main/LICENSE.txt)で公開されています。NumPyは活発で、互>いを尊重し、多様性を認め合う[コミュニティ](/ja/community)によって、 [GitHub](https://github.com/numpy/numpy)上でオープンに開発されていま す. ''' -{{< /card >}} -{{< /grid >}} +{{< /grid1 >}} diff --git a/content/pt/_index.md b/content/pt/_index.md index 3c58e7c..db817f5 100644 --- a/content/pt/_index.md +++ b/content/pt/_index.md @@ -1,49 +1,49 @@ --- title: --- -{{< grid columns="1 2 2 3" >}} +{{< grid1 columns="1 2 2 3" >}} -{{< card >}} +[[item]] +type = 'card' title = 'Arrays n-dimensionais poderosas' body = ''' Rápidos e versáteis, os conceitos de vetorização, indexação e broadcasting do NumPy são, na prática, o padrão em computação com arrays. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Ferramentas de computação numérica' body = ''' O NumPy oferece um conjunto completo de funções matemáticas, geradores de números aleatórios, rotinas de álgebra linear, transformadas de Fourier, e mais. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Interoperabilidade' body = ''' O NumPy suporta um grande número de plataformas de hardware e computação, e pode ser combinado com bibliotecas de computação com arrays esparsas, distribuidas ou em GPUs. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Alto desempenho' body = ''' O núcleo do NumPy é feito de código otimizado em C. Experimente a flexibilidade do Python com a velocidade de código compilado. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Fácil de usar' body = ''' A sintaxe de alto nível do NumPy torna-o acessível e produtivo para programadores de qualquer nível de experiência e formação. ''' -{{< /card >}} -{{< card >}} +[[item]] +type = 'card' title = 'Código aberto' body = ''' Distribuido com uma [licença BSD](https://github.com/numpy/numpy/blob/main/LICENSE.txt) liberal, o NumPy é desenvolvido e mantido [publicamente no GitHub](https://github.com/numpy/numpy) por uma [comunidade](/pt/community) vibrante, responsiva, e diversa. ''' -{{< /card >}} -{{< /grid >}} +{{< /grid1 >}}
rmiddle/shurly
33142980bc25a0cd407c213d7822fc036b3e13e4
Adding PHP output format to the README file
diff --git a/shurly_service/README.txt b/shurly_service/README.txt index 70aeea2..8b19635 100644 --- a/shurly_service/README.txt +++ b/shurly_service/README.txt @@ -1,25 +1,28 @@ SHORTENING A URL: ------------------------------- Default format is JSON: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com Text format returns just the short URL: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=txt XML format: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=xml +PHP serialized array: +http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=php + JSONP takes (optional) additional "func" argument to define function: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=jsonp&func=gimmeUrl API Keys: Users can create API keys and use them to associate a shortening request with their account. Additionally, their roles will be honored and the associated rate limiting will be used. http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&apiKey=84a29ac36f0507b7b98672a9d13a2e46_A EXPANDING A URL: ------------------------------- Works just as above, but returns expanded URL. All formats are supported. Here, the API key only modifies rate limiting. http://lbt.me/shurly/api/expand?shortUrl=http://lbt.me/Zk5 \ No newline at end of file
rmiddle/shurly
299034636abba03f5069f8928eea7c0849a98d10
fixing problem (user error) with double "http://"
diff --git a/shurly.module b/shurly.module index 578bb42..1fb91e8 100644 --- a/shurly.module +++ b/shurly.module @@ -1,804 +1,808 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_theme() */ function shurly_theme($existing, $type, $theme, $path) { return array( 'shurly_create_form' => array( 'arguments' => array('form' => NULL), //'file' => 'shurly_form.inc', ), ); } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); } unset($form_state['storage']['shurly']); return $form; } function theme_shurly_create_form($form) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); $output = ''; $output .= '<div class="container-inline">'; $output .= drupal_render($form['long_url']); $output .= drupal_render($form['submit']); $output .= '</div>'; $output .= drupal_render($form['short_url']); $output .= drupal_render($form); return $output; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } - elseif (!shurly_validate_long($vals['long_url'])) { + elseif (!shurly_validate_long($form_state['values']['long_url'])) { form_set_error('long_url', t('Invalid URL')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } -function shurly_validate_long($long_url) { +function shurly_validate_long(&$long_url) { $return = TRUE; $match = FALSE; + + // if the person didn't remove the original http:// from the field, pull it out + $long_url = preg_replace('!^http\://(http\://|https\://)!i', '\\1', $long_url); + $long_parse = parse_url($long_url); $base_parse = parse_url($GLOBALS['base_url']); if ($long_parse === FALSE || !$long_parse['host']) { // malformed URL // or no host in the URL $return = FALSE; } elseif ($long_parse['scheme'] != 'http' && $long_parse['scheme'] != 'https') { $return = FALSE; } else { $long_domain_parts = explode('.', $long_parse['host']); $base_domain_parts = explode('.', $base_parse['host']); // if last domain part of entered URL matches last part of this domain if ($long_domain_parts[count($long_domain_parts) - 1] == $base_domain_parts[count($long_domain_parts) - 1]) { // and (if there's a 2nd to last) if (count($long_domain_parts) >= 2) { // check that 2nd to last matches if ($long_domain_parts[count($long_domain_parts) - 2] == $base_domain_parts[count($long_domain_parts) - 2]) { // last 2 parts link to this domain $match = TRUE; } } else { // there's only one part, and it links here $match = TRUE; } // We only get down here if the long URL links to this domain // by the way, we're ignoring any subdomain... // so http://lbt.me/something and http://www.lbt.me/something are assumed to be the same if ($match) { // let's see if there's a $_GET['q'] in the long URL $query = $long_parse['query']; $query = html_entity_decode($query); $query_array = explode('&', $query); $queries = array(); foreach ($query_array as $val) { $x = explode('=', $val); $queries[$x[0]] = $x[1]; } if ($queries['q']) { // if there's a 'q' query, Drupal uses this instead of anything in the path $path = $queries['q']; } else { $path = $long_parse['path']; } // see if this is a link to an existing shortURL // remove the leading "/" from path, if it exists $path = array_pop(explode('/', $path, 2)); if ($path) { // get the base path of this Drupal install $base = array_pop(explode('/', base_path(), 2)); // remove the base from the path if ($base) { $path = preg_replace('!'. preg_quote($base, '!') .'!i', '', $path); } if (shurly_url_exists($path)) { $return = FALSE; } } } } } return $return; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { // Allow other modules to implement hook_shurly_redirect() // to add additional logging information to the database or perform other tasks module_invoke_all('shurly_redirect', $row); // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
435d67051149bfe20f6fdc0717b9020db069b179
hacking ZeroClipboard to position the Flash correctly
diff --git a/shurly.module b/shurly.module index 1170741..578bb42 100644 --- a/shurly.module +++ b/shurly.module @@ -1,709 +1,709 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_theme() */ function shurly_theme($existing, $type, $theme, $path) { return array( 'shurly_create_form' => array( 'arguments' => array('form' => NULL), //'file' => 'shurly_form.inc', ), ); } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), - '#field_suffix' => ' <div id="shurly-copy-container"><div id="shurly-copy">' . t('copy') . '</div></div> + '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); } unset($form_state['storage']['shurly']); return $form; } function theme_shurly_create_form($form) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); $output = ''; $output .= '<div class="container-inline">'; $output .= drupal_render($form['long_url']); $output .= drupal_render($form['submit']); $output .= '</div>'; $output .= drupal_render($form['short_url']); $output .= drupal_render($form); return $output; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (!shurly_validate_long($vals['long_url'])) { form_set_error('long_url', t('Invalid URL')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { $return = TRUE; $match = FALSE; $long_parse = parse_url($long_url); $base_parse = parse_url($GLOBALS['base_url']); if ($long_parse === FALSE || !$long_parse['host']) { // malformed URL // or no host in the URL $return = FALSE; } elseif ($long_parse['scheme'] != 'http' && $long_parse['scheme'] != 'https') { $return = FALSE; } else { $long_domain_parts = explode('.', $long_parse['host']); $base_domain_parts = explode('.', $base_parse['host']); // if last domain part of entered URL matches last part of this domain if ($long_domain_parts[count($long_domain_parts) - 1] == $base_domain_parts[count($long_domain_parts) - 1]) { // and (if there's a 2nd to last) if (count($long_domain_parts) >= 2) { // check that 2nd to last matches if ($long_domain_parts[count($long_domain_parts) - 2] == $base_domain_parts[count($long_domain_parts) - 2]) { // last 2 parts link to this domain $match = TRUE; } } else { // there's only one part, and it links here $match = TRUE; } // We only get down here if the long URL links to this domain // by the way, we're ignoring any subdomain... // so http://lbt.me/something and http://www.lbt.me/something are assumed to be the same if ($match) { // let's see if there's a $_GET['q'] in the long URL $query = $long_parse['query']; $query = html_entity_decode($query); $query_array = explode('&', $query); $queries = array(); foreach ($query_array as $val) { $x = explode('=', $val); $queries[$x[0]] = $x[1]; } if ($queries['q']) { // if there's a 'q' query, Drupal uses this instead of anything in the path $path = $queries['q']; } else { $path = $long_parse['path']; } // see if this is a link to an existing shortURL // remove the leading "/" from path, if it exists $path = array_pop(explode('/', $path, 2)); if ($path) { // get the base path of this Drupal install $base = array_pop(explode('/', base_path(), 2)); // remove the base from the path if ($base) { $path = preg_replace('!'. preg_quote($base, '!') .'!i', '', $path); } if (shurly_url_exists($path)) { $return = FALSE; } } } } } return $return; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } diff --git a/zeroclipboard/ZeroClipboard.js b/zeroclipboard/ZeroClipboard.js index 5adde95..19976bb 100755 --- a/zeroclipboard/ZeroClipboard.js +++ b/zeroclipboard/ZeroClipboard.js @@ -1,311 +1,312 @@ // Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard = { version: "1.0.7", clients: {}, // registered upload clients on page, indexed by id moviePath: 'ZeroClipboard.swf', // URL to movie nextId: 1, // ID of next movie $: function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { var classes = this.className.split(/\s+/); var idx = -1; for (var k = 0; k < classes.length; k++) { if (classes[k] == name) { idx = k; k = classes.length; } } if (idx > -1) { classes.splice( idx, 1 ); this.className = classes.join(' '); } return this; }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); }; } return thingy; }, setMoviePath: function(path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function(id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function(id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function(obj, stopObj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; - while (obj && (obj != stopObj)) { - info.left += obj.offsetLeft; - info.top += obj.offsetTop; - obj = obj.offsetParent; - } + // commented out.. requires relative parent around target element + //while (obj && (obj != stopObj)) { + // info.left += obj.offsetLeft; + // info.top += obj.offsetTop; + // obj = obj.offsetParent; + //} return info; }, Client: function(elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard.nextId++; this.movieId = 'ZeroClipboardMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers glue: function(elem, appendElem, stylesToAdd) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } if (typeof(appendElem) == 'string') { appendElem = ZeroClipboard.$(appendElem); } else if (typeof(appendElem) == 'undefined') { appendElem = document.getElementsByTagName('body')[0]; } // find X/Y position of domElement var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; style.width = '' + box.width + 'px'; style.height = '' + box.height + 'px'; style.zIndex = zIndex; if (typeof(stylesToAdd) == 'object') { for (addedStyle in stylesToAdd) { style[addedStyle] = stylesToAdd[addedStyle]; } } // style.backgroundColor = '#f00'; // debug appendElem.appendChild(this.div); this.div.innerHTML = this.getHTML( box.width, box.height ); }, getHTML: function(width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; } return html; }, hide: function() { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function() { // show ourselves after a call to hide() this.reposition(); }, destroy: function() { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild( this.div ); } catch(e) {;} this.domElement = null; this.div = null; } }, reposition: function(elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, setText: function(newText) { // set text to be copied to clipboard this.clipText = newText; if (this.ready) this.movie.setText(newText); }, addEventListener: function(eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) this.handlers[eventName] = []; this.handlers[eventName].push(func); }, setHandCursor: function(enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) this.movie.setHandCursor(enabled); }, setCSSEffects: function(enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function(eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 1 ); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 100 ); this.ready = true; return; } this.ready = true; this.movie.setText( this.clipText ); this.movie.setHandCursor( this.handCursorEnabled ); break; case 'mouseover': if (this.domElement && this.cssEffects) { this.domElement.addClass('hover'); if (this.recoverActive) this.domElement.addClass('active'); } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
rmiddle/shurly
cd70f74b5b025f7c7fca2110a9765b125b2c4c18
moving JS includes into theme function and adding conditional to ZeroClipboard call for better compatibility
diff --git a/shurly.js b/shurly.js index 0311219..18fdf7f 100644 --- a/shurly.js +++ b/shurly.js @@ -1,15 +1,17 @@ Drupal.behaviors.shurly = function() { $('#edit-result').focus(function(){ $(this).select(); }); //.data('origBG', $(this).css('backgroundColor')); - var clip = new ZeroClipboard.Client(); - clip.setText($('#edit-result').val()); - clip.setHandCursor( true ); - clip.glue('shurly-copy', 'shurly-copy-container'); - clip.addEventListener( 'onComplete', function() { - $('#edit-result').css('backgroundColor', '#FFFF3F').fadeTo(300, .1, function(){ - $(this).fadeTo(1, 1).css('backgroundColor', '#FFF'); + if ($('#edit-result').length) { + var clip = new ZeroClipboard.Client(); + clip.setText($('#edit-result').val()); + clip.setHandCursor( true ); + clip.glue('shurly-copy', 'shurly-copy-container'); + clip.addEventListener( 'onComplete', function() { + $('#edit-result').css('backgroundColor', '#FFFF3F').fadeTo(300, .1, function(){ + $(this).fadeTo(1, 1).css('backgroundColor', '#FFF'); + }); }); - }); + } } \ No newline at end of file diff --git a/shurly.module b/shurly.module index 2e9e3f2..1170741 100644 --- a/shurly.module +++ b/shurly.module @@ -1,727 +1,725 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_theme() */ function shurly_theme($existing, $type, $theme, $path) { return array( 'shurly_create_form' => array( 'arguments' => array('form' => NULL), //'file' => 'shurly_form.inc', ), ); } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { - - $path = drupal_get_path('module', 'shurly'); - - drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); - drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); - drupal_add_js($path . '/shurly.js'); - drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function theme_shurly_create_form($form) { + $path = drupal_get_path('module', 'shurly'); + drupal_add_css($path . '/shurly.css'); + drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); + drupal_add_js($path . '/shurly.js'); + drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); $output = ''; $output .= '<div class="container-inline">'; $output .= drupal_render($form['long_url']); $output .= drupal_render($form['submit']); $output .= '</div>'; $output .= drupal_render($form['short_url']); $output .= drupal_render($form); return $output; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (!shurly_validate_long($vals['long_url'])) { form_set_error('long_url', t('Invalid URL')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { $return = TRUE; $match = FALSE; $long_parse = parse_url($long_url); $base_parse = parse_url($GLOBALS['base_url']); if ($long_parse === FALSE || !$long_parse['host']) { // malformed URL // or no host in the URL $return = FALSE; } elseif ($long_parse['scheme'] != 'http' && $long_parse['scheme'] != 'https') { $return = FALSE; } else { $long_domain_parts = explode('.', $long_parse['host']); $base_domain_parts = explode('.', $base_parse['host']); // if last domain part of entered URL matches last part of this domain if ($long_domain_parts[count($long_domain_parts) - 1] == $base_domain_parts[count($long_domain_parts) - 1]) { // and (if there's a 2nd to last) if (count($long_domain_parts) >= 2) { // check that 2nd to last matches if ($long_domain_parts[count($long_domain_parts) - 2] == $base_domain_parts[count($long_domain_parts) - 2]) { // last 2 parts link to this domain $match = TRUE; } } else { // there's only one part, and it links here $match = TRUE; } // We only get down here if the long URL links to this domain // by the way, we're ignoring any subdomain... // so http://lbt.me/something and http://www.lbt.me/something are assumed to be the same if ($match) { // let's see if there's a $_GET['q'] in the long URL $query = $long_parse['query']; $query = html_entity_decode($query); $query_array = explode('&', $query); $queries = array(); foreach ($query_array as $val) { $x = explode('=', $val); $queries[$x[0]] = $x[1]; } if ($queries['q']) { // if there's a 'q' query, Drupal uses this instead of anything in the path $path = $queries['q']; } else { $path = $long_parse['path']; } // see if this is a link to an existing shortURL // remove the leading "/" from path, if it exists $path = array_pop(explode('/', $path, 2)); if ($path) { // get the base path of this Drupal install $base = array_pop(explode('/', base_path(), 2)); // remove the base from the path if ($base) { $path = preg_replace('!'. preg_quote($base, '!') .'!i', '', $path); } if (shurly_url_exists($path)) { $return = FALSE; } } } } } return $return; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) {
rmiddle/shurly
4fa08b60dad1463bfde78e7c70d10e01ede21848
correcting documentation
diff --git a/shurly_service/README.txt b/shurly_service/README.txt index 9817a2a..70aeea2 100644 --- a/shurly_service/README.txt +++ b/shurly_service/README.txt @@ -1,25 +1,25 @@ SHORTENING A URL: ------------------------------- Default format is JSON: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com Text format returns just the short URL: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=txt XML format: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=xml JSONP takes (optional) additional "func" argument to define function: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=jsonp&func=gimmeUrl API Keys: Users can create API keys and use them to associate a shortening request with their account. Additionally, their roles will be honored and the associated rate limiting will be used. http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&apiKey=84a29ac36f0507b7b98672a9d13a2e46_A EXPANDING A URL: ------------------------------- Works just as above, but returns expanded URL. All formats are supported. Here, the API key only modifies rate limiting. -http://lbt.me/shurly/api/expand?shortURL=http://lbt.me/Zk5 \ No newline at end of file +http://lbt.me/shurly/api/expand?shortUrl=http://lbt.me/Zk5 \ No newline at end of file
rmiddle/shurly
f6e8f86220148fc89ec71692d983b09e16eb0c8d
Return error for invalid API key
diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index 123cdf6..6adbc2f 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,142 +1,156 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** * Callback for shurly/api/shorten */ function shurly_service_shorten() { $defaults = array( 'format' => 'json', // 'domain' => NULL, 'longUrl' => '', //'shortUrl' => '', // intentionally not implemented for now... // 'login' => NULL, 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $account = NULL; if ($input['apiKey']) { module_load_include('inc', 'shurly_service', 'shurly_api_keys'); $uid = shurly_get_uid($input['apiKey']); + if (!$uid) { + $data = array( + 'success' => FALSE, + 'error' => t('Invalid API key'), + ); + return shurly_service_output($data, $input); + } $account = user_load($uid); } $data = shurly_shorten($input['longUrl'], NULL, $account); shurly_service_output($data, $input); } /** * Callback for shurly/api/shorten */ function shurly_service_expand() { $defaults = array( 'format' => 'json', // 'domain' => NULL, //'longUrl' => '', 'shortUrl' => '', // 'login' => NULL, 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $account = NULL; if ($input['apiKey']) { module_load_include('inc', 'shurly_service', 'shurly_api_keys'); $uid = shurly_get_uid($input['apiKey']); + if (!$uid) { + $data = array( + 'success' => FALSE, + 'error' => t('Invalid API key'), + ); + return shurly_service_output($data, $input); + } $account = user_load($uid); } $path = array_pop(explode('/', parse_url($input['shortUrl'], PHP_URL_PATH))); // only works with clean URLs $data = shurly_expand($path, $account); shurly_service_output($data, $input); } /** * Output data in a given format */ function shurly_service_output($data, $input) { $format = $input['format'] ? $input['format'] : 'json'; if (function_exists('shurly_service_output_' . $format)) { call_user_func('shurly_service_output_' . $format, $data, $input); } else { print t('invalid format request'); } } /** * Output JSON data */ function shurly_service_output_json($data) { drupal_json($data); } /** * Output JSON data */ function shurly_service_output_jsonp($data, $input) { $func = $input['func'] ? $input['func'] : 'urlData'; // send the header drupal_json(); print $func . '(' . drupal_to_js($data) . ');'; } /** * Output txt data * Just outputs the shortUrl attribute... won't show errors */ function shurly_service_output_txt($data) { // sniff the URL and figure out what to output switch (arg(2)) { case 'expand': $key = 'longUrl'; break; case 'shorten': default: $key = 'shortUrl'; } if ($data['success']) { print $data[$key]; } else { print t("ERROR: !error", array('!error' => $data['error'])); } } /** * Output PHP serialized data */ function shurly_service_output_php($data) { print serialize($data); } /** * Output xml data */ function shurly_service_output_xml($data) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); if (is_array($data)) { foreach($data as $key => $value) { $value = htmlentities($value); $xml->addChild($key, $value); } } $output = $xml->asXML(); header('Connection: close'); header('Content-Length: '. strlen($output)); header('Content-Type: text/xml'); header('Date: '. date('r')); print $output; }
rmiddle/shurly
f40cefed0f067293bffc8a12b647920e9c475142
Improving API documentation (slightly)
diff --git a/shurly_service/README.txt b/shurly_service/README.txt index 56a9b95..9817a2a 100644 --- a/shurly_service/README.txt +++ b/shurly_service/README.txt @@ -1,13 +1,25 @@ SHORTENING A URL: ------------------------------- Default format is JSON: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com Text format returns just the short URL: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=txt XML format: http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=xml JSONP takes (optional) additional "func" argument to define function: -http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=jsonp&func=gimmeUrl \ No newline at end of file +http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&format=jsonp&func=gimmeUrl + +API Keys: +Users can create API keys and use them to associate a shortening request with their account. Additionally, their roles will be honored and the associated rate limiting will be used. +http://lbt.me/shurly/api/shorten?longUrl=http://www.lullabot.com&apiKey=84a29ac36f0507b7b98672a9d13a2e46_A + + +EXPANDING A URL: +------------------------------- +Works just as above, but returns expanded URL. All formats are supported. +Here, the API key only modifies rate limiting. + +http://lbt.me/shurly/api/expand?shortURL=http://lbt.me/Zk5 \ No newline at end of file
rmiddle/shurly
99a62a3cc25ae8a65e4bf3454206d07c6a379b5a
Adding API key support to shurly/expand
diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index 2bb0d75..123cdf6 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,136 +1,142 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** * Callback for shurly/api/shorten */ function shurly_service_shorten() { $defaults = array( 'format' => 'json', // 'domain' => NULL, 'longUrl' => '', //'shortUrl' => '', // intentionally not implemented for now... // 'login' => NULL, 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $account = NULL; if ($input['apiKey']) { module_load_include('inc', 'shurly_service', 'shurly_api_keys'); $uid = shurly_get_uid($input['apiKey']); $account = user_load($uid); } $data = shurly_shorten($input['longUrl'], NULL, $account); shurly_service_output($data, $input); } /** * Callback for shurly/api/shorten */ function shurly_service_expand() { $defaults = array( 'format' => 'json', // 'domain' => NULL, //'longUrl' => '', 'shortUrl' => '', // 'login' => NULL, - // 'apiKey' => NULL, + 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; + $account = NULL; + + if ($input['apiKey']) { + module_load_include('inc', 'shurly_service', 'shurly_api_keys'); + $uid = shurly_get_uid($input['apiKey']); + $account = user_load($uid); + } - $path = array_pop(explode('/', $input['shortUrl'])); - //$path = substr(strrchr($input['shortUrl'], "/"), 1); - $data = shurly_expand($path); + $path = array_pop(explode('/', parse_url($input['shortUrl'], PHP_URL_PATH))); // only works with clean URLs + $data = shurly_expand($path, $account); shurly_service_output($data, $input); } /** * Output data in a given format */ function shurly_service_output($data, $input) { $format = $input['format'] ? $input['format'] : 'json'; if (function_exists('shurly_service_output_' . $format)) { call_user_func('shurly_service_output_' . $format, $data, $input); } else { print t('invalid format request'); } } /** * Output JSON data */ function shurly_service_output_json($data) { drupal_json($data); } /** * Output JSON data */ function shurly_service_output_jsonp($data, $input) { $func = $input['func'] ? $input['func'] : 'urlData'; // send the header drupal_json(); print $func . '(' . drupal_to_js($data) . ');'; } /** * Output txt data * Just outputs the shortUrl attribute... won't show errors */ function shurly_service_output_txt($data) { // sniff the URL and figure out what to output switch (arg(2)) { case 'expand': $key = 'longUrl'; break; case 'shorten': default: $key = 'shortUrl'; } if ($data['success']) { print $data[$key]; } else { print t("ERROR: !error", array('!error' => $data['error'])); } } /** * Output PHP serialized data */ function shurly_service_output_php($data) { print serialize($data); } /** * Output xml data */ function shurly_service_output_xml($data) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); if (is_array($data)) { foreach($data as $key => $value) { $value = htmlentities($value); $xml->addChild($key, $value); } } $output = $xml->asXML(); header('Connection: close'); header('Content-Length: '. strlen($output)); header('Content-Type: text/xml'); header('Date: '. date('r')); print $output; }
rmiddle/shurly
1c017040c0ccd8d5a20331d78ca39bd0dbb5fba5
Working API key generation implemented as a block. Users can generate an API key, and use it to associate short URLs with their account when accessing through the API.
diff --git a/shurly_service/shurly_api_keys.inc b/shurly_service/shurly_api_keys.inc new file mode 100644 index 0000000..2dc5202 --- /dev/null +++ b/shurly_service/shurly_api_keys.inc @@ -0,0 +1,26 @@ +<?php + +define('API_VERSION', 'A'); + +/** + * Generate a new api key for this user and put it into the database + * @return the new API key or FALSE on database insert error + */ +function shurly_generate_new_api_key($uid) { + // be sure that the new key is unique + do { + $key = md5(uniqid(rand(), TRUE)) . '_' . API_VERSION; + } while (shurly_get_uid($key)); + db_query('DELETE FROM {shurly_keys} WHERE uid = %d', $uid); + $result = db_query("INSERT INTO {shurly_keys} (uid, apikey) VALUES (%d,'%s')", $uid, $key); + return $result ? $key : FALSE; +} + +function shurly_get_uid($key) { + return db_result(db_query("SELECT uid FROM {shurly_keys} WHERE apikey = '%s'", $key)); +} + +function shurly_get_api_key($uid) { + return db_result(db_query("SELECT apikey FROM {shurly_keys} WHERE uid = %d", $uid)); +} + diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index 3df5f16..2bb0d75 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,129 +1,136 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** * Callback for shurly/api/shorten */ function shurly_service_shorten() { $defaults = array( 'format' => 'json', // 'domain' => NULL, 'longUrl' => '', //'shortUrl' => '', // intentionally not implemented for now... // 'login' => NULL, - // 'apiKey' => NULL, + 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; + $account = NULL; + + if ($input['apiKey']) { + module_load_include('inc', 'shurly_service', 'shurly_api_keys'); + $uid = shurly_get_uid($input['apiKey']); + $account = user_load($uid); + } - $data = shurly_shorten($input['longUrl']); + $data = shurly_shorten($input['longUrl'], NULL, $account); shurly_service_output($data, $input); } /** * Callback for shurly/api/shorten */ function shurly_service_expand() { $defaults = array( 'format' => 'json', // 'domain' => NULL, //'longUrl' => '', 'shortUrl' => '', // 'login' => NULL, // 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $path = array_pop(explode('/', $input['shortUrl'])); //$path = substr(strrchr($input['shortUrl'], "/"), 1); $data = shurly_expand($path); shurly_service_output($data, $input); } /** * Output data in a given format */ function shurly_service_output($data, $input) { $format = $input['format'] ? $input['format'] : 'json'; if (function_exists('shurly_service_output_' . $format)) { call_user_func('shurly_service_output_' . $format, $data, $input); } else { print t('invalid format request'); } } /** * Output JSON data */ function shurly_service_output_json($data) { drupal_json($data); } /** * Output JSON data */ function shurly_service_output_jsonp($data, $input) { $func = $input['func'] ? $input['func'] : 'urlData'; // send the header drupal_json(); print $func . '(' . drupal_to_js($data) . ');'; } /** * Output txt data * Just outputs the shortUrl attribute... won't show errors */ function shurly_service_output_txt($data) { // sniff the URL and figure out what to output switch (arg(2)) { case 'expand': $key = 'longUrl'; break; case 'shorten': default: $key = 'shortUrl'; } if ($data['success']) { print $data[$key]; } else { print t("ERROR: !error", array('!error' => $data['error'])); } } /** * Output PHP serialized data */ function shurly_service_output_php($data) { print serialize($data); } /** * Output xml data */ function shurly_service_output_xml($data) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); if (is_array($data)) { foreach($data as $key => $value) { $value = htmlentities($value); $xml->addChild($key, $value); } } $output = $xml->asXML(); header('Connection: close'); header('Content-Length: '. strlen($output)); header('Content-Type: text/xml'); header('Date: '. date('r')); print $output; } diff --git a/shurly_service/shurly_service.install b/shurly_service/shurly_service.install new file mode 100644 index 0000000..1a47aed --- /dev/null +++ b/shurly_service/shurly_service.install @@ -0,0 +1,35 @@ +<?php + +/** + * Implement hook_schema(). + */ +function shurly_service_schema() { + $schema['shurly_keys'] = array( + 'description' => t('API keys for use with the Shurly module'), + 'fields' => array( + 'uid' => array( + 'description' => t('User ID'), + 'type' => 'int', + 'not null' => TRUE, + ), + 'apikey' => array( + 'description' => t('API key for user'), + 'type' => 'varchar', + 'length' => '35', + 'not null' => TRUE, + ), + ), + 'primary key' => array('apikey'), + 'indexes' => array( + 'uid' => array('uid'), + ), + ); + return $schema; +} + +/** + * Implement hook_install(). + */ +function shurly_service_install() { + drupal_install_schema('shurly_keys'); +} \ No newline at end of file diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module index cf8a03c..d608a45 100644 --- a/shurly_service/shurly_service.module +++ b/shurly_service/shurly_service.module @@ -1,42 +1,98 @@ <?php // $Id$ /** * @file * Link ShURLy functionalities to services module. * @todo * - add option to rate limit requests * - add option for user api keys * */ /** * Implementation of hook_perm(). */ function shurly_service_perm() { $perms = array('administer short URL services'); return $perms; } /** * Implementation of hook_menu(). */ function shurly_service_menu() { $items = array(); $items['shurly/api/shorten'] = array( 'file' => 'shurly_service.inc', 'page callback' => 'shurly_service_shorten', 'access arguments' => array('Create short URLs'), 'type' => MENU_CALLBACK, ); $items['shurly/api/expand'] = array( 'file' => 'shurly_service.inc', 'page callback' => 'shurly_service_expand', 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); return $items; } +function shurly_service_block($op = 'list', $delta = 0, $edit = array()) { + // create a block to add URL + switch ($op) { + case 'list': + $blocks['api_key'] = array('info' => t('Short URL API key')); + return $blocks; + case 'view': + global $user; + // anon user can't get API key, also check permissions + if ($delta == 'api_key' && $user->uid > 0 && user_access('Create short URLs') ) { + $block = array('subject' => t('API key'), + 'content' => drupal_get_form('shurly_api_key_form')); + return $block; + } + break; + } +} + +function shurly_api_key_form($form_state) { + global $user; + module_load_include('inc', 'shurly_service', 'shurly_api_keys'); + $key = shurly_get_api_key($user->uid); + + $form = array(); + if ($key) { + $form['key'] = array( + '#type' => 'textfield', + '#title' => t('API key'), + '#default_value' => $key, + '#description' => t('You can provide this key to 3rd party apps rather than sharing your password.'), + ); + $form['reset'] = array( + '#type' => 'submit', + '#value' => t('Reset'), + '#suffix' => t('If a 3rd party is misusing your API key, you can generate a new one.'), + ); + + } + else { + $form['new'] = array( + '#type' => 'submit', + '#value' => t('Create'), + '#suffix' => t('Create an API key to use with 3rd party applications.'), + ); + } + + return $form; +} + +function shurly_api_key_form_submit($form, &$form_state) { + // we don't need to do anything with the submitted form... + // just generate a new API key + global $user; + shurly_generate_new_api_key($user->uid); +} +
rmiddle/shurly
49fc9c67afb728bdb44d4f6e46f72ef84297484f
Better long URL validation includes prevention of links back to links on the site -- a.k.a. instant DOS attacks. Also fixing copy button in Chrome.
diff --git a/shurly.module b/shurly.module index 0607f12..2e9e3f2 100644 --- a/shurly.module +++ b/shurly.module @@ -1,734 +1,806 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_theme() */ function shurly_theme($existing, $type, $theme, $path) { return array( 'shurly_create_form' => array( 'arguments' => array('form' => NULL), //'file' => 'shurly_form.inc', ), ); } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); + drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), - '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> + '#field_suffix' => ' <div id="shurly-copy-container"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function theme_shurly_create_form($form) { $output = ''; $output .= '<div class="container-inline">'; $output .= drupal_render($form['long_url']); $output .= drupal_render($form['submit']); $output .= '</div>'; $output .= drupal_render($form['short_url']); $output .= drupal_render($form); return $output; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } - elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { - form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); + elseif (!shurly_validate_long($vals['long_url'])) { + form_set_error('long_url', t('Invalid URL')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { - return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); + $return = TRUE; + $match = FALSE; + $long_parse = parse_url($long_url); + $base_parse = parse_url($GLOBALS['base_url']); + + if ($long_parse === FALSE || !$long_parse['host']) { + // malformed URL + // or no host in the URL + $return = FALSE; + } + elseif ($long_parse['scheme'] != 'http' && $long_parse['scheme'] != 'https') { + $return = FALSE; + } + else { + $long_domain_parts = explode('.', $long_parse['host']); + $base_domain_parts = explode('.', $base_parse['host']); + // if last domain part of entered URL matches last part of this domain + if ($long_domain_parts[count($long_domain_parts) - 1] == $base_domain_parts[count($long_domain_parts) - 1]) { + // and (if there's a 2nd to last) + if (count($long_domain_parts) >= 2) { + // check that 2nd to last matches + if ($long_domain_parts[count($long_domain_parts) - 2] == $base_domain_parts[count($long_domain_parts) - 2]) { + // last 2 parts link to this domain + $match = TRUE; + } + } + else { + // there's only one part, and it links here + $match = TRUE; + } + + // We only get down here if the long URL links to this domain + // by the way, we're ignoring any subdomain... + // so http://lbt.me/something and http://www.lbt.me/something are assumed to be the same + if ($match) { + // let's see if there's a $_GET['q'] in the long URL + $query = $long_parse['query']; + $query = html_entity_decode($query); + $query_array = explode('&', $query); + $queries = array(); + foreach ($query_array as $val) { + $x = explode('=', $val); + $queries[$x[0]] = $x[1]; + } + + if ($queries['q']) { + // if there's a 'q' query, Drupal uses this instead of anything in the path + $path = $queries['q']; + } + else { + $path = $long_parse['path']; + } + + // see if this is a link to an existing shortURL + // remove the leading "/" from path, if it exists + $path = array_pop(explode('/', $path, 2)); + if ($path) { + // get the base path of this Drupal install + $base = array_pop(explode('/', base_path(), 2)); + // remove the base from the path + if ($base) { + $path = preg_replace('!'. preg_quote($base, '!') .'!i', '', $path); + } + if (shurly_url_exists($path)) { + $return = FALSE; + } + } + } + + } + } + return $return; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { // Allow other modules to implement hook_shurly_redirect() // to add additional logging information to the database or perform other tasks module_invoke_all('shurly_redirect', $row); // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
a56d744341281151ef87a377b240e0c393ae032e
Fixing copy button in Chrome
diff --git a/shurly.css b/shurly.css index 67bbfae..19aea5f 100644 --- a/shurly.css +++ b/shurly.css @@ -1,43 +1,44 @@ .shurly-choose { color: #999; } .shurly-result { border: 3px #999 solid; padding: 5px; margin: 5px 0; } .shurly-result .form-item { margin: 0; } #shurly-copy-container { display:inline; } #shurly-copy { border: 2px outset #999; background-color: #CCC; - position: relative; display: inline; padding: .1em .3em; } #shurly-copy.hover { border-color: #777; background-color: #DDD; } .shurly-bookmarklet { background-color: #999; color: #FFF; - border: 1px solid #333; padding: .1em .5em; text-decoration: none; + -moz-border-radius: .7em; + -webkit-border-radius: .7em; } .shurly-bookmarklet:hover { - background-color: #666; + background-color: #CCC; text-decoration: none; + color: #000; } \ No newline at end of file
rmiddle/shurly
e2346864bd8c43547b0a685c4612f6ae4710084e
Adding theme function for the form
diff --git a/shurly.module b/shurly.module index 9772ee9..0607f12 100644 --- a/shurly.module +++ b/shurly.module @@ -1,710 +1,734 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } +/** + * Implementation of hook_theme() + */ +function shurly_theme($existing, $type, $theme, $path) { + return array( + 'shurly_create_form' => array( + 'arguments' => array('form' => NULL), + //'file' => 'shurly_form.inc', + ), + ); +} + + /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } +function theme_shurly_create_form($form) { + $output = ''; + $output .= '<div class="container-inline">'; + $output .= drupal_render($form['long_url']); + $output .= drupal_render($form['submit']); + $output .= '</div>'; + $output .= drupal_render($form['short_url']); + $output .= drupal_render($form); + return $output; +} + function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { // Allow other modules to implement hook_shurly_redirect() // to add additional logging information to the database or perform other tasks module_invoke_all('shurly_redirect', $row); // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
1b33bf3b141caa5f0fb65fe7033dd095449b8a94
forgotten ;
diff --git a/shurly.module b/shurly.module index 9144835..9772ee9 100644 --- a/shurly.module +++ b/shurly.module @@ -178,533 +178,533 @@ function shurly_create_form($form_state) { if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { // Allow other modules to implement hook_shurly_redirect() // to add additional logging information to the database or perform other tasks - module_invoke_all('shurly_redirect', $row) + module_invoke_all('shurly_redirect', $row); // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
9f5dc26d4384eb621e4f7a31e0ed1058b45ace78
hook_shurly_redirect() got reverted accidentally... fixing
diff --git a/shurly.module b/shurly.module index f6f06ad..9144835 100644 --- a/shurly.module +++ b/shurly.module @@ -174,533 +174,537 @@ function shurly_create_form($form_state) { '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); - // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { + // Allow other modules to implement hook_shurly_redirect() + // to add additional logging information to the database or perform other tasks + module_invoke_all('shurly_redirect', $row) + + // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
92e44891faa407f06741fe3171e0319a8a4f5452
fixing default views glitch
diff --git a/shurly.module b/shurly.module index da1597b..f6f06ad 100644 --- a/shurly.module +++ b/shurly.module @@ -174,538 +174,533 @@ function shurly_create_form($form_state) { '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); + // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { - - // Allow other modules to implement hook_shurly_redirect() - // to add additional logging information to the database or perform other tasks - module_invoke_all('shurly_redirect', $row); - - // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/views/shurly.views_default.inc b/views/shurly.views_default.inc index 620610a..a5feef1 100644 --- a/views/shurly.views_default.inc +++ b/views/shurly.views_default.inc @@ -1,876 +1,877 @@ <?php // $Id$ /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL (trimmed)', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '30', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 1, 'text' => '<a href="[destination]" title="[destination]">[destination_1]</a>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '50', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '1', 'link' => 1, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j @ H:i:s', 'exclude' => 1, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'created_1' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 1, 'text' => '<div class="shurly-ago">[created_1]</div> <div class="shurly-date">[created]</div>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'created_1', 'table' => 'shurly', 'field' => 'created', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'destination' => array( 'operator' => 'contains', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'dest', 'identifier' => 'dest', 'label' => 'Long URL', 'optional' => 1, 'remember' => 0, ), 'case' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'source' => array( 'operator' => 'contains', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'source_op', 'identifier' => 'src', 'label' => 'Short URL', 'optional' => 1, 'remember' => 0, ), 'case' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'uid', 'label' => 'User', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'shurly', 'field' => 'uid', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('empty', 'No short URLs yet!'); $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 150); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'count' => 'count', 'destination_1' => 'destination_1', 'destination' => 'destination', 'source' => 'source', 'name' => 'name', 'created' => 'created', 'created_1' => 'created_1', 'last_used' => 'last_used', 'link_delete' => 'link_delete', ), 'info' => array( 'count' => array( 'sortable' => 1, 'separator' => '', ), 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'source' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 0, 'separator' => '', ), 'created_1' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created_1', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly/list'); $handler->override_option('menu', array( 'type' => 'default tab', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '-5', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); + $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL clipped', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '60', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '<a href="[destination]" title="[destination]" target="_blank">[destination_1]</a>', 'make_link' => 0, 'path' => '[destination]', 'link_class' => '', 'alt' => '[destination]', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '[source]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '0', 'link' => 0, 'exclude' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'nothing' => array( 'label' => 'Links', 'alter' => array( 'text' => '<div class="shurly-long"><a href="[source]" title="[destination]" target="_blank">[destination_1]</a></div> <div class="shurly-short">[source]</div>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'nothing', 'table' => 'views', 'field' => 'nothing', 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); $handler->override_option('use_ajax', TRUE); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'count' => 'count', 'destination_1' => 'destination_1', 'destination' => 'destination', 'source' => 'source', 'nothing' => 'nothing', 'created' => 'created', 'last_used' => 'last_used', 'link_delete' => 'link_delete', ), 'info' => array( 'count' => array( 'sortable' => 1, 'separator' => '', ), 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 0, 'separator' => '', ), 'source' => array( 'sortable' => 0, 'separator' => '', ), 'nothing' => array( 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('block_description', 'My short URLs'); $handler->override_option('block_caching', -1); $views[$view->name] = $view; return $views; }
rmiddle/shurly
db561bc45e245981302a5ee25d1e6c9638d96a8b
Updating admin default view to display as a tab
diff --git a/views/shurly.views_default.inc b/views/shurly.views_default.inc index e8edbf1..620610a 100644 --- a/views/shurly.views_default.inc +++ b/views/shurly.views_default.inc @@ -1,876 +1,876 @@ <?php // $Id$ /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL (trimmed)', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '30', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 1, 'text' => '<a href="[destination]" title="[destination]">[destination_1]</a>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '50', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '1', 'link' => 1, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j @ H:i:s', 'exclude' => 1, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'created_1' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 1, 'text' => '<div class="shurly-ago">[created_1]</div> -<div class="shurly-date">[created]</div>', + <div class="shurly-date">[created]</div>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'created_1', 'table' => 'shurly', 'field' => 'created', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'destination' => array( 'operator' => 'contains', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'dest', 'identifier' => 'dest', 'label' => 'Long URL', 'optional' => 1, 'remember' => 0, ), 'case' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'source' => array( 'operator' => 'contains', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'source_op', 'identifier' => 'src', 'label' => 'Short URL', 'optional' => 1, 'remember' => 0, ), 'case' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'uid' => array( 'operator' => 'in', 'value' => '', 'group' => '0', 'exposed' => TRUE, 'expose' => array( 'use_operator' => 0, 'operator' => 'uid_op', 'identifier' => 'uid', 'label' => 'User', 'optional' => 1, 'remember' => 0, 'reduce' => 0, ), 'id' => 'uid', 'table' => 'shurly', 'field' => 'uid', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('empty', 'No short URLs yet!'); $handler->override_option('empty_format', '1'); - $handler->override_option('items_per_page', 100); + $handler->override_option('items_per_page', 150); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'count' => 'count', 'destination_1' => 'destination_1', 'destination' => 'destination', 'source' => 'source', 'name' => 'name', 'created' => 'created', 'created_1' => 'created_1', 'last_used' => 'last_used', 'link_delete' => 'link_delete', ), 'info' => array( 'count' => array( 'sortable' => 1, 'separator' => '', ), 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'source' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 0, 'separator' => '', ), 'created_1' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created_1', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); - $handler->override_option('path', 'admin/build/shurly'); + $handler->override_option('path', 'admin/build/shurly/list'); $handler->override_option('menu', array( - 'type' => 'normal', + 'type' => 'default tab', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', - 'weight' => '0', + 'weight' => '-5', 'name' => 'navigation', )); $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, + 'type' => 'normal', + 'title' => 'Short URLs', + 'description' => 'List, sort, and edit Shurly short URLs', + 'weight' => '0', 'name' => 'navigation', )); - $views[$view->name] = $view; + /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL clipped', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '60', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '<a href="[destination]" title="[destination]" target="_blank">[destination_1]</a>', 'make_link' => 0, 'path' => '[destination]', 'link_class' => '', 'alt' => '[destination]', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '[source]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '0', 'link' => 0, 'exclude' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'nothing' => array( 'label' => 'Links', 'alter' => array( 'text' => '<div class="shurly-long"><a href="[source]" title="[destination]" target="_blank">[destination_1]</a></div> <div class="shurly-short">[source]</div>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'nothing', 'table' => 'views', 'field' => 'nothing', 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); $handler->override_option('use_ajax', TRUE); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'count' => 'count', 'destination_1' => 'destination_1', 'destination' => 'destination', 'source' => 'source', 'nothing' => 'nothing', 'created' => 'created', 'last_used' => 'last_used', 'link_delete' => 'link_delete', ), 'info' => array( 'count' => array( 'sortable' => 1, 'separator' => '', ), 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 0, 'separator' => '', ), 'source' => array( 'sortable' => 0, 'separator' => '', ), 'nothing' => array( 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('block_description', 'My short URLs'); $handler->override_option('block_caching', -1); $views[$view->name] = $view; return $views; }
rmiddle/shurly
37d288da9571f80ef03f5afbe7792629fd874d7a
adding hook_shurly_redirect() capability
diff --git a/shurly.module b/shurly.module index f6f06ad..da1597b 100644 --- a/shurly.module +++ b/shurly.module @@ -174,533 +174,538 @@ function shurly_create_form($form_state) { '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); if ($latest) { $no_save = TRUE; $success = TRUE; $short = $latest; } else { $short = shurly_next_url(); } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); - // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { + + // Allow other modules to implement hook_shurly_redirect() + // to add additional logging information to the database or perform other tasks + module_invoke_all('shurly_redirect', $row); + + // Allow modules to react to the end of the page request before redirecting. module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
1c1cee4827450ba56acf2512044db228a43acb94
Fixing bug where existing URLs are saved back into the database... when submitted through the api
diff --git a/shurly.module b/shurly.module index 98741d2..f6f06ad 100644 --- a/shurly.module +++ b/shurly.module @@ -1,698 +1,706 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); $items['admin/build/shurly/settings'] = array( 'title' => 'Settings', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_settings_form'), 'access arguments' => array('Administer short URLs'), 'type' => MENU_LOCAL_TASK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $rate_limit = shurly_rate_limit_allowed(); if (!$rate_limit['allowed']) { form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } function shurly_settings_form($form_state) { $form['shurly_throttle'] = array( '#type' => 'fieldset', '#title' => t('Rate limiting'), '#tree' => TRUE, '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), ); $saved = variable_get('shurly_throttle', array()); foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { $form['shurly_throttle'][$rid] = array( '#type' => 'fieldset', '#title' => $name, '#tree' => TRUE, ); $form['shurly_throttle'][$rid]['rate'] = array( '#type' => 'textfield', '#size' => '3', '#prefix' => '<div class="container-inline">', '#field_suffix' => ' ' . t('requests'), '#default_value' => $saved[$rid]['rate'], ); $form['shurly_throttle'][$rid]['time'] = array( '#type' => 'textfield', '#size' => '3', '#field_prefix' => t('within'), '#field_suffix' => ' ' . t('minutes'), '#default_value' => $saved[$rid]['time'], '#suffix' => '</div>', ); $form['shurly_throttle'][$rid]['weight'] = array( '#type' => 'weight', '#title' => t('Weight'), '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), ); } return system_settings_form($form); } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /************************************************************** * Backport of the flood controls from Drupal 7 * these functions won't be needed in the D7 version of ShURLy **************************************************************/ function shurly_cron() { // Cleanup the flood. db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); } function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); } function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { if (!isset($identifier)) { $identifier = ip_address(); } $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); return ($number < $threshold); } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; + $no_save = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); - $short = $latest ? $latest : shurly_next_url(); + if ($latest) { + $no_save = TRUE; + $success = TRUE; + $short = $latest; + } + else { + $short = shurly_next_url(); + } } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } - if (!$error) { + if (!$error && !$no_save) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, - 'shortUrl' => url($short, array('absolute' => TRUE)), + 'shortUrl' => isset($short) ? url($short, array('absolute' => TRUE)) : '', ); } function shurly_expand($short, $account = NULL) { $error = ''; $success = FALSE; $rate_limit = shurly_rate_limit_allowed($account); if (!$rate_limit['allowed']) { $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); } elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * Check rate limit for this user * return an array in the following format * array( * 'allowed' => TRUE/FALSE * 'rate' => number of requests allowed * 'time' => period of time in minutes * ) */ function shurly_rate_limit_allowed($account = NULL) { if (!isset($account)) { global $user; $account = $user; } $settings = variable_get('shurly_throttle', array()); if (is_array($account->roles)) { $use_rid = array_shift(array_keys($account->roles)); // get list of roles with permission to create short URLs $creating_roles = user_roles(FALSE, 'Create short URLs'); foreach($account->roles as $rid => $name) { // check that this role has permission to create URLs, otherwise discard it if (array_key_exists($rid, $creating_roles)) { // find the lightest role... if roles are the same weight, use the next role $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; } } } if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { // see if it's allowed $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); // increment the counter shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); $return = array( 'allowed' => $allowed, 'rate' => $settings[$use_rid]['rate'], 'time' => $settings[$use_rid]['time'], ); } else { // not set... don't do a flood check $return = array( 'allowed' => TRUE, ); } return $return; } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
277ee4d6defc9a8e7b9464ad3c2f9d6c3ac6311d
Adding flood control rate limiting. In D6, this requires an extra table -- adding table to schema and update function
diff --git a/shurly.install b/shurly.install index a900582..9d0a608 100644 --- a/shurly.install +++ b/shurly.install @@ -1,91 +1,149 @@ <?php // $Id$ /** * @file Shurly install file */ /** * Implement hook_schema(). */ function shurly_schema() { $schema['shurly'] = array( 'description' => t('URL redirects for the Shurly module'), 'fields' => array( 'rid' => array( 'description' => t('unique redirect id'), 'type' => 'serial', 'not null' => TRUE, ), 'uid' => array( 'description' => t('user id of owner'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'source' => array( 'description' => t('source path'), 'type' => 'varchar', 'length' => '255', 'not null' => TRUE, ), 'destination' => array( 'description' => t('redirect URL'), 'type' => 'varchar', 'length' => '255', 'not null' => TRUE, ), 'created' => array( 'description' => t('datestamp of creation'), 'type' => 'int', 'not null' => TRUE, ), 'count' => array( 'description' => t('usage count'), 'type' => 'int', 'not null' => TRUE, ), 'last_used' => array( 'description' => t('datestamp of last use'), 'type' => 'int', 'not null' => TRUE, ), 'custom' => array( 'description' => t('flag for custom path'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'active' => array( 'description' => t('allows links to be deactivated'), 'type' => 'int', 'not null' => TRUE, 'default' => 1, ), ), 'primary key' => array('rid'), 'indexes' => array( 'source' => array('source'), ), ); + + $schema['shurly_flood'] = array( + 'description' => t('Flood controls the threshold of events, such as the number of contact attempts.'), + 'fields' => array( + 'fid' => array( + 'description' => t('Unique flood event ID.'), + 'type' => 'serial', + 'not null' => TRUE, + ), + 'event' => array( + 'description' => t('Name of event (e.g. contact).'), + 'type' => 'varchar', + 'length' => 64, + 'not null' => TRUE, + 'default' => '', + ), + 'identifier' => array( + 'description' => t('Identifier of the visitor, such as an IP address or hostname.'), + 'type' => 'varchar', + 'length' => 128, + 'not null' => TRUE, + 'default' => '', + ), + 'timestamp' => array( + 'description' => t('Timestamp of the event.'), + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + ), + 'expiration' => array( + 'description' => t('Expiration timestamp. Expired events are purged on cron run.'), + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + ), + ), + 'primary key' => array('fid'), + 'indexes' => array( + 'allow' => array('event', 'identifier', 'timestamp'), + //'purge' => array('expiration'), + ), + ); + + + return $schema; } /** * Implement hook_install(). */ function shurly_install() { drupal_install_schema('shurly'); + drupal_install_schema('shurly_flood'); +} + +function shurly_update_6100() { + $module = 'shurly'; + $schema = drupal_get_schema_unprocessed($module); + _drupal_initialize_schema($module, $schema); + + $ret = array(); + db_create_table($ret, 'shurly_flood', $schema['shurly_flood']); + + return $ret; } /** * Implement hook_uninstall(). */ function shurly_uninstall() { // Remove tables. drupal_uninstall_schema('shurly'); + drupal_uninstall_schema('shurly_flood'); // Remove variables. } diff --git a/shurly.module b/shurly.module index 5ffe5f2..98741d2 100644 --- a/shurly.module +++ b/shurly.module @@ -1,560 +1,698 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); + $items['admin/build/shurly/settings'] = array( + 'title' => 'Settings', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('shurly_settings_form'), + 'access arguments' => array('Administer short URLs'), + 'type' => MENU_LOCAL_TASK, + ); + return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } + $rate_limit = shurly_rate_limit_allowed(); + if (!$rate_limit['allowed']) { + form_set_error('', t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time']))); + return; + } + $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } + +function shurly_settings_form($form_state) { + $form['shurly_throttle'] = array( + '#type' => 'fieldset', + '#title' => t('Rate limiting'), + '#tree' => TRUE, + '#description' => t('Limit requests by IP address. Leave blank for no rate limiting.<br /><strong>Note:</strong> Only roles with the \'Create short URLs\' permission are listed here. Change that permission <a href="!url">here</a>.', array('!url' => url('admin/user/permissions', array('fragment' => 'module-shurly')))), + ); + $saved = variable_get('shurly_throttle', array()); + foreach (user_roles(FALSE, 'Create short URLs') as $rid => $name) { + $form['shurly_throttle'][$rid] = array( + '#type' => 'fieldset', + '#title' => $name, + '#tree' => TRUE, + ); + $form['shurly_throttle'][$rid]['rate'] = array( + '#type' => 'textfield', + '#size' => '3', + '#prefix' => '<div class="container-inline">', + '#field_suffix' => ' ' . t('requests'), + '#default_value' => $saved[$rid]['rate'], + ); + $form['shurly_throttle'][$rid]['time'] = array( + '#type' => 'textfield', + '#size' => '3', + '#field_prefix' => t('within'), + '#field_suffix' => ' ' . t('minutes'), + '#default_value' => $saved[$rid]['time'], + '#suffix' => '</div>', + ); + $form['shurly_throttle'][$rid]['weight'] = array( + '#type' => 'weight', + '#title' => t('Weight'), + '#default_value' => isset($saved[$rid]['weight']) ? $saved[$rid]['weight'] : 0, + '#description' => t('Order of this role when considering a user with multiple roles. A user\'s lightest role will take precedence.'), + ); + + } + return system_settings_form($form); +} + /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } +/************************************************************** + * Backport of the flood controls from Drupal 7 + * these functions won't be needed in the D7 version of ShURLy + **************************************************************/ + +function shurly_cron() { + // Cleanup the flood. + db_query('DELETE FROM {shurly_flood} WHERE expiration < %d', time()); +} + +function shurly_flood_register_event($name, $window = 3600, $identifier = NULL) { + if (!isset($identifier)) { + $identifier = ip_address(); + } + db_query("INSERT INTO {shurly_flood} (event, identifier, timestamp, expiration) VALUES ('%s', '%s', %d, %d)", $name, ip_address(), time(), time() + $window); + +} + +function shurly_flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) { + if (!isset($identifier)) { + $identifier = ip_address(); + } + $number = db_result(db_query("SELECT COUNT(*) FROM {shurly_flood} WHERE event = '%s' AND identifier = '%s' AND timestamp > %d", $name, $identifier, time() - $window)); + return ($number < $threshold); +} + /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; - if (!shurly_validate_long($long_url)) { + $rate_limit = shurly_rate_limit_allowed($account); + if (!$rate_limit['allowed']) { + $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); + } + elseif (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); $short = $latest ? $latest : shurly_next_url(); } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } -function shurly_expand($short) { - if ($redirect = shurly_get_redirect($short, TRUE)) { +function shurly_expand($short, $account = NULL) { + $error = ''; + $success = FALSE; + $rate_limit = shurly_rate_limit_allowed($account); + if (!$rate_limit['allowed']) { + $error = t('Rate limit exceeded. You are limited to @rate requests per @time minute period.', array('@rate' => $rate_limit['rate'], '@time' => $rate_limit['time'])); + } + elseif ($redirect = shurly_get_redirect($short, TRUE)) { $success = TRUE; $long_url = $redirect->destination; } else { - $success = FALSE; - $error = t('not found'); + $error = t('Not found'); } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } + +/** + * Check rate limit for this user + * return an array in the following format + * array( + * 'allowed' => TRUE/FALSE + * 'rate' => number of requests allowed + * 'time' => period of time in minutes + * ) + */ +function shurly_rate_limit_allowed($account = NULL) { + if (!isset($account)) { + global $user; + $account = $user; + } + $settings = variable_get('shurly_throttle', array()); + if (is_array($account->roles)) { + $use_rid = array_shift(array_keys($account->roles)); + // get list of roles with permission to create short URLs + $creating_roles = user_roles(FALSE, 'Create short URLs'); + foreach($account->roles as $rid => $name) { + // check that this role has permission to create URLs, otherwise discard it + if (array_key_exists($rid, $creating_roles)) { + // find the lightest role... if roles are the same weight, use the next role + $settings[$rid]['weight'] = isset($settings[$rid]['weight']) ? $settings[$rid]['weight'] : 0; + $use_rid = $settings[$use_rid]['weight'] < $settings[$rid]['weight'] ? $use_rid : $rid; + } + } + } + if (is_numeric($settings[$use_rid]['rate']) && is_numeric($settings[$use_rid]['time'])) { + // see if it's allowed + $allowed = shurly_flood_is_allowed('shurly', $settings[$use_rid]['rate'], $settings[$use_rid]['time'] * 60); + // increment the counter + shurly_flood_register_event('shurly', $settings[$use_rid]['time'] * 60); + $return = array( + 'allowed' => $allowed, + 'rate' => $settings[$use_rid]['rate'], + 'time' => $settings[$use_rid]['time'], + ); + } + else { + // not set... don't do a flood check + $return = array( + 'allowed' => TRUE, + ); + } + return $return; +} /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; if ($check_active) { $query .= ' AND active = 1'; } $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index e3fae7f..3df5f16 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,124 +1,129 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** * Callback for shurly/api/shorten */ function shurly_service_shorten() { $defaults = array( 'format' => 'json', // 'domain' => NULL, 'longUrl' => '', //'shortUrl' => '', // intentionally not implemented for now... // 'login' => NULL, // 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $data = shurly_shorten($input['longUrl']); shurly_service_output($data, $input); } /** * Callback for shurly/api/shorten */ function shurly_service_expand() { $defaults = array( 'format' => 'json', // 'domain' => NULL, //'longUrl' => '', 'shortUrl' => '', // 'login' => NULL, // 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $path = array_pop(explode('/', $input['shortUrl'])); //$path = substr(strrchr($input['shortUrl'], "/"), 1); - $data = shurly_expand($path, TRUE); + $data = shurly_expand($path); shurly_service_output($data, $input); } /** * Output data in a given format */ function shurly_service_output($data, $input) { $format = $input['format'] ? $input['format'] : 'json'; if (function_exists('shurly_service_output_' . $format)) { call_user_func('shurly_service_output_' . $format, $data, $input); } else { print t('invalid format request'); } } /** * Output JSON data */ function shurly_service_output_json($data) { drupal_json($data); } /** * Output JSON data */ function shurly_service_output_jsonp($data, $input) { $func = $input['func'] ? $input['func'] : 'urlData'; // send the header drupal_json(); print $func . '(' . drupal_to_js($data) . ');'; } /** * Output txt data * Just outputs the shortUrl attribute... won't show errors */ function shurly_service_output_txt($data) { // sniff the URL and figure out what to output switch (arg(2)) { case 'expand': $key = 'longUrl'; break; case 'shorten': default: $key = 'shortUrl'; } - print $data[$key]; + if ($data['success']) { + print $data[$key]; + } + else { + print t("ERROR: !error", array('!error' => $data['error'])); + } } /** * Output PHP serialized data */ function shurly_service_output_php($data) { print serialize($data); } /** * Output xml data */ function shurly_service_output_xml($data) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); if (is_array($data)) { foreach($data as $key => $value) { $value = htmlentities($value); $xml->addChild($key, $value); } } $output = $xml->asXML(); header('Connection: close'); header('Content-Length: '. strlen($output)); header('Content-Type: text/xml'); header('Date: '. date('r')); print $output; } diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module index 6481bfe..cf8a03c 100644 --- a/shurly_service/shurly_service.module +++ b/shurly_service/shurly_service.module @@ -1,42 +1,42 @@ <?php // $Id$ /** * @file * Link ShURLy functionalities to services module. * @todo - * - add option to rate limit + * - add option to rate limit requests * - add option for user api keys * */ /** * Implementation of hook_perm(). */ function shurly_service_perm() { $perms = array('administer short URL services'); return $perms; } /** * Implementation of hook_menu(). */ function shurly_service_menu() { $items = array(); $items['shurly/api/shorten'] = array( 'file' => 'shurly_service.inc', 'page callback' => 'shurly_service_shorten', 'access arguments' => array('Create short URLs'), 'type' => MENU_CALLBACK, ); $items['shurly/api/expand'] = array( 'file' => 'shurly_service.inc', 'page callback' => 'shurly_service_expand', 'access callback' => TRUE, 'type' => MENU_CALLBACK, ); return $items; }
rmiddle/shurly
b91df8fe88fda42156fcda0aae0fd907921e7d9d
shurly/api/expand functionality
diff --git a/shurly.module b/shurly.module index e5008ff..5ffe5f2 100644 --- a/shurly.module +++ b/shurly.module @@ -1,539 +1,560 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; if (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); $short = $latest ? $latest : shurly_next_url(); } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, 'shortUrl' => url($short, array('absolute' => TRUE)), ); } + +function shurly_expand($short) { + if ($redirect = shurly_get_redirect($short, TRUE)) { + $success = TRUE; + $long_url = $redirect->destination; + } + else { + $success = FALSE; + $error = t('not found'); + } + return array( + 'success' => $success, + 'error' => $error, + 'longUrl' => $long_url, + 'shortUrl' => url($short, array('absolute' => TRUE)), + ); +} /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ -function shurly_get_redirect($short_url) { +function shurly_get_redirect($short_url, $check_active = FALSE) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query - $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); + $query = "SELECT * FROM {shurly} WHERE BINARY source = '%s'"; + if ($check_active) { + $query .= ' AND active = 1'; + } + $redirect = db_fetch_object(db_query($query, $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index 8bab78d..e3fae7f 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,91 +1,124 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** * Callback for shurly/api/shorten */ function shurly_service_shorten() { $defaults = array( 'format' => 'json', // 'domain' => NULL, 'longUrl' => '', - // 'short' => '', // intentionally not implemented for now... + //'shortUrl' => '', // intentionally not implemented for now... // 'login' => NULL, // 'apiKey' => NULL, 'func' => 'urlData', // function name for padded JSON ); $input = $_REQUEST + $defaults; $data = shurly_shorten($input['longUrl']); shurly_service_output($data, $input); } +/** + * Callback for shurly/api/shorten + */ +function shurly_service_expand() { + $defaults = array( + 'format' => 'json', + // 'domain' => NULL, + //'longUrl' => '', + 'shortUrl' => '', + // 'login' => NULL, + // 'apiKey' => NULL, + 'func' => 'urlData', // function name for padded JSON + ); + $input = $_REQUEST + $defaults; + + $path = array_pop(explode('/', $input['shortUrl'])); + //$path = substr(strrchr($input['shortUrl'], "/"), 1); + $data = shurly_expand($path, TRUE); + + shurly_service_output($data, $input); + +} + /** * Output data in a given format */ function shurly_service_output($data, $input) { $format = $input['format'] ? $input['format'] : 'json'; if (function_exists('shurly_service_output_' . $format)) { call_user_func('shurly_service_output_' . $format, $data, $input); } else { print t('invalid format request'); } } /** * Output JSON data */ function shurly_service_output_json($data) { drupal_json($data); } /** * Output JSON data */ function shurly_service_output_jsonp($data, $input) { $func = $input['func'] ? $input['func'] : 'urlData'; // send the header drupal_json(); print $func . '(' . drupal_to_js($data) . ');'; } /** * Output txt data * Just outputs the shortUrl attribute... won't show errors */ function shurly_service_output_txt($data) { - print $data['shortUrl']; + // sniff the URL and figure out what to output + switch (arg(2)) { + case 'expand': + $key = 'longUrl'; + break; + + case 'shorten': + default: + $key = 'shortUrl'; + } + print $data[$key]; } /** * Output PHP serialized data */ function shurly_service_output_php($data) { print serialize($data); } /** * Output xml data */ function shurly_service_output_xml($data) { $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); if (is_array($data)) { foreach($data as $key => $value) { $value = htmlentities($value); $xml->addChild($key, $value); } } $output = $xml->asXML(); header('Connection: close'); header('Content-Length: '. strlen($output)); header('Content-Type: text/xml'); header('Date: '. date('r')); print $output; } diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module index 254e992..6481bfe 100644 --- a/shurly_service/shurly_service.module +++ b/shurly_service/shurly_service.module @@ -1,34 +1,42 @@ <?php // $Id$ /** * @file * Link ShURLy functionalities to services module. + * @todo + * - add option to rate limit + * - add option for user api keys + * */ /** * Implementation of hook_perm(). */ function shurly_service_perm() { $perms = array('administer short URL services'); return $perms; } /** * Implementation of hook_menu(). */ function shurly_service_menu() { $items = array(); $items['shurly/api/shorten'] = array( - 'title' => t('Search Service'), - 'description' => t('Configure search service.'), 'file' => 'shurly_service.inc', 'page callback' => 'shurly_service_shorten', 'access arguments' => array('Create short URLs'), 'type' => MENU_CALLBACK, ); + $items['shurly/api/expand'] = array( + 'file' => 'shurly_service.inc', + 'page callback' => 'shurly_service_expand', + 'access callback' => TRUE, + 'type' => MENU_CALLBACK, + ); return $items; }
rmiddle/shurly
7fa626e5ab04f8f8850202bdab48045d87e7d2ae
fixing shortUrl returned by shorty_shorten() to be a complete absolute URL
diff --git a/shurly.module b/shurly.module index 60bb86d..e5008ff 100644 --- a/shurly.module +++ b/shurly.module @@ -1,539 +1,539 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; $error = ''; if (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); $short = $latest ? $latest : shurly_next_url(); } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, 'longUrl' => $long_url, - 'shortUrl' => $short, + 'shortUrl' => url($short, array('absolute' => TRUE)), ); } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
a6f6d7b5a25169c526accef2c634c7f8e12b25ba
Working handrolled Shurly web service module
diff --git a/shurly.info b/shurly.info index dae7ba3..be62239 100755 --- a/shurly.info +++ b/shurly.info @@ -1,5 +1,6 @@ ; $Id$ name = ShURLy +package = ShURLy description = A complete short URL service. dependencies[] = views core = 6.x \ No newline at end of file diff --git a/shurly.module b/shurly.module index 5055bba..60bb86d 100644 --- a/shurly.module +++ b/shurly.module @@ -1,538 +1,539 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to shorten a URL * @arg $long_url - the long URL to shorten * @arg $custom - optional custom short URL * * @return an array with the following keys * 'success' => TRUE or FALSE * 'error' => reason for for failure * 'long_url' => the long url * 'short_url' => the short url */ function shurly_shorten($long_url, $custom = NULL, $account = NULL) { $success = FALSE; $account = ($account) ? $account : $GLOBALS['user']; + $error = ''; if (!shurly_validate_long($long_url)) { $error = t('Invalid long URL.'); } elseif (is_null($custom)) { $latest = shurly_get_latest_short($long_url, $account->uid); $short = $latest ? $latest : shurly_next_url(); } else { $short = $custom; if (!shurly_validate_custom($short)) { $error .= $error ? ' ' : ''; $error .= t('Invalid short URL.'); } elseif (shurly_url_exists($short)) { $error .= $error ? ' ' : ''; $error .= t('Existing short URL.'); } } if (!$error) { if (shurly_save_url($long_url, $short, $account, $custom)) { $success = TRUE; } else { $error = t('Unknown database error.'); } } return array( 'success' => $success, 'error' => $error, - 'long_url' => $long_url, - 'short_url' => $short, + 'longUrl' => $long_url, + 'shortUrl' => $short, ); } /** * API function to save a URL * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we should probably check that $custom is a string here // we should check the length of the string // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } function shurly_validate_long($long_url) { return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc index 5042682..8bab78d 100644 --- a/shurly_service/shurly_service.inc +++ b/shurly_service/shurly_service.inc @@ -1,144 +1,91 @@ <?php // $Id$ /** * @file * Link general search functionalities to services module. */ /** - * Return search results for nodes. - * - * @param $keys - * The keywords to search for within the nodes. - * @param $simple - * When set to TRUE, only the fields indicated in $stdkeys will be returned. - * This can be helpful to limit the size of the search results. - * @param $fields - * An array of the node properties that should be returned. When $simple - * is not set, a full node object is returned with each result. You can - * limit the properties of these objects to only the ones you need by - * specifying them in this array. Again, this gives the opportunity to - * limit your result set. - * - * @return - * An array of search results. If $simple is TRUE, this array will contain - * only results and no node objects. If $simple is FALSE the array will - * contain both results and full node objects, possibly limited by the - * properties indicated in $fields. - * - * @see hook_search() - * @see node_search() + * Callback for shurly/api/shorten */ -function shurly_service_nodes($keys, $simple = FALSE, $fields = array()) { - // define standard keys for simple set - $stdkeys = array('node', 'link', 'type', 'title', 'user', 'date', 'snippet'); +function shurly_service_shorten() { + $defaults = array( + 'format' => 'json', + // 'domain' => NULL, + 'longUrl' => '', + // 'short' => '', // intentionally not implemented for now... + // 'login' => NULL, + // 'apiKey' => NULL, + 'func' => 'urlData', // function name for padded JSON + ); + $input = $_REQUEST + $defaults; + + $data = shurly_shorten($input['longUrl']); + + shurly_service_output($data, $input); + +} - // invoke the search hook to generate results - $results = module_invoke('node', 'search', 'search', $keys); - if ($results && is_array($results) && count($results)) { - // if simple results requested, remove extra data - if ($simple) { - $num = count($results); - for ($i = 0; $i<$num; $i++) { - $keys = array_keys($results[$i]); - foreach ($keys as $key) { - if ($key == 'node') { - $results[$i][$key] = $results[$i]['node']->nid; - } - if (!in_array($key, $stdkeys)) { - unset($results[$i][$key]); - } - } - } - } - else { - foreach ($results as $key => $result) { - $result['node'] = services_node_load($result['node'], $fields); - $results[$key] = $result; - } - } - return $results; +/** + * Output data in a given format + */ +function shurly_service_output($data, $input) { + $format = $input['format'] ? $input['format'] : 'json'; + if (function_exists('shurly_service_output_' . $format)) { + call_user_func('shurly_service_output_' . $format, $data, $input); + } + else { + print t('invalid format request'); } - return services_error(t('Search returned no results.'), 404); } /** - * Return site content specified by a system setting. - * - * This service returns search results across the site, as specified by the - * user at admin/settings/shurly_service. This can combine results from any - * module that implements hook_search(). - * - * @param $keys - * The keywords to search for within the content. - * @param $simple - * When set to TRUE, only the fields indicated in $stdkeys will be returned. - * This can be helpful to limit the size of the search results. - * - * @return - * An array of search results. If $simple is TRUE, this array will contain - * only results and no content objects. If $simple is FALSE the array will - * contain both results and full content objects. - * - * @see hook_search() + * Output JSON data */ -function shurly_service_content($keys, $simple = FALSE) { - // define standard keys for simple set - $stdkeys = array('link', 'type', 'title', 'user', 'date', 'snippet'); - - // invoke the search hook to generate results - $results = array(); - $shurly_hooks = variable_get('shurly_service_options', array('node' => 'node')); - - watchdog('shurly_service', t('search.content invoked for !keys using hooks !hooks', array('!keys' => $keys, '!hooks' => implode(', ', $shurly_hooks)))); +function shurly_service_output_json($data) { + drupal_json($data); +} - // run through only select hook_search() as defined in /admin/settings/shurly_service - foreach ($shurly_hooks as $hook) { - if (! empty($hook)) { - $shurly_results = module_invoke($hook, 'search', 'search', $keys); - if (! empty($shurly_results) ) { - $results = array_merge($results, $shurly_results); - } - } - } +/** + * Output JSON data + */ +function shurly_service_output_jsonp($data, $input) { + $func = $input['func'] ? $input['func'] : 'urlData'; + // send the header + drupal_json(); + print $func . '(' . drupal_to_js($data) . ');'; +} - watchdog('shurly_service', t('search.content returned !count results for !keys using hooks !hooks', array('!count' => count($results), '!keys' => $keys, '!hooks' => implode($shurly_hooks, ', ')))); +/** + * Output txt data + * Just outputs the shortUrl attribute... won't show errors + */ +function shurly_service_output_txt($data) { + print $data['shortUrl']; +} - if ($results and is_array($results) and count($results)) { - // if simple results requested, remove extra data - if ($simple) { - $num = count($results); - for ($i = 0; $i<$num; $i++) { - $keys = array_keys($results[$i]); - foreach ($keys as $key) { - if (!in_array($key, $stdkeys)) { - unset($results[$i][$key]); - } - } - } - } - return $results; - } - return services_error(t('Search returned no results.'), 401); +/** + * Output PHP serialized data + */ +function shurly_service_output_php($data) { + print serialize($data); } /** - * Return search results for users. - * - * @param $keys - * The keywords to search for within the users. - * - * @return - * An array of search results. - * - * @see hook_search() - * @see user_search() + * Output xml data */ -function shurly_service_users($keys) { - // invoke the search hook to generate results - $results = module_invoke('user', 'search', 'search', $keys); - if ($results && is_array($results) && count($results)) { - return $results; +function shurly_service_output_xml($data) { + $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><data />"); + if (is_array($data)) { + foreach($data as $key => $value) { + $value = htmlentities($value); + $xml->addChild($key, $value); + } } - return services_error(t('Search returned no results.'), 401); + $output = $xml->asXML(); + header('Connection: close'); + header('Content-Length: '. strlen($output)); + header('Content-Type: text/xml'); + header('Date: '. date('r')); + print $output; } diff --git a/shurly_service/shurly_service.info b/shurly_service/shurly_service.info index 59c7858..513d22d 100644 --- a/shurly_service/shurly_service.info +++ b/shurly_service/shurly_service.info @@ -1,9 +1,8 @@ ; $Id$ name = ShURLy Service description = Provides web services for the ShURLy module. -package = Services - services -dependencies[] = services +package = ShURLy dependencies[] = shurly core = 6.x diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module index f6b7814..254e992 100644 --- a/shurly_service/shurly_service.module +++ b/shurly_service/shurly_service.module @@ -1,33 +1,34 @@ <?php // $Id$ /** * @file * Link ShURLy functionalities to services module. */ /** * Implementation of hook_perm(). */ function shurly_service_perm() { $perms = array('administer short URL services'); return $perms; } /** * Implementation of hook_menu(). */ -function search_service_menu() { +function shurly_service_menu() { $items = array(); $items['shurly/api/shorten'] = array( 'title' => t('Search Service'), 'description' => t('Configure search service.'), 'file' => 'shurly_service.inc', - 'page callback' => 'drupal_get_form', + 'page callback' => 'shurly_service_shorten', 'access arguments' => array('Create short URLs'), 'type' => MENU_CALLBACK, ); return $items; } +
rmiddle/shurly
978a4760ab6b477693fb59c21c3cf652cd2b7fb1
setting up hook_menu
diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module index 652f804..f6b7814 100644 --- a/shurly_service/shurly_service.module +++ b/shurly_service/shurly_service.module @@ -1,57 +1,33 @@ <?php // $Id$ /** * @file * Link ShURLy functionalities to services module. */ /** * Implementation of hook_perm(). */ function shurly_service_perm() { - $perms = array('administer short URL service'); + $perms = array('administer short URL services'); return $perms; } /** * Implementation of hook_menu(). */ -/* + function search_service_menu() { $items = array(); - $items['admin/settings/search_service'] = array( + $items['shurly/api/shorten'] = array( 'title' => t('Search Service'), 'description' => t('Configure search service.'), + 'file' => 'shurly_service.inc', 'page callback' => 'drupal_get_form', - 'page arguments' => array('search_service_admin'), - 'file' => 'search_service_admin.inc', - 'access arguments' => array('administer search service'), + 'access arguments' => array('Create short URLs'), + 'type' => MENU_CALLBACK, ); return $items; } -*/ - -/** - * Implementation of hook_service(). - */ -function shurly_service_service() { - return array( - array( - '#method' => 'shurly.shorten', - '#callback' => 'shurly_shorten', - '#access arguments' => array('Create short URLs'), - //'#file' => array('file' => 'inc', 'module' => 'shurly_service'), - '#args' => array( - array( - '#name' => 'long', - '#type' => 'string', - '#description' => t('Long URL to be shortened.'), - ), - ), - '#return' => 'array', - '#help' => t('Shorten a URL.'), - ), - ); -} \ No newline at end of file
rmiddle/shurly
62e179fb3f0d9f9dd6dc13d00700fe55277e53d7
ShURLy integration with Services module... questionable attempt...
diff --git a/shurly_service/shurly_service.inc b/shurly_service/shurly_service.inc new file mode 100644 index 0000000..5042682 --- /dev/null +++ b/shurly_service/shurly_service.inc @@ -0,0 +1,144 @@ +<?php +// $Id$ +/** + * @file + * Link general search functionalities to services module. + */ + +/** + * Return search results for nodes. + * + * @param $keys + * The keywords to search for within the nodes. + * @param $simple + * When set to TRUE, only the fields indicated in $stdkeys will be returned. + * This can be helpful to limit the size of the search results. + * @param $fields + * An array of the node properties that should be returned. When $simple + * is not set, a full node object is returned with each result. You can + * limit the properties of these objects to only the ones you need by + * specifying them in this array. Again, this gives the opportunity to + * limit your result set. + * + * @return + * An array of search results. If $simple is TRUE, this array will contain + * only results and no node objects. If $simple is FALSE the array will + * contain both results and full node objects, possibly limited by the + * properties indicated in $fields. + * + * @see hook_search() + * @see node_search() + */ +function shurly_service_nodes($keys, $simple = FALSE, $fields = array()) { + // define standard keys for simple set + $stdkeys = array('node', 'link', 'type', 'title', 'user', 'date', 'snippet'); + + // invoke the search hook to generate results + $results = module_invoke('node', 'search', 'search', $keys); + if ($results && is_array($results) && count($results)) { + // if simple results requested, remove extra data + if ($simple) { + $num = count($results); + for ($i = 0; $i<$num; $i++) { + $keys = array_keys($results[$i]); + foreach ($keys as $key) { + if ($key == 'node') { + $results[$i][$key] = $results[$i]['node']->nid; + } + if (!in_array($key, $stdkeys)) { + unset($results[$i][$key]); + } + } + } + } + else { + foreach ($results as $key => $result) { + $result['node'] = services_node_load($result['node'], $fields); + $results[$key] = $result; + } + } + return $results; + } + return services_error(t('Search returned no results.'), 404); +} + +/** + * Return site content specified by a system setting. + * + * This service returns search results across the site, as specified by the + * user at admin/settings/shurly_service. This can combine results from any + * module that implements hook_search(). + * + * @param $keys + * The keywords to search for within the content. + * @param $simple + * When set to TRUE, only the fields indicated in $stdkeys will be returned. + * This can be helpful to limit the size of the search results. + * + * @return + * An array of search results. If $simple is TRUE, this array will contain + * only results and no content objects. If $simple is FALSE the array will + * contain both results and full content objects. + * + * @see hook_search() + */ +function shurly_service_content($keys, $simple = FALSE) { + // define standard keys for simple set + $stdkeys = array('link', 'type', 'title', 'user', 'date', 'snippet'); + + // invoke the search hook to generate results + $results = array(); + $shurly_hooks = variable_get('shurly_service_options', array('node' => 'node')); + + watchdog('shurly_service', t('search.content invoked for !keys using hooks !hooks', array('!keys' => $keys, '!hooks' => implode(', ', $shurly_hooks)))); + + // run through only select hook_search() as defined in /admin/settings/shurly_service + foreach ($shurly_hooks as $hook) { + if (! empty($hook)) { + $shurly_results = module_invoke($hook, 'search', 'search', $keys); + if (! empty($shurly_results) ) { + $results = array_merge($results, $shurly_results); + } + } + } + + watchdog('shurly_service', t('search.content returned !count results for !keys using hooks !hooks', array('!count' => count($results), '!keys' => $keys, '!hooks' => implode($shurly_hooks, ', ')))); + + if ($results and is_array($results) and count($results)) { + // if simple results requested, remove extra data + if ($simple) { + $num = count($results); + for ($i = 0; $i<$num; $i++) { + $keys = array_keys($results[$i]); + foreach ($keys as $key) { + if (!in_array($key, $stdkeys)) { + unset($results[$i][$key]); + } + } + } + } + return $results; + } + return services_error(t('Search returned no results.'), 401); +} + +/** + * Return search results for users. + * + * @param $keys + * The keywords to search for within the users. + * + * @return + * An array of search results. + * + * @see hook_search() + * @see user_search() + */ +function shurly_service_users($keys) { + // invoke the search hook to generate results + $results = module_invoke('user', 'search', 'search', $keys); + if ($results && is_array($results) && count($results)) { + return $results; + } + return services_error(t('Search returned no results.'), 401); +} diff --git a/shurly_service/shurly_service.info b/shurly_service/shurly_service.info new file mode 100644 index 0000000..59c7858 --- /dev/null +++ b/shurly_service/shurly_service.info @@ -0,0 +1,9 @@ +; $Id$ +name = ShURLy Service +description = Provides web services for the ShURLy module. +package = Services - services +dependencies[] = services +dependencies[] = shurly +core = 6.x + + diff --git a/shurly_service/shurly_service.module b/shurly_service/shurly_service.module new file mode 100644 index 0000000..652f804 --- /dev/null +++ b/shurly_service/shurly_service.module @@ -0,0 +1,57 @@ +<?php +// $Id$ +/** + * @file + * Link ShURLy functionalities to services module. + */ + +/** + * Implementation of hook_perm(). + */ +function shurly_service_perm() { + $perms = array('administer short URL service'); + + return $perms; +} + +/** + * Implementation of hook_menu(). + */ +/* +function search_service_menu() { + $items = array(); + $items['admin/settings/search_service'] = array( + 'title' => t('Search Service'), + 'description' => t('Configure search service.'), + 'page callback' => 'drupal_get_form', + 'page arguments' => array('search_service_admin'), + 'file' => 'search_service_admin.inc', + 'access arguments' => array('administer search service'), + ); + + return $items; +} +*/ + +/** + * Implementation of hook_service(). + */ +function shurly_service_service() { + return array( + array( + '#method' => 'shurly.shorten', + '#callback' => 'shurly_shorten', + '#access arguments' => array('Create short URLs'), + //'#file' => array('file' => 'inc', 'module' => 'shurly_service'), + '#args' => array( + array( + '#name' => 'long', + '#type' => 'string', + '#description' => t('Long URL to be shortened.'), + ), + ), + '#return' => 'array', + '#help' => t('Shorten a URL.'), + ), + ); +} \ No newline at end of file diff --git a/shurly_service/shurly_service_admin.inc b/shurly_service/shurly_service_admin.inc new file mode 100644 index 0000000..9293a3f --- /dev/null +++ b/shurly_service/shurly_service_admin.inc @@ -0,0 +1,39 @@ +<?php +// $Id: search_service_admin.inc,v 1.1.2.1.2.1 2010/02/22 01:53:33 heyrocker Exp $ + +/** + * @file + * Search Service settings + */ + +/** + * Menu callback to set content search service settings. + */ +function search_service_admin() { + + // For each enabled module, look for hook_search + foreach (module_list() as $name) { + if (function_exists($name . '_search')) { + $options[$name] = $name; + } + } + + // If search_service_options not initialized, then make sure that it is an array + $default_value = variable_get('search_service_options', 'node'); + if (! is_array($default_value)) { + $default_value = array($default_value); + } + $form['search_service_message'] = array( + '#type' => 'markup', + '#value' => t('Choose search hooks that return local results. Do not choose aggregated or distributed results, as this may cause recursion.'), + ); + // Display checkboxes of list of hook_search() + $form['search_service_options'] = array( + '#type' => 'checkboxes', + '#title' => t('Search content services, returns searches results using'), + '#options' => $options, + '#default_value' => $default_value, + ); + + return system_settings_form($form); +}
rmiddle/shurly
4ae44d3ab8144a6b2fbc7ebf269804c4240cf13a
Adding new shurly_shorten() api function to module for quick URL shortening via function call
diff --git a/shurly.module b/shurly.module index 3bfd5d0..5055bba 100644 --- a/shurly.module +++ b/shurly.module @@ -1,480 +1,538 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ +/** + * API function to shorten a URL + * @arg $long_url - the long URL to shorten + * @arg $custom - optional custom short URL + * + * @return an array with the following keys + * 'success' => TRUE or FALSE + * 'error' => reason for for failure + * 'long_url' => the long url + * 'short_url' => the short url + */ +function shurly_shorten($long_url, $custom = NULL, $account = NULL) { + $success = FALSE; + $account = ($account) ? $account : $GLOBALS['user']; + if (!shurly_validate_long($long_url)) { + $error = t('Invalid long URL.'); + } + elseif (is_null($custom)) { + $latest = shurly_get_latest_short($long_url, $account->uid); + $short = $latest ? $latest : shurly_next_url(); + } + else { + $short = $custom; + if (!shurly_validate_custom($short)) { + $error .= $error ? ' ' : ''; + $error .= t('Invalid short URL.'); + } + elseif (shurly_url_exists($short)) { + $error .= $error ? ' ' : ''; + $error .= t('Existing short URL.'); + } + } + if (!$error) { + if (shurly_save_url($long_url, $short, $account, $custom)) { + $success = TRUE; + } + else { + $error = t('Unknown database error.'); + } + } + return array( + 'success' => $success, + 'error' => $error, + 'long_url' => $long_url, + 'short_url' => $short, + ); +} + /** * API function to save a URL + * @arg $custom is a TRUE/FALSE */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { + // we should probably check that $custom is a string here + + // we should check the length of the string + // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } + +function shurly_validate_long($long_url) { + return (stripos($long_url, "http://") === 0 || stripos($long_url, "https://") === 0); +} + /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
bf3599e67b9fb7ab68dff616f57f04f268cfe3e4
Updating README and todos
diff --git a/README.txt b/README.txt index 24c1515..ba5b320 100644 --- a/README.txt +++ b/README.txt @@ -1,48 +1,52 @@ // $Id$ ShURLy is a URL shortening service implemented as a module for Drupal. This module was written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me http://www.youtube.com/watch?v=Qo7qoonzTCE New URLs are created by going to /shurly and entering the long URL and an optional custom short URL. Short URLs have ownership and each user can track click statistics for his/her URLs. To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain any non-reserved characters including UTF8 characters, glyphs, and icons. How fun is that!? Views: ---------------------------- ShURLy is completely integrated with the Views module and ShURLy links can be listed/sorted/displayed using Views. Views is a dependency of this module since all listings are created using Views, including the administrative page at admin/build/shurly. Views also provides a page at /myurls where users with "View own URL stats" can see & sort their URLs. Views integration also means that you could create new pages/blocks with listings like "most popular URLs", "users with most popular URLs", "most recent URLs", "most recently clicked URLs", or a tab on a user's page to show others their most recent URLs, and that sort of thing. Blocks: --------------------------- - Create a short URL the form to create a URL - ShURLy bookmarklet A block containing a "drag to your bookmarks bar" link. Clicking this bookmarklet when on a page bring the user to the the URL shortening site with the URL field filled in for that page. - My URLs This block is created by Views and is basically just a mirror the /myurls page. However, by putting this content into a block, you can put it into the 'content bottom' region on the /shurly page and get a single page with both the entry form and the URL listing USAGE: ---------------------------- -Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory without clean URLs. +1) Visit admin/user/permissions to set up permissions for Shurly (see explanation of permissions below). +2) To create a new short URL, visit /shurly or add the "Create a short URL" block to your site. +3) To view your own URLs, visit /myurls or add the 'My URLs' + +Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory or without clean URLs. Permissions: ---------------------- - Create short URLs: Allow users in this role to create URLs. This permission also allows users to delete URLs which they have created. - Enter custom URLs: Allow users in this role to enter their own short URLs, without this permission all URLs will be autogenerated - View own URL stats: Allow users to view the "My URLs" page (at /myurls) - Delete own URLs: Users may 'delete' URLs which they have created. For security reasons, these URLs are actually only deactivated. They still exist in the database and new URLs are not allowed to be created with the same short URL path. - Administer short URLs This permission allows users to edit/delete/view all short URLs by all users. This is the administrative permission and should be used carefully diff --git a/shurly.module b/shurly.module index 6a1ee8e..3bfd5d0 100644 --- a/shurly.module +++ b/shurly.module @@ -1,480 +1,480 @@ <?php // $Id$ /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views + * - fix zeroclipboard position in Chrome * - create REST API * - prevent endless loop links (back to themselves or others on this site) - * - allow for fun UTF characters in custom URLs */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
8fed061326e724cf1b358c68fba2eacd59143741
newer/better admin view with exposed filters
diff --git a/views/shurly.views_default.inc b/views/shurly.views_default.inc index 0abeaa1..e8edbf1 100644 --- a/views/shurly.views_default.inc +++ b/views/shurly.views_default.inc @@ -1,763 +1,876 @@ <?php // $Id$ -/** - * @file Shurly default views - */ - /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL (trimmed)', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '30', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 1, 'text' => '<a href="[destination]" title="[destination]">[destination_1]</a>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '50', 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '1', 'link' => 1, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( - 'label' => 'Created', + 'label' => 'Created date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, - 'date_format' => 'small', - 'custom_date_format' => '', - 'exclude' => 0, + 'date_format' => 'custom', + 'custom_date_format' => 'M j @ H:i:s', + 'exclude' => 1, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'created_1' => array( + 'label' => 'Created', + 'alter' => array( + 'alter_text' => 1, + 'text' => '<div class="shurly-ago">[created_1]</div> +<div class="shurly-date">[created]</div>', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'time ago', + 'custom_date_format' => '1', + 'exclude' => 0, + 'id' => 'created_1', + 'table' => 'shurly', + 'field' => 'created', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); + $handler->override_option('filters', array( + 'destination' => array( + 'operator' => 'contains', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'dest', + 'identifier' => 'dest', + 'label' => 'Long URL', + 'optional' => 1, + 'remember' => 0, + ), + 'case' => 0, + 'id' => 'destination', + 'table' => 'shurly', + 'field' => 'destination', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + 'source' => array( + 'operator' => 'contains', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'source_op', + 'identifier' => 'src', + 'label' => 'Short URL', + 'optional' => 1, + 'remember' => 0, + ), + 'case' => 1, + 'id' => 'source', + 'table' => 'shurly', + 'field' => 'source', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + 'uid' => array( + 'operator' => 'in', + 'value' => '', + 'group' => '0', + 'exposed' => TRUE, + 'expose' => array( + 'use_operator' => 0, + 'operator' => 'uid_op', + 'identifier' => 'uid', + 'label' => 'User', + 'optional' => 1, + 'remember' => 0, + 'reduce' => 0, + ), + 'id' => 'uid', + 'table' => 'shurly', + 'field' => 'uid', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); + $handler->override_option('empty', 'No short URLs yet!'); + $handler->override_option('empty_format', '1'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( - 'source' => 'source', - 'custom' => 'custom', + 'count' => 'count', + 'destination_1' => 'destination_1', 'destination' => 'destination', + 'source' => 'source', 'name' => 'name', 'created' => 'created', + 'created_1' => 'created_1', 'last_used' => 'last_used', - 'count' => 'count', + 'link_delete' => 'link_delete', ), 'info' => array( - 'source' => array( + 'count' => array( 'sortable' => 1, 'separator' => '', ), - 'custom' => array( + 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), + 'source' => array( + 'sortable' => 1, + 'separator' => '', + ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'created_1' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), - 'count' => array( - 'sortable' => 1, + 'link_delete' => array( 'separator' => '', ), ), - 'default' => 'created', + 'default' => 'created_1', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination_1' => array( 'label' => 'Long URL clipped', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 1, 'max_length' => '60', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination_1', 'table' => 'shurly', 'field' => 'destination', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '<a href="[destination]" title="[destination]" target="_blank">[destination_1]</a>', 'make_link' => 0, 'path' => '[destination]', 'link_class' => '', 'alt' => '[destination]', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 1, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '[source]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'longshort' => '0', 'link' => 0, 'exclude' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'nothing' => array( 'label' => 'Links', 'alter' => array( 'text' => '<div class="shurly-long"><a href="[source]" title="[destination]" target="_blank">[destination_1]</a></div> <div class="shurly-short">[source]</div>', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'nothing', 'table' => 'views', 'field' => 'nothing', 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); $handler->override_option('use_ajax', TRUE); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'count' => 'count', 'destination_1' => 'destination_1', 'destination' => 'destination', 'source' => 'source', 'nothing' => 'nothing', 'created' => 'created', 'last_used' => 'last_used', 'link_delete' => 'link_delete', ), 'info' => array( 'count' => array( 'sortable' => 1, 'separator' => '', ), 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 0, 'separator' => '', ), 'source' => array( 'sortable' => 0, 'separator' => '', ), 'nothing' => array( 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('block_description', 'My short URLs'); $handler->override_option('block_caching', -1); $views[$view->name] = $view; return $views; }
rmiddle/shurly
bf7a2b2fb1dcee33f3919ef4e377e088117c90a3
New default views. More/better views options for short URLs.
diff --git a/views/shurly.views.inc b/views/shurly.views.inc index 8523f72..6f0a1a7 100644 --- a/views/shurly.views.inc +++ b/views/shurly.views.inc @@ -1,257 +1,257 @@ <?php // $Id$ /** * @file Shurly Views data include file */ function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); //$data['shurly']['table']['join'] = array( // 'users' => array( // 'left_field' => 'uid', // 'field' => 'uid', // ), //); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( 'handler' => 'shurly_handler_field_short_url', 'parent' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( //'handler' => 'shurly_handler_field_destination', 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( 'title' => t('Clicks'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['shurly']['link_test'] = array( 'field' => array( 'title' => t('Test URL'), 'help' => t('Redirecting link.'), 'handler' => 'shurly_handler_field_shurly_link_test', 'parent' => 'views_handler_field', ), ); $data['shurly']['link_delete'] = array( 'field' => array( 'title' => t('Delete URL'), 'help' => t('Link to delete the URL'), 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function shurly_views_handlers() { return array( 'info' => array( - 'path' => drupal_get_path('module', 'shurly'), + 'path' => drupal_get_path('module', 'shurly') . '/views', ), 'handlers' => array( 'shurly_handler_field_shurly_link_delete' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_shurly_link_test' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_short_url' => array( 'parent' => 'views_handler_field', ), ), ); } diff --git a/views/shurly.views_default.inc b/views/shurly.views_default.inc index 7409e70..0abeaa1 100644 --- a/views/shurly.views_default.inc +++ b/views/shurly.views_default.inc @@ -1,657 +1,763 @@ <?php // $Id$ /** * @file Shurly default views */ /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), - 'destination' => array( - 'label' => 'Long URL', + 'destination_1' => array( + 'label' => 'Long URL (trimmed)', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', + 'trim' => 1, + 'max_length' => '30', + 'word_boundary' => 0, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 1, + 'id' => 'destination_1', + 'table' => 'shurly', + 'field' => 'destination', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + 'destination' => array( + 'label' => 'Long URL', + 'alter' => array( + 'alter_text' => 1, + 'text' => '<a href="[destination]" title="[destination]">[destination_1]</a>', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, + 'max_length' => '50', + 'word_boundary' => 0, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, + 'text' => '', + 'longshort' => '1', + 'link' => 1, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'small', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), + 'destination_1' => array( + 'label' => 'Long URL clipped', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 1, + 'max_length' => '60', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 1, + 'id' => 'destination_1', + 'table' => 'shurly', + 'field' => 'destination', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, - 'text' => '', - 'make_link' => 1, + 'text' => '<a href="[destination]" title="[destination]" target="_blank">[destination_1]</a>', + 'make_link' => 0, 'path' => '[destination]', 'link_class' => '', - 'alt' => '', + 'alt' => '[destination]', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, - 'exclude' => 0, + 'exclude' => 1, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', - 'make_link' => 1, + 'make_link' => 0, 'path' => '[source]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', - 'exclude' => 0, + 'longshort' => '0', + 'link' => 0, + 'exclude' => 1, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), - 'link' => 1, + ), + 'nothing' => array( + 'label' => 'Links', + 'alter' => array( + 'text' => '<div class="shurly-long"><a href="[source]" title="[destination]" target="_blank">[destination_1]</a></div> +<div class="shurly-short">[source]</div>', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'nothing', + 'table' => 'views', + 'field' => 'nothing', + 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); $handler->override_option('use_ajax', TRUE); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( - 'source' => 'source', - 'custom' => 'custom', + 'count' => 'count', + 'destination_1' => 'destination_1', 'destination' => 'destination', - 'name' => 'name', + 'source' => 'source', + 'nothing' => 'nothing', 'created' => 'created', 'last_used' => 'last_used', - 'count' => 'count', + 'link_delete' => 'link_delete', ), 'info' => array( - 'source' => array( + 'count' => array( 'sortable' => 1, 'separator' => '', ), - 'custom' => array( + 'destination_1' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( - 'sortable' => 1, + 'sortable' => 0, 'separator' => '', ), - 'name' => array( - 'sortable' => 1, + 'source' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'nothing' => array( 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), - 'count' => array( - 'sortable' => 1, + 'link_delete' => array( 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $handler = $view->new_display('block', 'Block', 'block_1'); $handler->override_option('block_description', 'My short URLs'); $handler->override_option('block_caching', -1); $views[$view->name] = $view; return $views; } diff --git a/views/shurly_handler_field_short_url.inc b/views/shurly_handler_field_short_url.inc index 91382ee..5e15dac 100644 --- a/views/shurly_handler_field_short_url.inc +++ b/views/shurly_handler_field_short_url.inc @@ -1,45 +1,83 @@ <?php // $Id$ /** * @file Shurly Views handler for short URL */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_short_url extends views_handler_field { function construct() { parent::construct(); $this->additional_fields['source'] = 'source'; } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); + $options['longshort'] = array('default' => 0, 'translatable' => FALSE); + $options['link'] = array('default' => FALSE, 'translatable' => FALSE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); + + // this field will never be empty + unset($form['empty']); + unset($form['hide_empty']); + unset($form['hide_empty']); + $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); + + $form['longshort'] = array( + '#type' => 'radios', + '#options' => array( + 0 => t('Output full URL including base path'), + 1 => t('Output only the short path'), + ), + '#default_value' => $this->options['longshort'], + ); + $form['link'] = array( + '#type' => 'checkbox', + '#title' => t('Output as link'), + '#default_value' => $this->options['link'], + '#description' => t('Wrap output with a link to the short URL. Use <em>Output this field as a link</em> above for more complex options.'), + ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function render($values) { // rawurldecode() allows URLs to be shown with UTF8 characters // however, this could cause other problems... - $text = !empty($this->options['text']) ? $this->options['text'] : rawurldecode(url($values->{$this->aliases['source']}, array('absolute' => TRUE))); + if (!empty($this->options['text'])) { + $text = $this->options['text']; + } + else { + if ($this->options['longshort']) { + $text = $values->{$this->aliases['source']}; + } + else { + $text = rawurldecode(url($values->{$this->aliases['source']}, array('absolute' => TRUE))); + } + } + + if ($this->options['link']) { + $text = '<a href="' . url($values->{$this->aliases['source']}, array('absolute' => TRUE)) . '">' . $text . '</a>'; + } + return $text; } }
rmiddle/shurly
0acd713abfa4e5ca18a5ffcf670a07af48ce80d6
rearranging files
diff --git a/views/shurly.views.inc b/views/shurly.views.inc new file mode 100644 index 0000000..8523f72 --- /dev/null +++ b/views/shurly.views.inc @@ -0,0 +1,257 @@ +<?php +// $Id$ + +/** + * @file Shurly Views data include file + */ + +function shurly_views_data() { + + // Basic table information. + + $data['shurly']['table']['group'] = t('Shurly'); + + // Advertise this table as a possible base table + $data['shurly']['table']['base'] = array( + 'field' => 'rid', + 'title' => t('Short URLs'), + 'help' => t('Shurly shortened URLs.'), + 'weight' => 10, + ); + + //$data['shurly']['table']['join'] = array( + // 'users' => array( + // 'left_field' => 'uid', + // 'field' => 'uid', + // ), + //); + + // note that this next line adds to the $data['users'] array + // and avoids us from having to do relationships in order to get + // user data into our Views of Shurly links + $data['users']['table']['join']['shurly'] = array( + 'left_field' => 'uid', + 'field' => 'uid', + ); + + // User ID + $data['shurly']['uid'] = array( + 'title' => t('User ID'), + 'help' => t('ID of user who created the link.'), + 'field' => array( + 'handler' => 'views_handler_field_user', + 'click sortable' => TRUE, + ), + 'argument' => array( + 'handler' => 'views_handler_argument_user_uid', + 'name field' => 'name', // display this field in the summary + ), + 'filter' => array( + 'title' => t('Name'), + 'handler' => 'views_handler_filter_user_name', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'relationship' => array( + 'handler' => 'views_handler_relationship', + 'base' => 'users', + 'base field' => 'uid', + 'label' => t('user'), + ), + ); + + // uid + $data['shurly']['uid_current'] = array( + 'real field' => 'uid', + 'title' => t('Current user'), + 'help' => t('Filter the view to the currently logged in user.'), + 'filter' => array( + 'handler' => 'views_handler_filter_user_current', + 'type' => 'yes-no', + ), + ); + + // Shurly Source - Short URL + $data['shurly']['source'] = array( + 'title' => t('Short URL'), + 'help' => t('The source URL which generates a redirect'), + 'field' => array( + 'handler' => 'shurly_handler_field_short_url', + 'parent' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_string', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_string', + ), + ); + + // Shurly Desination - Long URL + $data['shurly']['destination'] = array( + 'title' => t('Long URL'), + 'help' => t('The destination URL'), + 'field' => array( + //'handler' => 'shurly_handler_field_destination', + 'handler' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_string', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_string', + ), + ); + + // Link created timestamp + $data['shurly']['created'] = array( + 'title' => t('Created date'), + 'help' => t('The date/time the link was created.'), + 'field' => array( + 'handler' => 'views_handler_field_date', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_date', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_date', + ), + ); + + // Count + $data['shurly']['count'] = array( + 'title' => t('Clicks'), + 'help' => t('Number of times this link has been followed.'), + 'field' => array( + 'handler' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_numeric', + 'allow empty' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + + ); + + // Link last used timestamp + $data['shurly']['last_used'] = array( + 'title' => t('Last used date'), + 'help' => t('The last date/time the link was used.'), + 'field' => array( + 'handler' => 'views_handler_field_date', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_date', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_date', + ), + ); + + // Boolean for custom entry + $data['shurly']['custom'] = array( + 'title' => t('Custom URL'), + 'help' => t('Boolean flag set for custom short URLs entered by user.'), + 'field' => array( + 'handler' => 'views_handler_field_boolean', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_boolean_operator', + 'label' => t('Custom'), + 'type' => 'yes-no', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + ); + + // Boolean for active link + $data['shurly']['active'] = array( + 'title' => t('URL active'), + 'help' => t('Is this link active or has it been deactivated?'), + 'field' => array( + 'handler' => 'views_handler_field_boolean', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_boolean_operator', + 'label' => t('Custom'), + 'type' => 'yes-no', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + ); + + $data['shurly']['link_test'] = array( + 'field' => array( + 'title' => t('Test URL'), + 'help' => t('Redirecting link.'), + 'handler' => 'shurly_handler_field_shurly_link_test', + 'parent' => 'views_handler_field', + ), + ); + + $data['shurly']['link_delete'] = array( + 'field' => array( + 'title' => t('Delete URL'), + 'help' => t('Link to delete the URL'), + 'handler' => 'shurly_handler_field_shurly_link_delete', + 'parent' => 'views_handler_field', + ), + ); + + return $data; +} + +/** + * Implementation of hook_views_handlers(). + */ +function shurly_views_handlers() { + return array( + 'info' => array( + 'path' => drupal_get_path('module', 'shurly'), + ), + 'handlers' => array( + 'shurly_handler_field_shurly_link_delete' => array( + 'parent' => 'views_handler_field', + ), + 'shurly_handler_field_shurly_link_test' => array( + 'parent' => 'views_handler_field', + ), + 'shurly_handler_field_short_url' => array( + 'parent' => 'views_handler_field', + ), + ), + ); +} diff --git a/views/shurly.views_default.inc b/views/shurly.views_default.inc new file mode 100644 index 0000000..7409e70 --- /dev/null +++ b/views/shurly.views_default.inc @@ -0,0 +1,657 @@ +<?php +// $Id$ + +/** + * @file Shurly default views + */ + +/** + * Implementation of hook_views_default_views(). + */ +function shurly_views_default_views() { + /* + * View 'shurly_admin' + */ + $view = new view; + $view->name = 'shurly_admin'; + $view->description = 'Shurly administration'; + $view->tag = 'shurly'; + $view->view_php = ''; + $view->base_table = 'shurly'; + $view->is_cacheable = FALSE; + $view->api_version = 2; + $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ + $handler = $view->new_display('default', 'Defaults', 'default'); + $handler->override_option('fields', array( + 'count' => array( + 'label' => 'Clicks', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'count', + 'table' => 'shurly', + 'field' => 'count', + 'relationship' => 'none', + ), + 'destination' => array( + 'label' => 'Long URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'destination', + 'table' => 'shurly', + 'field' => 'destination', + 'relationship' => 'none', + ), + 'source' => array( + 'label' => 'Short URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'source', + 'table' => 'shurly', + 'field' => 'source', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'User', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'link_to_user' => 1, + 'overwrite_anonymous' => 0, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'none', + ), + 'created' => array( + 'label' => 'Created', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'small', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + 'last_used' => array( + 'label' => 'Last used', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'time ago', + 'custom_date_format' => '1', + 'exclude' => 0, + 'id' => 'last_used', + 'table' => 'shurly', + 'field' => 'last_used', + 'relationship' => 'none', + ), + 'link_delete' => array( + 'label' => '', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'text' => '', + 'exclude' => 0, + 'id' => 'link_delete', + 'table' => 'shurly', + 'field' => 'link_delete', + 'relationship' => 'none', + ), + )); + $handler->override_option('sorts', array( + 'created' => array( + 'order' => 'DESC', + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + )); + $handler->override_option('access', array( + 'type' => 'perm', + 'perm' => 'Administer short URLs', + )); + $handler->override_option('cache', array( + 'type' => 'none', + )); + $handler->override_option('title', 'Short URLs'); + $handler->override_option('items_per_page', 100); + $handler->override_option('use_pager', '1'); + $handler->override_option('style_plugin', 'table'); + $handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 0, + 'order' => 'desc', + 'columns' => array( + 'source' => 'source', + 'custom' => 'custom', + 'destination' => 'destination', + 'name' => 'name', + 'created' => 'created', + 'last_used' => 'last_used', + 'count' => 'count', + ), + 'info' => array( + 'source' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'custom' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'destination' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'created' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'last_used' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'count' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => 'created', + )); + $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); + $handler->override_option('path', 'admin/build/shurly'); + $handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'Short URLs', + 'description' => 'List, sort, and edit Shurly short URLs', + 'weight' => '0', + 'name' => 'navigation', + )); + $handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', + )); + $views[$view->name] = $view; + + /* + * View 'shurly_my_urls' + */ + $view = new view; + $view->name = 'shurly_my_urls'; + $view->description = 'My short URLs'; + $view->tag = 'shurly'; + $view->view_php = ''; + $view->base_table = 'shurly'; + $view->is_cacheable = FALSE; + $view->api_version = 2; + $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ + $handler = $view->new_display('default', 'Defaults', 'default'); + $handler->override_option('fields', array( + 'count' => array( + 'label' => 'Clicks', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'count', + 'table' => 'shurly', + 'field' => 'count', + 'relationship' => 'none', + ), + 'destination' => array( + 'label' => 'Long URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 1, + 'path' => '[destination]', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '_blank', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'destination', + 'table' => 'shurly', + 'field' => 'destination', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'source' => array( + 'label' => 'Short URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 1, + 'path' => '[source]', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '_blank', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'text' => '', + 'exclude' => 0, + 'id' => 'source', + 'table' => 'shurly', + 'field' => 'source', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + 'link' => 1, + ), + 'created' => array( + 'label' => 'Date', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'custom', + 'custom_date_format' => 'M j', + 'exclude' => 0, + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'last_used' => array( + 'label' => 'Last used', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'time ago', + 'custom_date_format' => '1', + 'exclude' => 0, + 'id' => 'last_used', + 'table' => 'shurly', + 'field' => 'last_used', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'link_delete' => array( + 'label' => '', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'text' => '', + 'exclude' => 0, + 'id' => 'link_delete', + 'table' => 'shurly', + 'field' => 'link_delete', + 'relationship' => 'none', + ), + )); + $handler->override_option('sorts', array( + 'created' => array( + 'order' => 'DESC', + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + )); + $handler->override_option('filters', array( + 'uid_current' => array( + 'operator' => '=', + 'value' => '1', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'uid_current', + 'table' => 'shurly', + 'field' => 'uid_current', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + 'active' => array( + 'operator' => '=', + 'value' => '1', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'active', + 'table' => 'shurly', + 'field' => 'active', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + )); + $handler->override_option('access', array( + 'type' => 'perm', + 'perm' => 'View own URL stats', + )); + $handler->override_option('cache', array( + 'type' => 'none', + )); + $handler->override_option('title', 'My short URLs'); + $handler->override_option('use_ajax', TRUE); + $handler->override_option('items_per_page', 100); + $handler->override_option('use_pager', '1'); + $handler->override_option('style_plugin', 'table'); + $handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 0, + 'order' => 'desc', + 'columns' => array( + 'source' => 'source', + 'custom' => 'custom', + 'destination' => 'destination', + 'name' => 'name', + 'created' => 'created', + 'last_used' => 'last_used', + 'count' => 'count', + ), + 'info' => array( + 'source' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'custom' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'destination' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'created' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'last_used' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'count' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => 'created', + )); + $handler = $view->new_display('page', 'My URLs', 'page_1'); + $handler->override_option('path', 'myurls'); + $handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'My URLs', + 'description' => 'List, sort, and delete short URLs', + 'weight' => '0', + 'name' => 'navigation', + )); + $handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', + )); + $handler = $view->new_display('block', 'Block', 'block_1'); + $handler->override_option('block_description', 'My short URLs'); + $handler->override_option('block_caching', -1); + $views[$view->name] = $view; + + return $views; +} + + diff --git a/views/shurly_handler_field_short_url.inc b/views/shurly_handler_field_short_url.inc new file mode 100644 index 0000000..91382ee --- /dev/null +++ b/views/shurly_handler_field_short_url.inc @@ -0,0 +1,45 @@ +<?php +// $Id$ + +/** + * @file Shurly Views handler for short URL + */ + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_short_url extends views_handler_field { + function construct() { + parent::construct(); + $this->additional_fields['source'] = 'source'; + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function render($values) { + // rawurldecode() allows URLs to be shown with UTF8 characters + // however, this could cause other problems... + $text = !empty($this->options['text']) ? $this->options['text'] : rawurldecode(url($values->{$this->aliases['source']}, array('absolute' => TRUE))); + return $text; + } +} diff --git a/views/shurly_handler_field_shurly_link_delete.inc b/views/shurly_handler_field_shurly_link_delete.inc new file mode 100644 index 0000000..eef1832 --- /dev/null +++ b/views/shurly_handler_field_shurly_link_delete.inc @@ -0,0 +1,47 @@ +<?php +// $Id$ + +/** + * @file Shurly Views handler for delete links function + */ + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_shurly_link_delete extends views_handler_field { + function construct() { + parent::construct(); + $this->additional_fields['uid'] = 'uid'; + } + + function option_definition() { + $options = parent::option_definition(); + $options['text'] = array('default' => '', 'translatable' => TRUE); + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function render($values) { + global $user; + $uid = $values->{$this->aliases['uid']}; + // only allow the user to view the link if they can actually delete + if (user_access('Administer short URLs') || (user_access('Delete own URLs') && $uid == $user->uid)) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); + $rid = $values->rid; + return l($text, "shurly/delete/$rid", array('query' => drupal_get_destination())); + } + } +} diff --git a/views/shurly_handler_field_shurly_link_test.inc b/views/shurly_handler_field_shurly_link_test.inc new file mode 100644 index 0000000..a01836a --- /dev/null +++ b/views/shurly_handler_field_shurly_link_test.inc @@ -0,0 +1,43 @@ +<?php +// $Id$ + +/** + * @file Shurly Views handler for test link + */ + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_shurly_link_test extends views_handler_field { + function construct() { + parent::construct(); + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function render($values) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('test'); + $source = $values->shurly_source; + return l($text, $source); + } +}
rmiddle/shurly
75951edbe8af63abd1cbae2c19140e8c1eefca6b
rearranging files
diff --git a/README.txt b/README.txt index 27f3b00..24c1515 100644 --- a/README.txt +++ b/README.txt @@ -1,46 +1,48 @@ +// $Id$ + ShURLy is a URL shortening service implemented as a module for Drupal. This module was written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me http://www.youtube.com/watch?v=Qo7qoonzTCE New URLs are created by going to /shurly and entering the long URL and an optional custom short URL. Short URLs have ownership and each user can track click statistics for his/her URLs. To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain any non-reserved characters including UTF8 characters, glyphs, and icons. How fun is that!? Views: ---------------------------- ShURLy is completely integrated with the Views module and ShURLy links can be listed/sorted/displayed using Views. Views is a dependency of this module since all listings are created using Views, including the administrative page at admin/build/shurly. Views also provides a page at /myurls where users with "View own URL stats" can see & sort their URLs. Views integration also means that you could create new pages/blocks with listings like "most popular URLs", "users with most popular URLs", "most recent URLs", "most recently clicked URLs", or a tab on a user's page to show others their most recent URLs, and that sort of thing. Blocks: --------------------------- - Create a short URL the form to create a URL - ShURLy bookmarklet A block containing a "drag to your bookmarks bar" link. Clicking this bookmarklet when on a page bring the user to the the URL shortening site with the URL field filled in for that page. - My URLs This block is created by Views and is basically just a mirror the /myurls page. However, by putting this content into a block, you can put it into the 'content bottom' region on the /shurly page and get a single page with both the entry form and the URL listing USAGE: ---------------------------- Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory without clean URLs. Permissions: ---------------------- - Create short URLs: Allow users in this role to create URLs. This permission also allows users to delete URLs which they have created. - Enter custom URLs: Allow users in this role to enter their own short URLs, without this permission all URLs will be autogenerated - View own URL stats: Allow users to view the "My URLs" page (at /myurls) - Delete own URLs: Users may 'delete' URLs which they have created. For security reasons, these URLs are actually only deactivated. They still exist in the database and new URLs are not allowed to be created with the same short URL path. - Administer short URLs This permission allows users to edit/delete/view all short URLs by all users. This is the administrative permission and should be used carefully diff --git a/shurly.module b/shurly.module index 0535bba..6a1ee8e 100644 --- a/shurly.module +++ b/shurly.module @@ -1,477 +1,480 @@ <?php +// $Id$ + /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) * - allow for fun UTF characters in custom URLs */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // if the path has any slashes in it, it's not a short URL // so we can bail out and save ourselves a database call if (strpos($_GET['q'], '/') === FALSE) { $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, + 'path' => drupal_get_path('module', 'shurly') . '/views', ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly.views.inc b/shurly.views.inc deleted file mode 100644 index 8523f72..0000000 --- a/shurly.views.inc +++ /dev/null @@ -1,257 +0,0 @@ -<?php -// $Id$ - -/** - * @file Shurly Views data include file - */ - -function shurly_views_data() { - - // Basic table information. - - $data['shurly']['table']['group'] = t('Shurly'); - - // Advertise this table as a possible base table - $data['shurly']['table']['base'] = array( - 'field' => 'rid', - 'title' => t('Short URLs'), - 'help' => t('Shurly shortened URLs.'), - 'weight' => 10, - ); - - //$data['shurly']['table']['join'] = array( - // 'users' => array( - // 'left_field' => 'uid', - // 'field' => 'uid', - // ), - //); - - // note that this next line adds to the $data['users'] array - // and avoids us from having to do relationships in order to get - // user data into our Views of Shurly links - $data['users']['table']['join']['shurly'] = array( - 'left_field' => 'uid', - 'field' => 'uid', - ); - - // User ID - $data['shurly']['uid'] = array( - 'title' => t('User ID'), - 'help' => t('ID of user who created the link.'), - 'field' => array( - 'handler' => 'views_handler_field_user', - 'click sortable' => TRUE, - ), - 'argument' => array( - 'handler' => 'views_handler_argument_user_uid', - 'name field' => 'name', // display this field in the summary - ), - 'filter' => array( - 'title' => t('Name'), - 'handler' => 'views_handler_filter_user_name', - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'relationship' => array( - 'handler' => 'views_handler_relationship', - 'base' => 'users', - 'base field' => 'uid', - 'label' => t('user'), - ), - ); - - // uid - $data['shurly']['uid_current'] = array( - 'real field' => 'uid', - 'title' => t('Current user'), - 'help' => t('Filter the view to the currently logged in user.'), - 'filter' => array( - 'handler' => 'views_handler_filter_user_current', - 'type' => 'yes-no', - ), - ); - - // Shurly Source - Short URL - $data['shurly']['source'] = array( - 'title' => t('Short URL'), - 'help' => t('The source URL which generates a redirect'), - 'field' => array( - 'handler' => 'shurly_handler_field_short_url', - 'parent' => 'views_handler_field', - 'click sortable' => TRUE, - ), - 'filter' => array( - 'handler' => 'views_handler_filter_string', - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_string', - ), - ); - - // Shurly Desination - Long URL - $data['shurly']['destination'] = array( - 'title' => t('Long URL'), - 'help' => t('The destination URL'), - 'field' => array( - //'handler' => 'shurly_handler_field_destination', - 'handler' => 'views_handler_field', - 'click sortable' => TRUE, - ), - 'filter' => array( - 'handler' => 'views_handler_filter_string', - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_string', - ), - ); - - // Link created timestamp - $data['shurly']['created'] = array( - 'title' => t('Created date'), - 'help' => t('The date/time the link was created.'), - 'field' => array( - 'handler' => 'views_handler_field_date', - 'click sortable' => TRUE, - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'filter' => array( - 'handler' => 'views_handler_filter_date', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_date', - ), - ); - - // Count - $data['shurly']['count'] = array( - 'title' => t('Clicks'), - 'help' => t('Number of times this link has been followed.'), - 'field' => array( - 'handler' => 'views_handler_field', - 'click sortable' => TRUE, - ), - 'filter' => array( - 'handler' => 'views_handler_filter_numeric', - 'allow empty' => TRUE, - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_numeric', - ), - - ); - - // Link last used timestamp - $data['shurly']['last_used'] = array( - 'title' => t('Last used date'), - 'help' => t('The last date/time the link was used.'), - 'field' => array( - 'handler' => 'views_handler_field_date', - 'click sortable' => TRUE, - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'filter' => array( - 'handler' => 'views_handler_filter_date', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_date', - ), - ); - - // Boolean for custom entry - $data['shurly']['custom'] = array( - 'title' => t('Custom URL'), - 'help' => t('Boolean flag set for custom short URLs entered by user.'), - 'field' => array( - 'handler' => 'views_handler_field_boolean', - 'click sortable' => TRUE, - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'filter' => array( - 'handler' => 'views_handler_filter_boolean_operator', - 'label' => t('Custom'), - 'type' => 'yes-no', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_numeric', - ), - ); - - // Boolean for active link - $data['shurly']['active'] = array( - 'title' => t('URL active'), - 'help' => t('Is this link active or has it been deactivated?'), - 'field' => array( - 'handler' => 'views_handler_field_boolean', - 'click sortable' => TRUE, - ), - 'sort' => array( - 'handler' => 'views_handler_sort', - ), - 'filter' => array( - 'handler' => 'views_handler_filter_boolean_operator', - 'label' => t('Custom'), - 'type' => 'yes-no', - ), - 'argument' => array( - 'handler' => 'views_handler_argument_numeric', - ), - ); - - $data['shurly']['link_test'] = array( - 'field' => array( - 'title' => t('Test URL'), - 'help' => t('Redirecting link.'), - 'handler' => 'shurly_handler_field_shurly_link_test', - 'parent' => 'views_handler_field', - ), - ); - - $data['shurly']['link_delete'] = array( - 'field' => array( - 'title' => t('Delete URL'), - 'help' => t('Link to delete the URL'), - 'handler' => 'shurly_handler_field_shurly_link_delete', - 'parent' => 'views_handler_field', - ), - ); - - return $data; -} - -/** - * Implementation of hook_views_handlers(). - */ -function shurly_views_handlers() { - return array( - 'info' => array( - 'path' => drupal_get_path('module', 'shurly'), - ), - 'handlers' => array( - 'shurly_handler_field_shurly_link_delete' => array( - 'parent' => 'views_handler_field', - ), - 'shurly_handler_field_shurly_link_test' => array( - 'parent' => 'views_handler_field', - ), - 'shurly_handler_field_short_url' => array( - 'parent' => 'views_handler_field', - ), - ), - ); -} diff --git a/shurly.views_default.inc b/shurly.views_default.inc deleted file mode 100644 index 7409e70..0000000 --- a/shurly.views_default.inc +++ /dev/null @@ -1,657 +0,0 @@ -<?php -// $Id$ - -/** - * @file Shurly default views - */ - -/** - * Implementation of hook_views_default_views(). - */ -function shurly_views_default_views() { - /* - * View 'shurly_admin' - */ - $view = new view; - $view->name = 'shurly_admin'; - $view->description = 'Shurly administration'; - $view->tag = 'shurly'; - $view->view_php = ''; - $view->base_table = 'shurly'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('fields', array( - 'count' => array( - 'label' => 'Clicks', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'exclude' => 0, - 'id' => 'count', - 'table' => 'shurly', - 'field' => 'count', - 'relationship' => 'none', - ), - 'destination' => array( - 'label' => 'Long URL', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'exclude' => 0, - 'id' => 'destination', - 'table' => 'shurly', - 'field' => 'destination', - 'relationship' => 'none', - ), - 'source' => array( - 'label' => 'Short URL', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'exclude' => 0, - 'id' => 'source', - 'table' => 'shurly', - 'field' => 'source', - 'relationship' => 'none', - ), - 'name' => array( - 'label' => 'User', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'link_to_user' => 1, - 'overwrite_anonymous' => 0, - 'anonymous_text' => '', - 'exclude' => 0, - 'id' => 'name', - 'table' => 'users', - 'field' => 'name', - 'relationship' => 'none', - ), - 'created' => array( - 'label' => 'Created', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'date_format' => 'small', - 'custom_date_format' => '', - 'exclude' => 0, - 'id' => 'created', - 'table' => 'shurly', - 'field' => 'created', - 'relationship' => 'none', - ), - 'last_used' => array( - 'label' => 'Last used', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'date_format' => 'time ago', - 'custom_date_format' => '1', - 'exclude' => 0, - 'id' => 'last_used', - 'table' => 'shurly', - 'field' => 'last_used', - 'relationship' => 'none', - ), - 'link_delete' => array( - 'label' => '', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'text' => '', - 'exclude' => 0, - 'id' => 'link_delete', - 'table' => 'shurly', - 'field' => 'link_delete', - 'relationship' => 'none', - ), - )); - $handler->override_option('sorts', array( - 'created' => array( - 'order' => 'DESC', - 'id' => 'created', - 'table' => 'shurly', - 'field' => 'created', - 'relationship' => 'none', - ), - )); - $handler->override_option('access', array( - 'type' => 'perm', - 'perm' => 'Administer short URLs', - )); - $handler->override_option('cache', array( - 'type' => 'none', - )); - $handler->override_option('title', 'Short URLs'); - $handler->override_option('items_per_page', 100); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 0, - 'order' => 'desc', - 'columns' => array( - 'source' => 'source', - 'custom' => 'custom', - 'destination' => 'destination', - 'name' => 'name', - 'created' => 'created', - 'last_used' => 'last_used', - 'count' => 'count', - ), - 'info' => array( - 'source' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'custom' => array( - 'sortable' => 0, - 'separator' => '', - ), - 'destination' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'created' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'last_used' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'count' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => 'created', - )); - $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); - $handler->override_option('path', 'admin/build/shurly'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'Short URLs', - 'description' => 'List, sort, and edit Shurly short URLs', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => 'navigation', - )); - $views[$view->name] = $view; - - /* - * View 'shurly_my_urls' - */ - $view = new view; - $view->name = 'shurly_my_urls'; - $view->description = 'My short URLs'; - $view->tag = 'shurly'; - $view->view_php = ''; - $view->base_table = 'shurly'; - $view->is_cacheable = FALSE; - $view->api_version = 2; - $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ - $handler = $view->new_display('default', 'Defaults', 'default'); - $handler->override_option('fields', array( - 'count' => array( - 'label' => 'Clicks', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'exclude' => 0, - 'id' => 'count', - 'table' => 'shurly', - 'field' => 'count', - 'relationship' => 'none', - ), - 'destination' => array( - 'label' => 'Long URL', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 1, - 'path' => '[destination]', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '_blank', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'exclude' => 0, - 'id' => 'destination', - 'table' => 'shurly', - 'field' => 'destination', - 'relationship' => 'none', - 'override' => array( - 'button' => 'Override', - ), - ), - 'source' => array( - 'label' => 'Short URL', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 1, - 'path' => '[source]', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '_blank', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'text' => '', - 'exclude' => 0, - 'id' => 'source', - 'table' => 'shurly', - 'field' => 'source', - 'relationship' => 'none', - 'override' => array( - 'button' => 'Override', - ), - 'link' => 1, - ), - 'created' => array( - 'label' => 'Date', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'date_format' => 'custom', - 'custom_date_format' => 'M j', - 'exclude' => 0, - 'id' => 'created', - 'table' => 'shurly', - 'field' => 'created', - 'relationship' => 'none', - 'override' => array( - 'button' => 'Override', - ), - ), - 'last_used' => array( - 'label' => 'Last used', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'date_format' => 'time ago', - 'custom_date_format' => '1', - 'exclude' => 0, - 'id' => 'last_used', - 'table' => 'shurly', - 'field' => 'last_used', - 'relationship' => 'none', - 'override' => array( - 'button' => 'Override', - ), - ), - 'link_delete' => array( - 'label' => '', - 'alter' => array( - 'alter_text' => 0, - 'text' => '', - 'make_link' => 0, - 'path' => '', - 'link_class' => '', - 'alt' => '', - 'prefix' => '', - 'suffix' => '', - 'target' => '', - 'help' => '', - 'trim' => 0, - 'max_length' => '', - 'word_boundary' => 1, - 'ellipsis' => 1, - 'html' => 0, - 'strip_tags' => 0, - ), - 'empty' => '', - 'hide_empty' => 0, - 'empty_zero' => 0, - 'text' => '', - 'exclude' => 0, - 'id' => 'link_delete', - 'table' => 'shurly', - 'field' => 'link_delete', - 'relationship' => 'none', - ), - )); - $handler->override_option('sorts', array( - 'created' => array( - 'order' => 'DESC', - 'id' => 'created', - 'table' => 'shurly', - 'field' => 'created', - 'relationship' => 'none', - ), - )); - $handler->override_option('filters', array( - 'uid_current' => array( - 'operator' => '=', - 'value' => '1', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'uid_current', - 'table' => 'shurly', - 'field' => 'uid_current', - 'override' => array( - 'button' => 'Override', - ), - 'relationship' => 'none', - ), - 'active' => array( - 'operator' => '=', - 'value' => '1', - 'group' => '0', - 'exposed' => FALSE, - 'expose' => array( - 'operator' => FALSE, - 'label' => '', - ), - 'id' => 'active', - 'table' => 'shurly', - 'field' => 'active', - 'override' => array( - 'button' => 'Override', - ), - 'relationship' => 'none', - ), - )); - $handler->override_option('access', array( - 'type' => 'perm', - 'perm' => 'View own URL stats', - )); - $handler->override_option('cache', array( - 'type' => 'none', - )); - $handler->override_option('title', 'My short URLs'); - $handler->override_option('use_ajax', TRUE); - $handler->override_option('items_per_page', 100); - $handler->override_option('use_pager', '1'); - $handler->override_option('style_plugin', 'table'); - $handler->override_option('style_options', array( - 'grouping' => '', - 'override' => 1, - 'sticky' => 0, - 'order' => 'desc', - 'columns' => array( - 'source' => 'source', - 'custom' => 'custom', - 'destination' => 'destination', - 'name' => 'name', - 'created' => 'created', - 'last_used' => 'last_used', - 'count' => 'count', - ), - 'info' => array( - 'source' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'custom' => array( - 'sortable' => 0, - 'separator' => '', - ), - 'destination' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'name' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'created' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'last_used' => array( - 'sortable' => 1, - 'separator' => '', - ), - 'count' => array( - 'sortable' => 1, - 'separator' => '', - ), - ), - 'default' => 'created', - )); - $handler = $view->new_display('page', 'My URLs', 'page_1'); - $handler->override_option('path', 'myurls'); - $handler->override_option('menu', array( - 'type' => 'normal', - 'title' => 'My URLs', - 'description' => 'List, sort, and delete short URLs', - 'weight' => '0', - 'name' => 'navigation', - )); - $handler->override_option('tab_options', array( - 'type' => 'none', - 'title' => '', - 'description' => '', - 'weight' => 0, - 'name' => 'navigation', - )); - $handler = $view->new_display('block', 'Block', 'block_1'); - $handler->override_option('block_description', 'My short URLs'); - $handler->override_option('block_caching', -1); - $views[$view->name] = $view; - - return $views; -} - - diff --git a/shurly_handler_field_short_url.inc b/shurly_handler_field_short_url.inc deleted file mode 100644 index 91382ee..0000000 --- a/shurly_handler_field_short_url.inc +++ /dev/null @@ -1,45 +0,0 @@ -<?php -// $Id$ - -/** - * @file Shurly Views handler for short URL - */ - -/** - * Field handler to present a link to the short URL entry. - */ -class shurly_handler_field_short_url extends views_handler_field { - function construct() { - parent::construct(); - $this->additional_fields['source'] = 'source'; - } - - function option_definition() { - $options = parent::option_definition(); - - $options['text'] = array('default' => '', 'translatable' => TRUE); - - return $options; - } - - function options_form(&$form, &$form_state) { - parent::options_form($form, $form_state); - $form['text'] = array( - '#type' => 'textfield', - '#title' => t('Text to display'), - '#default_value' => $this->options['text'], - ); - } - - function query() { - $this->ensure_my_table(); - $this->add_additional_fields(); - } - - function render($values) { - // rawurldecode() allows URLs to be shown with UTF8 characters - // however, this could cause other problems... - $text = !empty($this->options['text']) ? $this->options['text'] : rawurldecode(url($values->{$this->aliases['source']}, array('absolute' => TRUE))); - return $text; - } -} diff --git a/shurly_handler_field_shurly_link_delete.inc b/shurly_handler_field_shurly_link_delete.inc deleted file mode 100644 index eef1832..0000000 --- a/shurly_handler_field_shurly_link_delete.inc +++ /dev/null @@ -1,47 +0,0 @@ -<?php -// $Id$ - -/** - * @file Shurly Views handler for delete links function - */ - -/** - * Field handler to present a link to the short URL entry. - */ -class shurly_handler_field_shurly_link_delete extends views_handler_field { - function construct() { - parent::construct(); - $this->additional_fields['uid'] = 'uid'; - } - - function option_definition() { - $options = parent::option_definition(); - $options['text'] = array('default' => '', 'translatable' => TRUE); - return $options; - } - - function options_form(&$form, &$form_state) { - parent::options_form($form, $form_state); - $form['text'] = array( - '#type' => 'textfield', - '#title' => t('Text to display'), - '#default_value' => $this->options['text'], - ); - } - - function query() { - $this->ensure_my_table(); - $this->add_additional_fields(); - } - - function render($values) { - global $user; - $uid = $values->{$this->aliases['uid']}; - // only allow the user to view the link if they can actually delete - if (user_access('Administer short URLs') || (user_access('Delete own URLs') && $uid == $user->uid)) { - $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); - $rid = $values->rid; - return l($text, "shurly/delete/$rid", array('query' => drupal_get_destination())); - } - } -} diff --git a/shurly_handler_field_shurly_link_test.inc b/shurly_handler_field_shurly_link_test.inc deleted file mode 100644 index a01836a..0000000 --- a/shurly_handler_field_shurly_link_test.inc +++ /dev/null @@ -1,43 +0,0 @@ -<?php -// $Id$ - -/** - * @file Shurly Views handler for test link - */ - -/** - * Field handler to present a link to the short URL entry. - */ -class shurly_handler_field_shurly_link_test extends views_handler_field { - function construct() { - parent::construct(); - } - - function option_definition() { - $options = parent::option_definition(); - - $options['text'] = array('default' => '', 'translatable' => TRUE); - - return $options; - } - - function options_form(&$form, &$form_state) { - parent::options_form($form, $form_state); - $form['text'] = array( - '#type' => 'textfield', - '#title' => t('Text to display'), - '#default_value' => $this->options['text'], - ); - } - - function query() { - $this->ensure_my_table(); - $this->add_additional_fields(); - } - - function render($values) { - $text = !empty($this->options['text']) ? $this->options['text'] : t('test'); - $source = $values->shurly_source; - return l($text, $source); - } -}
rmiddle/shurly
28f41b3e8a8569a8c433169a07874d18b39fb08c
Fix for #1. Removed bootstrapping of path.inc... which had the effect GREATLY speeding up the redirect process. Improvements overall!
diff --git a/shurly.module b/shurly.module index da9fd62..0535bba 100644 --- a/shurly.module +++ b/shurly.module @@ -1,476 +1,477 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) * - allow for fun UTF characters in custom URLs */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { - // we boostrap the path.inc file early to set up $_GET['q'] - // this is a little bit of a hack and may impact performance of sites with page caching slightly - _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); - $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); - if ($row) { - shurly_goto($row); + // if the path has any slashes in it, it's not a short URL + // so we can bail out and save ourselves a database call + if (strpos($_GET['q'], '/') === FALSE) { + $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); + if ($row) { + shurly_goto($row); + } } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
9ffd6f63a85621107adeef955a73fe9da65e2abc
Updating README to mention use of UTF8 characters
diff --git a/README.txt b/README.txt index bfa922d..27f3b00 100644 --- a/README.txt +++ b/README.txt @@ -1,46 +1,46 @@ ShURLy is a URL shortening service implemented as a module for Drupal. This module was written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me http://www.youtube.com/watch?v=Qo7qoonzTCE New URLs are created by going to /shurly and entering the long URL and an optional custom short URL. Short URLs have ownership and each user can track click statistics for his/her URLs. -To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain characters A-Z, a-z, 0-9, also "-" and "_". +To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain any non-reserved characters including UTF8 characters, glyphs, and icons. How fun is that!? Views: ---------------------------- ShURLy is completely integrated with the Views module and ShURLy links can be listed/sorted/displayed using Views. Views is a dependency of this module since all listings are created using Views, including the administrative page at admin/build/shurly. Views also provides a page at /myurls where users with "View own URL stats" can see & sort their URLs. Views integration also means that you could create new pages/blocks with listings like "most popular URLs", "users with most popular URLs", "most recent URLs", "most recently clicked URLs", or a tab on a user's page to show others their most recent URLs, and that sort of thing. Blocks: --------------------------- - Create a short URL the form to create a URL - ShURLy bookmarklet A block containing a "drag to your bookmarks bar" link. Clicking this bookmarklet when on a page bring the user to the the URL shortening site with the URL field filled in for that page. - My URLs This block is created by Views and is basically just a mirror the /myurls page. However, by putting this content into a block, you can put it into the 'content bottom' region on the /shurly page and get a single page with both the entry form and the URL listing USAGE: ---------------------------- Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory without clean URLs. Permissions: ---------------------- - Create short URLs: Allow users in this role to create URLs. This permission also allows users to delete URLs which they have created. - Enter custom URLs: Allow users in this role to enter their own short URLs, without this permission all URLs will be autogenerated - View own URL stats: Allow users to view the "My URLs" page (at /myurls) - Delete own URLs: Users may 'delete' URLs which they have created. For security reasons, these URLs are actually only deactivated. They still exist in the database and new URLs are not allowed to be created with the same short URL path. - Administer short URLs This permission allows users to edit/delete/view all short URLs by all users. This is the administrative permission and should be used carefully
rmiddle/shurly
38242fa2624937754e8464e21428145e303b4af3
UTF8 URL's, baby!
diff --git a/shurly.module b/shurly.module index 2094bf3..da9fd62 100644 --- a/shurly.module +++ b/shurly.module @@ -1,474 +1,476 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) * - allow for fun UTF characters in custom URLs */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'bookmarklet' && user_access('Create short URLs')) { drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); $block = array('subject' => t('Bookmarklet'), 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; if (!$user->uid) { // anonymous users can't delete URLs return FALSE; } // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { - form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); + form_set_error('short_url', t('Short URL contains unallowed characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; - $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); + $final_url = $form_state['storage']['shurly']['final_url'] = rawurldecode(url($short_url, array('absolute' => TRUE))); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; + // return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; + // disallow: #%&@*{}\:;<>?/+.,$|`^[] and space character + return preg_match('/[#%&@*\{\}\\:\;<>\?\/\+ \.\,\'\"\$\|`^\[\]]/u', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly_handler_field_short_url.inc b/shurly_handler_field_short_url.inc index fc70a2b..91382ee 100644 --- a/shurly_handler_field_short_url.inc +++ b/shurly_handler_field_short_url.inc @@ -1,43 +1,45 @@ <?php // $Id$ /** * @file Shurly Views handler for short URL */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_short_url extends views_handler_field { function construct() { parent::construct(); $this->additional_fields['source'] = 'source'; } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function render($values) { - $text = !empty($this->options['text']) ? $this->options['text'] : url($values->{$this->aliases['source']}, array('absolute' => TRUE)); + // rawurldecode() allows URLs to be shown with UTF8 characters + // however, this could cause other problems... + $text = !empty($this->options['text']) ? $this->options['text'] : rawurldecode(url($values->{$this->aliases['source']}, array('absolute' => TRUE))); return $text; } }
rmiddle/shurly
b6f0e9907e5f300723233234fcc0a5f4be05bcc4
More enlightening description
diff --git a/README.txt b/README.txt index 9e7fea6..bfa922d 100644 --- a/README.txt +++ b/README.txt @@ -1,44 +1,46 @@ ShURLy is a URL shortening service implemented as a module for Drupal. This module was written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me +http://www.youtube.com/watch?v=Qo7qoonzTCE + New URLs are created by going to /shurly and entering the long URL and an optional custom short URL. Short URLs have ownership and each user can track click statistics for his/her URLs. To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain characters A-Z, a-z, 0-9, also "-" and "_". Views: ---------------------------- ShURLy is completely integrated with the Views module and ShURLy links can be listed/sorted/displayed using Views. Views is a dependency of this module since all listings are created using Views, including the administrative page at admin/build/shurly. Views also provides a page at /myurls where users with "View own URL stats" can see & sort their URLs. Views integration also means that you could create new pages/blocks with listings like "most popular URLs", "users with most popular URLs", "most recent URLs", "most recently clicked URLs", or a tab on a user's page to show others their most recent URLs, and that sort of thing. Blocks: --------------------------- - Create a short URL the form to create a URL - ShURLy bookmarklet A block containing a "drag to your bookmarks bar" link. Clicking this bookmarklet when on a page bring the user to the the URL shortening site with the URL field filled in for that page. - My URLs This block is created by Views and is basically just a mirror the /myurls page. However, by putting this content into a block, you can put it into the 'content bottom' region on the /shurly page and get a single page with both the entry form and the URL listing USAGE: ---------------------------- Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory without clean URLs. Permissions: ---------------------- - Create short URLs: Allow users in this role to create URLs. This permission also allows users to delete URLs which they have created. - Enter custom URLs: Allow users in this role to enter their own short URLs, without this permission all URLs will be autogenerated - View own URL stats: Allow users to view the "My URLs" page (at /myurls) - Delete own URLs: Users may 'delete' URLs which they have created. For security reasons, these URLs are actually only deactivated. They still exist in the database and new URLs are not allowed to be created with the same short URL path. - Administer short URLs This permission allows users to edit/delete/view all short URLs by all users. This is the administrative permission and should be used carefully
rmiddle/shurly
3ae3fe7b591769be9f1edfa754e4ba5ff221d441
I think there's an unnecessary join in the views definition. Commenting it out.
diff --git a/shurly.views.inc b/shurly.views.inc index 3f248cb..8523f72 100644 --- a/shurly.views.inc +++ b/shurly.views.inc @@ -1,257 +1,257 @@ <?php // $Id$ /** * @file Shurly Views data include file */ function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); - $data['shurly']['table']['join'] = array( - 'users' => array( - 'left_field' => 'uid', - 'field' => 'uid', - ), - ); + //$data['shurly']['table']['join'] = array( + // 'users' => array( + // 'left_field' => 'uid', + // 'field' => 'uid', + // ), + //); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( 'handler' => 'shurly_handler_field_short_url', 'parent' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( //'handler' => 'shurly_handler_field_destination', 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( 'title' => t('Clicks'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['shurly']['link_test'] = array( 'field' => array( 'title' => t('Test URL'), 'help' => t('Redirecting link.'), 'handler' => 'shurly_handler_field_shurly_link_test', 'parent' => 'views_handler_field', ), ); $data['shurly']['link_delete'] = array( 'field' => array( 'title' => t('Delete URL'), 'help' => t('Link to delete the URL'), 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function shurly_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'shurly'), ), 'handlers' => array( 'shurly_handler_field_shurly_link_delete' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_shurly_link_test' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_short_url' => array( 'parent' => 'views_handler_field', ), ), ); }
rmiddle/shurly
fd1e31f2732de5a6ee99573de6e22ac198f83a2b
Using 'delete own URLs' permission in delete link handler
diff --git a/shurly_handler_field_shurly_link_delete.inc b/shurly_handler_field_shurly_link_delete.inc index 3e8a101..eef1832 100644 --- a/shurly_handler_field_shurly_link_delete.inc +++ b/shurly_handler_field_shurly_link_delete.inc @@ -1,47 +1,47 @@ <?php // $Id$ /** * @file Shurly Views handler for delete links function */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_shurly_link_delete extends views_handler_field { function construct() { parent::construct(); $this->additional_fields['uid'] = 'uid'; } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function render($values) { global $user; $uid = $values->{$this->aliases['uid']}; // only allow the user to view the link if they can actually delete - if (user_access('Administer short URLs') || $uid == $user->uid) { + if (user_access('Administer short URLs') || (user_access('Delete own URLs') && $uid == $user->uid)) { $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); $rid = $values->rid; return l($text, "shurly/delete/$rid", array('query' => drupal_get_destination())); } } }
rmiddle/shurly
e05aef515d36c24f0808be9cfa80ccebda644b52
Tweaking out default Views
diff --git a/shurly.views_default.inc b/shurly.views_default.inc index 854d015..7409e70 100644 --- a/shurly.views_default.inc +++ b/shurly.views_default.inc @@ -1,645 +1,657 @@ <?php // $Id$ /** * @file Shurly default views */ /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'small', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '', - 'make_link' => 0, - 'path' => '', + 'make_link' => 1, + 'path' => '[destination]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', - 'target' => '', + 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', - 'make_link' => 0, - 'path' => '', + 'make_link' => 1, + 'path' => '[source]', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', - 'target' => '', + 'target' => '_blank', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, + 'text' => '', 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + 'link' => 1, ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); + $handler->override_option('use_ajax', TRUE); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); + $handler = $view->new_display('block', 'Block', 'block_1'); + $handler->override_option('block_description', 'My short URLs'); + $handler->override_option('block_caching', -1); $views[$view->name] = $view; return $views; }
rmiddle/shurly
9c159287a4923fd7d440c3681ff8a45be7e7383e
A LOT more content in the README file
diff --git a/README.txt b/README.txt index 8203f53..9e7fea6 100644 --- a/README.txt +++ b/README.txt @@ -1,4 +1,44 @@ -ShURLy is a URL shortening service implemented as a module for Drupal. +ShURLy is a URL shortening service implemented as a module for Drupal. This module was written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me -It was originally written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me +New URLs are created by going to /shurly and entering the long URL and an optional custom short URL. Short URLs have ownership and each user can track click statistics for his/her URLs. +To maximize the use of characters, URLs are case sensitive. With the correct permissions, short URLs can either be entered custom or autogenerated. Autogenerated URLs use the character set of A-Z, a-z, 0-9. However the characters "01lIO" are not used since these characters are often ambiguous, particularly in print (thanks to Tantek ‚elik for this suggestion). Custom URLs may contain characters A-Z, a-z, 0-9, also "-" and "_". + +Views: ---------------------------- +ShURLy is completely integrated with the Views module and ShURLy links can be listed/sorted/displayed using Views. Views is a dependency of this module since all listings are created using Views, including the administrative page at admin/build/shurly. Views also provides a page at /myurls where users with "View own URL stats" can see & sort their URLs. + +Views integration also means that you could create new pages/blocks with listings like "most popular URLs", "users with most popular URLs", "most recent URLs", "most recently clicked URLs", or a tab on a user's page to show others their most recent URLs, and that sort of thing. + +Blocks: --------------------------- +- Create a short URL + the form to create a URL +- ShURLy bookmarklet + A block containing a "drag to your bookmarks bar" link. Clicking this + bookmarklet when on a page bring the user to the the URL shortening + site with the URL field filled in for that page. +- My URLs + This block is created by Views and is basically just a mirror the + /myurls page. However, by putting this content into a block, you can + put it into the 'content bottom' region on the /shurly page and get + a single page with both the entry form and the URL listing + +USAGE: ---------------------------- +Since short URLs are created at the root path of the site (http://example.com/myURL), it is recommended that this module be used as the basis for a complete site, not as an add-on to an existing site. That being said, the module does its best to ensure that entered URLs don't conflict with existing menu entries and path aliases in the current Drupal installation. ShURLy should work even if Drupal is installed in a subdirectory without clean URLs. + +Permissions: ---------------------- +- Create short URLs: + Allow users in this role to create URLs. This permission also allows users to delete URLs which they have created. +- Enter custom URLs: + Allow users in this role to enter their own short URLs, + without this permission all URLs will be autogenerated +- View own URL stats: + Allow users to view the "My URLs" page (at /myurls) +- Delete own URLs: + Users may 'delete' URLs which they have created. For security reasons, + these URLs are actually only deactivated. They still exist in the + database and new URLs are not allowed to be created with the same + short URL path. +- Administer short URLs + This permission allows users to edit/delete/view all short URLs by + all users. This is the administrative permission and should be + used carefully
rmiddle/shurly
1afcb109b016150f6bd7e2e20fc91c03d7fed717
added Views as a dependency
diff --git a/shurly.info b/shurly.info index 63c2ada..dae7ba3 100755 --- a/shurly.info +++ b/shurly.info @@ -1,4 +1,5 @@ ; $Id$ -name = Shurly +name = ShURLy description = A complete short URL service. -core = 6.x +dependencies[] = views +core = 6.x \ No newline at end of file
rmiddle/shurly
f2022cfba37299175bfae18672c043185e58eb69
Add new permission for 'delete own URLs'
diff --git a/shurly.module b/shurly.module index a7fcad6..2094bf3 100644 --- a/shurly.module +++ b/shurly.module @@ -1,470 +1,474 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) + * - allow for fun UTF characters in custom URLs */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); $items['shurly/delete/%'] = array( 'title' => 'Delete URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_confirm_delete_form', 2), 'access callback' => 'shurly_delete_access', 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { - return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Administer short URLs'); + return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Delete own URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); - $blocks['history'] = array('info' => t('Link history')); + $blocks['bookmarklet'] = array('info' => t('ShURLy bookmarklet')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } - if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { - $block = array('subject' => t('Link history'), - 'content' => shurly_link_history()); + if ($delta == 'bookmarklet' && user_access('Create short URLs')) { + drupal_add_css(drupal_get_path('module', 'shurly') . '/shurly.css'); + $block = array('subject' => t('Bookmarklet'), + 'content' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), + ); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /** * Access callback for deleting (deactivating) a URL */ function shurly_delete_access($rid) { if (is_numeric($rid)) { global $user; + if (!$user->uid) { + // anonymous users can't delete URLs + return FALSE; + } + // see if there's a row $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); - if ($row && (user_access('Administer short URLs') || $row->uid == $user->uid)) { + // if there's a row, and either the user is an admin, or they've got permission to create and they own this URL, then let them access + if ($row && (user_access('Administer short URLs') || (user_access('Delete own URLs') && $row->uid == $user->uid))) { return TRUE; } } return FALSE; } /** * Confirmation form to delete a link */ function shurly_confirm_delete_form(&$form_state, $rid) { $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); // the 'destination' argument here is a bit of a hack... return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } /** * Submit handler for above form */ function shurly_confirm_delete_form_submit($form, &$form_state) { drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', - '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), + '#default_value' => isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] : ($_GET['url'] ? $_GET['url'] : 'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } - $form['bookmarklet'] = array( - '#type' => 'markup', - '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), - ); - unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { form_set_error('short_url', t('This short URL has already been used')); //if ($exists == 'found') { // form_set_error('short_url', t('This short URL is already used')); //} //else { // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); // $form_state['url_exists'] = TRUE; // drupal_set_message(t('This URL pair already exists'), 'error'); //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
e49b6c8523a3dd8e74303054ca0f2b4018f2f1d5
Moved delete to shurly/delete. Created menu access callback function and rearranged the way that the delete form is called.
diff --git a/shurly.module b/shurly.module index 0df9691..a7fcad6 100644 --- a/shurly.module +++ b/shurly.module @@ -1,464 +1,470 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo - * - (option to) make short URL Views fields longer in listing * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); - $items['admin/build/shurly/delete/%'] = array( + $items['shurly/delete/%'] = array( 'title' => 'Delete URL', - 'page callback' => 'shurly_confirm_delete', - 'page arguments' => array(4), - 'access arguments' => array('Create short URLs'), + 'page callback' => 'drupal_get_form', + 'page arguments' => array('shurly_confirm_delete_form', 2), + 'access callback' => 'shurly_delete_access', + 'access arguments' => array(2), 'type' => MENU_CALLBACK, ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['history'] = array('info' => t('Link history')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { $block = array('subject' => t('Link history'), 'content' => shurly_link_history()); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } -function shurly_confirm_delete($rid) { - // check access - global $user; +/** + * Implementation of hook_views_api. + * Notifies the Views module that we're compatible with a particular API revision. + */ +function shurly_views_api() { + return array( + 'api' => 2, + ); +} + +/** + * Access callback for deleting (deactivating) a URL + */ +function shurly_delete_access($rid) { if (is_numeric($rid)) { - $row = db_fetch_object(db_query('SELECT uid FROM {shurly} WHERE rid = %d', $rid)); - } - if ($row && (user_access('Administer short URLs') || $row->uid == $user->uid)) { - return drupal_get_form('shurly_confirm_delete_form', $rid); - } - else { - drupal_access_denied(); - return; + global $user; + $row = db_fetch_object(db_query('SELECT uid, source, destination FROM {shurly} WHERE rid = %d', $rid)); + if ($row && (user_access('Administer short URLs') || $row->uid == $user->uid)) { + return TRUE; + } } + return FALSE; } +/** + * Confirmation form to delete a link + */ function shurly_confirm_delete_form(&$form_state, $rid) { + $row = db_fetch_object(db_query('SELECT destination FROM {shurly} WHERE rid = %d', $rid)); $form['rid'] = array( '#type' => 'value', '#value' => $rid, ); - return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_GET['destination']), t('Once this item is deleted, you will not be able to create another link with the same short URL.')); + // the 'destination' argument here is a bit of a hack... + return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_REQUEST['destination']), t('You are about to deactivate the link which redirects to %url. Once this item is deleted, you will not be able to create another link with the same short URL.', array('%url' => $row->destination))); } +/** + * Submit handler for above form + */ function shurly_confirm_delete_form_submit($form, &$form_state) { - drupal_set_message(t('URL deactivated')); + drupal_set_message(t('URL has been deactivated')); shurly_set_link_active($form_state['values']['rid'], 0); } /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } $form['bookmarklet'] = array( '#type' => 'markup', '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { - if ($exists == 'found') { - form_set_error('short_url', t('This short URL is already used')); - } - else { - $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); - $form_state['url_exists'] = TRUE; - drupal_set_message(t('This URL pair already exists'), 'error'); - } + form_set_error('short_url', t('This short URL has already been used')); + //if ($exists == 'found') { + // form_set_error('short_url', t('This short URL is already used')); + //} + //else { + // $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); + // $form_state['url_exists'] = TRUE; + // drupal_set_message(t('This URL pair already exists'), 'error'); + //} } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } - - /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } -/** - * Implementation of hook_views_api. - * Notifies the Views module that we're compatible with a particular API revision. - */ -function shurly_views_api() { - return array( - 'api' => 2, - ); -} - /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
bee26b96d2ed358e536512ed39aad738d6341cab
Cleaning up Views handler code and adding proper access checks before displaying delete links
diff --git a/shurly_handler_field_short_url.inc b/shurly_handler_field_short_url.inc index dc90eba..fc70a2b 100644 --- a/shurly_handler_field_short_url.inc +++ b/shurly_handler_field_short_url.inc @@ -1,43 +1,43 @@ <?php // $Id$ /** - * @file Shurly Views handler for test link + * @file Shurly Views handler for short URL */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_short_url extends views_handler_field { function construct() { parent::construct(); $this->additional_fields['source'] = 'source'; } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function render($values) { - $text = !empty($this->options['text']) ? $this->options['text'] : url($values->shurly_source, array('absolute' => TRUE)); + $text = !empty($this->options['text']) ? $this->options['text'] : url($values->{$this->aliases['source']}, array('absolute' => TRUE)); return $text; } } diff --git a/shurly_handler_field_shurly_link_delete.inc b/shurly_handler_field_shurly_link_delete.inc index a6be5da..3e8a101 100644 --- a/shurly_handler_field_shurly_link_delete.inc +++ b/shurly_handler_field_shurly_link_delete.inc @@ -1,49 +1,47 @@ <?php // $Id$ /** * @file Shurly Views handler for delete links function */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_shurly_link_delete extends views_handler_field { function construct() { parent::construct(); + $this->additional_fields['uid'] = 'uid'; } function option_definition() { $options = parent::option_definition(); - $options['text'] = array('default' => '', 'translatable' => TRUE); - return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } - - function access() { - global $user; - $uid = $values->{$this->aliases['uid']}; - return user_access('Administer short URLs'); // || $this->uid == $user->uid - } function render($values) { - $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); - $rid = $values->rid; - return l($text, "admin/build/shurly/delete/$rid", array('query' => drupal_get_destination())); + global $user; + $uid = $values->{$this->aliases['uid']}; + // only allow the user to view the link if they can actually delete + if (user_access('Administer short URLs') || $uid == $user->uid) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); + $rid = $values->rid; + return l($text, "shurly/delete/$rid", array('query' => drupal_get_destination())); + } } }
rmiddle/shurly
60279db80492aa7768b35f1604ef2231fc9479e9
delete callback
diff --git a/shurly.module b/shurly.module index 92ebb6a..0df9691 100644 --- a/shurly.module +++ b/shurly.module @@ -1,428 +1,464 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - (option to) make short URL Views fields longer in listing * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); + $items['admin/build/shurly/delete/%'] = array( + 'title' => 'Delete URL', + 'page callback' => 'shurly_confirm_delete', + 'page arguments' => array(4), + 'access arguments' => array('Create short URLs'), + 'type' => MENU_CALLBACK, + ); + return $items; } /** * Implementation of hook_perm() */ function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['history'] = array('info' => t('Link history')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { $block = array('subject' => t('Link history'), 'content' => shurly_link_history()); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } +function shurly_confirm_delete($rid) { + // check access + global $user; + if (is_numeric($rid)) { + $row = db_fetch_object(db_query('SELECT uid FROM {shurly} WHERE rid = %d', $rid)); + } + if ($row && (user_access('Administer short URLs') || $row->uid == $user->uid)) { + return drupal_get_form('shurly_confirm_delete_form', $rid); + } + else { + drupal_access_denied(); + return; + } +} + +function shurly_confirm_delete_form(&$form_state, $rid) { + $form['rid'] = array( + '#type' => 'value', + '#value' => $rid, + ); + return confirm_form($form, t('Are you sure you want to delete and deactivate this URL?'), rawurldecode($_GET['destination']), t('Once this item is deleted, you will not be able to create another link with the same short URL.')); +} + +function shurly_confirm_delete_form_submit($form, &$form_state) { + drupal_set_message(t('URL deactivated')); + shurly_set_link_active($form_state['values']['rid'], 0); +} + /** * The main form */ function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } $form['bookmarklet'] = array( '#type' => 'markup', '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { if ($exists == 'found') { form_set_error('short_url', t('This short URL is already used')); } else { $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); $form_state['url_exists'] = TRUE; drupal_set_message(t('This URL pair already exists'), 'error'); } } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); } elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file
rmiddle/shurly
14c61c1e07152ce64cff273993249af751e8e297
short url field handler
diff --git a/shurly.views.inc b/shurly.views.inc index 09b1a36..3f248cb 100644 --- a/shurly.views.inc +++ b/shurly.views.inc @@ -1,252 +1,257 @@ <?php // $Id$ /** * @file Shurly Views data include file */ function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); $data['shurly']['table']['join'] = array( 'users' => array( 'left_field' => 'uid', 'field' => 'uid', ), ); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( - 'handler' => 'views_handler_field', + 'handler' => 'shurly_handler_field_short_url', + 'parent' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( + //'handler' => 'shurly_handler_field_destination', 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( 'title' => t('Clicks'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['shurly']['link_test'] = array( 'field' => array( 'title' => t('Test URL'), 'help' => t('Redirecting link.'), 'handler' => 'shurly_handler_field_shurly_link_test', 'parent' => 'views_handler_field', ), ); $data['shurly']['link_delete'] = array( 'field' => array( 'title' => t('Delete URL'), 'help' => t('Link to delete the URL'), 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function shurly_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'shurly'), ), 'handlers' => array( 'shurly_handler_field_shurly_link_delete' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_shurly_link_test' => array( 'parent' => 'views_handler_field', ), + 'shurly_handler_field_short_url' => array( + 'parent' => 'views_handler_field', + ), ), ); }
rmiddle/shurly
e8de930901a13b88d0da72764719228cda6bf2ce
short url field handler
diff --git a/shurly_handler_field_short_url.inc b/shurly_handler_field_short_url.inc new file mode 100644 index 0000000..dc90eba --- /dev/null +++ b/shurly_handler_field_short_url.inc @@ -0,0 +1,43 @@ +<?php +// $Id$ + +/** + * @file Shurly Views handler for test link + */ + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_short_url extends views_handler_field { + function construct() { + parent::construct(); + $this->additional_fields['source'] = 'source'; + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function render($values) { + $text = !empty($this->options['text']) ? $this->options['text'] : url($values->shurly_source, array('absolute' => TRUE)); + return $text; + } +}
rmiddle/shurly
6f2df34e9fad9b3a0ff36e39aa15bb47afc0a6e1
Coder module cleanup
diff --git a/shurly.install b/shurly.install index 900b363..a900582 100644 --- a/shurly.install +++ b/shurly.install @@ -1,86 +1,91 @@ <?php +// $Id$ + +/** + * @file Shurly install file + */ /** * Implement hook_schema(). */ function shurly_schema() { $schema['shurly'] = array( 'description' => t('URL redirects for the Shurly module'), 'fields' => array( 'rid' => array( 'description' => t('unique redirect id'), 'type' => 'serial', 'not null' => TRUE, ), 'uid' => array( 'description' => t('user id of owner'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'source' => array( 'description' => t('source path'), 'type' => 'varchar', 'length' => '255', 'not null' => TRUE, ), 'destination' => array( 'description' => t('redirect URL'), 'type' => 'varchar', 'length' => '255', 'not null' => TRUE, ), 'created' => array( 'description' => t('datestamp of creation'), 'type' => 'int', 'not null' => TRUE, ), 'count' => array( 'description' => t('usage count'), 'type' => 'int', 'not null' => TRUE, ), 'last_used' => array( 'description' => t('datestamp of last use'), 'type' => 'int', 'not null' => TRUE, ), 'custom' => array( 'description' => t('flag for custom path'), 'type' => 'int', 'not null' => TRUE, 'default' => 0, ), 'active' => array( 'description' => t('allows links to be deactivated'), 'type' => 'int', 'not null' => TRUE, 'default' => 1, ), ), 'primary key' => array('rid'), 'indexes' => array( 'source' => array('source'), ), ); return $schema; } /** * Implement hook_install(). */ function shurly_install() { drupal_install_schema('shurly'); } /** * Implement hook_uninstall(). */ function shurly_uninstall() { // Remove tables. drupal_uninstall_schema('shurly'); // Remove variables. } diff --git a/shurly.module b/shurly.module index c88abc1..92ebb6a 100644 --- a/shurly.module +++ b/shurly.module @@ -1,425 +1,428 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo + * - (option to) make short URL Views fields longer in listing + * - click to copy link in views * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ -function shurly_menu(){ +function shurly_menu() { // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); return $items; } /** * Implementation of hook_perm() */ -function shurly_perm(){ +function shurly_perm() { return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Administer short URLs'); } -function shurly_block($op = 'list', $delta = 0, $edit = array()){ +function shurly_block($op = 'list', $delta = 0, $edit = array()) { // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['history'] = array('info' => t('Link history')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { $block = array('subject' => t('Link history'), 'content' => shurly_link_history()); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } /** * The main form */ -function shurly_create_form($form_state){ +function shurly_create_form($form_state) { $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => $short_default, '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), - '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">'. t('copy'). '</div></div> - <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">'. t('Create a Twitter message with this link') .'</a></div></div>', + '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">' . t('copy') . '</div></div> + <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">' . t('Create a Twitter message with this link') . '</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } $form['bookmarklet'] = array( '#type' => 'markup', '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } - elseif($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { + elseif ($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { if ($exists == 'found') { form_set_error('short_url', t('This short URL is already used')); } else { $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); $form_state['url_exists'] = TRUE; drupal_set_message(t('This URL pair already exists'), 'error'); } } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ -function shurly_dec2any($num, $base=62, $index=false) { +function shurly_dec2any($num, $base=62, $index=FALSE) { if (! $base ) { $base = strlen( $index ); - } else if (! $index ) { + } + elseif (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO - $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base ); + $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 0, $base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ -function shurly_path_available($path){ +function shurly_path_available($path) { $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly.views.inc b/shurly.views.inc index c65afad..09b1a36 100644 --- a/shurly.views.inc +++ b/shurly.views.inc @@ -1,247 +1,252 @@ <?php +// $Id$ + +/** + * @file Shurly Views data include file + */ function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); $data['shurly']['table']['join'] = array( 'users' => array( 'left_field' => 'uid', 'field' => 'uid', ), ); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( 'title' => t('Clicks'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['shurly']['link_test'] = array( 'field' => array( 'title' => t('Test URL'), 'help' => t('Redirecting link.'), 'handler' => 'shurly_handler_field_shurly_link_test', 'parent' => 'views_handler_field', ), ); $data['shurly']['link_delete'] = array( 'field' => array( 'title' => t('Delete URL'), 'help' => t('Link to delete the URL'), 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function shurly_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'shurly'), ), 'handlers' => array( 'shurly_handler_field_shurly_link_delete' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_shurly_link_test' => array( 'parent' => 'views_handler_field', ), ), ); } diff --git a/shurly.views_default.inc b/shurly.views_default.inc index 4ec3f13..854d015 100644 --- a/shurly.views_default.inc +++ b/shurly.views_default.inc @@ -1,514 +1,518 @@ <?php +// $Id$ +/** + * @file Shurly default views + */ /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'small', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', diff --git a/shurly_handler_field_shurly_link_delete.inc b/shurly_handler_field_shurly_link_delete.inc index c2e8a66..a6be5da 100644 --- a/shurly_handler_field_shurly_link_delete.inc +++ b/shurly_handler_field_shurly_link_delete.inc @@ -1,44 +1,49 @@ <?php +// $Id$ + +/** + * @file Shurly Views handler for delete links function + */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_shurly_link_delete extends views_handler_field { function construct() { parent::construct(); } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function access() { global $user; $uid = $values->{$this->aliases['uid']}; return user_access('Administer short URLs'); // || $this->uid == $user->uid } function render($values) { $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); $rid = $values->rid; return l($text, "admin/build/shurly/delete/$rid", array('query' => drupal_get_destination())); } } diff --git a/shurly_handler_field_shurly_link_test.inc b/shurly_handler_field_shurly_link_test.inc index 22ddd0e..a01836a 100644 --- a/shurly_handler_field_shurly_link_test.inc +++ b/shurly_handler_field_shurly_link_test.inc @@ -1,38 +1,43 @@ <?php +// $Id$ + +/** + * @file Shurly Views handler for test link + */ /** * Field handler to present a link to the short URL entry. */ class shurly_handler_field_shurly_link_test extends views_handler_field { function construct() { parent::construct(); } function option_definition() { $options = parent::option_definition(); $options['text'] = array('default' => '', 'translatable' => TRUE); return $options; } function options_form(&$form, &$form_state) { parent::options_form($form, $form_state); $form['text'] = array( '#type' => 'textfield', '#title' => t('Text to display'), '#default_value' => $this->options['text'], ); } function query() { $this->ensure_my_table(); $this->add_additional_fields(); } function render($values) { $text = !empty($this->options['text']) ? $this->options['text'] : t('test'); $source = $values->shurly_source; return l($text, $source); } }
rmiddle/shurly
d3f7f63e7283408256b1667e68b802587acb9e32
Adding new permissions for 'Enter custom URLs', 'View own URL stats'
diff --git a/shurly.module b/shurly.module index 078830a..c88abc1 100644 --- a/shurly.module +++ b/shurly.module @@ -1,422 +1,425 @@ <?php /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu(){ // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); return $items; } /** * Implementation of hook_perm() */ function shurly_perm(){ - return array('Create short URLs', 'Administer short URLs'); + return array('Create short URLs', 'Enter custom URLs', 'View own URL stats', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()){ // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['history'] = array('info' => t('Link history')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { $block = array('subject' => t('Link history'), 'content' => shurly_link_history()); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } /** * The main form */ function shurly_create_form($form_state){ $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); + $short_default = user_access('Enter custom URLs') ? (isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '') : ''; + $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', - '#default_value' => isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '', + '#default_value' => $short_default, + '#access' => user_access('Enter custom URLs'), ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">'. t('copy'). '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">'. t('Create a Twitter message with this link') .'</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } $form['bookmarklet'] = array( '#type' => 'markup', '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } elseif($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { if ($exists == 'found') { form_set_error('short_url', t('This short URL is already used')); } else { $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); $form_state['url_exists'] = TRUE; drupal_set_message(t('This URL pair already exists'), 'error'); } } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=false) { if (! $base ) { $base = strlen( $index ); } else if (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path){ $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly.views_default.inc b/shurly.views_default.inc index 450815d..4ec3f13 100644 --- a/shurly.views_default.inc +++ b/shurly.views_default.inc @@ -53,589 +53,589 @@ function shurly_views_default_views() { 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( 'label' => 'Created', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'small', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', 'perm' => 'Administer short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'Short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); $handler->override_option('path', 'admin/build/shurly'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'Short URLs', 'description' => 'List, sort, and edit Shurly short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; /* * View 'shurly_my_urls' */ $view = new view; $view->name = 'shurly_my_urls'; $view->description = 'My short URLs'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( 'count' => array( 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), 'destination' => array( 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'destination', 'table' => 'shurly', 'field' => 'destination', 'relationship' => 'none', ), 'source' => array( 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'source', 'table' => 'shurly', 'field' => 'source', 'relationship' => 'none', ), 'created' => array( 'label' => 'Date', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'custom', 'custom_date_format' => 'M j', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'last_used' => array( 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', 'override' => array( 'button' => 'Override', ), ), 'link_delete' => array( 'label' => '', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'text' => '', 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); $handler->override_option('filters', array( 'uid_current' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'uid_current', 'table' => 'shurly', 'field' => 'uid_current', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), 'active' => array( 'operator' => '=', 'value' => '1', 'group' => '0', 'exposed' => FALSE, 'expose' => array( 'operator' => FALSE, 'label' => '', ), 'id' => 'active', 'table' => 'shurly', 'field' => 'active', 'override' => array( 'button' => 'Override', ), 'relationship' => 'none', ), )); $handler->override_option('access', array( 'type' => 'perm', - 'perm' => 'Create short URLs', + 'perm' => 'View own URL stats', )); $handler->override_option('cache', array( 'type' => 'none', )); $handler->override_option('title', 'My short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); $handler = $view->new_display('page', 'My URLs', 'page_1'); $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', 'title' => 'My URLs', 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; return $views; }
rmiddle/shurly
e9d6e0d49e87fbd6c923bfbdd70d325d64e60e02
Adding new "My URLs" default view
diff --git a/shurly.views_default.inc b/shurly.views_default.inc index 61c9cf9..450815d 100644 --- a/shurly.views_default.inc +++ b/shurly.views_default.inc @@ -1,335 +1,641 @@ <?php /** * Implementation of hook_views_default_views(). */ function shurly_views_default_views() { /* * View 'shurly_admin' */ $view = new view; $view->name = 'shurly_admin'; $view->description = 'Shurly administration'; $view->tag = 'shurly'; $view->view_php = ''; $view->base_table = 'shurly'; $view->is_cacheable = FALSE; $view->api_version = 2; $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ $handler = $view->new_display('default', 'Defaults', 'default'); $handler->override_option('fields', array( - 'source' => array( - 'label' => 'Short URL', + 'count' => array( + 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, - 'id' => 'source', + 'id' => 'count', 'table' => 'shurly', - 'field' => 'source', + 'field' => 'count', 'relationship' => 'none', ), - 'custom' => array( - 'label' => 'Custom', + 'destination' => array( + 'label' => 'Long URL', 'alter' => array( 'alter_text' => 0, - 'text' => '✓', + 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', - 'hide_empty' => 1, - 'empty_zero' => 1, - 'type' => 'yes-no', - 'not' => 0, + 'hide_empty' => 0, + 'empty_zero' => 0, 'exclude' => 0, - 'id' => 'custom', + 'id' => 'destination', 'table' => 'shurly', - 'field' => 'custom', + 'field' => 'destination', 'relationship' => 'none', - 'override' => array( - 'button' => 'Override', - ), ), - 'destination' => array( - 'label' => 'Long URL', + 'source' => array( + 'label' => 'Short URL', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, - 'id' => 'destination', + 'id' => 'source', 'table' => 'shurly', - 'field' => 'destination', + 'field' => 'source', 'relationship' => 'none', ), 'name' => array( 'label' => 'User', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'link_to_user' => 1, 'overwrite_anonymous' => 0, 'anonymous_text' => '', 'exclude' => 0, 'id' => 'name', 'table' => 'users', 'field' => 'name', 'relationship' => 'none', ), 'created' => array( - 'label' => 'Created date', + 'label' => 'Created', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'small', 'custom_date_format' => '', 'exclude' => 0, 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), 'last_used' => array( - 'label' => 'Last used date', + 'label' => 'Last used', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'date_format' => 'time ago', - 'custom_date_format' => '', + 'custom_date_format' => '1', 'exclude' => 0, 'id' => 'last_used', 'table' => 'shurly', 'field' => 'last_used', 'relationship' => 'none', ), + 'link_delete' => array( + 'label' => '', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'text' => '', + 'exclude' => 0, + 'id' => 'link_delete', + 'table' => 'shurly', + 'field' => 'link_delete', + 'relationship' => 'none', + ), + )); + $handler->override_option('sorts', array( + 'created' => array( + 'order' => 'DESC', + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + )); + $handler->override_option('access', array( + 'type' => 'perm', + 'perm' => 'Administer short URLs', + )); + $handler->override_option('cache', array( + 'type' => 'none', + )); + $handler->override_option('title', 'Short URLs'); + $handler->override_option('items_per_page', 100); + $handler->override_option('use_pager', '1'); + $handler->override_option('style_plugin', 'table'); + $handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 0, + 'order' => 'desc', + 'columns' => array( + 'source' => 'source', + 'custom' => 'custom', + 'destination' => 'destination', + 'name' => 'name', + 'created' => 'created', + 'last_used' => 'last_used', + 'count' => 'count', + ), + 'info' => array( + 'source' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'custom' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'destination' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'created' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'last_used' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'count' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => 'created', + )); + $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); + $handler->override_option('path', 'admin/build/shurly'); + $handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'Short URLs', + 'description' => 'List, sort, and edit Shurly short URLs', + 'weight' => '0', + 'name' => 'navigation', + )); + $handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', + )); + $views[$view->name] = $view; + + /* + * View 'shurly_my_urls' + */ + $view = new view; + $view->name = 'shurly_my_urls'; + $view->description = 'My short URLs'; + $view->tag = 'shurly'; + $view->view_php = ''; + $view->base_table = 'shurly'; + $view->is_cacheable = FALSE; + $view->api_version = 2; + $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ + $handler = $view->new_display('default', 'Defaults', 'default'); + $handler->override_option('fields', array( 'count' => array( - 'label' => 'Count', + 'label' => 'Clicks', 'alter' => array( 'alter_text' => 0, 'text' => '', 'make_link' => 0, 'path' => '', 'link_class' => '', 'alt' => '', 'prefix' => '', 'suffix' => '', 'target' => '', 'help' => '', 'trim' => 0, 'max_length' => '', 'word_boundary' => 1, 'ellipsis' => 1, 'html' => 0, 'strip_tags' => 0, ), 'empty' => '', 'hide_empty' => 0, 'empty_zero' => 0, 'exclude' => 0, 'id' => 'count', 'table' => 'shurly', 'field' => 'count', 'relationship' => 'none', ), + 'destination' => array( + 'label' => 'Long URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'destination', + 'table' => 'shurly', + 'field' => 'destination', + 'relationship' => 'none', + ), + 'source' => array( + 'label' => 'Short URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'source', + 'table' => 'shurly', + 'field' => 'source', + 'relationship' => 'none', + ), + 'created' => array( + 'label' => 'Date', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'custom', + 'custom_date_format' => 'M j', + 'exclude' => 0, + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'last_used' => array( + 'label' => 'Last used', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'time ago', + 'custom_date_format' => '1', + 'exclude' => 0, + 'id' => 'last_used', + 'table' => 'shurly', + 'field' => 'last_used', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), 'link_delete' => array( + 'label' => '', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'text' => '', + 'exclude' => 0, 'id' => 'link_delete', 'table' => 'shurly', 'field' => 'link_delete', - ), - 'link_test' => array( - 'id' => 'link_test', - 'table' => 'shurly', - 'field' => 'link_test', + 'relationship' => 'none', ), )); $handler->override_option('sorts', array( 'created' => array( 'order' => 'DESC', 'id' => 'created', 'table' => 'shurly', 'field' => 'created', 'relationship' => 'none', ), )); + $handler->override_option('filters', array( + 'uid_current' => array( + 'operator' => '=', + 'value' => '1', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'uid_current', + 'table' => 'shurly', + 'field' => 'uid_current', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + 'active' => array( + 'operator' => '=', + 'value' => '1', + 'group' => '0', + 'exposed' => FALSE, + 'expose' => array( + 'operator' => FALSE, + 'label' => '', + ), + 'id' => 'active', + 'table' => 'shurly', + 'field' => 'active', + 'override' => array( + 'button' => 'Override', + ), + 'relationship' => 'none', + ), + )); $handler->override_option('access', array( 'type' => 'perm', - 'perm' => 'Administer short URLs', + 'perm' => 'Create short URLs', )); $handler->override_option('cache', array( 'type' => 'none', )); - $handler->override_option('title', 'Short URLs'); + $handler->override_option('title', 'My short URLs'); $handler->override_option('items_per_page', 100); $handler->override_option('use_pager', '1'); $handler->override_option('style_plugin', 'table'); $handler->override_option('style_options', array( 'grouping' => '', 'override' => 1, 'sticky' => 0, 'order' => 'desc', 'columns' => array( 'source' => 'source', 'custom' => 'custom', 'destination' => 'destination', 'name' => 'name', 'created' => 'created', 'last_used' => 'last_used', 'count' => 'count', ), 'info' => array( 'source' => array( 'sortable' => 1, 'separator' => '', ), 'custom' => array( 'sortable' => 0, 'separator' => '', ), 'destination' => array( 'sortable' => 1, 'separator' => '', ), 'name' => array( 'sortable' => 1, 'separator' => '', ), 'created' => array( 'sortable' => 1, 'separator' => '', ), 'last_used' => array( 'sortable' => 1, 'separator' => '', ), 'count' => array( 'sortable' => 1, 'separator' => '', ), ), 'default' => 'created', )); - $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); - $handler->override_option('path', 'admin/build/shurly'); + $handler = $view->new_display('page', 'My URLs', 'page_1'); + $handler->override_option('path', 'myurls'); $handler->override_option('menu', array( 'type' => 'normal', - 'title' => 'Short URLs', - 'description' => 'List, sort, and edit Shurly short URLs', + 'title' => 'My URLs', + 'description' => 'List, sort, and delete short URLs', 'weight' => '0', 'name' => 'navigation', )); $handler->override_option('tab_options', array( 'type' => 'none', 'title' => '', 'description' => '', 'weight' => 0, 'name' => 'navigation', )); $views[$view->name] = $view; return $views; }
rmiddle/shurly
65fea10497d680c5250606e13fad9117c38a24c3
Cleaning up and fixing some bugs
diff --git a/shurly.module b/shurly.module index b45a9b5..078830a 100644 --- a/shurly.module +++ b/shurly.module @@ -1,440 +1,422 @@ <?php -//include_once('shurly.views.inc'); -//include_once('views_handler_field_shurly_link.inc'); - /** * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE * * @todo * - create REST API * - prevent endless loop links (back to themselves or others on this site) */ /** * Implementation of hook_menu() */ function shurly_menu(){ // callback for creation of URLs $items = array(); $items['shurly'] = array( 'title' => 'Create URL', 'description' => 'Create a short URL', 'page callback' => 'drupal_get_form', 'page arguments' => array('shurly_create_form'), 'access arguments' => array('Create short URLs'), ); - //$items['i'] = array( - // 'title' => 'URL Info', - // 'page callback' => 'drupal_get_form', - // 'page arguments' => array('shurly_create_form'), - // 'access arguments' => array('Create short URLs'), - //); - - $items['myurls'] = array( - 'title' => 'URL Info', - 'description' => 'Create a short URL', - 'page callback' => 'drupal_get_form', - 'page arguments' => array('shurly_create_form'), - 'access arguments' => array('Create short URLs'), - ); - return $items; } /** * Implementation of hook_perm() */ function shurly_perm(){ return array('Create short URLs', 'Administer short URLs'); } function shurly_block($op = 'list', $delta = 0, $edit = array()){ // create a block to add URL switch ($op) { case 'list': $blocks['form'] = array('info' => t('Short URL form')); $blocks['history'] = array('info' => t('Link history')); return $blocks; case 'view': // don't show the block when user is on the callback page if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { $block = array('subject' => t('Create a short URL'), 'content' => drupal_get_form('shurly_create_form')); return $block; } if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { $block = array('subject' => t('Link history'), 'content' => shurly_link_history()); return $block; } break; } } /** * Implementation of hook_boot() */ function shurly_boot() { // we boostrap the path.inc file early to set up $_GET['q'] // this is a little bit of a hack and may impact performance of sites with page caching slightly _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); if ($row) { shurly_goto($row); } } /** * The main form */ function shurly_create_form($form_state){ $path = drupal_get_path('module', 'shurly'); drupal_add_css($path . '/shurly.css'); // form to create new short URLs $form['long_url'] = array( '#title' => t('Enter a long URL to make short'), '#type' => 'textfield', '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), ); $form['submit'] = array( '#type' => 'submit', '#value' => t('Make it!'), ); $form['short_url'] = array( '#type' => 'textfield', '#size' => 6, '#field_prefix' => $GLOBALS['base_url'] .'/', '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', '#default_value' => isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '', ); if (isset($form_state['storage']['shurly']['final_url'])) { $form['result'] = array( '#type' => 'textfield', '#size' => 30, '#value' => $form_state['storage']['shurly']['final_url'], '#prefix' => '<div class="shurly-result">', '#suffix' => '</div>', '#field_prefix' => t('Your short URL: '), '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">'. t('copy'). '</div></div> <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">'. t('Create a Twitter message with this link') .'</a></div></div>', ); drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); drupal_add_js($path . '/shurly.js'); drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); } $form['bookmarklet'] = array( '#type' => 'markup', '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), ); unset($form_state['storage']['shurly']); return $form; } function shurly_create_form_validate(&$form, &$form_state) { - if (!user_access('create short URLs')) { + if (!user_access('Create short URLs')) { form_set_error('', t('You do not have permission to create short URLs on this site')); return; } $form_state['values']['long_url'] = trim($form_state['values']['long_url']); $form_state['values']['short_url'] = trim($form_state['values']['short_url']); $vals = $form_state['values']; // check that they've entered a URL if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { form_set_error('long_url', t('Please enter a web URL')); } elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); } if (trim($vals['short_url']) != '') { // a custom short URL has been entered $form_state['custom'] = TRUE; if (!shurly_validate_custom($vals['short_url'])) { form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); } elseif($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { if ($exists == 'found') { form_set_error('short_url', t('This short URL is already used')); } else { $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); $form_state['url_exists'] = TRUE; drupal_set_message(t('This URL pair already exists'), 'error'); } } elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { // check that link isn't to itself (creating infinite loop) // problem - http vs https form_set_error('short_url', t('You cannot create links to themselves')); } elseif (!shurly_path_available($vals['short_url'])) { form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); } } else { // custom short URL field is empty $form_state['custom'] = FALSE; if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { $short = $exist; // we flag this as URL Exists so that it displays but doesn't get saved to the db $form_state['url_exists'] = TRUE; } else { $short = shurly_next_url(); } $form_state['values']['short_url'] = $short; $form_state['storage']['shurly']['short_url'] = $short; } } function shurly_create_form_submit($form, &$form_state) { // submit the short URL form $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); $custom = $form_state['custom']; if (empty($form_state['url_exists'])) { shurly_save_url($long_url, $short_url, NULL, $custom); } } /** * From http://www.php.net/manual/en/function.base-convert.php#52450 * * Parameters: * $num - your decimal integer * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") */ function shurly_dec2any($num, $base=62, $index=false) { if (! $base ) { $base = strlen( $index ); } else if (! $index ) { // note: we could rearrange this string to get more random looking URLs // another note, to create printable URLs, omit the following characters: 01lIO $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base ); } $out = ""; for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { $a = floor( $num / pow( $base, $t ) ); $out = $out . substr( $index, $a, 1 ); $num = $num - ( $a * pow( $base, $t ) ); } return $out; } /** * Implementation of hook_views_api. * Notifies the Views module that we're compatible with a particular API revision. */ function shurly_views_api() { return array( 'api' => 2, ); } /****************************************************** * API functions ****************************************************** */ /** * API function to save a URL */ function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { if (is_null($account)) { $account = $GLOBALS['user']; } $record = array(); $record['destination'] = $long_url; $record['custom'] = $custom ? 1 : 0; $record['created'] = time(); $record['source'] = $short_path; $record['uid'] = $account->uid; $record['count'] = $record['last_used'] = 0; $record['active'] = 1; return drupal_write_record('shurly', $record); } /** * Activate or deactivate a link */ function shurly_set_link_active($rid, $active) { $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); if ($record) { $record['rid'] = $rid; $record['active'] = $active ? 1 : 0; return drupal_write_record('shurly', $record, 'rid'); } else { return FALSE; } } /** * Validate custom short URL string * * @return TRUE if valid, FALSE if invalid */ function shurly_validate_custom($custom) { // we allow alphanumeric characters as well as _, and - return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; } /** * Generate a random short URL * Pretty much unused at this point * this method could take a LOOOONG time on a site with lots of URLs */ function shurly_generate_random($len = NULL) { if ($len == NULL) { $len = variable_get('shurly_length', 4); } $charset = "abcdefghijklmnopqrstuvwxyz123456789"; $charlen = strlen($charset) - 1; do { $str = ''; for ($i=0; $i<$len; $i++) { $str .= $charset[mt_rand(0, $charlen)]; } // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); return $str; } /** * Return next available short URL */ function shurly_next_url() { $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters do { $count++; // counter is stored as base 10 // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters // a custom index can be created as a variable override in settings.php $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); $str = shurly_dec2any($count, NULL, $index); // check that this string hasn't been used already // check that the string is a valid (available) path } while (shurly_url_exists($str) || !shurly_path_available($str)); variable_set('shurly_counter', $count); return $str; } /** * Checks to see if there's a menu handler or a path alias for a given path * * @return TRUE if there are no conflicts */ function shurly_path_available($path){ $return = TRUE; // see if $path is an alias $source = drupal_lookup_path('source', $path); if ($source) { // if so, set alias source to $path $path = $source; } // check to see if $path has a menu callback if (menu_get_item($path)) { $return = FALSE; } return $return; } /** * Check to see if this short URL already exists */ function shurly_url_exists($short, $long = NULL) { $redirect = shurly_get_redirect($short); $return = FALSE; if ($redirect) { $return = 'found'; } if ($long && $redirect->destination == $long) { $return = 'match'; } return $return; } /** * Given the short URL, return the long one * NOTE: Always check $redirect->active before using the result */ function shurly_get_redirect($short_url) { // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); return $redirect; } /** * Get the latest generated short URL by a given user for a given long URL */ function shurly_get_latest_short($long, $uid) { return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); } /** * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() */ function shurly_goto($row) { if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { return; } $url = $row->destination; // Remove newlines from the URL to avoid header injection attacks. $url = str_replace(array("\n", "\r"), '', $url); // Allow modules to react to the end of the page request before redirecting. // We do not want this while running update.php. if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { module_invoke_all('exit', $url); } // Even though session_write_close() is registered as a shutdown function, we // need all session data written to the database before redirecting. session_write_close(); header('Location: '. $url, TRUE, 301); // update access information on this row db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); // The "Location" header sends a redirect status code to the HTTP daemon. In // some cases this can be wrong, so we make sure none of the code below the // drupal_goto() call gets executed upon redirection. exit(); } \ No newline at end of file diff --git a/shurly.views.inc b/shurly.views.inc index 691e635..c65afad 100644 --- a/shurly.views.inc +++ b/shurly.views.inc @@ -1,247 +1,247 @@ <?php function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); $data['shurly']['table']['join'] = array( 'users' => array( 'left_field' => 'uid', 'field' => 'uid', ), ); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( - 'title' => t('Use count'), + 'title' => t('Clicks'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); $data['shurly']['link_test'] = array( 'field' => array( 'title' => t('Test URL'), 'help' => t('Redirecting link.'), 'handler' => 'shurly_handler_field_shurly_link_test', 'parent' => 'views_handler_field', ), ); $data['shurly']['link_delete'] = array( 'field' => array( 'title' => t('Delete URL'), 'help' => t('Link to delete the URL'), 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); return $data; } /** * Implementation of hook_views_handlers(). */ function shurly_views_handlers() { return array( 'info' => array( 'path' => drupal_get_path('module', 'shurly'), ), 'handlers' => array( 'shurly_handler_field_shurly_link_delete' => array( 'parent' => 'views_handler_field', ), 'shurly_handler_field_shurly_link_test' => array( 'parent' => 'views_handler_field', ), ), ); } diff --git a/shurly_handler_field_shurly_link.inc b/shurly_handler_field_shurly_link.inc deleted file mode 100644 index 0026812..0000000 --- a/shurly_handler_field_shurly_link.inc +++ /dev/null @@ -1,43 +0,0 @@ -<?php - -/** - * Field handler to present a link to the short URL entry. - */ -class shurly_handler_field_shurly_link extends views_handler_field { - function construct() { - parent::construct(); - $this->additional_fields['source'] = 'source'; - } - - function option_definition() { - $options = parent::option_definition(); - - $options['text'] = array('default' => '', 'translatable' => TRUE); - - return $options; - } - - function options_form(&$form, &$form_state) { - parent::options_form($form, $form_state); - $form['text'] = array( - '#type' => 'textfield', - '#title' => t('Text to display'), - '#default_value' => $this->options['text'], - ); - } - - function query() { - $this->ensure_my_table(); - $this->add_additional_fields(); - } - - //function access() { - //return user_access('administer users'); - //} - - function render($values) { - $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); - $uid = $values->{$this->aliases['uid']}; - return l($text, "user/$uid/delete", array('query' => drupal_get_destination())); - } -}
rmiddle/shurly
c43028bd366fe2e94953000660e79120823cddb2
Working Views handlers. Working default View. Good stuff!
diff --git a/shurly.views.inc b/shurly.views.inc index e756234..691e635 100644 --- a/shurly.views.inc +++ b/shurly.views.inc @@ -1,220 +1,247 @@ <?php function shurly_views_data() { // Basic table information. $data['shurly']['table']['group'] = t('Shurly'); // Advertise this table as a possible base table $data['shurly']['table']['base'] = array( 'field' => 'rid', - 'title' => t('Link'), + 'title' => t('Short URLs'), 'help' => t('Shurly shortened URLs.'), 'weight' => 10, ); $data['shurly']['table']['join'] = array( 'users' => array( 'left_field' => 'uid', 'field' => 'uid', ), ); // note that this next line adds to the $data['users'] array // and avoids us from having to do relationships in order to get // user data into our Views of Shurly links $data['users']['table']['join']['shurly'] = array( 'left_field' => 'uid', 'field' => 'uid', ); // User ID $data['shurly']['uid'] = array( 'title' => t('User ID'), 'help' => t('ID of user who created the link.'), 'field' => array( 'handler' => 'views_handler_field_user', 'click sortable' => TRUE, ), 'argument' => array( 'handler' => 'views_handler_argument_user_uid', 'name field' => 'name', // display this field in the summary ), 'filter' => array( 'title' => t('Name'), 'handler' => 'views_handler_filter_user_name', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'relationship' => array( 'handler' => 'views_handler_relationship', 'base' => 'users', 'base field' => 'uid', 'label' => t('user'), ), ); // uid $data['shurly']['uid_current'] = array( 'real field' => 'uid', 'title' => t('Current user'), 'help' => t('Filter the view to the currently logged in user.'), 'filter' => array( 'handler' => 'views_handler_filter_user_current', 'type' => 'yes-no', ), ); // Shurly Source - Short URL $data['shurly']['source'] = array( 'title' => t('Short URL'), 'help' => t('The source URL which generates a redirect'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Shurly Desination - Long URL $data['shurly']['destination'] = array( 'title' => t('Long URL'), 'help' => t('The destination URL'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_string', ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_string', ), ); // Link created timestamp $data['shurly']['created'] = array( 'title' => t('Created date'), 'help' => t('The date/time the link was created.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Count $data['shurly']['count'] = array( - 'title' => t('Count'), + 'title' => t('Use count'), 'help' => t('Number of times this link has been followed.'), 'field' => array( 'handler' => 'views_handler_field', 'click sortable' => TRUE, ), 'filter' => array( 'handler' => 'views_handler_filter_numeric', 'allow empty' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Link last used timestamp $data['shurly']['last_used'] = array( 'title' => t('Last used date'), 'help' => t('The last date/time the link was used.'), 'field' => array( 'handler' => 'views_handler_field_date', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_date', ), 'argument' => array( 'handler' => 'views_handler_argument_date', ), ); // Boolean for custom entry $data['shurly']['custom'] = array( - 'title' => t('Custom link'), + 'title' => t('Custom URL'), 'help' => t('Boolean flag set for custom short URLs entered by user.'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); // Boolean for active link $data['shurly']['active'] = array( - 'title' => t('Link active'), + 'title' => t('URL active'), 'help' => t('Is this link active or has it been deactivated?'), 'field' => array( 'handler' => 'views_handler_field_boolean', 'click sortable' => TRUE, ), 'sort' => array( 'handler' => 'views_handler_sort', ), 'filter' => array( 'handler' => 'views_handler_filter_boolean_operator', 'label' => t('Custom'), 'type' => 'yes-no', ), 'argument' => array( 'handler' => 'views_handler_argument_numeric', ), ); - $data['shurly']['source_link'] = array( + $data['shurly']['link_test'] = array( 'field' => array( - 'title' => t('Test link'), + 'title' => t('Test URL'), 'help' => t('Redirecting link.'), - 'handler' => 'shurly_handler_field_shurly_link', + 'handler' => 'shurly_handler_field_shurly_link_test', + 'parent' => 'views_handler_field', + ), + ); + + $data['shurly']['link_delete'] = array( + 'field' => array( + 'title' => t('Delete URL'), + 'help' => t('Link to delete the URL'), + 'handler' => 'shurly_handler_field_shurly_link_delete', 'parent' => 'views_handler_field', ), ); - return $data; } + +/** + * Implementation of hook_views_handlers(). + */ +function shurly_views_handlers() { + return array( + 'info' => array( + 'path' => drupal_get_path('module', 'shurly'), + ), + 'handlers' => array( + 'shurly_handler_field_shurly_link_delete' => array( + 'parent' => 'views_handler_field', + ), + 'shurly_handler_field_shurly_link_test' => array( + 'parent' => 'views_handler_field', + ), + ), + ); +} diff --git a/shurly.views_default.inc b/shurly.views_default.inc new file mode 100644 index 0000000..61c9cf9 --- /dev/null +++ b/shurly.views_default.inc @@ -0,0 +1,335 @@ +<?php + + +/** + * Implementation of hook_views_default_views(). + */ +function shurly_views_default_views() { + /* + * View 'shurly_admin' + */ + $view = new view; + $view->name = 'shurly_admin'; + $view->description = 'Shurly administration'; + $view->tag = 'shurly'; + $view->view_php = ''; + $view->base_table = 'shurly'; + $view->is_cacheable = FALSE; + $view->api_version = 2; + $view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */ + $handler = $view->new_display('default', 'Defaults', 'default'); + $handler->override_option('fields', array( + 'source' => array( + 'label' => 'Short URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'source', + 'table' => 'shurly', + 'field' => 'source', + 'relationship' => 'none', + ), + 'custom' => array( + 'label' => 'Custom', + 'alter' => array( + 'alter_text' => 0, + 'text' => '✓', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 1, + 'empty_zero' => 1, + 'type' => 'yes-no', + 'not' => 0, + 'exclude' => 0, + 'id' => 'custom', + 'table' => 'shurly', + 'field' => 'custom', + 'relationship' => 'none', + 'override' => array( + 'button' => 'Override', + ), + ), + 'destination' => array( + 'label' => 'Long URL', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'destination', + 'table' => 'shurly', + 'field' => 'destination', + 'relationship' => 'none', + ), + 'name' => array( + 'label' => 'User', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'link_to_user' => 1, + 'overwrite_anonymous' => 0, + 'anonymous_text' => '', + 'exclude' => 0, + 'id' => 'name', + 'table' => 'users', + 'field' => 'name', + 'relationship' => 'none', + ), + 'created' => array( + 'label' => 'Created date', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'small', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + 'last_used' => array( + 'label' => 'Last used date', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'date_format' => 'time ago', + 'custom_date_format' => '', + 'exclude' => 0, + 'id' => 'last_used', + 'table' => 'shurly', + 'field' => 'last_used', + 'relationship' => 'none', + ), + 'count' => array( + 'label' => 'Count', + 'alter' => array( + 'alter_text' => 0, + 'text' => '', + 'make_link' => 0, + 'path' => '', + 'link_class' => '', + 'alt' => '', + 'prefix' => '', + 'suffix' => '', + 'target' => '', + 'help' => '', + 'trim' => 0, + 'max_length' => '', + 'word_boundary' => 1, + 'ellipsis' => 1, + 'html' => 0, + 'strip_tags' => 0, + ), + 'empty' => '', + 'hide_empty' => 0, + 'empty_zero' => 0, + 'exclude' => 0, + 'id' => 'count', + 'table' => 'shurly', + 'field' => 'count', + 'relationship' => 'none', + ), + 'link_delete' => array( + 'id' => 'link_delete', + 'table' => 'shurly', + 'field' => 'link_delete', + ), + 'link_test' => array( + 'id' => 'link_test', + 'table' => 'shurly', + 'field' => 'link_test', + ), + )); + $handler->override_option('sorts', array( + 'created' => array( + 'order' => 'DESC', + 'id' => 'created', + 'table' => 'shurly', + 'field' => 'created', + 'relationship' => 'none', + ), + )); + $handler->override_option('access', array( + 'type' => 'perm', + 'perm' => 'Administer short URLs', + )); + $handler->override_option('cache', array( + 'type' => 'none', + )); + $handler->override_option('title', 'Short URLs'); + $handler->override_option('items_per_page', 100); + $handler->override_option('use_pager', '1'); + $handler->override_option('style_plugin', 'table'); + $handler->override_option('style_options', array( + 'grouping' => '', + 'override' => 1, + 'sticky' => 0, + 'order' => 'desc', + 'columns' => array( + 'source' => 'source', + 'custom' => 'custom', + 'destination' => 'destination', + 'name' => 'name', + 'created' => 'created', + 'last_used' => 'last_used', + 'count' => 'count', + ), + 'info' => array( + 'source' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'custom' => array( + 'sortable' => 0, + 'separator' => '', + ), + 'destination' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'name' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'created' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'last_used' => array( + 'sortable' => 1, + 'separator' => '', + ), + 'count' => array( + 'sortable' => 1, + 'separator' => '', + ), + ), + 'default' => 'created', + )); + $handler = $view->new_display('page', 'Administer short URLs', 'page_1'); + $handler->override_option('path', 'admin/build/shurly'); + $handler->override_option('menu', array( + 'type' => 'normal', + 'title' => 'Short URLs', + 'description' => 'List, sort, and edit Shurly short URLs', + 'weight' => '0', + 'name' => 'navigation', + )); + $handler->override_option('tab_options', array( + 'type' => 'none', + 'title' => '', + 'description' => '', + 'weight' => 0, + 'name' => 'navigation', + )); + $views[$view->name] = $view; + + return $views; +} + + diff --git a/shurly_handler_field_shurly_link_delete.inc b/shurly_handler_field_shurly_link_delete.inc new file mode 100644 index 0000000..c2e8a66 --- /dev/null +++ b/shurly_handler_field_shurly_link_delete.inc @@ -0,0 +1,44 @@ +<?php + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_shurly_link_delete extends views_handler_field { + function construct() { + parent::construct(); + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function access() { + global $user; + $uid = $values->{$this->aliases['uid']}; + return user_access('Administer short URLs'); // || $this->uid == $user->uid + } + + function render($values) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); + $rid = $values->rid; + return l($text, "admin/build/shurly/delete/$rid", array('query' => drupal_get_destination())); + } +} diff --git a/shurly_handler_field_shurly_link_test.inc b/shurly_handler_field_shurly_link_test.inc new file mode 100644 index 0000000..22ddd0e --- /dev/null +++ b/shurly_handler_field_shurly_link_test.inc @@ -0,0 +1,38 @@ +<?php + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_shurly_link_test extends views_handler_field { + function construct() { + parent::construct(); + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + function render($values) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('test'); + $source = $values->shurly_source; + return l($text, $source); + } +}
rmiddle/shurly
58810f7ed8d1b67b9c7e47a57bb27d9cea36ddb0
ShURLy Module initial commit to GitHub. *Mostly* working, with the exception of the current inability to delete links, no built-in views, and a non-working Views field handler
diff --git a/README.txt b/README.txt index e69de29..8203f53 100644 --- a/README.txt +++ b/README.txt @@ -0,0 +1,4 @@ +ShURLy is a URL shortening service implemented as a module for Drupal. + +It was originally written by Jeff Robbins for Lullabot's "lbt.me" shortening service at http://lbt.me + diff --git a/shurly.css b/shurly.css new file mode 100644 index 0000000..67bbfae --- /dev/null +++ b/shurly.css @@ -0,0 +1,43 @@ +.shurly-choose { + color: #999; +} + +.shurly-result { + border: 3px #999 solid; + padding: 5px; + margin: 5px 0; +} + +.shurly-result .form-item { + margin: 0; +} + +#shurly-copy-container { + display:inline; +} + +#shurly-copy { + border: 2px outset #999; + background-color: #CCC; + position: relative; + display: inline; + padding: .1em .3em; +} + +#shurly-copy.hover { + border-color: #777; + background-color: #DDD; +} + +.shurly-bookmarklet { + background-color: #999; + color: #FFF; + border: 1px solid #333; + padding: .1em .5em; + text-decoration: none; +} + +.shurly-bookmarklet:hover { + background-color: #666; + text-decoration: none; +} \ No newline at end of file diff --git a/shurly.info b/shurly.info new file mode 100755 index 0000000..63c2ada --- /dev/null +++ b/shurly.info @@ -0,0 +1,4 @@ +; $Id$ +name = Shurly +description = A complete short URL service. +core = 6.x diff --git a/shurly.install b/shurly.install new file mode 100644 index 0000000..900b363 --- /dev/null +++ b/shurly.install @@ -0,0 +1,86 @@ +<?php + +/** + * Implement hook_schema(). + */ +function shurly_schema() { + $schema['shurly'] = array( + 'description' => t('URL redirects for the Shurly module'), + 'fields' => array( + 'rid' => array( + 'description' => t('unique redirect id'), + 'type' => 'serial', + 'not null' => TRUE, + ), + 'uid' => array( + 'description' => t('user id of owner'), + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + ), + 'source' => array( + 'description' => t('source path'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE, + ), + 'destination' => array( + 'description' => t('redirect URL'), + 'type' => 'varchar', + 'length' => '255', + 'not null' => TRUE, + ), + 'created' => array( + 'description' => t('datestamp of creation'), + 'type' => 'int', + 'not null' => TRUE, + ), + 'count' => array( + 'description' => t('usage count'), + 'type' => 'int', + 'not null' => TRUE, + ), + 'last_used' => array( + 'description' => t('datestamp of last use'), + 'type' => 'int', + 'not null' => TRUE, + ), + 'custom' => array( + 'description' => t('flag for custom path'), + 'type' => 'int', + 'not null' => TRUE, + 'default' => 0, + ), + 'active' => array( + 'description' => t('allows links to be deactivated'), + 'type' => 'int', + 'not null' => TRUE, + 'default' => 1, + ), + ), + 'primary key' => array('rid'), + 'indexes' => array( + 'source' => array('source'), + ), + ); + return $schema; +} + + +/** + * Implement hook_install(). + */ +function shurly_install() { + drupal_install_schema('shurly'); +} + +/** + * Implement hook_uninstall(). + */ +function shurly_uninstall() { + // Remove tables. + drupal_uninstall_schema('shurly'); + + // Remove variables. + +} diff --git a/shurly.js b/shurly.js new file mode 100644 index 0000000..0311219 --- /dev/null +++ b/shurly.js @@ -0,0 +1,15 @@ +Drupal.behaviors.shurly = function() { + $('#edit-result').focus(function(){ + $(this).select(); + }); + //.data('origBG', $(this).css('backgroundColor')); + var clip = new ZeroClipboard.Client(); + clip.setText($('#edit-result').val()); + clip.setHandCursor( true ); + clip.glue('shurly-copy', 'shurly-copy-container'); + clip.addEventListener( 'onComplete', function() { + $('#edit-result').css('backgroundColor', '#FFFF3F').fadeTo(300, .1, function(){ + $(this).fadeTo(1, 1).css('backgroundColor', '#FFF'); + }); + }); +} \ No newline at end of file diff --git a/shurly.module b/shurly.module new file mode 100644 index 0000000..b45a9b5 --- /dev/null +++ b/shurly.module @@ -0,0 +1,440 @@ +<?php + +//include_once('shurly.views.inc'); +//include_once('views_handler_field_shurly_link.inc'); + +/** + * @file description http://www.youtube.com/watch?v=Qo7qoonzTCE + * + * @todo + * - create REST API + * - prevent endless loop links (back to themselves or others on this site) + */ + +/** + * Implementation of hook_menu() + */ +function shurly_menu(){ + // callback for creation of URLs + $items = array(); + + $items['shurly'] = array( + 'title' => 'Create URL', + 'description' => 'Create a short URL', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('shurly_create_form'), + 'access arguments' => array('Create short URLs'), + ); + + //$items['i'] = array( + // 'title' => 'URL Info', + // 'page callback' => 'drupal_get_form', + // 'page arguments' => array('shurly_create_form'), + // 'access arguments' => array('Create short URLs'), + //); + + $items['myurls'] = array( + 'title' => 'URL Info', + 'description' => 'Create a short URL', + 'page callback' => 'drupal_get_form', + 'page arguments' => array('shurly_create_form'), + 'access arguments' => array('Create short URLs'), + ); + + return $items; +} + +/** + * Implementation of hook_perm() + */ +function shurly_perm(){ + return array('Create short URLs', 'Administer short URLs'); +} + +function shurly_block($op = 'list', $delta = 0, $edit = array()){ + // create a block to add URL + switch ($op) { + case 'list': + $blocks['form'] = array('info' => t('Short URL form')); + $blocks['history'] = array('info' => t('Link history')); + return $blocks; + case 'view': + // don't show the block when user is on the callback page + if ($delta == 'form' && user_access('Create short URLs') && arg(0) != 'shurly') { + $block = array('subject' => t('Create a short URL'), + 'content' => drupal_get_form('shurly_create_form')); + return $block; + } + if ($delta == 'history' && $GLOBALS['user']->uid != 0 && arg(0) != 'shurly') { + $block = array('subject' => t('Link history'), + 'content' => shurly_link_history()); + return $block; + } + break; + } +} + +/** + * Implementation of hook_boot() + */ +function shurly_boot() { + // we boostrap the path.inc file early to set up $_GET['q'] + // this is a little bit of a hack and may impact performance of sites with page caching slightly + _drupal_bootstrap(DRUPAL_BOOTSTRAP_PATH); + $row = db_fetch_object(db_query("SELECT rid, destination FROM {shurly} WHERE BINARY source = '%s' AND active = 1", $_GET['q'])); + if ($row) { + shurly_goto($row); + } +} + +/** + * The main form + */ +function shurly_create_form($form_state){ + + $path = drupal_get_path('module', 'shurly'); + drupal_add_css($path . '/shurly.css'); + + // form to create new short URLs + $form['long_url'] = array( + '#title' => t('Enter a long URL to make short'), + '#type' => 'textfield', + '#default_value' => $_GET['url'] ? $_GET['url'] : (isset($form_state['storage']['shurly']['long_url']) ? $form_state['storage']['shurly']['long_url'] :'http://'), + ); + + $form['submit'] = array( + '#type' => 'submit', + '#value' => t('Make it!'), + ); + + $form['short_url'] = array( + '#type' => 'textfield', + '#size' => 6, + '#field_prefix' => $GLOBALS['base_url'] .'/', + '#field_suffix' => ' <span class="shurly-choose">&lt;--- ' . t('create custom URL') . '</span>', + '#default_value' => isset($form_state['storage']['shurly']['short_url']) ? $form_state['storage']['shurly']['short_url'] : '', + ); + + if (isset($form_state['storage']['shurly']['final_url'])) { + $form['result'] = array( + '#type' => 'textfield', + '#size' => 30, + '#value' => $form_state['storage']['shurly']['final_url'], + '#prefix' => '<div class="shurly-result">', + '#suffix' => '</div>', + '#field_prefix' => t('Your short URL: '), + '#field_suffix' => ' <div id="shurly-copy-container" style="position:relative;"><div id="shurly-copy">'. t('copy'). '</div></div> + <div><a href="http://twitter.com?status='. urlencode($form_state['storage']['shurly']['final_url']) .'">'. t('Create a Twitter message with this link') .'</a></div></div>', + ); + drupal_add_js($path . '/zeroclipboard/ZeroClipboard.js'); + drupal_add_js($path . '/shurly.js'); + drupal_add_js("ZeroClipboard.setMoviePath( '". url($path .'/zeroclipboard/ZeroClipboard.swf') ."' );", 'inline'); + } + + $form['bookmarklet'] = array( + '#type' => 'markup', + '#value' => t("<p>Drag this link to your bookmark bar to quickly create a short URL from any page: <a class=\"shurly-bookmarklet\" href=\"!jsurl\">!sitename</a></p>", array('!jsurl' => "javascript:void(location.href='". url('shurly', array('absolute' => TRUE)) ."?url='+encodeURIComponent(location.href))", '!sitename' => variable_get('site_name', 'Drupal'))), + ); + + unset($form_state['storage']['shurly']); + + return $form; + +} + + +function shurly_create_form_validate(&$form, &$form_state) { + + if (!user_access('create short URLs')) { + form_set_error('', t('You do not have permission to create short URLs on this site')); + return; + } + + $form_state['values']['long_url'] = trim($form_state['values']['long_url']); + $form_state['values']['short_url'] = trim($form_state['values']['short_url']); + $vals = $form_state['values']; + + // check that they've entered a URL + if ($vals['long_url'] == '' || $vals['long_url'] == 'http://' || $vals['long_url'] == 'https://') { + form_set_error('long_url', t('Please enter a web URL')); + } + elseif (stripos($vals['long_url'], "http://") !== 0 && stripos($vals['long_url'], "https://") !== 0) { + form_set_error('long_url', t('Please enter a web URL beginning with http:// or https://')); + } + + if (trim($vals['short_url']) != '') { + // a custom short URL has been entered + $form_state['custom'] = TRUE; + if (!shurly_validate_custom($vals['short_url'])) { + form_set_error('short_url', t('Short URL may only contain alphanumeric characters')); + } + elseif($exists = shurly_url_exists($vals['short_url'], $vals['long_url'])) { + if ($exists == 'found') { + form_set_error('short_url', t('This short URL is already used')); + } + else { + $form_state['storage']['shurly']['final_url'] = url($vals['short_url'], array('absolute' => TRUE)); + $form_state['url_exists'] = TRUE; + drupal_set_message(t('This URL pair already exists'), 'error'); + } + } + elseif (url($vals['short_url'], array('absolute' => TRUE)) == $vals['long_url']) { + // check that link isn't to itself (creating infinite loop) + // problem - http vs https + form_set_error('short_url', t('You cannot create links to themselves')); + } + elseif (!shurly_path_available($vals['short_url'])) { + form_set_error('short_url', t('This custom URL is reserved. Please choose another.')); + } + } + else { + // custom short URL field is empty + $form_state['custom'] = FALSE; + if ($exist = shurly_get_latest_short($vals['long_url'], $GLOBALS['user']->uid)) { + $short = $exist; + // we flag this as URL Exists so that it displays but doesn't get saved to the db + $form_state['url_exists'] = TRUE; + } + else { + $short = shurly_next_url(); + } + $form_state['values']['short_url'] = $short; + $form_state['storage']['shurly']['short_url'] = $short; + } + +} + +function shurly_create_form_submit($form, &$form_state) { + // submit the short URL form + $long_url = $form_state['storage']['shurly']['long_url'] = $form_state['values']['long_url']; + $short_url = $form_state['storage']['shurly']['short_url'] = $form_state['values']['short_url']; + $final_url = $form_state['storage']['shurly']['final_url'] = url($short_url, array('absolute' => TRUE)); + $custom = $form_state['custom']; + if (empty($form_state['url_exists'])) { + shurly_save_url($long_url, $short_url, NULL, $custom); + } +} + + + +/** + * From http://www.php.net/manual/en/function.base-convert.php#52450 + * + * Parameters: + * $num - your decimal integer + * $base - base to which you wish to convert $num (leave it 0 if you are providing $index or omit if you're using default (62)) + * $index - if you wish to use the default list of digits (0-1a-zA-Z), omit this option, otherwise provide a string (ex.: "zyxwvu") + */ +function shurly_dec2any($num, $base=62, $index=false) { + if (! $base ) { + $base = strlen( $index ); + } else if (! $index ) { + // note: we could rearrange this string to get more random looking URLs + // another note, to create printable URLs, omit the following characters: 01lIO + $index = substr("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ,0 ,$base ); + } + $out = ""; + for ( $t = floor( log10( $num ) / log10( $base ) ); $t >= 0; $t-- ) { + $a = floor( $num / pow( $base, $t ) ); + $out = $out . substr( $index, $a, 1 ); + $num = $num - ( $a * pow( $base, $t ) ); + } + return $out; +} + +/** + * Implementation of hook_views_api. + * Notifies the Views module that we're compatible with a particular API revision. + */ +function shurly_views_api() { + return array( + 'api' => 2, + ); +} + + + +/****************************************************** + * API functions + ****************************************************** + */ + +/** + * API function to save a URL + */ +function shurly_save_url($long_url, $short_path, $account = NULL, $custom = NULL) { + + if (is_null($account)) { + $account = $GLOBALS['user']; + } + + $record = array(); + $record['destination'] = $long_url; + $record['custom'] = $custom ? 1 : 0; + $record['created'] = time(); + $record['source'] = $short_path; + $record['uid'] = $account->uid; + $record['count'] = $record['last_used'] = 0; + $record['active'] = 1; + + return drupal_write_record('shurly', $record); + +} + + +/** + * Activate or deactivate a link + */ +function shurly_set_link_active($rid, $active) { + $record = db_fetch_array(db_query('SELECT * FROM {shurly} WHERE rid = %d', $rid)); + if ($record) { + $record['rid'] = $rid; + $record['active'] = $active ? 1 : 0; + return drupal_write_record('shurly', $record, 'rid'); + } + else { + return FALSE; + } +} + +/** + * Validate custom short URL string + * + * @return TRUE if valid, FALSE if invalid + */ +function shurly_validate_custom($custom) { + // we allow alphanumeric characters as well as _, and - + return preg_match('/[^0-9A-Za-z_-]/', $custom) ? FALSE : TRUE; +} + +/** + * Generate a random short URL + * Pretty much unused at this point + * this method could take a LOOOONG time on a site with lots of URLs + */ +function shurly_generate_random($len = NULL) { + if ($len == NULL) { + $len = variable_get('shurly_length', 4); + } + $charset = "abcdefghijklmnopqrstuvwxyz123456789"; + $charlen = strlen($charset) - 1; + do { + $str = ''; + for ($i=0; $i<$len; $i++) { + $str .= $charset[mt_rand(0, $charlen)]; + } + // check that this string hasn't been used already + // check that the string is a valid (available) path + } while (shurly_url_exists($str) || !shurly_path_available($str)); + + return $str; +} + +/** + * Return next available short URL + */ +function shurly_next_url() { + $count = variable_get('shurly_counter', 3249); // starts the URLs with 3 characters + do { + $count++; + // counter is stored as base 10 + // $index is a-z, A-Z, 0-9, sorted randomly, with confusing characters (01lIO) removed - 57 characters + // a custom index can be created as a variable override in settings.php + $index = variable_get('shurly_index', 'kZ4oJ3Uwi5STqcpGNxfYgMQAdPWmsenh78XB26uLbEaRDzKrHVj9CyFtv'); + $str = shurly_dec2any($count, NULL, $index); + + // check that this string hasn't been used already + // check that the string is a valid (available) path + } while (shurly_url_exists($str) || !shurly_path_available($str)); + + variable_set('shurly_counter', $count); + + return $str; +} + +/** + * Checks to see if there's a menu handler or a path alias for a given path + * + * @return TRUE if there are no conflicts + */ +function shurly_path_available($path){ + $return = TRUE; + // see if $path is an alias + $source = drupal_lookup_path('source', $path); + if ($source) { + // if so, set alias source to $path + $path = $source; + } + // check to see if $path has a menu callback + if (menu_get_item($path)) { + $return = FALSE; + } + return $return; +} + +/** + * Check to see if this short URL already exists + */ +function shurly_url_exists($short, $long = NULL) { + $redirect = shurly_get_redirect($short); + $return = FALSE; + if ($redirect) { + $return = 'found'; + } + if ($long && $redirect->destination == $long) { + $return = 'match'; + } + return $return; +} + +/** + * Given the short URL, return the long one + * NOTE: Always check $redirect->active before using the result + */ +function shurly_get_redirect($short_url) { + // we add 'BINARY' to ensure that we're doing a CASE SENSITIVE query + $redirect = db_fetch_object(db_query("SELECT * FROM {shurly} WHERE BINARY source = '%s'", $short_url)); + return $redirect; +} + +/** + * Get the latest generated short URL by a given user for a given long URL + */ +function shurly_get_latest_short($long, $uid) { + return db_result(db_query("SELECT source FROM {shurly} WHERE destination = '%s' AND uid = %d AND custom = 0 AND active = 1 ORDER BY rid DESC", $long, $uid)); +} + +/** + * A heavily modified version of drupal_goto() (which hasn't been bootstrapped during hook_boot() + */ +function shurly_goto($row) { + if (!$row || (isset($_REQUEST['redirect']) && $_REQUEST['redirect'] == 'false')) { + return; + } + + $url = $row->destination; + + // Remove newlines from the URL to avoid header injection attacks. + $url = str_replace(array("\n", "\r"), '', $url); + + // Allow modules to react to the end of the page request before redirecting. + // We do not want this while running update.php. + if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') { + module_invoke_all('exit', $url); + } + + // Even though session_write_close() is registered as a shutdown function, we + // need all session data written to the database before redirecting. + session_write_close(); + + header('Location: '. $url, TRUE, 301); + + // update access information on this row + db_query('UPDATE {shurly} SET count = count + 1, last_used = %d WHERE rid = %d', time(), $row->rid); + + // The "Location" header sends a redirect status code to the HTTP daemon. In + // some cases this can be wrong, so we make sure none of the code below the + // drupal_goto() call gets executed upon redirection. + exit(); + +} \ No newline at end of file diff --git a/shurly.views.inc b/shurly.views.inc new file mode 100644 index 0000000..e756234 --- /dev/null +++ b/shurly.views.inc @@ -0,0 +1,220 @@ +<?php + +function shurly_views_data() { + + // Basic table information. + + $data['shurly']['table']['group'] = t('Shurly'); + + // Advertise this table as a possible base table + $data['shurly']['table']['base'] = array( + 'field' => 'rid', + 'title' => t('Link'), + 'help' => t('Shurly shortened URLs.'), + 'weight' => 10, + ); + + $data['shurly']['table']['join'] = array( + 'users' => array( + 'left_field' => 'uid', + 'field' => 'uid', + ), + ); + + // note that this next line adds to the $data['users'] array + // and avoids us from having to do relationships in order to get + // user data into our Views of Shurly links + $data['users']['table']['join']['shurly'] = array( + 'left_field' => 'uid', + 'field' => 'uid', + ); + + // User ID + $data['shurly']['uid'] = array( + 'title' => t('User ID'), + 'help' => t('ID of user who created the link.'), + 'field' => array( + 'handler' => 'views_handler_field_user', + 'click sortable' => TRUE, + ), + 'argument' => array( + 'handler' => 'views_handler_argument_user_uid', + 'name field' => 'name', // display this field in the summary + ), + 'filter' => array( + 'title' => t('Name'), + 'handler' => 'views_handler_filter_user_name', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'relationship' => array( + 'handler' => 'views_handler_relationship', + 'base' => 'users', + 'base field' => 'uid', + 'label' => t('user'), + ), + ); + + // uid + $data['shurly']['uid_current'] = array( + 'real field' => 'uid', + 'title' => t('Current user'), + 'help' => t('Filter the view to the currently logged in user.'), + 'filter' => array( + 'handler' => 'views_handler_filter_user_current', + 'type' => 'yes-no', + ), + ); + + // Shurly Source - Short URL + $data['shurly']['source'] = array( + 'title' => t('Short URL'), + 'help' => t('The source URL which generates a redirect'), + 'field' => array( + 'handler' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_string', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_string', + ), + ); + + // Shurly Desination - Long URL + $data['shurly']['destination'] = array( + 'title' => t('Long URL'), + 'help' => t('The destination URL'), + 'field' => array( + 'handler' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_string', + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_string', + ), + ); + + // Link created timestamp + $data['shurly']['created'] = array( + 'title' => t('Created date'), + 'help' => t('The date/time the link was created.'), + 'field' => array( + 'handler' => 'views_handler_field_date', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_date', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_date', + ), + ); + + // Count + $data['shurly']['count'] = array( + 'title' => t('Count'), + 'help' => t('Number of times this link has been followed.'), + 'field' => array( + 'handler' => 'views_handler_field', + 'click sortable' => TRUE, + ), + 'filter' => array( + 'handler' => 'views_handler_filter_numeric', + 'allow empty' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + + ); + + // Link last used timestamp + $data['shurly']['last_used'] = array( + 'title' => t('Last used date'), + 'help' => t('The last date/time the link was used.'), + 'field' => array( + 'handler' => 'views_handler_field_date', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_date', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_date', + ), + ); + + // Boolean for custom entry + $data['shurly']['custom'] = array( + 'title' => t('Custom link'), + 'help' => t('Boolean flag set for custom short URLs entered by user.'), + 'field' => array( + 'handler' => 'views_handler_field_boolean', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_boolean_operator', + 'label' => t('Custom'), + 'type' => 'yes-no', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + ); + + // Boolean for active link + $data['shurly']['active'] = array( + 'title' => t('Link active'), + 'help' => t('Is this link active or has it been deactivated?'), + 'field' => array( + 'handler' => 'views_handler_field_boolean', + 'click sortable' => TRUE, + ), + 'sort' => array( + 'handler' => 'views_handler_sort', + ), + 'filter' => array( + 'handler' => 'views_handler_filter_boolean_operator', + 'label' => t('Custom'), + 'type' => 'yes-no', + ), + 'argument' => array( + 'handler' => 'views_handler_argument_numeric', + ), + ); + + $data['shurly']['source_link'] = array( + 'field' => array( + 'title' => t('Test link'), + 'help' => t('Redirecting link.'), + 'handler' => 'shurly_handler_field_shurly_link', + 'parent' => 'views_handler_field', + ), + ); + + + return $data; +} diff --git a/shurly_handler_field_shurly_link.inc b/shurly_handler_field_shurly_link.inc new file mode 100644 index 0000000..0026812 --- /dev/null +++ b/shurly_handler_field_shurly_link.inc @@ -0,0 +1,43 @@ +<?php + +/** + * Field handler to present a link to the short URL entry. + */ +class shurly_handler_field_shurly_link extends views_handler_field { + function construct() { + parent::construct(); + $this->additional_fields['source'] = 'source'; + } + + function option_definition() { + $options = parent::option_definition(); + + $options['text'] = array('default' => '', 'translatable' => TRUE); + + return $options; + } + + function options_form(&$form, &$form_state) { + parent::options_form($form, $form_state); + $form['text'] = array( + '#type' => 'textfield', + '#title' => t('Text to display'), + '#default_value' => $this->options['text'], + ); + } + + function query() { + $this->ensure_my_table(); + $this->add_additional_fields(); + } + + //function access() { + //return user_access('administer users'); + //} + + function render($values) { + $text = !empty($this->options['text']) ? $this->options['text'] : t('delete'); + $uid = $values->{$this->aliases['uid']}; + return l($text, "user/$uid/delete", array('query' => drupal_get_destination())); + } +} diff --git a/zeroclipboard/ZeroClipboard.as b/zeroclipboard/ZeroClipboard.as new file mode 100755 index 0000000..26ad18b --- /dev/null +++ b/zeroclipboard/ZeroClipboard.as @@ -0,0 +1,81 @@ +package { + // Simple Set Clipboard System + // Author: Joseph Huckaby + + import flash.display.Stage; + import flash.display.Sprite; + import flash.display.LoaderInfo; + import flash.display.StageScaleMode; + import flash.events.*; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.external.ExternalInterface; + import flash.system.Security; + import flash.utils.*; + import flash.system.System; + + public class ZeroClipboard extends Sprite { + + private var id:String = ''; + private var button:Sprite; + private var clipText:String = ''; + + public function ZeroClipboard() { + // constructor, setup event listeners and external interfaces + stage.scaleMode = StageScaleMode.EXACT_FIT; + flash.system.Security.allowDomain("*"); + + // import flashvars + var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters; + id = flashvars.id; + + // invisible button covers entire stage + button = new Sprite(); + button.buttonMode = true; + button.useHandCursor = true; + button.graphics.beginFill(0xCCFF00); + button.graphics.drawRect(0, 0, Math.floor(flashvars.width), Math.floor(flashvars.height)); + button.alpha = 0.0; + addChild(button); + button.addEventListener(MouseEvent.CLICK, clickHandler); + + button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event) { + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseOver', null ); + } ); + button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event) { + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseOut', null ); + } ); + button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event) { + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseDown', null ); + } ); + button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event) { + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseUp', null ); + } ); + + // external functions + ExternalInterface.addCallback("setHandCursor", setHandCursor); + ExternalInterface.addCallback("setText", setText); + + // signal to the browser that we are ready + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'load', null ); + } + + public function setText(newText) { + // set the maximum number of files allowed + clipText = newText; + } + + public function setHandCursor(enabled:Boolean) { + // control whether the hand cursor is shown on rollover (true) + // or the default arrow cursor (false) + button.useHandCursor = enabled; + } + + private function clickHandler(event:Event):void { + // user click copies text to clipboard + // as of flash player 10, this MUST happen from an in-movie flash click event + System.setClipboard( clipText ); + ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'complete', clipText ); + } + } +} diff --git a/zeroclipboard/ZeroClipboard.fla b/zeroclipboard/ZeroClipboard.fla new file mode 100755 index 0000000..007dc94 Binary files /dev/null and b/zeroclipboard/ZeroClipboard.fla differ diff --git a/zeroclipboard/ZeroClipboard.js b/zeroclipboard/ZeroClipboard.js new file mode 100755 index 0000000..5adde95 --- /dev/null +++ b/zeroclipboard/ZeroClipboard.js @@ -0,0 +1,311 @@ +// Simple Set Clipboard System +// Author: Joseph Huckaby + +var ZeroClipboard = { + + version: "1.0.7", + clients: {}, // registered upload clients on page, indexed by id + moviePath: 'ZeroClipboard.swf', // URL to movie + nextId: 1, // ID of next movie + + $: function(thingy) { + // simple DOM lookup utility function + if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); + if (!thingy.addClass) { + // extend element with a few useful methods + thingy.hide = function() { this.style.display = 'none'; }; + thingy.show = function() { this.style.display = ''; }; + thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; + thingy.removeClass = function(name) { + var classes = this.className.split(/\s+/); + var idx = -1; + for (var k = 0; k < classes.length; k++) { + if (classes[k] == name) { idx = k; k = classes.length; } + } + if (idx > -1) { + classes.splice( idx, 1 ); + this.className = classes.join(' '); + } + return this; + }; + thingy.hasClass = function(name) { + return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); + }; + } + return thingy; + }, + + setMoviePath: function(path) { + // set path to ZeroClipboard.swf + this.moviePath = path; + }, + + dispatch: function(id, eventName, args) { + // receive event from flash movie, send to client + var client = this.clients[id]; + if (client) { + client.receiveEvent(eventName, args); + } + }, + + register: function(id, client) { + // register new client to receive events + this.clients[id] = client; + }, + + getDOMObjectPosition: function(obj, stopObj) { + // get absolute coordinates for dom element + var info = { + left: 0, + top: 0, + width: obj.width ? obj.width : obj.offsetWidth, + height: obj.height ? obj.height : obj.offsetHeight + }; + + while (obj && (obj != stopObj)) { + info.left += obj.offsetLeft; + info.top += obj.offsetTop; + obj = obj.offsetParent; + } + + return info; + }, + + Client: function(elem) { + // constructor for new simple upload client + this.handlers = {}; + + // unique ID + this.id = ZeroClipboard.nextId++; + this.movieId = 'ZeroClipboardMovie_' + this.id; + + // register client with singleton to receive flash events + ZeroClipboard.register(this.id, this); + + // create movie + if (elem) this.glue(elem); + } +}; + +ZeroClipboard.Client.prototype = { + + id: 0, // unique ID for us + ready: false, // whether movie is ready to receive events or not + movie: null, // reference to movie object + clipText: '', // text to copy to clipboard + handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor + cssEffects: true, // enable CSS mouse effects on dom container + handlers: null, // user event handlers + + glue: function(elem, appendElem, stylesToAdd) { + // glue to DOM element + // elem can be ID or actual DOM element object + this.domElement = ZeroClipboard.$(elem); + + // float just above object, or zIndex 99 if dom element isn't set + var zIndex = 99; + if (this.domElement.style.zIndex) { + zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; + } + + if (typeof(appendElem) == 'string') { + appendElem = ZeroClipboard.$(appendElem); + } + else if (typeof(appendElem) == 'undefined') { + appendElem = document.getElementsByTagName('body')[0]; + } + + // find X/Y position of domElement + var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); + + // create floating DIV above element + this.div = document.createElement('div'); + var style = this.div.style; + style.position = 'absolute'; + style.left = '' + box.left + 'px'; + style.top = '' + box.top + 'px'; + style.width = '' + box.width + 'px'; + style.height = '' + box.height + 'px'; + style.zIndex = zIndex; + + if (typeof(stylesToAdd) == 'object') { + for (addedStyle in stylesToAdd) { + style[addedStyle] = stylesToAdd[addedStyle]; + } + } + + // style.backgroundColor = '#f00'; // debug + + appendElem.appendChild(this.div); + + this.div.innerHTML = this.getHTML( box.width, box.height ); + }, + + getHTML: function(width, height) { + // return HTML for movie + var html = ''; + var flashvars = 'id=' + this.id + + '&width=' + width + + '&height=' + height; + + if (navigator.userAgent.match(/MSIE/)) { + // IE gets an OBJECT tag + var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; + html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; + } + else { + // all other browsers get an EMBED tag + html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; + } + return html; + }, + + hide: function() { + // temporarily hide floater offscreen + if (this.div) { + this.div.style.left = '-2000px'; + } + }, + + show: function() { + // show ourselves after a call to hide() + this.reposition(); + }, + + destroy: function() { + // destroy control and floater + if (this.domElement && this.div) { + this.hide(); + this.div.innerHTML = ''; + + var body = document.getElementsByTagName('body')[0]; + try { body.removeChild( this.div ); } catch(e) {;} + + this.domElement = null; + this.div = null; + } + }, + + reposition: function(elem) { + // reposition our floating div, optionally to new container + // warning: container CANNOT change size, only position + if (elem) { + this.domElement = ZeroClipboard.$(elem); + if (!this.domElement) this.hide(); + } + + if (this.domElement && this.div) { + var box = ZeroClipboard.getDOMObjectPosition(this.domElement); + var style = this.div.style; + style.left = '' + box.left + 'px'; + style.top = '' + box.top + 'px'; + } + }, + + setText: function(newText) { + // set text to be copied to clipboard + this.clipText = newText; + if (this.ready) this.movie.setText(newText); + }, + + addEventListener: function(eventName, func) { + // add user event listener for event + // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel + eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + if (!this.handlers[eventName]) this.handlers[eventName] = []; + this.handlers[eventName].push(func); + }, + + setHandCursor: function(enabled) { + // enable hand cursor (true), or default arrow cursor (false) + this.handCursorEnabled = enabled; + if (this.ready) this.movie.setHandCursor(enabled); + }, + + setCSSEffects: function(enabled) { + // enable or disable CSS effects on DOM container + this.cssEffects = !!enabled; + }, + + receiveEvent: function(eventName, args) { + // receive event from flash + eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + + // special behavior for certain events + switch (eventName) { + case 'load': + // movie claims it is ready, but in IE this isn't always the case... + // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function + this.movie = document.getElementById(this.movieId); + if (!this.movie) { + var self = this; + setTimeout( function() { self.receiveEvent('load', null); }, 1 ); + return; + } + + // firefox on pc needs a "kick" in order to set these in certain cases + if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { + var self = this; + setTimeout( function() { self.receiveEvent('load', null); }, 100 ); + this.ready = true; + return; + } + + this.ready = true; + this.movie.setText( this.clipText ); + this.movie.setHandCursor( this.handCursorEnabled ); + break; + + case 'mouseover': + if (this.domElement && this.cssEffects) { + this.domElement.addClass('hover'); + if (this.recoverActive) this.domElement.addClass('active'); + } + break; + + case 'mouseout': + if (this.domElement && this.cssEffects) { + this.recoverActive = false; + if (this.domElement.hasClass('active')) { + this.domElement.removeClass('active'); + this.recoverActive = true; + } + this.domElement.removeClass('hover'); + } + break; + + case 'mousedown': + if (this.domElement && this.cssEffects) { + this.domElement.addClass('active'); + } + break; + + case 'mouseup': + if (this.domElement && this.cssEffects) { + this.domElement.removeClass('active'); + this.recoverActive = false; + } + break; + } // switch eventName + + if (this.handlers[eventName]) { + for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { + var func = this.handlers[eventName][idx]; + + if (typeof(func) == 'function') { + // actual function reference + func(this, args); + } + else if ((typeof(func) == 'object') && (func.length == 2)) { + // PHP style object + method, i.e. [myObject, 'myMethod'] + func[0][ func[1] ](this, args); + } + else if (typeof(func) == 'string') { + // name of function + window[func](this, args); + } + } // foreach event handler defined + } // user defined handler for event + } + +}; diff --git a/zeroclipboard/ZeroClipboard.swf b/zeroclipboard/ZeroClipboard.swf new file mode 100755 index 0000000..13bf8e3 Binary files /dev/null and b/zeroclipboard/ZeroClipboard.swf differ diff --git a/zeroclipboard/ZeroClipboard10.as b/zeroclipboard/ZeroClipboard10.as new file mode 100644 index 0000000..7b07a6a --- /dev/null +++ b/zeroclipboard/ZeroClipboard10.as @@ -0,0 +1 @@ +package { // Simple Set Clipboard System // Author: Joseph Huckaby import flash.display.Stage; import flash.display.Sprite; import flash.desktop.Clipboard; import flash.desktop.ClipboardFormats; import flash.desktop.ClipboardTransferMode; import flash.display.LoaderInfo; import flash.display.StageScaleMode; import flash.events.*; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.external.ExternalInterface; import flash.system.Security; import flash.utils.*; import flash.system.System; public class ZeroClipboard10 extends Sprite { private var id:String = ''; private var button:Sprite; private var clipText:String = ''; public function ZeroClipboard10() { // constructor, setup event listeners and external interfaces stage.scaleMode = StageScaleMode.EXACT_FIT; flash.system.Security.allowDomain("*"); // import flashvars var flashvars:Object = LoaderInfo( this.root.loaderInfo ).parameters; id = flashvars.id; // invisible button covers entire stage button = new Sprite(); button.buttonMode = true; button.useHandCursor = true; button.graphics.beginFill(0xCCFF00); button.graphics.drawRect(0, 0, Math.floor(flashvars.width), Math.floor(flashvars.height)); button.alpha = 0.0; addChild(button); button.addEventListener(MouseEvent.CLICK, clickHandler); button.addEventListener(MouseEvent.MOUSE_OVER, function(event:Event) { ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseOver', null ); } ); button.addEventListener(MouseEvent.MOUSE_OUT, function(event:Event) { ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseOut', null ); } ); button.addEventListener(MouseEvent.MOUSE_DOWN, function(event:Event) { ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseDown', null ); } ); button.addEventListener(MouseEvent.MOUSE_UP, function(event:Event) { ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'mouseUp', null ); } ); // external functions ExternalInterface.addCallback("setHandCursor", setHandCursor); ExternalInterface.addCallback("setText", setText); // signal to the browser that we are ready ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'load', null ); } public function setText(newText) { // set the maximum number of files allowed clipText = newText; } public function setHandCursor(enabled:Boolean) { // control whether the hand cursor is shown on rollover (true) // or the default arrow cursor (false) button.useHandCursor = enabled; } private function clickHandler(event:Event):void { // user click copies text to clipboard // as of flash player 10, this MUST happen from an in-movie flash click event Clipboard.generalClipboard.clear(); Clipboard.generalClipboard.setData(ClipboardFormats.TEXT_FORMAT, clipText); Clipboard.generalClipboard.setData(ClipboardFormats.HTML_FORMAT, clipText); ExternalInterface.call( 'ZeroClipboard.dispatch', id, 'complete', clipText ); } } } \ No newline at end of file diff --git a/zeroclipboard/ZeroClipboard10.fla b/zeroclipboard/ZeroClipboard10.fla new file mode 100755 index 0000000..b98b5b9 Binary files /dev/null and b/zeroclipboard/ZeroClipboard10.fla differ diff --git a/zeroclipboard/ZeroClipboard10.swf b/zeroclipboard/ZeroClipboard10.swf new file mode 100644 index 0000000..bfed97f Binary files /dev/null and b/zeroclipboard/ZeroClipboard10.swf differ diff --git a/zeroclipboard/test.html b/zeroclipboard/test.html new file mode 100755 index 0000000..a6da39e --- /dev/null +++ b/zeroclipboard/test.html @@ -0,0 +1,76 @@ +<html> +<head> + <title>Zero Clipboard Test</title> + <style type="text/css"> + body { font-family:arial,sans-serif; font-size:9pt; } + + .my_clip_button { width:150px; text-align:center; border:1px solid black; background-color:#ccc; margin:10px; padding:10px; cursor:default; font-size:9pt; } + .my_clip_button.hover { background-color:#eee; } + .my_clip_button.active { background-color:#aaa; } + </style> + <script type="text/javascript" src="ZeroClipboard.js"></script> + <script language="JavaScript"> + var clip = null; + + function $(id) { return document.getElementById(id); } + + function init() { + clip = new ZeroClipboard.Client(); + clip.setHandCursor( true ); + + clip.addEventListener('load', function (client) { + debugstr("Flash movie loaded and ready."); + }); + + clip.addEventListener('mouseOver', function (client) { + // update the text on mouse over + clip.setText( $('fe_text').value ); + }); + + clip.addEventListener('complete', function (client, text) { + debugstr("Copied text to clipboard: " + text ); + }); + + clip.glue( 'd_clip_button', 'd_clip_container' ); + } + + function debugstr(msg) { + var p = document.createElement('p'); + p.innerHTML = msg; + $('d_debug').appendChild(p); + } + </script> +</head> +<body onLoad="init()"> + <h1>Zero Clipboard Test</h1> + <p><script>document.write("Your browser: " + navigator.userAgent);</script></p> + <table width="100%"> + <tr> + <td width="50%" valign="top"> + <!-- Upload Form --> + <table> + <tr> + <td align="right"><b>Text:</b></td> + <td align="left"><textarea id="fe_text" cols=50 rows=5 onChange="clip.setText(this.value)">Copy me!</textarea></td> + </tr> + </table> + <br/> + <div id="d_clip_container" style="position:relative"> + <div id="d_clip_button" class="my_clip_button"><b>Copy To Clipboard...</b></div> + </div> + </td> + <td width="50%" valign="top"> + <!-- Debug Console --> + <div id="d_debug" style="border:1px solid #aaa; padding: 10px; font-size:9pt;"> + <h3>Debug Console:</h3> + </div> + </td> + </tr> + </table> + + <br/><br/> + You can paste text here if you want, to make sure it worked:<br/> + <textarea id="testarea" cols=50 rows=10></textarea><br/> + <input type=button value="Clear Test Area" onClick="$('testarea').value = '';"/> +</body> +</html>
orlandov/couchwiki
3d41f23cac9c937bf9fb392c201cbd309e1c79dd
Refactor create_update into two functions
diff --git a/couchwiki/config/routing.py b/couchwiki/config/routing.py index e55abfc..f4e7593 100644 --- a/couchwiki/config/routing.py +++ b/couchwiki/config/routing.py @@ -1,35 +1,35 @@ """Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') - map.redirect('/', '/pages') - map.connect('/pages', controller='pages', action='index', - conditions=dict(method=['GET'])) - map.connect('/pages', controller='pages', action='create_update', - conditions=dict(method=['POST'])), map.connect('/pages/{page_id}/edit', conditions=dict(method=['GET']), controller='pages', action='edit') map.connect('/pages/{page_id}/create', - conditions=dict(method=['GET']), controller='pages', action='create') + conditions=dict(method=['GET']), controller='pages', action='edit_new') map.connect('/pages/{page_id}', conditions=dict(method=['GET']), controller='pages', action='view') map.connect('/pages/{page_id}', - conditions=dict(method=['POST']), controller='pages', action='create_update') + conditions=dict(method=['POST']), controller='pages', action='update') + map.connect('/pages', controller='pages', action='index', + conditions=dict(method=['GET'])) + map.connect('/pages', controller='pages', action='create', + conditions=dict(method=['POST'])), + map.redirect('/', '/pages') return map
orlandov/couchwiki
ba44342ae304301eef0bc8bae77f767601592a00
Add the colour white
diff --git a/couchwiki/public/css/style.css b/couchwiki/public/css/style.css index 959a3c2..0403930 100644 --- a/couchwiki/public/css/style.css +++ b/couchwiki/public/css/style.css @@ -1,40 +1,42 @@ .background-1 { background-color: #0086FF } .background-2 { background-color: #406180 } .background-3 { background-color: #00284D } .background-4 { background-color: #80C3FF } .background-5 { background-color: #E6F3FF } +.background-5 { background-color: #FFFFFF } .color-1 { background-color: #0086FF } .color-2 { background-color: #406180 } .color-3 { background-color: #00284D } .color-4 { background-color: #80C3FF } .color-5 { background-color: #E6F3FF } +.color-5 { background-color: #FFFFFF } html { height: 100%; } body { margin: 0; padding: 0; height: 100%; } h1 { padding: 0; margin: 0; } #content { font-family: sans-serif; margin-left: auto; margin-right: auto; padding: 0px 32px 0px 32px; border-width: 0px 1px 0px 1px; border-color: #80C3FF; border-style: solid; width: 700px; height: 100%; }
orlandov/couchwiki
65115d41f783b37785d84ba28de52ef98b290dee
Use h.url_for instead of hardcoding paths
diff --git a/couchwiki/templates/edit_page.html b/couchwiki/templates/edit_page.html index aea8ccb..00a85e5 100644 --- a/couchwiki/templates/edit_page.html +++ b/couchwiki/templates/edit_page.html @@ -1,27 +1,27 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" lang="en"> <xi:include href="site.html" /> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title py:content="c.title">2Wikid</title> <link rel="stylesheet" type="text/css" href="default.css" py:attrs="{'href': '/default.css'}" /> <script> $(function() { $('textarea.body').focus(); }); </script> </head> <body> - <form class="page-form" method="POST" action="/pages/${c.page.name}"> + <form class="page-form" method="POST" action="${h.url_for(controller='pages', action='create', page_id=c.page_name)}"> Page name: <input type="text" name="page_name" value="${c.page.name}"/><br/> <textarea class="body" name="body">${c.page.body}</textarea> <input type="submit" /> </form> </body></html> diff --git a/couchwiki/templates/new_page.html b/couchwiki/templates/new_page.html index 40905df..5bf4a05 100644 --- a/couchwiki/templates/new_page.html +++ b/couchwiki/templates/new_page.html @@ -1,28 +1,28 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" lang="en"> <xi:include href="site.html" /> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title py:content="c.title">2Wikid</title> <link rel="stylesheet" type="text/css" href="default.css" py:attrs="{'href': '/default.css'}" /> <script> $(function() { $('textarea.body').focus(); }); </script> </head> <body><h1>hi</h1> <form class="page-form" method="POST" - action="${h.url_for(controller='pages', action='create_update')}"> + action="${h.url_for(controller='pages', action='create')}"> Page name: <input type="text" name="page_name" value="${c.desired_page_name}"/><br/> <textarea class="body" name="body"></textarea> <input type="submit" /> </form> </body></html> diff --git a/couchwiki/templates/page.html b/couchwiki/templates/page.html index b21bd03..066785c 100644 --- a/couchwiki/templates/page.html +++ b/couchwiki/templates/page.html @@ -1,20 +1,24 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" lang="en"> <xi:include href="site.html" /> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title py:content="c.title">2Wikid</title> <link rel="stylesheet" type="text/css" href="default.css" py:attrs="{'href': '/default.css'}" /> </head> <body> <h1 class="name">${c.page.name}</h1> <hr/> - [ <a href="/pages/${c.page.page_id}/edit">edit</a> ] + [ <a href="${h.url_for(controller='pages', action='edit', + page_id=c.page.page_id)}">edit</a> ] <div class="content">${c.page.body}</div> + + <hr/> + <div class="date">Created <span class="date">${c.page.created}</span>.</div> </body></html> diff --git a/couchwiki/templates/pages.html b/couchwiki/templates/pages.html index f9246a6..be0cf60 100644 --- a/couchwiki/templates/pages.html +++ b/couchwiki/templates/pages.html @@ -1,44 +1,46 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" lang="en"> <xi:include href="site.html" /> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title py:content="c.title">2Wikid</title> <script> $(function() { $('.create-page .link').click(function() { $('.create-page .options').show(); $('.create-page input.name').focus(); }); $('.create-page form').submit(function() { var page_name = $('.create-page form .name').val(); - window.location = '${h.url_for(controller='pages', - action='create_update')}/' + page_name + '/create'; + var url = '${h.url_for(controller="pages", + page_id="__page_id__", action="edit_new")}'; + url = url.replace('__page_id__', page_name); + window.location = url; return false; }); }); </script> </head> <body> <h1 class="name">Pages</h1> <ul> <li class="create-page"> <a class="link" href="#">Create a page</a> <div class="options" style="display:none"> <form> <input class="name" type="text" /> <input class="submit" type="submit" value="Create" /> </form> </div> </li> <li py:for="page in c.pages"> <a href="${h.url_for(controller='pages', page_id=page.url_name, action='view')}">${page.name}</a> </li> </ul> </body></html> diff --git a/couchwiki/templates/site.html b/couchwiki/templates/site.html index 059016c..77dcab6 100644 --- a/couchwiki/templates/site.html +++ b/couchwiki/templates/site.html @@ -1,17 +1,17 @@ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" xmlns:xi="http://www.w3.org/2001/XInclude" lang="en" py:strip=""> <head py:match="head" py:attrs="select('@*')"> <script language="javascript" src="/js/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="/css/style.css"></link> <meta py:replace="select('*|text()')" /> </head> - <body py:match="body" py:attrs="select('@*')"> - <div id="content" class="background-5"> + <body class="background-5" py:match="body" py:attrs="select('@*')"> + <div id="content" class="background-6"> <div py:replace="select('*|text()')">This page has no content.</div> </div> </body> </html>
orlandov/couchwiki
bb16d1b046cf84da9a46ab7597bf9ad75d5d3147
Refactor create_update into two functions
diff --git a/couchwiki/controllers/pages.py b/couchwiki/controllers/pages.py index f0c3b9c..f0ce847 100644 --- a/couchwiki/controllers/pages.py +++ b/couchwiki/controllers/pages.py @@ -1,66 +1,79 @@ import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from couchwiki.lib.base import BaseController, render, h from couchwiki.model import Page log = logging.getLogger(__name__) class PagesController(BaseController): def render_page(self, page_id): db = self._get_db() page = Page.load(db, "page_%s" % (page_id,)) if not page: c.desired_page_name = page_id return render("new_page.html") c.page = page c.page.page_id = page_id return render("page.html") def edit(self, **kwargs): db = self._get_db() page_id = kwargs.get("page_id") doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) c.page = page return render("edit_page.html") - def create(self, **kwargs): + def edit_new(self, **kwargs): c.desired_page_name = kwargs.get("page_id") return render("new_page.html") def index(self): db = self._get_db() - pages = [ p.value for p in db.view('_design/wiki/_view/pages') ] - c.pages = pages - c.pagey = h.url_for(controller='pages', page_id="boner", action='create_update') + c.pages = [ p.value for p in db.view('_design/wiki/_view/pages') ] return render("pages.html") - def create_update(self, **kwargs): + def create(self, **kwargs): + db = self._get_db() + + page_id = request.POST['page_name'] + doc_name = "page_%s" % (page_id,) + page = Page.load(db, doc_name) + + if page: + raise "Page already exists" + else: + page = Page(doc_name, name=page_id, body=request.POST['body']) + page.store(db) + + redirect_to(str('/pages/%s' % (page_id,))) + return + + def update(self, **kwargs): db = self._get_db() page_id = request.POST['page_name'] doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) if page: page.name = request.POST['page_name'] page.body = request.POST['body'] page.store(db) else: - page = Page(doc_name, name=page_id, body=request.POST['body']) - page.store(db) + raise "Page doesn't exist" redirect_to(str('/pages/%s' % (page_id,))) return def view(self, **kwargs): return self.render_page(kwargs['page_id'])
orlandov/couchwiki
bce1ee6f66f6b4da4c099c77033d1e082cd64c36
Change the application prefix to '/wiki'
diff --git a/couchwiki/config/middleware.py b/couchwiki/config/middleware.py index 8a95a24..f61f3d4 100644 --- a/couchwiki/config/middleware.py +++ b/couchwiki/config/middleware.py @@ -1,69 +1,71 @@ """Pylons middleware initialization""" from beaker.middleware import CacheMiddleware, SessionMiddleware from paste.cascade import Cascade from paste.registry import RegistryManager from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool from pylons import config from pylons.middleware import ErrorHandler, StatusCodeRedirect from pylons.wsgiapp import PylonsApp from routes.middleware import RoutesMiddleware +from paste.deploy.config import PrefixMiddleware from couchwiki.config.environment import load_environment def make_app(global_conf, full_stack=True, static_files=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``static_files`` Whether this application serves its own static files; disable when another web server is responsible for serving them. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste ini file (where <name> defaults to main). """ # Configure the Pylons environment load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() # Routing/Session/Cache Middleware app = RoutesMiddleware(app, config['routes.map']) app = SessionMiddleware(app, config) app = CacheMiddleware(app, config) + app = PrefixMiddleware(app, config, prefix='/wiki') # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) if asbool(config['debug']): app = StatusCodeRedirect(app) else: app = StatusCodeRedirect(app, [400, 401, 403, 404, 500]) # Establish the Registry for this application app = RegistryManager(app) if asbool(static_files): # Serve static files static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, app]) return app
orlandov/couchwiki
60f3ac7ed8f33c6d4cf77515c6e689089c2d3a57
Allow us to use the SCGI forked server mode
diff --git a/couchwiki.egg-info/entry_points.txt b/couchwiki.egg-info/entry_points.txt index 27dd18d..55e3373 100644 --- a/couchwiki.egg-info/entry_points.txt +++ b/couchwiki.egg-info/entry_points.txt @@ -1,7 +1,10 @@ [paste.app_factory] main = couchwiki.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller - \ No newline at end of file + + [paste.server_runner] + pyscgi_threaded=pyscgi_wsgi:run_scgi_thread + pyscgi_forked=pyscgi_wsgi:run_scgi_fork
orlandov/couchwiki
839b4a1b905dd88eaf746d862b823db62fc00903
templates should now have a proper extension?
diff --git a/couchwiki/config/routing.py b/couchwiki/config/routing.py index b149aea..e55abfc 100644 --- a/couchwiki/config/routing.py +++ b/couchwiki/config/routing.py @@ -1,43 +1,35 @@ """Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') - # CUSTOM ROUTES HERE - - map.connect('/{controller}/{action}') - map.connect('/{controller}/{action}/{id}') - - -# mine map.redirect('/', '/pages') - map.connect('/pages', controller='pages', action='index', conditions=dict(method=['GET'])) map.connect('/pages', controller='pages', action='create_update', conditions=dict(method=['POST'])), map.connect('/pages/{page_id}/edit', conditions=dict(method=['GET']), controller='pages', action='edit') map.connect('/pages/{page_id}/create', conditions=dict(method=['GET']), controller='pages', action='create') map.connect('/pages/{page_id}', conditions=dict(method=['GET']), controller='pages', action='view') map.connect('/pages/{page_id}', conditions=dict(method=['POST']), controller='pages', action='create_update') return map diff --git a/couchwiki/controllers/pages.py b/couchwiki/controllers/pages.py index 24df638..f0c3b9c 100644 --- a/couchwiki/controllers/pages.py +++ b/couchwiki/controllers/pages.py @@ -1,64 +1,66 @@ import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to from couchwiki.lib.base import BaseController, render, h +from couchwiki.model import Page + log = logging.getLogger(__name__) class PagesController(BaseController): def render_page(self, page_id): db = self._get_db() page = Page.load(db, "page_%s" % (page_id,)) if not page: c.desired_page_name = page_id - return render("new_page") + return render("new_page.html") c.page = page c.page.page_id = page_id - return render("page") + return render("page.html") def edit(self, **kwargs): db = self._get_db() page_id = kwargs.get("page_id") doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) c.page = page - return render("edit_page") + return render("edit_page.html") def create(self, **kwargs): c.desired_page_name = kwargs.get("page_id") - return render("new_page") + return render("new_page.html") def index(self): db = self._get_db() pages = [ p.value for p in db.view('_design/wiki/_view/pages') ] c.pages = pages c.pagey = h.url_for(controller='pages', page_id="boner", action='create_update') return render("pages.html") def create_update(self, **kwargs): db = self._get_db() page_id = request.POST['page_name'] doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) if page: page.name = request.POST['page_name'] page.body = request.POST['body'] page.store(db) else: page = Page(doc_name, name=page_id, body=request.POST['body']) page.store(db) redirect_to(str('/pages/%s' % (page_id,))) return def view(self, **kwargs): return self.render_page(kwargs['page_id']) diff --git a/couchwiki/model/__init__.py b/couchwiki/model/__init__.py index e69de29..daefe12 100644 --- a/couchwiki/model/__init__.py +++ b/couchwiki/model/__init__.py @@ -0,0 +1,3 @@ +#!python + +from couchwiki.model.page import Page diff --git a/couchwiki/public/index.html b/couchwiki/public/index.html deleted file mode 100644 index 0719061..0000000 --- a/couchwiki/public/index.html +++ /dev/null @@ -1,137 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!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> - <title>Welcome to Pylons!</title> - <style type="text/css"> - body { - font-family: arial, helvetica, sans-serif; - background-color: #ffc900; - background-image: url(bg.png); - background-repeat: repeat-x; - width:100%; - height:100%; - margin:0; - max-height: 100%; - padding:0; - border:none; - line-height:1.4; - } - #container { - color:white; - background-color:#111; - position: absolute; - left: 50%; - width: 500px; - margin-left: -300px; - padding:50px; - height:100%; - } - #footer { - margin: 120px 0 0 0; - padding: 3px; - text-align:center; - font-size:small; - background-color:#222; - letter-spacing: 1px; - } - h1 { - text-align:center; - font-size:xx-large; - font-weight:normal; - margin: 0 0 20px 0; - border:none; - padding:0; - letter-spacing: 5px; - } - h2 { - font-size:xx-large; - font-weight:normal; - margin: 0 0 20px 0; - border:none; - padding:0; - } - hr { - margin-bottom:30px; - border: 1px solid #222; - background-color: #222; - padding: 2px; - } - #logo { - background-image: url(signum8b_spk.png); - background-repeat: no-repeat; - height: 0; - overflow: hidden; - padding-top: 99px; - width: 239px; - } - #left { - float:left; - width:250px; - margin:0 50px 0 0; - border:none; - padding:0 0 0 10px; - } - #right { - margin:0 0 0 330px; - border:none; - padding:0; - } - ul { - list-style:none; - margin:0; - border:none; - padding:0; - } - a:visited { - color:white; - text-decoration:none; - } - a:link { - color:white; - text-decoration:none; - }</style> - </head> - <body> - <div id="container"> - <h1>Welcome to <img src="pylons-logo.gif" alt="Logo displaying the word Pylons" - style="vertical-align:-15px; width: 250px;"/> - </h1> - <hr/> - <div id="left"> - <h2>Let's begin!</h2> - <p>If you haven't used Pylons before, start with the <a href="http://pylonshq.com/docs/en/0.9.7/gettingstarted/" - style="text-decoration:underline;">beginners' tutorial</a>.</p> - </div> - <div id="right"> - <h2>Help</h2> - <ul> - <li> - <a href="http://pylonshq.com/docs/en/0.9.7/">Official documentation</a> - </li> - <li> - <a href="http://wiki.pylonshq.com/display/pylonsfaq/Home">FAQ</a> - </li> - <li> - <a href="http://wiki.pylonshq.com/dashboard.action">Wiki</a> - </li> - <li> - <a href="http://wiki.pylonshq.com/display/pylonscommunity/Home#Home-JointheMailingLists">Mailing list</a> - </li> - <li> - <a href="http://wiki.pylonshq.com/display/pylonscommunity/Home#Home-IRC">IRC</a> - </li> - <li> - <a href="http://pylonshq.com/project/pylonshq/roadmap">Bug tracker</a> - </li> - </ul> - </div> - <div id="footer"> - <a href="http://www.pylonshq.com" style="color: #ccc; text-decoration:none;" - >www.pylonshq.com</a> - </div> - </div> - </body> -</html>
orlandov/couchwiki
757ac0b34e57c5701d93dc17becda3bdc7254eb9
port over more changes from old version
diff --git a/couchwiki/config/routing.py b/couchwiki/config/routing.py index 3ff8e54..b149aea 100644 --- a/couchwiki/config/routing.py +++ b/couchwiki/config/routing.py @@ -1,26 +1,43 @@ """Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') + +# mine + map.redirect('/', '/pages') + + map.connect('/pages', controller='pages', action='index', + conditions=dict(method=['GET'])) + map.connect('/pages', controller='pages', action='create_update', + conditions=dict(method=['POST'])), + map.connect('/pages/{page_id}/edit', + conditions=dict(method=['GET']), controller='pages', action='edit') + map.connect('/pages/{page_id}/create', + conditions=dict(method=['GET']), controller='pages', action='create') + map.connect('/pages/{page_id}', + conditions=dict(method=['GET']), controller='pages', action='view') + map.connect('/pages/{page_id}', + conditions=dict(method=['POST']), controller='pages', action='create_update') + return map diff --git a/couchwiki/controllers/pages.py b/couchwiki/controllers/pages.py index 14445a4..24df638 100644 --- a/couchwiki/controllers/pages.py +++ b/couchwiki/controllers/pages.py @@ -1,64 +1,64 @@ import logging from pylons import request, response, session, tmpl_context as c from pylons.controllers.util import abort, redirect_to -from couchwiki.lib.base import BaseController, render +from couchwiki.lib.base import BaseController, render, h log = logging.getLogger(__name__) class PagesController(BaseController): def render_page(self, page_id): db = self._get_db() page = Page.load(db, "page_%s" % (page_id,)) if not page: c.desired_page_name = page_id return render("new_page") c.page = page c.page.page_id = page_id return render("page") def edit(self, **kwargs): db = self._get_db() page_id = kwargs.get("page_id") doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) c.page = page return render("edit_page") def create(self, **kwargs): c.desired_page_name = kwargs.get("page_id") return render("new_page") def index(self): db = self._get_db() pages = [ p.value for p in db.view('_design/wiki/_view/pages') ] c.pages = pages c.pagey = h.url_for(controller='pages', page_id="boner", action='create_update') - return render("pages") + return render("pages.html") def create_update(self, **kwargs): db = self._get_db() page_id = request.POST['page_name'] doc_name = "page_%s" % (page_id,) page = Page.load(db, doc_name) if page: page.name = request.POST['page_name'] page.body = request.POST['body'] page.store(db) else: page = Page(doc_name, name=page_id, body=request.POST['body']) page.store(db) redirect_to(str('/pages/%s' % (page_id,))) return def view(self, **kwargs): return self.render_page(kwargs['page_id']) diff --git a/couchwiki/couchapp/.couchapprc b/couchwiki/couchapp/.couchapprc new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/couchwiki/couchapp/.couchapprc @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/couchwiki/couchapp/views/example/map.js b/couchwiki/couchapp/views/example/map.js new file mode 100644 index 0000000..30eca2f --- /dev/null +++ b/couchwiki/couchapp/views/example/map.js @@ -0,0 +1,5 @@ +function(doc) { + var k, keys = [] + for (k in doc) keys.push(k); + emit(doc._id, keys); +}; diff --git a/couchwiki/couchapp/views/example/reduce.js b/couchwiki/couchapp/views/example/reduce.js new file mode 100644 index 0000000..8b9c188 --- /dev/null +++ b/couchwiki/couchapp/views/example/reduce.js @@ -0,0 +1,10 @@ +// example reduce function to count the +// number of rows in a given key range. + +function(keys, values, rereduce) { + if (rereduce) { + return sum(values); + } else { + return values.length; + } +}; diff --git a/couchwiki/couchapp/views/pages/map.js b/couchwiki/couchapp/views/pages/map.js new file mode 100644 index 0000000..dae7662 --- /dev/null +++ b/couchwiki/couchapp/views/pages/map.js @@ -0,0 +1,6 @@ +function(doc) { + if (doc.type && doc.type == "page") { + var url_name = doc._id.replace(/^page_/, ''); + emit(doc._id, { name: doc.name, url_name: url_name }); + } +} diff --git a/couchwiki/lib/base.py b/couchwiki/lib/base.py index 02c32cd..210190c 100644 --- a/couchwiki/lib/base.py +++ b/couchwiki/lib/base.py @@ -1,18 +1,19 @@ """The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_genshi as render - +import couchwiki.lib.helpers as h import couchdb.client + class BaseController(WSGIController): def _get_db(self): return couchdb.client.Database('http://localhost:5984/wiki') def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] return WSGIController.__call__(self, environ, start_response) diff --git a/couchwiki/lib/helpers.py b/couchwiki/lib/helpers.py index 878b888..6848123 100644 --- a/couchwiki/lib/helpers.py +++ b/couchwiki/lib/helpers.py @@ -1,7 +1,8 @@ """Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as 'h'. """ # Import helpers as desired, or define your own, ie: #from webhelpers.html.tags import checkbox, password +from routes import url_for diff --git a/couchwiki/push-couchapp.sh b/couchwiki/push-couchapp.sh new file mode 100755 index 0000000..cf03394 --- /dev/null +++ b/couchwiki/push-couchapp.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +couchapp push couchapp wiki http://localhost:5984/wiki diff --git a/pyscgi_wsgi.py b/pyscgi_wsgi.py new file mode 120000 index 0000000..2b6cebd --- /dev/null +++ b/pyscgi_wsgi.py @@ -0,0 +1 @@ +/home/orlando/pyscgi_wsgi/pyscgi_wsgi.py \ No newline at end of file diff --git a/start-scgi.sh b/start-scgi.sh new file mode 100755 index 0000000..c5162e9 --- /dev/null +++ b/start-scgi.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +cd /var/www/couchwiki +/usr/bin/paster serve wiki_scgi.ini diff --git a/wiki_scgi.ini b/wiki_scgi.ini new file mode 100644 index 0000000..d2e5c4c --- /dev/null +++ b/wiki_scgi.ini @@ -0,0 +1,58 @@ +# +# wiki - Pylons configuration +# +# The %(here)s variable will be replaced with the parent directory of this file +# +[DEFAULT] +debug = true +email_to = [email protected] +smtp_server = localhost +error_email_from = paste@localhost + +[server:main] +use = egg:wiki#pyscgi +host = 0.0.0.0 +port = 4000 + +[app:main] +use = egg:wiki +full_stack = true +cache_dir = %(here)s/data +beaker.session.key = wiki +beaker.session.secret = vUFW7VPkCtaZRrIoz/MuTgxfH +app_instance_uuid = {cb0acc40-1335-45fb-828a-5f443b72a5dc} + +# If you'd like to fine-tune the individual locations of the cache data dirs +# for the Cache data, or the Session saves, un-comment the desired settings +# here: +#beaker.cache.data_dir = %(here)s/data/cache +#beaker.session.data_dir = %(here)s/data/sessions + +# WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* +# Debug mode will enable the interactive debugging tool, allowing ANYONE to +# execute malicious code after an exception is raised. +set debug = false + + +# Logging configuration +[loggers] +keys = root + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = INFO +handlers = console + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s
orlandov/couchwiki
1f6a47367157c07b6fcdec00d918f60dc648a728
copy over all the controllers and model and templates from the old version
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..159d548 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.py[co] +.*.sw[a-z] diff --git a/couchwiki/controllers/pages.py b/couchwiki/controllers/pages.py new file mode 100644 index 0000000..14445a4 --- /dev/null +++ b/couchwiki/controllers/pages.py @@ -0,0 +1,64 @@ +import logging + +from pylons import request, response, session, tmpl_context as c +from pylons.controllers.util import abort, redirect_to + +from couchwiki.lib.base import BaseController, render + +log = logging.getLogger(__name__) + +class PagesController(BaseController): + + def render_page(self, page_id): + db = self._get_db() + page = Page.load(db, "page_%s" % (page_id,)) + + if not page: + c.desired_page_name = page_id + return render("new_page") + + c.page = page + c.page.page_id = page_id + return render("page") + + def edit(self, **kwargs): + db = self._get_db() + page_id = kwargs.get("page_id") + doc_name = "page_%s" % (page_id,) + page = Page.load(db, doc_name) + + c.page = page + + return render("edit_page") + + def create(self, **kwargs): + c.desired_page_name = kwargs.get("page_id") + return render("new_page") + + def index(self): + db = self._get_db() + pages = [ p.value for p in db.view('_design/wiki/_view/pages') ] + c.pages = pages + c.pagey = h.url_for(controller='pages', page_id="boner", action='create_update') + return render("pages") + + def create_update(self, **kwargs): + db = self._get_db() + + page_id = request.POST['page_name'] + doc_name = "page_%s" % (page_id,) + page = Page.load(db, doc_name) + + if page: + page.name = request.POST['page_name'] + page.body = request.POST['body'] + page.store(db) + else: + page = Page(doc_name, name=page_id, body=request.POST['body']) + page.store(db) + + redirect_to(str('/pages/%s' % (page_id,))) + return + + def view(self, **kwargs): + return self.render_page(kwargs['page_id']) diff --git a/couchwiki/lib/base.py b/couchwiki/lib/base.py index 936441e..02c32cd 100644 --- a/couchwiki/lib/base.py +++ b/couchwiki/lib/base.py @@ -1,15 +1,18 @@ """The base Controller API Provides the BaseController class for subclassing. """ from pylons.controllers import WSGIController from pylons.templating import render_genshi as render +import couchdb.client class BaseController(WSGIController): + def _get_db(self): + return couchdb.client.Database('http://localhost:5984/wiki') def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] return WSGIController.__call__(self, environ, start_response) diff --git a/couchwiki/model/page.py b/couchwiki/model/page.py new file mode 100644 index 0000000..dbf855a --- /dev/null +++ b/couchwiki/model/page.py @@ -0,0 +1,13 @@ +#!python + +import datetime +from couchdb.schema import Document, TextField, DateTimeField + +class Page(Document): + body = TextField() + name = TextField() + type = TextField(default="page") + created = DateTimeField(default=datetime.datetime.now()) + + def __init__(self, *args, **kwargs): + Document.__init__(self, *args, **kwargs) diff --git a/couchwiki/public/css/style.css b/couchwiki/public/css/style.css new file mode 100644 index 0000000..959a3c2 --- /dev/null +++ b/couchwiki/public/css/style.css @@ -0,0 +1,40 @@ +.background-1 { background-color: #0086FF } +.background-2 { background-color: #406180 } +.background-3 { background-color: #00284D } +.background-4 { background-color: #80C3FF } +.background-5 { background-color: #E6F3FF } + +.color-1 { background-color: #0086FF } +.color-2 { background-color: #406180 } +.color-3 { background-color: #00284D } +.color-4 { background-color: #80C3FF } +.color-5 { background-color: #E6F3FF } + + + +html { + height: 100%; +} + +body { + margin: 0; + padding: 0; + height: 100%; +} + +h1 { + padding: 0; + margin: 0; +} + +#content { + font-family: sans-serif; + margin-left: auto; + margin-right: auto; + padding: 0px 32px 0px 32px; + border-width: 0px 1px 0px 1px; + border-color: #80C3FF; + border-style: solid; + width: 700px; + height: 100%; +} diff --git a/couchwiki/public/js/jquery.min.js b/couchwiki/public/js/jquery.min.js new file mode 100644 index 0000000..b1ae21d --- /dev/null +++ b/couchwiki/public/js/jquery.min.js @@ -0,0 +1,19 @@ +/* + * jQuery JavaScript Library v1.3.2 + * http://jquery.com/ + * + * Copyright (c) 2009 John Resig + * Dual licensed under the MIT and GPL licenses. + * http://docs.jquery.com/License + * + * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009) + * Revision: 6246 + */ +(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}}); +/* + * Sizzle CSS Selector Engine - v0.9.3 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})(); \ No newline at end of file diff --git a/couchwiki/templates/edit_page.html b/couchwiki/templates/edit_page.html new file mode 100644 index 0000000..aea8ccb --- /dev/null +++ b/couchwiki/templates/edit_page.html @@ -0,0 +1,27 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" + "http://www.w3.org/TR/html4/loose.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en"> +<xi:include href="site.html" /> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title py:content="c.title">2Wikid</title> + <link rel="stylesheet" type="text/css" href="default.css" + py:attrs="{'href': '/default.css'}" /> + + <script> + $(function() { + $('textarea.body').focus(); + }); + </script> +</head> +<body> + <form class="page-form" method="POST" action="/pages/${c.page.name}"> + Page name: <input type="text" name="page_name" value="${c.page.name}"/><br/> + <textarea class="body" name="body">${c.page.body}</textarea> + <input type="submit" /> + </form> +</body></html> + diff --git a/couchwiki/templates/index.html b/couchwiki/templates/index.html new file mode 100644 index 0000000..ba522b5 --- /dev/null +++ b/couchwiki/templates/index.html @@ -0,0 +1,11 @@ +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en" + py:strip=""> + <head> + <title py:content="c.title"></title> + </head> + <body> + </body> +</html> diff --git a/couchwiki/templates/new_page.html b/couchwiki/templates/new_page.html new file mode 100644 index 0000000..40905df --- /dev/null +++ b/couchwiki/templates/new_page.html @@ -0,0 +1,28 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" + "http://www.w3.org/TR/html4/loose.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en"> +<xi:include href="site.html" /> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title py:content="c.title">2Wikid</title> + <link rel="stylesheet" type="text/css" href="default.css" + py:attrs="{'href': '/default.css'}" /> + + <script> + $(function() { + $('textarea.body').focus(); + }); + </script> +</head> +<body><h1>hi</h1> + <form class="page-form" method="POST" + action="${h.url_for(controller='pages', action='create_update')}"> + Page name: <input type="text" name="page_name" value="${c.desired_page_name}"/><br/> + <textarea class="body" name="body"></textarea> + <input type="submit" /> + </form> +</body></html> + diff --git a/couchwiki/templates/page.html b/couchwiki/templates/page.html new file mode 100644 index 0000000..b21bd03 --- /dev/null +++ b/couchwiki/templates/page.html @@ -0,0 +1,20 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" + "http://www.w3.org/TR/html4/loose.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en"> +<xi:include href="site.html" /> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title py:content="c.title">2Wikid</title> + <link rel="stylesheet" type="text/css" href="default.css" + py:attrs="{'href': '/default.css'}" /> +</head> +<body> + <h1 class="name">${c.page.name}</h1> + <hr/> + [ <a href="/pages/${c.page.page_id}/edit">edit</a> ] + <div class="content">${c.page.body}</div> +</body></html> + diff --git a/couchwiki/templates/pages.html b/couchwiki/templates/pages.html new file mode 100644 index 0000000..f9246a6 --- /dev/null +++ b/couchwiki/templates/pages.html @@ -0,0 +1,44 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" + "http://www.w3.org/TR/html4/loose.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en"> +<xi:include href="site.html" /> +<head> + <meta http-equiv="content-type" content="text/html; charset=utf-8" /> + <title py:content="c.title">2Wikid</title> + <script> + $(function() { + $('.create-page .link').click(function() { + $('.create-page .options').show(); + $('.create-page input.name').focus(); + }); + + $('.create-page form').submit(function() { + var page_name = $('.create-page form .name').val(); + window.location = '${h.url_for(controller='pages', + action='create_update')}/' + page_name + '/create'; + return false; + }); + }); + </script> +</head> +<body> +<h1 class="name">Pages</h1> +<ul> + <li class="create-page"> + <a class="link" href="#">Create a page</a> + <div class="options" style="display:none"> + <form> + <input class="name" type="text" /> + <input class="submit" type="submit" value="Create" /> + </form> + </div> + </li> + <li py:for="page in c.pages"> + <a href="${h.url_for(controller='pages', page_id=page.url_name, + action='view')}">${page.name}</a> + </li> +</ul> +</body></html> diff --git a/couchwiki/templates/site.html b/couchwiki/templates/site.html new file mode 100644 index 0000000..059016c --- /dev/null +++ b/couchwiki/templates/site.html @@ -0,0 +1,17 @@ +<html xmlns="http://www.w3.org/1999/xhtml" + xmlns:py="http://genshi.edgewall.org/" + xmlns:xi="http://www.w3.org/2001/XInclude" + lang="en" + py:strip=""> + <head py:match="head" py:attrs="select('@*')"> + <script language="javascript" src="/js/jquery.min.js"></script> + <link rel="stylesheet" type="text/css" href="/css/style.css"></link> + <meta py:replace="select('*|text()')" /> + </head> + <body py:match="body" py:attrs="select('@*')"> + <div id="content" class="background-5"> + <div py:replace="select('*|text()')">This page has no content.</div> + </div> + </body> +</html> + diff --git a/couchwiki/tests/functional/test_pages.py b/couchwiki/tests/functional/test_pages.py new file mode 100644 index 0000000..28c4fb2 --- /dev/null +++ b/couchwiki/tests/functional/test_pages.py @@ -0,0 +1,7 @@ +from couchwiki.tests import * + +class TestPagesController(TestController): + + def test_index(self): + response = self.app.get(url(controller='pages', action='index')) + # Test response... diff --git a/development.ini b/development.ini index 56b4457..d821bc0 100644 --- a/development.ini +++ b/development.ini @@ -1,72 +1,72 @@ # # couchwiki - Pylons development environment configuration # # The %(here)s variable will be replaced with the parent directory of this file # [DEFAULT] debug = true # Uncomment and replace with the address which should receive any error reports #email_to = [email protected] smtp_server = localhost error_email_from = paste@localhost [server:main] use = egg:Paste#http -host = 127.0.0.1 +host = wiki.2wycked.net port = 5000 [app:main] use = egg:couchwiki full_stack = true static_files = true cache_dir = %(here)s/data beaker.session.key = couchwiki beaker.session.secret = somesecret # If you'd like to fine-tune the individual locations of the cache data dirs # for the Cache data, or the Session saves, un-comment the desired settings # here: #beaker.cache.data_dir = %(here)s/data/cache #beaker.session.data_dir = %(here)s/data/sessions # WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* # Debug mode will enable the interactive debugging tool, allowing ANYONE to # execute malicious code after an exception is raised. #set debug = false # Logging configuration [loggers] keys = root, routes, couchwiki [handlers] keys = console [formatters] keys = generic [logger_root] level = INFO handlers = console [logger_routes] level = INFO handlers = qualname = routes.middleware # "level = DEBUG" logs the route matched and routing variables. [logger_couchwiki] level = DEBUG handlers = qualname = couchwiki [handler_console] class = StreamHandler args = (sys.stderr,) level = NOTSET formatter = generic [formatter_generic] format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s datefmt = %H:%M:%S
orlandov/couchwiki
811140e71435d88786b7ae1c4f2dc4e2fe311f9f
initial add of couch wiki
diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..9ac6bec --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,3 @@ +include couchwiki/config/deployment.ini_tmpl +recursive-include couchwiki/public * +recursive-include couchwiki/templates * diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..d0dc6e8 --- /dev/null +++ b/README.txt @@ -0,0 +1,19 @@ +This file is for you to describe the couchwiki application. Typically +you would include information such as the information below: + +Installation and Setup +====================== + +Install ``couchwiki`` using easy_install:: + + easy_install couchwiki + +Make a config file as follows:: + + paster make-config couchwiki config.ini + +Tweak the config file as appropriate and then setup the application:: + + paster setup-app config.ini + +Then you are ready to go. diff --git a/couchwiki.egg-info/PKG-INFO b/couchwiki.egg-info/PKG-INFO new file mode 100644 index 0000000..0ebab3a --- /dev/null +++ b/couchwiki.egg-info/PKG-INFO @@ -0,0 +1,10 @@ +Metadata-Version: 1.0 +Name: couchwiki +Version: 0.1dev +Summary: UNKNOWN +Home-page: UNKNOWN +Author: UNKNOWN +Author-email: UNKNOWN +License: UNKNOWN +Description: UNKNOWN +Platform: UNKNOWN diff --git a/couchwiki.egg-info/SOURCES.txt b/couchwiki.egg-info/SOURCES.txt new file mode 100644 index 0000000..d1ebde0 --- /dev/null +++ b/couchwiki.egg-info/SOURCES.txt @@ -0,0 +1,34 @@ +MANIFEST.in +README.txt +setup.cfg +setup.py +couchwiki/__init__.py +couchwiki/websetup.py +couchwiki.egg-info/PKG-INFO +couchwiki.egg-info/SOURCES.txt +couchwiki.egg-info/dependency_links.txt +couchwiki.egg-info/entry_points.txt +couchwiki.egg-info/not-zip-safe +couchwiki.egg-info/paster_plugins.txt +couchwiki.egg-info/requires.txt +couchwiki.egg-info/top_level.txt +couchwiki/config/__init__.py +couchwiki/config/deployment.ini_tmpl +couchwiki/config/environment.py +couchwiki/config/middleware.py +couchwiki/config/routing.py +couchwiki/controllers/__init__.py +couchwiki/controllers/error.py +couchwiki/lib/__init__.py +couchwiki/lib/app_globals.py +couchwiki/lib/base.py +couchwiki/lib/helpers.py +couchwiki/model/__init__.py +couchwiki/public/bg.png +couchwiki/public/favicon.ico +couchwiki/public/index.html +couchwiki/public/pylons-logo.gif +couchwiki/templates/__init__.py +couchwiki/tests/__init__.py +couchwiki/tests/test_models.py +couchwiki/tests/functional/__init__.py \ No newline at end of file diff --git a/couchwiki.egg-info/dependency_links.txt b/couchwiki.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/couchwiki.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/couchwiki.egg-info/entry_points.txt b/couchwiki.egg-info/entry_points.txt new file mode 100644 index 0000000..27dd18d --- /dev/null +++ b/couchwiki.egg-info/entry_points.txt @@ -0,0 +1,7 @@ + + [paste.app_factory] + main = couchwiki.config.middleware:make_app + + [paste.app_install] + main = pylons.util:PylonsInstaller + \ No newline at end of file diff --git a/couchwiki.egg-info/not-zip-safe b/couchwiki.egg-info/not-zip-safe new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/couchwiki.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/couchwiki.egg-info/paster_plugins.txt b/couchwiki.egg-info/paster_plugins.txt new file mode 100644 index 0000000..c24c7fe --- /dev/null +++ b/couchwiki.egg-info/paster_plugins.txt @@ -0,0 +1,2 @@ +PasteScript +Pylons diff --git a/couchwiki.egg-info/requires.txt b/couchwiki.egg-info/requires.txt new file mode 100644 index 0000000..cbeece6 --- /dev/null +++ b/couchwiki.egg-info/requires.txt @@ -0,0 +1,2 @@ +Pylons>=0.9.7 +Genshi>=0.4 \ No newline at end of file diff --git a/couchwiki.egg-info/top_level.txt b/couchwiki.egg-info/top_level.txt new file mode 100644 index 0000000..6957fa9 --- /dev/null +++ b/couchwiki.egg-info/top_level.txt @@ -0,0 +1 @@ +couchwiki diff --git a/couchwiki/__init__.py b/couchwiki/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/config/__init__.py b/couchwiki/config/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/config/deployment.ini_tmpl b/couchwiki/config/deployment.ini_tmpl new file mode 100644 index 0000000..26f6263 --- /dev/null +++ b/couchwiki/config/deployment.ini_tmpl @@ -0,0 +1,60 @@ +# +# couchwiki - Pylons configuration +# +# The %(here)s variable will be replaced with the parent directory of this file +# +[DEFAULT] +debug = true +email_to = [email protected] +smtp_server = localhost +error_email_from = paste@localhost + +[server:main] +use = egg:Paste#http +host = 0.0.0.0 +port = 5000 + +[app:main] +use = egg:couchwiki +full_stack = true +static_files = true + +cache_dir = %(here)s/data +beaker.session.key = couchwiki +beaker.session.secret = ${app_instance_secret} +app_instance_uuid = ${app_instance_uuid} + +# If you'd like to fine-tune the individual locations of the cache data dirs +# for the Cache data, or the Session saves, un-comment the desired settings +# here: +#beaker.cache.data_dir = %(here)s/data/cache +#beaker.session.data_dir = %(here)s/data/sessions + +# WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* +# Debug mode will enable the interactive debugging tool, allowing ANYONE to +# execute malicious code after an exception is raised. +set debug = false + + +# Logging configuration +[loggers] +keys = root + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = INFO +handlers = console + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(asctime)s %(levelname)-5.5s [%(name)s] %(message)s diff --git a/couchwiki/config/environment.py b/couchwiki/config/environment.py new file mode 100644 index 0000000..3ef08fc --- /dev/null +++ b/couchwiki/config/environment.py @@ -0,0 +1,34 @@ +"""Pylons environment configuration""" +import os + +from genshi.template import TemplateLoader +from pylons import config + +import couchwiki.lib.app_globals as app_globals +import couchwiki.lib.helpers +from couchwiki.config.routing import make_map + +def load_environment(global_conf, app_conf): + """Configure the Pylons environment via the ``pylons.config`` + object + """ + # Pylons paths + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + paths = dict(root=root, + controllers=os.path.join(root, 'controllers'), + static_files=os.path.join(root, 'public'), + templates=[os.path.join(root, 'templates')]) + + # Initialize config with the basic options + config.init_app(global_conf, app_conf, package='couchwiki', paths=paths) + + config['routes.map'] = make_map() + config['pylons.app_globals'] = app_globals.Globals() + config['pylons.h'] = couchwiki.lib.helpers + + # Create the Genshi TemplateLoader + config['pylons.app_globals'].genshi_loader = TemplateLoader( + paths['templates'], auto_reload=True) + + # CONFIGURATION OPTIONS HERE (note: all config options will override + # any Pylons config options) diff --git a/couchwiki/config/middleware.py b/couchwiki/config/middleware.py new file mode 100644 index 0000000..8a95a24 --- /dev/null +++ b/couchwiki/config/middleware.py @@ -0,0 +1,69 @@ +"""Pylons middleware initialization""" +from beaker.middleware import CacheMiddleware, SessionMiddleware +from paste.cascade import Cascade +from paste.registry import RegistryManager +from paste.urlparser import StaticURLParser +from paste.deploy.converters import asbool +from pylons import config +from pylons.middleware import ErrorHandler, StatusCodeRedirect +from pylons.wsgiapp import PylonsApp +from routes.middleware import RoutesMiddleware + +from couchwiki.config.environment import load_environment + +def make_app(global_conf, full_stack=True, static_files=True, **app_conf): + """Create a Pylons WSGI application and return it + + ``global_conf`` + The inherited configuration for this application. Normally from + the [DEFAULT] section of the Paste ini file. + + ``full_stack`` + Whether this application provides a full WSGI stack (by default, + meaning it handles its own exceptions and errors). Disable + full_stack when this application is "managed" by another WSGI + middleware. + + ``static_files`` + Whether this application serves its own static files; disable + when another web server is responsible for serving them. + + ``app_conf`` + The application's local configuration. Normally specified in + the [app:<name>] section of the Paste ini file (where <name> + defaults to main). + + """ + # Configure the Pylons environment + load_environment(global_conf, app_conf) + + # The Pylons WSGI app + app = PylonsApp() + + # Routing/Session/Cache Middleware + app = RoutesMiddleware(app, config['routes.map']) + app = SessionMiddleware(app, config) + app = CacheMiddleware(app, config) + + # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) + + if asbool(full_stack): + # Handle Python exceptions + app = ErrorHandler(app, global_conf, **config['pylons.errorware']) + + # Display error documents for 401, 403, 404 status codes (and + # 500 when debug is disabled) + if asbool(config['debug']): + app = StatusCodeRedirect(app) + else: + app = StatusCodeRedirect(app, [400, 401, 403, 404, 500]) + + # Establish the Registry for this application + app = RegistryManager(app) + + if asbool(static_files): + # Serve static files + static_app = StaticURLParser(config['pylons.paths']['static_files']) + app = Cascade([static_app, app]) + + return app diff --git a/couchwiki/config/routing.py b/couchwiki/config/routing.py new file mode 100644 index 0000000..3ff8e54 --- /dev/null +++ b/couchwiki/config/routing.py @@ -0,0 +1,26 @@ +"""Routes configuration + +The more specific and detailed routes should be defined first so they +may take precedent over the more generic routes. For more information +refer to the routes manual at http://routes.groovie.org/docs/ +""" +from pylons import config +from routes import Mapper + +def make_map(): + """Create, configure and return the routes Mapper""" + map = Mapper(directory=config['pylons.paths']['controllers'], + always_scan=config['debug']) + map.minimization = False + + # The ErrorController route (handles 404/500 error pages); it should + # likely stay at the top, ensuring it can always be resolved + map.connect('/error/{action}', controller='error') + map.connect('/error/{action}/{id}', controller='error') + + # CUSTOM ROUTES HERE + + map.connect('/{controller}/{action}') + map.connect('/{controller}/{action}/{id}') + + return map diff --git a/couchwiki/controllers/__init__.py b/couchwiki/controllers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/controllers/error.py b/couchwiki/controllers/error.py new file mode 100644 index 0000000..eef1838 --- /dev/null +++ b/couchwiki/controllers/error.py @@ -0,0 +1,46 @@ +import cgi + +from paste.urlparser import PkgResourcesParser +from pylons import request +from pylons.controllers.util import forward +from pylons.middleware import error_document_template +from webhelpers.html.builder import literal + +from couchwiki.lib.base import BaseController + +class ErrorController(BaseController): + + """Generates error documents as and when they are required. + + The ErrorDocuments middleware forwards to ErrorController when error + related status codes are returned from the application. + + This behaviour can be altered by changing the parameters to the + ErrorDocuments middleware in your config/middleware.py file. + + """ + + def document(self): + """Render the error document""" + resp = request.environ.get('pylons.original_response') + content = literal(resp.body) or cgi.escape(request.GET.get('message', '')) + page = error_document_template % \ + dict(prefix=request.environ.get('SCRIPT_NAME', ''), + code=cgi.escape(request.GET.get('code', str(resp.status_int))), + message=content) + return page + + def img(self, id): + """Serve Pylons' stock images""" + return self._serve_file('/'.join(['media/img', id])) + + def style(self, id): + """Serve Pylons' stock stylesheets""" + return self._serve_file('/'.join(['media/style', id])) + + def _serve_file(self, path): + """Call Paste's FileApp (a WSGI application) to serve the file + at the specified path + """ + request.environ['PATH_INFO'] = '/%s' % path + return forward(PkgResourcesParser('pylons', 'pylons')) diff --git a/couchwiki/lib/__init__.py b/couchwiki/lib/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/lib/app_globals.py b/couchwiki/lib/app_globals.py new file mode 100644 index 0000000..8e62241 --- /dev/null +++ b/couchwiki/lib/app_globals.py @@ -0,0 +1,15 @@ +"""The application's Globals object""" + +class Globals(object): + + """Globals acts as a container for objects available throughout the + life of the application + + """ + + def __init__(self): + """One instance of Globals is created during application + initialization and is available during requests via the + 'app_globals' variable + + """ diff --git a/couchwiki/lib/base.py b/couchwiki/lib/base.py new file mode 100644 index 0000000..936441e --- /dev/null +++ b/couchwiki/lib/base.py @@ -0,0 +1,15 @@ +"""The base Controller API + +Provides the BaseController class for subclassing. +""" +from pylons.controllers import WSGIController +from pylons.templating import render_genshi as render + +class BaseController(WSGIController): + + def __call__(self, environ, start_response): + """Invoke the Controller""" + # WSGIController.__call__ dispatches to the Controller method + # the request is routed to. This routing information is + # available in environ['pylons.routes_dict'] + return WSGIController.__call__(self, environ, start_response) diff --git a/couchwiki/lib/helpers.py b/couchwiki/lib/helpers.py new file mode 100644 index 0000000..878b888 --- /dev/null +++ b/couchwiki/lib/helpers.py @@ -0,0 +1,7 @@ +"""Helper functions + +Consists of functions to typically be used within templates, but also +available to Controllers. This module is available to templates as 'h'. +""" +# Import helpers as desired, or define your own, ie: +#from webhelpers.html.tags import checkbox, password diff --git a/couchwiki/model/__init__.py b/couchwiki/model/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/public/bg.png b/couchwiki/public/bg.png new file mode 100644 index 0000000..69c1798 Binary files /dev/null and b/couchwiki/public/bg.png differ diff --git a/couchwiki/public/favicon.ico b/couchwiki/public/favicon.ico new file mode 100644 index 0000000..21e215e Binary files /dev/null and b/couchwiki/public/favicon.ico differ diff --git a/couchwiki/public/index.html b/couchwiki/public/index.html new file mode 100644 index 0000000..0719061 --- /dev/null +++ b/couchwiki/public/index.html @@ -0,0 +1,137 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!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> + <title>Welcome to Pylons!</title> + <style type="text/css"> + body { + font-family: arial, helvetica, sans-serif; + background-color: #ffc900; + background-image: url(bg.png); + background-repeat: repeat-x; + width:100%; + height:100%; + margin:0; + max-height: 100%; + padding:0; + border:none; + line-height:1.4; + } + #container { + color:white; + background-color:#111; + position: absolute; + left: 50%; + width: 500px; + margin-left: -300px; + padding:50px; + height:100%; + } + #footer { + margin: 120px 0 0 0; + padding: 3px; + text-align:center; + font-size:small; + background-color:#222; + letter-spacing: 1px; + } + h1 { + text-align:center; + font-size:xx-large; + font-weight:normal; + margin: 0 0 20px 0; + border:none; + padding:0; + letter-spacing: 5px; + } + h2 { + font-size:xx-large; + font-weight:normal; + margin: 0 0 20px 0; + border:none; + padding:0; + } + hr { + margin-bottom:30px; + border: 1px solid #222; + background-color: #222; + padding: 2px; + } + #logo { + background-image: url(signum8b_spk.png); + background-repeat: no-repeat; + height: 0; + overflow: hidden; + padding-top: 99px; + width: 239px; + } + #left { + float:left; + width:250px; + margin:0 50px 0 0; + border:none; + padding:0 0 0 10px; + } + #right { + margin:0 0 0 330px; + border:none; + padding:0; + } + ul { + list-style:none; + margin:0; + border:none; + padding:0; + } + a:visited { + color:white; + text-decoration:none; + } + a:link { + color:white; + text-decoration:none; + }</style> + </head> + <body> + <div id="container"> + <h1>Welcome to <img src="pylons-logo.gif" alt="Logo displaying the word Pylons" + style="vertical-align:-15px; width: 250px;"/> + </h1> + <hr/> + <div id="left"> + <h2>Let's begin!</h2> + <p>If you haven't used Pylons before, start with the <a href="http://pylonshq.com/docs/en/0.9.7/gettingstarted/" + style="text-decoration:underline;">beginners' tutorial</a>.</p> + </div> + <div id="right"> + <h2>Help</h2> + <ul> + <li> + <a href="http://pylonshq.com/docs/en/0.9.7/">Official documentation</a> + </li> + <li> + <a href="http://wiki.pylonshq.com/display/pylonsfaq/Home">FAQ</a> + </li> + <li> + <a href="http://wiki.pylonshq.com/dashboard.action">Wiki</a> + </li> + <li> + <a href="http://wiki.pylonshq.com/display/pylonscommunity/Home#Home-JointheMailingLists">Mailing list</a> + </li> + <li> + <a href="http://wiki.pylonshq.com/display/pylonscommunity/Home#Home-IRC">IRC</a> + </li> + <li> + <a href="http://pylonshq.com/project/pylonshq/roadmap">Bug tracker</a> + </li> + </ul> + </div> + <div id="footer"> + <a href="http://www.pylonshq.com" style="color: #ccc; text-decoration:none;" + >www.pylonshq.com</a> + </div> + </div> + </body> +</html> diff --git a/couchwiki/public/pylons-logo.gif b/couchwiki/public/pylons-logo.gif new file mode 100644 index 0000000..61b2d9a Binary files /dev/null and b/couchwiki/public/pylons-logo.gif differ diff --git a/couchwiki/templates/__init__.py b/couchwiki/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/tests/__init__.py b/couchwiki/tests/__init__.py new file mode 100644 index 0000000..d51f6f2 --- /dev/null +++ b/couchwiki/tests/__init__.py @@ -0,0 +1,36 @@ +"""Pylons application test package + +This package assumes the Pylons environment is already loaded, such as +when this script is imported from the `nosetests --with-pylons=test.ini` +command. + +This module initializes the application via ``websetup`` (`paster +setup-app`) and provides the base testing objects. +""" +from unittest import TestCase + +from paste.deploy import loadapp +from paste.script.appinstall import SetupCommand +from pylons import config, url +from routes.util import URLGenerator +from webtest import TestApp + +import pylons.test + +__all__ = ['environ', 'url', 'TestController'] + +# Invoke websetup with the current config file +SetupCommand('setup-app').run([config['__file__']]) + +environ = {} + +class TestController(TestCase): + + def __init__(self, *args, **kwargs): + if pylons.test.pylonsapp: + wsgiapp = pylons.test.pylonsapp + else: + wsgiapp = loadapp('config:%s' % config['__file__']) + self.app = TestApp(wsgiapp) + url._push_object(URLGenerator(config['routes.map'], environ)) + TestCase.__init__(self, *args, **kwargs) diff --git a/couchwiki/tests/functional/__init__.py b/couchwiki/tests/functional/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/tests/test_models.py b/couchwiki/tests/test_models.py new file mode 100644 index 0000000..e69de29 diff --git a/couchwiki/websetup.py b/couchwiki/websetup.py new file mode 100644 index 0000000..210de20 --- /dev/null +++ b/couchwiki/websetup.py @@ -0,0 +1,10 @@ +"""Setup the couchwiki application""" +import logging + +from couchwiki.config.environment import load_environment + +log = logging.getLogger(__name__) + +def setup_app(command, conf, vars): + """Place any commands to setup couchwiki here""" + load_environment(conf.global_conf, conf.local_conf) diff --git a/development.ini b/development.ini new file mode 100644 index 0000000..56b4457 --- /dev/null +++ b/development.ini @@ -0,0 +1,72 @@ +# +# couchwiki - Pylons development environment configuration +# +# The %(here)s variable will be replaced with the parent directory of this file +# +[DEFAULT] +debug = true +# Uncomment and replace with the address which should receive any error reports +#email_to = [email protected] +smtp_server = localhost +error_email_from = paste@localhost + +[server:main] +use = egg:Paste#http +host = 127.0.0.1 +port = 5000 + +[app:main] +use = egg:couchwiki +full_stack = true +static_files = true + +cache_dir = %(here)s/data +beaker.session.key = couchwiki +beaker.session.secret = somesecret + +# If you'd like to fine-tune the individual locations of the cache data dirs +# for the Cache data, or the Session saves, un-comment the desired settings +# here: +#beaker.cache.data_dir = %(here)s/data/cache +#beaker.session.data_dir = %(here)s/data/sessions + +# WARNING: *THE LINE BELOW MUST BE UNCOMMENTED ON A PRODUCTION ENVIRONMENT* +# Debug mode will enable the interactive debugging tool, allowing ANYONE to +# execute malicious code after an exception is raised. +#set debug = false + + +# Logging configuration +[loggers] +keys = root, routes, couchwiki + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = INFO +handlers = console + +[logger_routes] +level = INFO +handlers = +qualname = routes.middleware +# "level = DEBUG" logs the route matched and routing variables. + +[logger_couchwiki] +level = DEBUG +handlers = +qualname = couchwiki + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/docs/index.txt b/docs/index.txt new file mode 100644 index 0000000..5be970c --- /dev/null +++ b/docs/index.txt @@ -0,0 +1,19 @@ +couchwiki ++++++++++ + +This is the main index page of your documentation. It should be written in +`reStructuredText format <http://docutils.sourceforge.net/rst.html>`_. + +You can generate your documentation in HTML format by running this command:: + + setup.py pudge + +For this to work you will need to download and install `buildutils`_, +`pudge`_, and `pygments`_. The ``pudge`` command is disabled by +default; to ativate it in your project, run:: + + setup.py addcommand -p buildutils.pudge_command + +.. _buildutils: http://pypi.python.org/pypi/buildutils +.. _pudge: http://pudge.lesscode.org/ +.. _pygments: http://pygments.org/ diff --git a/ez_setup.py b/ez_setup.py new file mode 100644 index 0000000..d24e845 --- /dev/null +++ b/ez_setup.py @@ -0,0 +1,276 @@ +#!python +"""Bootstrap setuptools installation + +If you want to use setuptools in your package's setup.py, just include this +file in the same directory with it, and add this to the top of your setup.py:: + + from ez_setup import use_setuptools + use_setuptools() + +If you want to require a specific version of setuptools, set a download +mirror, or use an alternate download directory, you can do so by supplying +the appropriate options to ``use_setuptools()``. + +This file can also be run as a script to install or upgrade setuptools. +""" +import sys +DEFAULT_VERSION = "0.6c9" +DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] + +md5_data = { + 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', + 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', + 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', + 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', + 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', + 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', + 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', + 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', + 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', + 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', + 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', + 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', + 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', + 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', + 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', + 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', + 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', + 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', + 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', + 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', + 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', + 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', + 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', + 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', + 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', + 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', + 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', + 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', + 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', + 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', + 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', + 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', + 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', + 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', +} + +import sys, os +try: from hashlib import md5 +except ImportError: from md5 import md5 + +def _validate_md5(egg_name, data): + if egg_name in md5_data: + digest = md5(data).hexdigest() + if digest != md5_data[egg_name]: + print >>sys.stderr, ( + "md5 validation of %s failed! (Possible download problem?)" + % egg_name + ) + sys.exit(2) + return data + +def use_setuptools( + version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, + download_delay=15 +): + """Automatically find/download setuptools and make it available on sys.path + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end with + a '/'). `to_dir` is the directory where setuptools will be downloaded, if + it is not already available. If `download_delay` is specified, it should + be the number of seconds that will be paused before initiating a download, + should one be required. If an older version of setuptools is installed, + this routine will print a message to ``sys.stderr`` and raise SystemExit in + an attempt to abort the calling script. + """ + was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules + def do_download(): + egg = download_setuptools(version, download_base, to_dir, download_delay) + sys.path.insert(0, egg) + import setuptools; setuptools.bootstrap_install_from = egg + try: + import pkg_resources + except ImportError: + return do_download() + try: + pkg_resources.require("setuptools>="+version); return + except pkg_resources.VersionConflict, e: + if was_imported: + print >>sys.stderr, ( + "The required version of setuptools (>=%s) is not available, and\n" + "can't be installed while this script is running. Please install\n" + " a more recent version first, using 'easy_install -U setuptools'." + "\n\n(Currently using %r)" + ) % (version, e.args[0]) + sys.exit(2) + else: + del pkg_resources, sys.modules['pkg_resources'] # reload ok + return do_download() + except pkg_resources.DistributionNotFound: + return do_download() + +def download_setuptools( + version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, + delay = 15 +): + """Download setuptools from a specified location and return its filename + + `version` should be a valid setuptools version number that is available + as an egg for download under the `download_base` URL (which should end + with a '/'). `to_dir` is the directory where the egg will be downloaded. + `delay` is the number of seconds to pause before an actual download attempt. + """ + import urllib2, shutil + egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) + url = download_base + egg_name + saveto = os.path.join(to_dir, egg_name) + src = dst = None + if not os.path.exists(saveto): # Avoid repeated downloads + try: + from distutils import log + if delay: + log.warn(""" +--------------------------------------------------------------------------- +This script requires setuptools version %s to run (even to display +help). I will attempt to download it for you (from +%s), but +you may need to enable firewall access for this script first. +I will start the download in %d seconds. + +(Note: if this machine does not have network access, please obtain the file + + %s + +and place it in this directory before rerunning this script.) +---------------------------------------------------------------------------""", + version, download_base, delay, url + ); from time import sleep; sleep(delay) + log.warn("Downloading %s", url) + src = urllib2.urlopen(url) + # Read/write all in one block, so we don't create a corrupt file + # if the download is interrupted. + data = _validate_md5(egg_name, src.read()) + dst = open(saveto,"wb"); dst.write(data) + finally: + if src: src.close() + if dst: dst.close() + return os.path.realpath(saveto) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +def main(argv, version=DEFAULT_VERSION): + """Install or upgrade setuptools and EasyInstall""" + try: + import setuptools + except ImportError: + egg = None + try: + egg = download_setuptools(version, delay=0) + sys.path.insert(0,egg) + from setuptools.command.easy_install import main + return main(list(argv)+[egg]) # we're done here + finally: + if egg and os.path.exists(egg): + os.unlink(egg) + else: + if setuptools.__version__ == '0.0.1': + print >>sys.stderr, ( + "You have an obsolete version of setuptools installed. Please\n" + "remove it from your system entirely before rerunning this script." + ) + sys.exit(2) + + req = "setuptools>="+version + import pkg_resources + try: + pkg_resources.require(req) + except pkg_resources.VersionConflict: + try: + from setuptools.command.easy_install import main + except ImportError: + from easy_install import main + main(list(argv)+[download_setuptools(delay=0)]) + sys.exit(0) # try to force an exit + else: + if argv: + from setuptools.command.easy_install import main + main(argv) + else: + print "Setuptools version",version,"or greater has been installed." + print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' + +def update_md5(filenames): + """Update our built-in md5 registry""" + + import re + + for name in filenames: + base = os.path.basename(name) + f = open(name,'rb') + md5_data[base] = md5(f.read()).hexdigest() + f.close() + + data = [" %r: %r,\n" % it for it in md5_data.items()] + data.sort() + repl = "".join(data) + + import inspect + srcfile = inspect.getsourcefile(sys.modules[__name__]) + f = open(srcfile, 'rb'); src = f.read(); f.close() + + match = re.search("\nmd5_data = {\n([^}]+)}", src) + if not match: + print >>sys.stderr, "Internal error!" + sys.exit(2) + + src = src[:match.start(1)] + repl + src[match.end(1):] + f = open(srcfile,'w') + f.write(src) + f.close() + + +if __name__=='__main__': + if len(sys.argv)>2 and sys.argv[1]=='--md5update': + update_md5(sys.argv[2:]) + else: + main(sys.argv[1:]) + + + + + + diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..93837cb --- /dev/null +++ b/setup.cfg @@ -0,0 +1,31 @@ +[egg_info] +tag_build = dev +tag_svn_revision = true + +[easy_install] +find_links = http://www.pylonshq.com/download/ + +[nosetests] +with-pylons = test.ini + +# Babel configuration +[compile_catalog] +domain = couchwiki +directory = couchwiki/i18n +statistics = true + +[extract_messages] +add_comments = TRANSLATORS: +output_file = couchwiki/i18n/couchwiki.pot +width = 80 + +[init_catalog] +domain = couchwiki +input_file = couchwiki/i18n/couchwiki.pot +output_dir = couchwiki/i18n + +[update_catalog] +domain = couchwiki +input_file = couchwiki/i18n/couchwiki.pot +output_dir = couchwiki/i18n +previous = true diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..62d7540 --- /dev/null +++ b/setup.py @@ -0,0 +1,36 @@ +try: + from setuptools import setup, find_packages +except ImportError: + from ez_setup import use_setuptools + use_setuptools() + from setuptools import setup, find_packages + +setup( + name='couchwiki', + version='0.1', + description='', + author='', + author_email='', + url='', + install_requires=[ + "Pylons>=0.9.7", + "Genshi>=0.4", + ], + setup_requires=["PasteScript>=1.6.3"], + packages=find_packages(exclude=['ez_setup']), + include_package_data=True, + test_suite='nose.collector', + package_data={'couchwiki': ['i18n/*/LC_MESSAGES/*.mo']}, + #message_extractors={'couchwiki': [ + # ('**.py', 'python', None), + # ('public/**', 'ignore', None)]}, + zip_safe=False, + paster_plugins=['PasteScript', 'Pylons'], + entry_points=""" + [paste.app_factory] + main = couchwiki.config.middleware:make_app + + [paste.app_install] + main = pylons.util:PylonsInstaller + """, +) diff --git a/test.ini b/test.ini new file mode 100644 index 0000000..0595de7 --- /dev/null +++ b/test.ini @@ -0,0 +1,21 @@ +# +# couchwiki - Pylons testing environment configuration +# +# The %(here)s variable will be replaced with the parent directory of this file +# +[DEFAULT] +debug = true +# Uncomment and replace with the address which should receive any error reports +#email_to = [email protected] +smtp_server = localhost +error_email_from = paste@localhost + +[server:main] +use = egg:Paste#http +host = 127.0.0.1 +port = 5000 + +[app:main] +use = config:development.ini + +# Add additional test specific configuration options as necessary.
mcherry/WinProwl
5e1a3844cf2bc987675fdad7e323107d7e167447
Fixed warning about variable being used before assigning a value
diff --git a/WinProwl/Module1.vb b/WinProwl/Module1.vb index d749d00..0c82347 100644 --- a/WinProwl/Module1.vb +++ b/WinProwl/Module1.vb @@ -1,134 +1,134 @@ Module Module1 Sub Main(ByVal sArgs() As String) Dim oWeb As New System.Net.WebClient - Dim strResult As String + Dim strResult As String = Nothing Dim boolAuthorized As Boolean = True If sArgs.Count = 0 Then PrintUsage() Exit Sub End If Dim strProwlKey As String = "" Dim strApp As String = "" Dim strEvent As String = "" Dim strDesc As String = "" Dim strPriority As String = "" Dim myOpts As New Collection myOpts = GetOpts(sArgs) If myOpts.Contains("-k") Then strProwlKey = myOpts.Item("-k") If strProwlKey = "0" Then PrintError("No prowl key specified!") Exit Sub End If Else PrintError("No prowl key specified!") Exit Sub End If If myOpts.Contains("-a") Then strApp = myOpts.Item("-a") Else PrintError("No application name specified!") Exit Sub End If If myOpts.Contains("-e") Then strEvent = myOpts.Item("-e") Else PrintError("No event name specified!") Exit Sub End If If myOpts.Contains("-d") Then strDesc = myOpts.Item("-d") Else PrintError("No description specified!") Exit Sub End If If myOpts.Contains("-p") Then strPriority = myOpts.Item("-p") Else strPriority = "0" End If Dim strProwlURL As String = "https://prowl.weks.net/publicapi/add?apikey=" + strProwlKey + "&application=" + strApp + "&event=" + strEvent + "&description=" + strDesc + "&priority=" + strPriority Try strResult = oWeb.DownloadString(strProwlURL) Catch ex As Exception If ex.Message.ToString.Contains("(401) Unauthorized") Then boolAuthorized = False Else Console.WriteLine("Unknown error: " + ex.Message) End If End Try If boolAuthorized = True Then Dim doc As New Xml.XmlDocument doc.LoadXml(strResult) Dim reader As New Xml.XmlNodeReader(doc) While reader.Read Select Case reader.NodeType Case Xml.XmlNodeType.Element If reader.Name = "success" Then If reader.GetAttribute("code").ToString = "200" Then If Not myOpts.Contains("-q") Then Console.WriteLine("Successfully posted notification.") End If End If End If End Select End While Else Console.WriteLine("Invalid Prowl API key.") End If End Sub Sub PrintUsage() Console.WriteLine("WinProwl Version 1.0") Console.WriteLine("Written by Mike Cherry <[email protected]>") Console.WriteLine("") Console.WriteLine("Usage: WinProwl.exe -k apikey -a " + Chr(34) + "Name" + Chr(34) + " -e " + Chr(34) + "Event" + Chr(34) + " -d " + Chr(34) + "Description" + Chr(34) + " -p Priority") Console.WriteLine("") Console.WriteLine("-p is optional and defaults to 0") End Sub Sub PrintError(ByVal strErrorMsg As String) PrintUsage() Console.WriteLine("") Console.WriteLine(strErrorMsg) End Sub Public Function GetOpts(ByVal strOptions() As String) As Collection Dim retCollection As New Collection Dim strOpt, strValue As String Dim i As Integer For i = 0 To strOptions.Length - 1 strOpt = strOptions(i) If i < (strOptions.Length - 1) Then If strOptions(i + 1).StartsWith("-") Then strValue = "0" Else i += 1 strValue = strOptions(i) End If Else strValue = "0" End If retCollection.Add(strValue, strOpt) Next Return retCollection End Function End Module diff --git a/WinProwl/bin/Debug/WinProwl.vshost.exe b/WinProwl/bin/Debug/WinProwl.vshost.exe index 69ed6c0..14041ba 100644 Binary files a/WinProwl/bin/Debug/WinProwl.vshost.exe and b/WinProwl/bin/Debug/WinProwl.vshost.exe differ diff --git a/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt b/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt index 66cc7e1..1ddd38a 100644 --- a/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt +++ b/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt @@ -1,10 +1,14 @@ C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.exe C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.pdb C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.xml C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\ResolveAssemblyReference.cache C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.Resources.resources C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.vbproj.GenerateResource.Cache C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.exe C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.xml C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.pdb C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.exe.config +C:\GitStuff\WinProwl\WinProwl\bin\Release\WinProwl.exe.config +C:\GitStuff\WinProwl\WinProwl\obj\Release\WinProwl.exe +C:\GitStuff\WinProwl\WinProwl\obj\Release\WinProwl.xml +C:\GitStuff\WinProwl\WinProwl\obj\Release\WinProwl.pdb
mcherry/WinProwl
591c06a5bf4fd440471577e99c50fd1b9eb67154
still figuring this out
diff --git a/WinProwl.suo b/WinProwl.suo index 291db1c..7788e6b 100644 Binary files a/WinProwl.suo and b/WinProwl.suo differ diff --git a/WinProwl/Module1.vb b/WinProwl/Module1.vb index 497f07f..d749d00 100644 --- a/WinProwl/Module1.vb +++ b/WinProwl/Module1.vb @@ -1,134 +1,134 @@ Module Module1 Sub Main(ByVal sArgs() As String) Dim oWeb As New System.Net.WebClient Dim strResult As String Dim boolAuthorized As Boolean = True If sArgs.Count = 0 Then PrintUsage() Exit Sub End If Dim strProwlKey As String = "" Dim strApp As String = "" Dim strEvent As String = "" Dim strDesc As String = "" Dim strPriority As String = "" Dim myOpts As New Collection myOpts = GetOpts(sArgs) If myOpts.Contains("-k") Then strProwlKey = myOpts.Item("-k") If strProwlKey = "0" Then PrintError("No prowl key specified!") Exit Sub End If Else PrintError("No prowl key specified!") Exit Sub End If If myOpts.Contains("-a") Then strApp = myOpts.Item("-a") Else PrintError("No application name specified!") Exit Sub End If If myOpts.Contains("-e") Then strEvent = myOpts.Item("-e") Else PrintError("No event name specified!") Exit Sub End If If myOpts.Contains("-d") Then strDesc = myOpts.Item("-d") Else PrintError("No description specified!") Exit Sub End If If myOpts.Contains("-p") Then strPriority = myOpts.Item("-p") Else strPriority = "0" End If Dim strProwlURL As String = "https://prowl.weks.net/publicapi/add?apikey=" + strProwlKey + "&application=" + strApp + "&event=" + strEvent + "&description=" + strDesc + "&priority=" + strPriority Try strResult = oWeb.DownloadString(strProwlURL) Catch ex As Exception If ex.Message.ToString.Contains("(401) Unauthorized") Then boolAuthorized = False Else Console.WriteLine("Unknown error: " + ex.Message) End If End Try If boolAuthorized = True Then Dim doc As New Xml.XmlDocument doc.LoadXml(strResult) Dim reader As New Xml.XmlNodeReader(doc) While reader.Read Select Case reader.NodeType Case Xml.XmlNodeType.Element If reader.Name = "success" Then If reader.GetAttribute("code").ToString = "200" Then If Not myOpts.Contains("-q") Then Console.WriteLine("Successfully posted notification.") End If End If End If End Select End While Else Console.WriteLine("Invalid Prowl API key.") End If End Sub Sub PrintUsage() Console.WriteLine("WinProwl Version 1.0") Console.WriteLine("Written by Mike Cherry <[email protected]>") Console.WriteLine("") - Console.WriteLine("Usage: WinProwl.exe -a " + Chr(34) + "Name" + Chr(34) + " -e " + Chr(34) + "Event" + Chr(34) + " -d " + Chr(34) + "Description" + Chr(34) + " -p Priority") + Console.WriteLine("Usage: WinProwl.exe -k apikey -a " + Chr(34) + "Name" + Chr(34) + " -e " + Chr(34) + "Event" + Chr(34) + " -d " + Chr(34) + "Description" + Chr(34) + " -p Priority") Console.WriteLine("") Console.WriteLine("-p is optional and defaults to 0") End Sub Sub PrintError(ByVal strErrorMsg As String) PrintUsage() Console.WriteLine("") Console.WriteLine(strErrorMsg) End Sub Public Function GetOpts(ByVal strOptions() As String) As Collection Dim retCollection As New Collection Dim strOpt, strValue As String Dim i As Integer For i = 0 To strOptions.Length - 1 strOpt = strOptions(i) If i < (strOptions.Length - 1) Then If strOptions(i + 1).StartsWith("-") Then strValue = "0" Else i += 1 strValue = strOptions(i) End If Else strValue = "0" End If retCollection.Add(strValue, strOpt) Next Return retCollection End Function End Module diff --git a/WinProwl/bin/Release/WinProwl.exe b/WinProwl/bin/Release/WinProwl.exe index b87df76..3cfbced 100644 Binary files a/WinProwl/bin/Release/WinProwl.exe and b/WinProwl/bin/Release/WinProwl.exe differ diff --git a/WinProwl/bin/Release/WinProwl.pdb b/WinProwl/bin/Release/WinProwl.pdb index 01ba6b2..4f7030b 100644 Binary files a/WinProwl/bin/Release/WinProwl.pdb and b/WinProwl/bin/Release/WinProwl.pdb differ diff --git a/WinProwl/obj/Release/WinProwl.exe b/WinProwl/obj/Release/WinProwl.exe index b87df76..3cfbced 100644 Binary files a/WinProwl/obj/Release/WinProwl.exe and b/WinProwl/obj/Release/WinProwl.exe differ diff --git a/WinProwl/obj/Release/WinProwl.pdb b/WinProwl/obj/Release/WinProwl.pdb index 01ba6b2..4f7030b 100644 Binary files a/WinProwl/obj/Release/WinProwl.pdb and b/WinProwl/obj/Release/WinProwl.pdb differ
mcherry/WinProwl
9fc527e1009b9465b3bba5c839a0950493421747
project upload
diff --git a/WinProwl.sln b/WinProwl.sln new file mode 100644 index 0000000..8f4c707 --- /dev/null +++ b/WinProwl.sln @@ -0,0 +1,20 @@ + +Microsoft Visual Studio Solution File, Format Version 10.00 +# Visual Studio 2008 +Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "WinProwl", "WinProwl\WinProwl.vbproj", "{C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/WinProwl.suo b/WinProwl.suo new file mode 100644 index 0000000..291db1c Binary files /dev/null and b/WinProwl.suo differ diff --git a/WinProwl/Module1.vb b/WinProwl/Module1.vb new file mode 100644 index 0000000..497f07f --- /dev/null +++ b/WinProwl/Module1.vb @@ -0,0 +1,134 @@ +Module Module1 + + Sub Main(ByVal sArgs() As String) + Dim oWeb As New System.Net.WebClient + Dim strResult As String + Dim boolAuthorized As Boolean = True + + If sArgs.Count = 0 Then + PrintUsage() + Exit Sub + End If + + Dim strProwlKey As String = "" + Dim strApp As String = "" + Dim strEvent As String = "" + Dim strDesc As String = "" + Dim strPriority As String = "" + + Dim myOpts As New Collection + myOpts = GetOpts(sArgs) + + If myOpts.Contains("-k") Then + strProwlKey = myOpts.Item("-k") + If strProwlKey = "0" Then + PrintError("No prowl key specified!") + Exit Sub + End If + Else + PrintError("No prowl key specified!") + Exit Sub + End If + + If myOpts.Contains("-a") Then + strApp = myOpts.Item("-a") + Else + PrintError("No application name specified!") + Exit Sub + End If + + If myOpts.Contains("-e") Then + strEvent = myOpts.Item("-e") + Else + PrintError("No event name specified!") + Exit Sub + End If + + If myOpts.Contains("-d") Then + strDesc = myOpts.Item("-d") + Else + PrintError("No description specified!") + Exit Sub + End If + + If myOpts.Contains("-p") Then + strPriority = myOpts.Item("-p") + Else + strPriority = "0" + End If + + Dim strProwlURL As String = "https://prowl.weks.net/publicapi/add?apikey=" + strProwlKey + "&application=" + strApp + "&event=" + strEvent + "&description=" + strDesc + "&priority=" + strPriority + + Try + strResult = oWeb.DownloadString(strProwlURL) + Catch ex As Exception + If ex.Message.ToString.Contains("(401) Unauthorized") Then + boolAuthorized = False + Else + Console.WriteLine("Unknown error: " + ex.Message) + End If + End Try + + If boolAuthorized = True Then + Dim doc As New Xml.XmlDocument + doc.LoadXml(strResult) + + Dim reader As New Xml.XmlNodeReader(doc) + While reader.Read + Select Case reader.NodeType + Case Xml.XmlNodeType.Element + If reader.Name = "success" Then + If reader.GetAttribute("code").ToString = "200" Then + If Not myOpts.Contains("-q") Then + Console.WriteLine("Successfully posted notification.") + End If + End If + End If + End Select + End While + Else + Console.WriteLine("Invalid Prowl API key.") + End If + End Sub + + Sub PrintUsage() + Console.WriteLine("WinProwl Version 1.0") + Console.WriteLine("Written by Mike Cherry <[email protected]>") + Console.WriteLine("") + Console.WriteLine("Usage: WinProwl.exe -a " + Chr(34) + "Name" + Chr(34) + " -e " + Chr(34) + "Event" + Chr(34) + " -d " + Chr(34) + "Description" + Chr(34) + " -p Priority") + Console.WriteLine("") + Console.WriteLine("-p is optional and defaults to 0") + End Sub + + Sub PrintError(ByVal strErrorMsg As String) + PrintUsage() + Console.WriteLine("") + Console.WriteLine(strErrorMsg) + End Sub + + Public Function GetOpts(ByVal strOptions() As String) As Collection + Dim retCollection As New Collection + Dim strOpt, strValue As String + Dim i As Integer + + For i = 0 To strOptions.Length - 1 + strOpt = strOptions(i) + + If i < (strOptions.Length - 1) Then + If strOptions(i + 1).StartsWith("-") Then + strValue = "0" + Else + i += 1 + strValue = strOptions(i) + End If + Else + strValue = "0" + End If + + retCollection.Add(strValue, strOpt) + Next + + Return retCollection + End Function + +End Module diff --git a/WinProwl/My Project/Application.Designer.vb b/WinProwl/My Project/Application.Designer.vb new file mode 100644 index 0000000..d4e7c67 --- /dev/null +++ b/WinProwl/My Project/Application.Designer.vb @@ -0,0 +1,13 @@ +'------------------------------------------------------------------------------ +' <auto-generated> +' This code was generated by a tool. +' Runtime Version:2.0.50727.4927 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' </auto-generated> +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + diff --git a/WinProwl/My Project/Application.myapp b/WinProwl/My Project/Application.myapp new file mode 100644 index 0000000..e62f1a5 --- /dev/null +++ b/WinProwl/My Project/Application.myapp @@ -0,0 +1,10 @@ +<?xml version="1.0" encoding="utf-8"?> +<MyApplicationData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> + <MySubMain>false</MySubMain> + <SingleInstance>false</SingleInstance> + <ShutdownMode>0</ShutdownMode> + <EnableVisualStyles>true</EnableVisualStyles> + <AuthenticationMode>0</AuthenticationMode> + <ApplicationType>2</ApplicationType> + <SaveMySettingsOnExit>true</SaveMySettingsOnExit> +</MyApplicationData> diff --git a/WinProwl/My Project/AssemblyInfo.vb b/WinProwl/My Project/AssemblyInfo.vb new file mode 100644 index 0000000..47485f4 --- /dev/null +++ b/WinProwl/My Project/AssemblyInfo.vb @@ -0,0 +1,35 @@ +Imports System +Imports System.Reflection +Imports System.Runtime.InteropServices + +' General Information about an assembly is controlled through the following +' set of attributes. Change these attribute values to modify the information +' associated with an assembly. + +' Review the values of the assembly attributes + +<Assembly: AssemblyTitle("WinProwl")> +<Assembly: AssemblyDescription("")> +<Assembly: AssemblyCompany("")> +<Assembly: AssemblyProduct("WinProwl")> +<Assembly: AssemblyCopyright("Copyright © 2009")> +<Assembly: AssemblyTrademark("")> + +<Assembly: ComVisible(False)> + +'The following GUID is for the ID of the typelib if this project is exposed to COM +<Assembly: Guid("863a47d6-1a90-4736-87bc-d519b01a8e69")> + +' Version information for an assembly consists of the following four values: +' +' Major Version +' Minor Version +' Build Number +' Revision +' +' You can specify all the values or you can default the Build and Revision Numbers +' by using the '*' as shown below: +' <Assembly: AssemblyVersion("1.0.*")> + +<Assembly: AssemblyVersion("1.0.0.0")> +<Assembly: AssemblyFileVersion("1.0.0.0")> diff --git a/WinProwl/My Project/Resources.Designer.vb b/WinProwl/My Project/Resources.Designer.vb new file mode 100644 index 0000000..83e60b0 --- /dev/null +++ b/WinProwl/My Project/Resources.Designer.vb @@ -0,0 +1,62 @@ +'------------------------------------------------------------------------------ +' <auto-generated> +' This code was generated by a tool. +' Runtime Version:2.0.50727.4927 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' </auto-generated> +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My.Resources + + 'This class was auto-generated by the StronglyTypedResourceBuilder + 'class via a tool like ResGen or Visual Studio. + 'To add or remove a member, edit your .ResX file then rerun ResGen + 'with the /str option, or rebuild your VS project. + '<summary> + ' A strongly-typed resource class, for looking up localized strings, etc. + '</summary> + <Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0"), _ + Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ + Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ + Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _ + Friend Module Resources + + Private resourceMan As Global.System.Resources.ResourceManager + + Private resourceCulture As Global.System.Globalization.CultureInfo + + '<summary> + ' Returns the cached ResourceManager instance used by this class. + '</summary> + <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ + Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager + Get + If Object.ReferenceEquals(resourceMan, Nothing) Then + Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("WinProwl.Resources", GetType(Resources).Assembly) + resourceMan = temp + End If + Return resourceMan + End Get + End Property + + '<summary> + ' Overrides the current thread's CurrentUICulture property for all + ' resource lookups using this strongly typed resource class. + '</summary> + <Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ + Friend Property Culture() As Global.System.Globalization.CultureInfo + Get + Return resourceCulture + End Get + Set(ByVal value As Global.System.Globalization.CultureInfo) + resourceCulture = value + End Set + End Property + End Module +End Namespace diff --git a/WinProwl/My Project/Resources.resx b/WinProwl/My Project/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/WinProwl/My Project/Resources.resx @@ -0,0 +1,117 @@ +<?xml version="1.0" encoding="utf-8"?> +<root> + <!-- + Microsoft ResX Schema + + Version 2.0 + + The primary goals of this format is to allow a simple XML format + that is mostly human readable. The generation and parsing of the + various data types are done through the TypeConverter classes + associated with the data types. + + Example: + + ... ado.net/XML headers & schema ... + <resheader name="resmimetype">text/microsoft-resx</resheader> + <resheader name="version">2.0</resheader> + <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> + <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader> + <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data> + <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data> + <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> + <value>[base64 mime encoded serialized .NET Framework object]</value> + </data> + <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> + <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value> + <comment>This is a comment</comment> + </data> + + There are any number of "resheader" rows that contain simple + name/value pairs. + + Each data row contains a name, and value. The row also contains a + type or mimetype. Type corresponds to a .NET class that support + text/value conversion through the TypeConverter architecture. + Classes that don't support this are serialized and stored with the + mimetype set. + + The mimetype is used for serialized objects, and tells the + ResXResourceReader how to depersist the object. This is currently not + extensible. For a given mimetype the value must be set accordingly: + + Note - application/x-microsoft.net.object.binary.base64 is the format + that the ResXResourceWriter will generate, however the reader can + read any of the formats listed below. + + mimetype: application/x-microsoft.net.object.binary.base64 + value : The object must be serialized with + : System.Serialization.Formatters.Binary.BinaryFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.soap.base64 + value : The object must be serialized with + : System.Runtime.Serialization.Formatters.Soap.SoapFormatter + : and then encoded with base64 encoding. + + mimetype: application/x-microsoft.net.object.bytearray.base64 + value : The object must be serialized into a byte array + : using a System.ComponentModel.TypeConverter + : and then encoded with base64 encoding. + --> + <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> + <xsd:element name="root" msdata:IsDataSet="true"> + <xsd:complexType> + <xsd:choice maxOccurs="unbounded"> + <xsd:element name="metadata"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" /> + <xsd:attribute name="type" type="xsd:string" /> + <xsd:attribute name="mimetype" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="assembly"> + <xsd:complexType> + <xsd:attribute name="alias" type="xsd:string" /> + <xsd:attribute name="name" type="xsd:string" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="data"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" /> + <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" /> + <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="resheader"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> + </xsd:sequence> + <xsd:attribute name="name" type="xsd:string" use="required" /> + </xsd:complexType> + </xsd:element> + </xsd:choice> + </xsd:complexType> + </xsd:element> + </xsd:schema> + <resheader name="resmimetype"> + <value>text/microsoft-resx</value> + </resheader> + <resheader name="version"> + <value>2.0</value> + </resheader> + <resheader name="reader"> + <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> + <resheader name="writer"> + <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> + </resheader> +</root> \ No newline at end of file diff --git a/WinProwl/My Project/Settings.Designer.vb b/WinProwl/My Project/Settings.Designer.vb new file mode 100644 index 0000000..e40b3ed --- /dev/null +++ b/WinProwl/My Project/Settings.Designer.vb @@ -0,0 +1,73 @@ +'------------------------------------------------------------------------------ +' <auto-generated> +' This code was generated by a tool. +' Runtime Version:2.0.50727.4927 +' +' Changes to this file may cause incorrect behavior and will be lost if +' the code is regenerated. +' </auto-generated> +'------------------------------------------------------------------------------ + +Option Strict On +Option Explicit On + + +Namespace My + + <Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _ + Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "9.0.0.0"), _ + Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ + Partial Friend NotInheritable Class MySettings + Inherits Global.System.Configuration.ApplicationSettingsBase + + Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings),MySettings) + +#Region "My.Settings Auto-Save Functionality" +#If _MyType = "WindowsForms" Then + Private Shared addedHandler As Boolean + + Private Shared addedHandlerLockObject As New Object + + <Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _ + Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs) + If My.Application.SaveMySettingsOnExit Then + My.Settings.Save() + End If + End Sub +#End If +#End Region + + Public Shared ReadOnly Property [Default]() As MySettings + Get + +#If _MyType = "WindowsForms" Then + If Not addedHandler Then + SyncLock addedHandlerLockObject + If Not addedHandler Then + AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings + addedHandler = True + End If + End SyncLock + End If +#End If + Return defaultInstance + End Get + End Property + End Class +End Namespace + +Namespace My + + <Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _ + Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _ + Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _ + Friend Module MySettingsProperty + + <Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _ + Friend ReadOnly Property Settings() As Global.WinProwl.My.MySettings + Get + Return Global.WinProwl.My.MySettings.Default + End Get + End Property + End Module +End Namespace diff --git a/WinProwl/My Project/Settings.settings b/WinProwl/My Project/Settings.settings new file mode 100644 index 0000000..f7f176a --- /dev/null +++ b/WinProwl/My Project/Settings.settings @@ -0,0 +1,5 @@ +<?xml version='1.0' encoding='utf-8'?> +<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" UseMySettingsClassName="true"> + <Profiles /> + <Settings /> +</SettingsFile> \ No newline at end of file diff --git a/WinProwl/WinProwl.vbproj b/WinProwl/WinProwl.vbproj new file mode 100644 index 0000000..d5c282b --- /dev/null +++ b/WinProwl/WinProwl.vbproj @@ -0,0 +1,110 @@ +<?xml version="1.0" encoding="utf-8"?> +<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> + <PropertyGroup> + <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> + <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> + <ProductVersion>9.0.21022</ProductVersion> + <SchemaVersion>2.0</SchemaVersion> + <ProjectGuid>{C2D9225F-5BDD-4363-9EEC-FC53ED60B95F}</ProjectGuid> + <OutputType>Exe</OutputType> + <StartupObject>WinProwl.Module1</StartupObject> + <RootNamespace>WinProwl</RootNamespace> + <AssemblyName>WinProwl</AssemblyName> + <FileAlignment>512</FileAlignment> + <MyType>Console</MyType> + <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> + <OptionExplicit>On</OptionExplicit> + <OptionCompare>Binary</OptionCompare> + <OptionStrict>Off</OptionStrict> + <OptionInfer>On</OptionInfer> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> + <DebugSymbols>true</DebugSymbols> + <DebugType>full</DebugType> + <DefineDebug>true</DefineDebug> + <DefineTrace>true</DefineTrace> + <OutputPath>bin\Debug\</OutputPath> + <DocumentationFile>WinProwl.xml</DocumentationFile> + <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> + </PropertyGroup> + <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> + <DebugType>pdbonly</DebugType> + <DefineDebug>false</DefineDebug> + <DefineTrace>true</DefineTrace> + <Optimize>true</Optimize> + <OutputPath>bin\Release\</OutputPath> + <DocumentationFile>WinProwl.xml</DocumentationFile> + <NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn> + </PropertyGroup> + <ItemGroup> + <Reference Include="System" /> + <Reference Include="System.Data" /> + <Reference Include="System.Deployment" /> + <Reference Include="System.Xml" /> + <Reference Include="System.Core"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Xml.Linq"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + <Reference Include="System.Data.DataSetExtensions"> + <RequiredTargetFramework>3.5</RequiredTargetFramework> + </Reference> + </ItemGroup> + <ItemGroup> + <Import Include="Microsoft.VisualBasic" /> + <Import Include="System" /> + <Import Include="System.Collections" /> + <Import Include="System.Collections.Generic" /> + <Import Include="System.Data" /> + <Import Include="System.Diagnostics" /> + <Import Include="System.Linq" /> + <Import Include="System.Xml.Linq" /> + </ItemGroup> + <ItemGroup> + <Compile Include="Module1.vb" /> + <Compile Include="My Project\AssemblyInfo.vb" /> + <Compile Include="My Project\Application.Designer.vb"> + <AutoGen>True</AutoGen> + <DependentUpon>Application.myapp</DependentUpon> + </Compile> + <Compile Include="My Project\Resources.Designer.vb"> + <AutoGen>True</AutoGen> + <DesignTime>True</DesignTime> + <DependentUpon>Resources.resx</DependentUpon> + </Compile> + <Compile Include="My Project\Settings.Designer.vb"> + <AutoGen>True</AutoGen> + <DependentUpon>Settings.settings</DependentUpon> + <DesignTimeSharedInput>True</DesignTimeSharedInput> + </Compile> + </ItemGroup> + <ItemGroup> + <EmbeddedResource Include="My Project\Resources.resx"> + <Generator>VbMyResourcesResXFileCodeGenerator</Generator> + <LastGenOutput>Resources.Designer.vb</LastGenOutput> + <CustomToolNamespace>My.Resources</CustomToolNamespace> + <SubType>Designer</SubType> + </EmbeddedResource> + </ItemGroup> + <ItemGroup> + <None Include="app.config" /> + <None Include="My Project\Application.myapp"> + <Generator>MyApplicationCodeGenerator</Generator> + <LastGenOutput>Application.Designer.vb</LastGenOutput> + </None> + <None Include="My Project\Settings.settings"> + <Generator>SettingsSingleFileGenerator</Generator> + <CustomToolNamespace>My</CustomToolNamespace> + <LastGenOutput>Settings.Designer.vb</LastGenOutput> + </None> + </ItemGroup> + <Import Project="$(MSBuildToolsPath)\Microsoft.VisualBasic.targets" /> + <!-- To modify your build process, add your task inside one of the targets below and uncomment it. + Other similar extension points exist, see Microsoft.Common.targets. + <Target Name="BeforeBuild"> + </Target> + <Target Name="AfterBuild"> + </Target> + --> +</Project> \ No newline at end of file diff --git a/WinProwl/WinProwl.vbproj.user b/WinProwl/WinProwl.vbproj.user new file mode 100644 index 0000000..7ff3943 --- /dev/null +++ b/WinProwl/WinProwl.vbproj.user @@ -0,0 +1 @@ +<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" /> \ No newline at end of file diff --git a/WinProwl/app.config b/WinProwl/app.config new file mode 100644 index 0000000..65fd8c9 --- /dev/null +++ b/WinProwl/app.config @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8" ?> +<configuration> + <configSections> + </configSections> + <system.diagnostics> + <sources> + <!-- This section defines the logging configuration for My.Application.Log --> + <source name="DefaultSource" switchName="DefaultSwitch"> + <listeners> + <add name="FileLog"/> + <!-- Uncomment the below section to write to the Application Event Log --> + <!--<add name="EventLog"/>--> + </listeners> + </source> + </sources> + <switches> + <add name="DefaultSwitch" value="Information" /> + </switches> + <sharedListeners> + <add name="FileLog" + type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" + initializeData="FileLogWriter"/> + <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log --> + <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> --> + </sharedListeners> + </system.diagnostics> +</configuration> diff --git a/WinProwl/bin/Debug/WinProwl.vshost.exe b/WinProwl/bin/Debug/WinProwl.vshost.exe new file mode 100644 index 0000000..69ed6c0 Binary files /dev/null and b/WinProwl/bin/Debug/WinProwl.vshost.exe differ diff --git a/WinProwl/bin/Release/WinProwl.exe b/WinProwl/bin/Release/WinProwl.exe new file mode 100644 index 0000000..b87df76 Binary files /dev/null and b/WinProwl/bin/Release/WinProwl.exe differ diff --git a/WinProwl/bin/Release/WinProwl.exe.config b/WinProwl/bin/Release/WinProwl.exe.config new file mode 100644 index 0000000..65fd8c9 --- /dev/null +++ b/WinProwl/bin/Release/WinProwl.exe.config @@ -0,0 +1,27 @@ +<?xml version="1.0" encoding="utf-8" ?> +<configuration> + <configSections> + </configSections> + <system.diagnostics> + <sources> + <!-- This section defines the logging configuration for My.Application.Log --> + <source name="DefaultSource" switchName="DefaultSwitch"> + <listeners> + <add name="FileLog"/> + <!-- Uncomment the below section to write to the Application Event Log --> + <!--<add name="EventLog"/>--> + </listeners> + </source> + </sources> + <switches> + <add name="DefaultSwitch" value="Information" /> + </switches> + <sharedListeners> + <add name="FileLog" + type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" + initializeData="FileLogWriter"/> + <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log --> + <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> --> + </sharedListeners> + </system.diagnostics> +</configuration> diff --git a/WinProwl/bin/Release/WinProwl.pdb b/WinProwl/bin/Release/WinProwl.pdb new file mode 100644 index 0000000..01ba6b2 Binary files /dev/null and b/WinProwl/bin/Release/WinProwl.pdb differ diff --git a/WinProwl/bin/Release/WinProwl.xml b/WinProwl/bin/Release/WinProwl.xml new file mode 100644 index 0000000..9cd674a --- /dev/null +++ b/WinProwl/bin/Release/WinProwl.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<doc> +<assembly> +<name> +WinProwl +</name> +</assembly> +<members> + +</members> +</doc> \ No newline at end of file diff --git a/WinProwl/obj/Debug/TempPE/My Project.Resources.Designer.vb.dll b/WinProwl/obj/Debug/TempPE/My Project.Resources.Designer.vb.dll new file mode 100644 index 0000000..a94b8e7 Binary files /dev/null and b/WinProwl/obj/Debug/TempPE/My Project.Resources.Designer.vb.dll differ diff --git a/WinProwl/obj/Release/TempPE/My Project.Resources.Designer.vb.dll b/WinProwl/obj/Release/TempPE/My Project.Resources.Designer.vb.dll new file mode 100644 index 0000000..fdfb868 Binary files /dev/null and b/WinProwl/obj/Release/TempPE/My Project.Resources.Designer.vb.dll differ diff --git a/WinProwl/obj/Release/WinProwl.Resources.resources b/WinProwl/obj/Release/WinProwl.Resources.resources new file mode 100644 index 0000000..06c24d0 Binary files /dev/null and b/WinProwl/obj/Release/WinProwl.Resources.resources differ diff --git a/WinProwl/obj/Release/WinProwl.exe b/WinProwl/obj/Release/WinProwl.exe new file mode 100644 index 0000000..b87df76 Binary files /dev/null and b/WinProwl/obj/Release/WinProwl.exe differ diff --git a/WinProwl/obj/Release/WinProwl.pdb b/WinProwl/obj/Release/WinProwl.pdb new file mode 100644 index 0000000..01ba6b2 Binary files /dev/null and b/WinProwl/obj/Release/WinProwl.pdb differ diff --git a/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt b/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt new file mode 100644 index 0000000..66cc7e1 --- /dev/null +++ b/WinProwl/obj/Release/WinProwl.vbproj.FileListAbsolute.txt @@ -0,0 +1,10 @@ +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.exe +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.pdb +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.xml +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\ResolveAssemblyReference.cache +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.Resources.resources +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.vbproj.GenerateResource.Cache +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.exe +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.xml +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\obj\Release\WinProwl.pdb +C:\Users\Mike\Documents\Visual Studio 2008\Projects\WinProwl\WinProwl\bin\Release\WinProwl.exe.config diff --git a/WinProwl/obj/Release/WinProwl.vbproj.GenerateResource.Cache b/WinProwl/obj/Release/WinProwl.vbproj.GenerateResource.Cache new file mode 100644 index 0000000..e238b41 Binary files /dev/null and b/WinProwl/obj/Release/WinProwl.vbproj.GenerateResource.Cache differ diff --git a/WinProwl/obj/Release/WinProwl.xml b/WinProwl/obj/Release/WinProwl.xml new file mode 100644 index 0000000..9cd674a --- /dev/null +++ b/WinProwl/obj/Release/WinProwl.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<doc> +<assembly> +<name> +WinProwl +</name> +</assembly> +<members> + +</members> +</doc> \ No newline at end of file
brantb/VanaTime
973447f11d17517d5514b1aa6aa5b19ccd846f0a
OCD compliance
diff --git a/vanatime.js b/vanatime.js index 3ec9980..79b26fa 100644 --- a/vanatime.js +++ b/vanatime.js @@ -1,327 +1,327 @@ // VanaTime.js: A JavaScript library for Final Fantasy XI timekeeping. (function (window) { //////////////// // Constants // Earth time : 2002/06/23 16:00 GMT // Vana'diel time : 0898/02/01 00:00 var VANA_BIRTH = new Date(); VANA_BIRTH.setUTCFullYear(2002, 5, 23); VANA_BIRTH.setUTCHours(15, 0, 0, 0); var VANA_SECS_SINCE_YEAR_0 = (((898 * 360) + 30) * 24 * 60 * 60); var EARTH_TIME_YEAR_0 = new Date(VANA_BIRTH.getTime() - (VANA_SECS_SINCE_YEAR_0 * 1000) / 25); var VANA_SECS_PER_YEAR = 360 * 24 * 60 * 60; // 360 days per year var VANA_SECS_PER_MONTH = 30 * 24 * 60 * 60; // 30 days per month var VANA_SECS_PER_WEEK = 8 * 24 * 60 * 60; // Eight Days a Week var VANA_SECS_PER_DAY = 24 * 60 * 60; // 24 hours per day var VANA_SECS_PER_HOUR = 60 * 60; // 60 minutes per hour //////////////////// // Utility functions function getSecs(hours, minutes) { return (hours * VANA_SECS_PER_HOUR) + (minutes * 60); } // makeClass - By John Resig (MIT Licensed) function makeClass() { return function (args) { if (this instanceof arguments.callee) { if (typeof this.init == "function") this.init.apply(this, (args && args.callee) ? args : arguments); } else return new arguments.callee(arguments); }; } ///////////////////////////////////////////////////////////////////////////// // FFXI Class // Singleton with arrays containing shops, routes, translatable strings, etc. var FFXI = makeClass(); FFXI.prototype.init = function () { /////////////////////// // Translatable strings var _translations = { guilds: ["Fishing", "Woodworking", "Smithing", "Goldsmithing", "Clothcraft", "Leathercraft", "Bonecraft", "Alchemy", "Cooking", "Tenshodo (Jeuno)", "Tenshodo (Bastok)", "Tenshodo (Norg)"], routes: ["Jeuno-Bastok", "Bastok-Jeuno", "Jeuno-Windurst", "Windurst-Jeuno", "Jeuno-San d'Oria", "San d'Oria-Jeuno", "Jeuno-Kazham", "Kazham-Jeuno", "Selbina-Mhaura", "Al Zahbi-Mhaura", "Al Zahbi-Nashmau", "Bibiki-Puronogo", "Puronogo-Bibiki", "Maliyakaleya Reef Tour", "Dhalmel Rock Tour"] }; ////////////// // Shop class // Represents a shop with hours of operation and a weekly holiday. // nextOpen(), et al assume a shop is always closed at 00:00 and // 23:59, which is currently true for all of them. var Shop = makeClass(); Shop.prototype = { init: function (id, holiday, open, close) { this.name = _translations.guilds[id]; this.holiday = holiday; this.open = open; this.close = close; }, isOpen: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var time = getSecs(vanaDate.hour, vanaDate.minute); return (!this.isHoliday(vanaDate) && getSecs(this.open, 0) <= time && getSecs(this.close, 0) > time); }, isHoliday: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } return (this.holiday == vanaDate.weekDay); }, nextOpen: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var nextOpen; var time = getSecs(vanaDate.hour, vanaDate.minute); var openAt = getSecs(this.open, 0); //var closeAt = getSecs(this.close, 0); if (time < openAt) { nextOpen = vanaDate.start().time + openAt } else { nextOpen = vanaDate.next().start().time + openAt; } return new VanaDate(nextOpen); }, nextClose: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var nextClose; var time = getSecs(vanaDate.hour, vanaDate.minute); var closeAt = (getSecs(this.close, 0)); if (time < closeAt) { nextClose = vanaDate.start().time + closeAt; } else { nextClose = vanaDate.next().start().time + closeAt; } return new VanaDate(nextClose); } } ////////////// // Route class // Represents a one-directional route between two destinations via airship or boat. // Times are measured in Vana'diel seconds. // A route has 3 phases: Boarding, traveling, and inactive. // Cycle measures Vana'diel seconds between boardings. // Boarding begins at midnight+offset. var Route = makeClass(); Route.prototype = { init: function (id, boarding, travel, cycle, offset) { this.name = _translations.routes[id]; this.boarding = boarding; this.travel = travel; this.cycle = cycle; this.offset = offset; }, nextBoarding: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // get the first boarding of the day var nextBoardingAt = vanaDate.start().time + this.offset; while (nextBoardingAt < vanaDate.time) { nextBoardingAt = nextBoardingAt + this.cycle; } return new VanaDate(nextBoardingAt); }, nextDeparture: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // get the first departure of the day var nextDepartureAt = vanaDate.start().time + this.offset + this.boarding; while (nextDepartureAt < vanaDate.time) { nextDepartureAt = nextDepartureAt + this.cycle; } return new VanaDate(nextDepartureAt); }, isBoarding: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // Find the beginning of the most recent bording phase var nextBoard = this.nextBoarding().time; var lastBoard = nextBoard - this.cycle; var lastBoardEnd = lastBoard + this.boarding; return (vanaDate.time < lastBoardEnd && vanaDate.time > lastBoard); }, nextPhase: function (vanaDate) { // returns the next time the craft will start boarding or depart if (this.isBoarding(vanaDate)) { return this.nextDeparture(vanaDate); } else { return this.nextBoarding(vanaDate); } } }; var airBoard = 0; // TODO: How many seconds does an airship spend boarding? var airCycle = getSecs(6, 0); // airships arrive every 6 hours (4 times per day) var airTravel = airCycle - airBoard; var ferryCycle = getSecs(8, 0); // ferries arrive every 8 hours (3 times per day) //////////////////////////// // FFXI class public members this.translations = _translations; this.shops = { fishing: new Shop(0, 5, 3, 18), woodworking: new Shop(1, 0, 6, 21), smithing: new Shop(2, 2, 8, 23), goldsmithing: new Shop(3, 4, 8, 23), clothcraft: new Shop(4, 0, 6, 21), leathercraft: new Shop(5, 4, 3, 18), bonecraft: new Shop(6, 3, 8, 23), alchemy: new Shop(7, 6, 8, 23), cooking: new Shop(8, 7, 5, 20), tenshodoj: new Shop(9, 1, 1, 23), tenshodob: new Shop(10, 4, 1, 23), tenshodon: new Shop(11, 7, 1, 23) }; this.routes = { // Airships // TODO: Verify that these times are accurate jeunoToBastok: new Route(0, airBoard, airTravel, airCycle, getSecs(3, 11)), bastokToJeuno: new Route(1, airBoard, airTravel, airCycle, getSecs(0, 13)), jeunoToWindurst: new Route(2, airBoard, airTravel, airCycle, getSecs(1, 41)), windurstToJeuno: new Route(3, airBoard, airTravel, airCycle, getSecs(4, 47)), jeunoToSandoria: new Route(4, airBoard, airTravel, airCycle, getSecs(0, 11)), sandoriaToJeuno: new Route(5, airBoard, airTravel, airCycle, getSecs(3, 10)), jeunoToKazham: new Route(6, airBoard, airTravel, airCycle, getSecs(4, 49)), kazhamToJeuno: new Route(7, airBoard, airTravel, airCycle, getSecs(1, 48)), // Ferries have identical schedules in both directions, so we only need one for each route selbinaMhaura: new Route(8, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(6, 40)), alZahbiMhaura: new Route(9, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(2, 40)), alZahbiNashmau: new Route(10, getSecs(3, 0), getSecs(5, 0), ferryCycle, 0), // Manaclipper bibikiToPuronogo: new Route(11, getSecs(1, 0), getSecs(3, 0), getSecs(12, 0), getSecs(4, 50)), puronogoToBibiki: new Route(12, getSecs(0, 45), getSecs(3, 55), getSecs(12, 0), getSecs(0, 10)), reefTour: new Route(13, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(12, 10)), rockTour: new Route(14, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(0, 10)) }; }; ///////////////////////////////////////////////////////////////////// // VanaDate class // Represents a fixed point in time. // Constructor takes either a JavaScript Date representing Earth time, // or a number of Vana'diel seconds since Year 0. var VanaDate = makeClass(); this.VanaDate = VanaDate; VanaDate.prototype = { init: function (date) { // vTime is the number of Vana'diel seconds since 0000/01/01 var vTime, eTime; if (typeof (date) == 'number') { vTime = Math.round(date); eTime = new Date(EARTH_TIME_YEAR_0.getTime() + Math.round(vTime * 1000 / 25)); } else { if (date instanceof Date) { eTime = date; } else { eTime = new Date(); } var eMilliSinceVanaEpoch = eTime.getTime() - EARTH_TIME_YEAR_0.getTime(); vTime = Math.round(eMilliSinceVanaEpoch / 1000 * 25); } // Calculate the individual parts of the date this.earthDate = eTime; this.time = vTime; // number of vana'diel seconds since midnight 0000/01/01 this.year = Math.floor(vTime / VANA_SECS_PER_YEAR); this.month = Math.floor((vTime % VANA_SECS_PER_YEAR) / VANA_SECS_PER_MONTH); this.day = Math.floor((vTime % VANA_SECS_PER_MONTH) / VANA_SECS_PER_DAY); this.weekDay = Math.floor((vTime % VANA_SECS_PER_WEEK) / VANA_SECS_PER_DAY); this.hour = Math.floor((vTime % VANA_SECS_PER_DAY) / VANA_SECS_PER_HOUR); this.minute = Math.floor((vTime % VANA_SECS_PER_HOUR) / 60); this.second = Math.floor(vTime % 60); this.weekDayName = VanaDate.dayNames[this.weekDay]; // Calculate phase of the moon. var daysPerCycle = 84; // This formula was borrowed from the MithraPride clock. I have no fucking clue what is going on here. // The value ranges from -100 (full) to 0 (new) to 100 (full again). var moonPercent = ((((Math.floor(vTime / VANA_SECS_PER_DAY) + 26) % daysPerCycle) - (daysPerCycle / 2)) / (daysPerCycle / 2)) * 100; // There are gaps in the ranges here, but it still works because the moon phase only changes // at the beginning of a new day rather than continuously over time. if (moonPercent >= 7 && moonPercent <= 38) { moonPhase = 1; // Waxing Crescent } else if (moonPercent >= 40 && moonPercent <= 55) { moonPhase = 2; // First Quarter Moon } else if (moonPercent >= 57 && moonPercent <= 88) { moonPhase = 3; // Waxing Gibbous } else if (moonPercent >= 90 || moonPercent <= -95) { moonPhase = 4; // Full Moon } else if (moonPercent >= -93 && moonPercent <= -62) { moonPhase = 5; // Waning Gibbous } else if (moonPercent >= -60 && moonPercent <= -45) { moonPhase = 6; // Last Quarter Moon } else if (moonPercent >= -43 && moonPercent <= -12) { moonPhase = 7; // Waning Crescent } else { moonPhase = 0; // New Moon } this.moonPhase = moonPhase; this.moonPhaseName = VanaDate.moonPhases[moonPhase]; this.moonPercent = Math.round(Math.abs(moonPercent)); // Calculate when this day starts and ends in earth time var vSecSinceDayStart = (vTime % VANA_SECS_PER_DAY); var eMilliSinceDayStart = Math.floor(vSecSinceDayStart * 1000 / 25); this.dayStart = new Date(eTime.getTime() - eMilliSinceDayStart); var vSecUntilDayEnd = VANA_SECS_PER_DAY - (vTime % VANA_SECS_PER_DAY); var eMilliUntilDayEnd = Math.floor(vSecUntilDayEnd * 1000 / 25); this.dayEnd = new Date(eTime.getTime() + eMilliUntilDayEnd); }, start: function () { var newVTime = this.time - (this.time % VANA_SECS_PER_DAY); return new VanaDate(newVTime); }, next: function (days) { var numDays = days; if (typeof (numDays) != 'number') { numDays = 1; } var newVTime = this.time + (VANA_SECS_PER_DAY * numDays); return new VanaDate(newVTime); }, previous: function (days) { var numDays = dayNum; if (typeof (numDays) != 'number') { numDays = 1; } var newVTime = this.time - (VANA_SECS_PER_DAY * numDays); return new VanaDate(newVTime); } }; VanaDate.dayNames = ["Firesday", "Earthsday", "Watersday", "Windsday", "Iceday", "Lightningday", "Lightsday", "Darksday"]; VanaDate.moonPhases = ["New Moon", "Waxing Crescent", "First Quarter Moon", "Waxing Gibbous", - "Full Moon", "Waning Gibbous", "Last Quarter Moon", "Waning Crescent"]; + "Full Moon", "Waning Gibbous", "Last Quarter Moon", "Waning Crescent"]; // Create an FFXI object and put VanaDate class in the global scope window.FFXI = new FFXI(window); window.VanaDate = VanaDate; })(window);
brantb/VanaTime
ebe815f73d6bab249dcb3c419324cf337893301f
Added a demo page
diff --git a/demo.html b/demo.html new file mode 100644 index 0000000..390fef6 --- /dev/null +++ b/demo.html @@ -0,0 +1,57 @@ +<!doctype html> +<html> +<head> + <title>VanaTime demo</title> + <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> + <script type="text/javascript" src="vanatime.js"></script> +</head> +<body> + +<p>Current Vana'diel date and time: <span id="datetime"></span></p> +<p>Weekday: <span id="weekday"></span>. Tomorrow is <span id="tomorrow"></span>.</p> +<p>Moon phase: <span id="moon"></span> (<span id="moonPercent"></span>%)</p> +<p>The airship from Jeuno to Kazham departs at <span id="airship"></span>.</p> +<p id="shopstatus"></p> + +<script type="text/javascript"> +String.prototype.format = function() { + var formatted = this; + for (var i = 0; i < arguments.length; i++) { + var regexp = new RegExp('\\{'+i+'\\}', 'gi'); + formatted = formatted.replace(regexp, arguments[i]); + } + return formatted; +}; +function update() { + var now = new VanaDate(); + var dateTimeString = "{0}/{1}/{2} {3}:{4}.{5}" + .format(now.year, now.month, now.day, now.hour, now.minute, now.second); + $("#datetime").text(dateTimeString); + $("#weekday").text(now.weekDayName); + $("#tomorrow").text(now.next().weekDayName); + $("#moon").text(now.moonPhaseName); + $("#moonPercent").text(now.moonPercent); + + var airshipDeparture = FFXI.routes.jeunoToKazham.nextDeparture(); + var departureEarth = airshipDeparture.earthDate; + $("#airship").text(departureEarth.toString()); + + var guildOpen = FFXI.shops.cooking.nextOpen(); + var guildClose = FFXI.shops.cooking.nextClose(); + + var shopStatus = "The cooking guild is {0}. It {1} at {2}."; + if (FFXI.shops.cooking.isOpen()) { + shopStatus = shopStatus.format("open", "closes", guildClose.earthDate.toString()); + } else { + shopStatus = shopStatus.format("closed", "opens", guildOpen.earthDate.toString()); + } + $("#shopstatus").text(shopStatus); +} + +$(function() { + setInterval(update, 500); +}); + +</script> +</body> +</html>
brantb/VanaTime
f1193e60791df838d67922d31cb067a017bb6088
Fixed next() and previous() not working if you didn't pass a parameter
diff --git a/vanatime.js b/vanatime.js index e0a69c4..3ec9980 100644 --- a/vanatime.js +++ b/vanatime.js @@ -1,327 +1,327 @@ // VanaTime.js: A JavaScript library for Final Fantasy XI timekeeping. (function (window) { //////////////// // Constants // Earth time : 2002/06/23 16:00 GMT // Vana'diel time : 0898/02/01 00:00 var VANA_BIRTH = new Date(); VANA_BIRTH.setUTCFullYear(2002, 5, 23); VANA_BIRTH.setUTCHours(15, 0, 0, 0); var VANA_SECS_SINCE_YEAR_0 = (((898 * 360) + 30) * 24 * 60 * 60); var EARTH_TIME_YEAR_0 = new Date(VANA_BIRTH.getTime() - (VANA_SECS_SINCE_YEAR_0 * 1000) / 25); var VANA_SECS_PER_YEAR = 360 * 24 * 60 * 60; // 360 days per year var VANA_SECS_PER_MONTH = 30 * 24 * 60 * 60; // 30 days per month var VANA_SECS_PER_WEEK = 8 * 24 * 60 * 60; // Eight Days a Week var VANA_SECS_PER_DAY = 24 * 60 * 60; // 24 hours per day var VANA_SECS_PER_HOUR = 60 * 60; // 60 minutes per hour //////////////////// // Utility functions function getSecs(hours, minutes) { return (hours * VANA_SECS_PER_HOUR) + (minutes * 60); } // makeClass - By John Resig (MIT Licensed) function makeClass() { return function (args) { if (this instanceof arguments.callee) { if (typeof this.init == "function") this.init.apply(this, (args && args.callee) ? args : arguments); } else return new arguments.callee(arguments); }; } ///////////////////////////////////////////////////////////////////////////// // FFXI Class // Singleton with arrays containing shops, routes, translatable strings, etc. var FFXI = makeClass(); FFXI.prototype.init = function () { /////////////////////// // Translatable strings var _translations = { guilds: ["Fishing", "Woodworking", "Smithing", "Goldsmithing", "Clothcraft", "Leathercraft", "Bonecraft", "Alchemy", "Cooking", "Tenshodo (Jeuno)", "Tenshodo (Bastok)", "Tenshodo (Norg)"], routes: ["Jeuno-Bastok", "Bastok-Jeuno", "Jeuno-Windurst", "Windurst-Jeuno", "Jeuno-San d'Oria", "San d'Oria-Jeuno", "Jeuno-Kazham", "Kazham-Jeuno", "Selbina-Mhaura", "Al Zahbi-Mhaura", "Al Zahbi-Nashmau", "Bibiki-Puronogo", "Puronogo-Bibiki", "Maliyakaleya Reef Tour", "Dhalmel Rock Tour"] }; ////////////// // Shop class // Represents a shop with hours of operation and a weekly holiday. // nextOpen(), et al assume a shop is always closed at 00:00 and // 23:59, which is currently true for all of them. var Shop = makeClass(); Shop.prototype = { init: function (id, holiday, open, close) { this.name = _translations.guilds[id]; this.holiday = holiday; this.open = open; this.close = close; }, isOpen: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var time = getSecs(vanaDate.hour, vanaDate.minute); return (!this.isHoliday(vanaDate) && getSecs(this.open, 0) <= time && getSecs(this.close, 0) > time); }, isHoliday: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } return (this.holiday == vanaDate.weekDay); }, nextOpen: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var nextOpen; var time = getSecs(vanaDate.hour, vanaDate.minute); var openAt = getSecs(this.open, 0); //var closeAt = getSecs(this.close, 0); if (time < openAt) { nextOpen = vanaDate.start().time + openAt } else { nextOpen = vanaDate.next().start().time + openAt; } return new VanaDate(nextOpen); }, nextClose: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } var nextClose; var time = getSecs(vanaDate.hour, vanaDate.minute); var closeAt = (getSecs(this.close, 0)); if (time < closeAt) { nextClose = vanaDate.start().time + closeAt; } else { nextClose = vanaDate.next().start().time + closeAt; } return new VanaDate(nextClose); } } ////////////// // Route class // Represents a one-directional route between two destinations via airship or boat. // Times are measured in Vana'diel seconds. // A route has 3 phases: Boarding, traveling, and inactive. // Cycle measures Vana'diel seconds between boardings. // Boarding begins at midnight+offset. var Route = makeClass(); Route.prototype = { init: function (id, boarding, travel, cycle, offset) { this.name = _translations.routes[id]; this.boarding = boarding; this.travel = travel; this.cycle = cycle; this.offset = offset; }, nextBoarding: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // get the first boarding of the day var nextBoardingAt = vanaDate.start().time + this.offset; while (nextBoardingAt < vanaDate.time) { nextBoardingAt = nextBoardingAt + this.cycle; } return new VanaDate(nextBoardingAt); }, nextDeparture: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // get the first departure of the day var nextDepartureAt = vanaDate.start().time + this.offset + this.boarding; while (nextDepartureAt < vanaDate.time) { nextDepartureAt = nextDepartureAt + this.cycle; } return new VanaDate(nextDepartureAt); }, isBoarding: function (vanaDate) { if (typeof (vanaDate) == 'undefined') { vanaDate = new VanaDate(); } // Find the beginning of the most recent bording phase var nextBoard = this.nextBoarding().time; var lastBoard = nextBoard - this.cycle; var lastBoardEnd = lastBoard + this.boarding; return (vanaDate.time < lastBoardEnd && vanaDate.time > lastBoard); }, nextPhase: function (vanaDate) { // returns the next time the craft will start boarding or depart if (this.isBoarding(vanaDate)) { return this.nextDeparture(vanaDate); } else { return this.nextBoarding(vanaDate); } } }; var airBoard = 0; // TODO: How many seconds does an airship spend boarding? var airCycle = getSecs(6, 0); // airships arrive every 6 hours (4 times per day) var airTravel = airCycle - airBoard; var ferryCycle = getSecs(8, 0); // ferries arrive every 8 hours (3 times per day) //////////////////////////// // FFXI class public members this.translations = _translations; this.shops = { fishing: new Shop(0, 5, 3, 18), woodworking: new Shop(1, 0, 6, 21), smithing: new Shop(2, 2, 8, 23), goldsmithing: new Shop(3, 4, 8, 23), clothcraft: new Shop(4, 0, 6, 21), leathercraft: new Shop(5, 4, 3, 18), bonecraft: new Shop(6, 3, 8, 23), alchemy: new Shop(7, 6, 8, 23), cooking: new Shop(8, 7, 5, 20), tenshodoj: new Shop(9, 1, 1, 23), tenshodob: new Shop(10, 4, 1, 23), tenshodon: new Shop(11, 7, 1, 23) }; this.routes = { // Airships // TODO: Verify that these times are accurate jeunoToBastok: new Route(0, airBoard, airTravel, airCycle, getSecs(3, 11)), bastokToJeuno: new Route(1, airBoard, airTravel, airCycle, getSecs(0, 13)), jeunoToWindurst: new Route(2, airBoard, airTravel, airCycle, getSecs(1, 41)), windurstToJeuno: new Route(3, airBoard, airTravel, airCycle, getSecs(4, 47)), jeunoToSandoria: new Route(4, airBoard, airTravel, airCycle, getSecs(0, 11)), sandoriaToJeuno: new Route(5, airBoard, airTravel, airCycle, getSecs(3, 10)), jeunoToKazham: new Route(6, airBoard, airTravel, airCycle, getSecs(4, 49)), kazhamToJeuno: new Route(7, airBoard, airTravel, airCycle, getSecs(1, 48)), // Ferries have identical schedules in both directions, so we only need one for each route selbinaMhaura: new Route(8, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(6, 40)), alZahbiMhaura: new Route(9, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(2, 40)), alZahbiNashmau: new Route(10, getSecs(3, 0), getSecs(5, 0), ferryCycle, 0), // Manaclipper bibikiToPuronogo: new Route(11, getSecs(1, 0), getSecs(3, 0), getSecs(12, 0), getSecs(4, 50)), puronogoToBibiki: new Route(12, getSecs(0, 45), getSecs(3, 55), getSecs(12, 0), getSecs(0, 10)), reefTour: new Route(13, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(12, 10)), rockTour: new Route(14, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(0, 10)) }; }; ///////////////////////////////////////////////////////////////////// // VanaDate class // Represents a fixed point in time. // Constructor takes either a JavaScript Date representing Earth time, // or a number of Vana'diel seconds since Year 0. var VanaDate = makeClass(); this.VanaDate = VanaDate; VanaDate.prototype = { init: function (date) { // vTime is the number of Vana'diel seconds since 0000/01/01 var vTime, eTime; if (typeof (date) == 'number') { vTime = Math.round(date); eTime = new Date(EARTH_TIME_YEAR_0.getTime() + Math.round(vTime * 1000 / 25)); } else { if (date instanceof Date) { eTime = date; } else { eTime = new Date(); } var eMilliSinceVanaEpoch = eTime.getTime() - EARTH_TIME_YEAR_0.getTime(); vTime = Math.round(eMilliSinceVanaEpoch / 1000 * 25); } // Calculate the individual parts of the date this.earthDate = eTime; this.time = vTime; // number of vana'diel seconds since midnight 0000/01/01 this.year = Math.floor(vTime / VANA_SECS_PER_YEAR); this.month = Math.floor((vTime % VANA_SECS_PER_YEAR) / VANA_SECS_PER_MONTH); this.day = Math.floor((vTime % VANA_SECS_PER_MONTH) / VANA_SECS_PER_DAY); this.weekDay = Math.floor((vTime % VANA_SECS_PER_WEEK) / VANA_SECS_PER_DAY); this.hour = Math.floor((vTime % VANA_SECS_PER_DAY) / VANA_SECS_PER_HOUR); this.minute = Math.floor((vTime % VANA_SECS_PER_HOUR) / 60); this.second = Math.floor(vTime % 60); this.weekDayName = VanaDate.dayNames[this.weekDay]; // Calculate phase of the moon. var daysPerCycle = 84; // This formula was borrowed from the MithraPride clock. I have no fucking clue what is going on here. // The value ranges from -100 (full) to 0 (new) to 100 (full again). var moonPercent = ((((Math.floor(vTime / VANA_SECS_PER_DAY) + 26) % daysPerCycle) - (daysPerCycle / 2)) / (daysPerCycle / 2)) * 100; // There are gaps in the ranges here, but it still works because the moon phase only changes // at the beginning of a new day rather than continuously over time. if (moonPercent >= 7 && moonPercent <= 38) { moonPhase = 1; // Waxing Crescent } else if (moonPercent >= 40 && moonPercent <= 55) { moonPhase = 2; // First Quarter Moon } else if (moonPercent >= 57 && moonPercent <= 88) { moonPhase = 3; // Waxing Gibbous } else if (moonPercent >= 90 || moonPercent <= -95) { moonPhase = 4; // Full Moon } else if (moonPercent >= -93 && moonPercent <= -62) { moonPhase = 5; // Waning Gibbous } else if (moonPercent >= -60 && moonPercent <= -45) { moonPhase = 6; // Last Quarter Moon } else if (moonPercent >= -43 && moonPercent <= -12) { moonPhase = 7; // Waning Crescent } else { moonPhase = 0; // New Moon } this.moonPhase = moonPhase; this.moonPhaseName = VanaDate.moonPhases[moonPhase]; this.moonPercent = Math.round(Math.abs(moonPercent)); // Calculate when this day starts and ends in earth time var vSecSinceDayStart = (vTime % VANA_SECS_PER_DAY); var eMilliSinceDayStart = Math.floor(vSecSinceDayStart * 1000 / 25); this.dayStart = new Date(eTime.getTime() - eMilliSinceDayStart); var vSecUntilDayEnd = VANA_SECS_PER_DAY - (vTime % VANA_SECS_PER_DAY); var eMilliUntilDayEnd = Math.floor(vSecUntilDayEnd * 1000 / 25); this.dayEnd = new Date(eTime.getTime() + eMilliUntilDayEnd); }, start: function () { var newVTime = this.time - (this.time % VANA_SECS_PER_DAY); return new VanaDate(newVTime); }, next: function (days) { var numDays = days; if (typeof (numDays) != 'number') { - day = 1; + numDays = 1; } var newVTime = this.time + (VANA_SECS_PER_DAY * numDays); return new VanaDate(newVTime); }, previous: function (days) { var numDays = dayNum; if (typeof (numDays) != 'number') { - day = 1; + numDays = 1; } var newVTime = this.time - (VANA_SECS_PER_DAY * numDays); return new VanaDate(newVTime); } }; VanaDate.dayNames = ["Firesday", "Earthsday", "Watersday", "Windsday", "Iceday", "Lightningday", "Lightsday", "Darksday"]; VanaDate.moonPhases = ["New Moon", "Waxing Crescent", "First Quarter Moon", "Waxing Gibbous", "Full Moon", "Waning Gibbous", "Last Quarter Moon", "Waning Crescent"]; // Create an FFXI object and put VanaDate class in the global scope window.FFXI = new FFXI(window); window.VanaDate = VanaDate; })(window);
brantb/VanaTime
89ff951bb7ff221df027f197bcf4ae925401d108
Fixed more formatting
diff --git a/README.md b/README.md index c83232f..e5aa8fa 100644 --- a/README.md +++ b/README.md @@ -1,146 +1,148 @@ -VanaTime -======== - -VanaTime is a JavaScript library that tracks FFXI game time. It was written by me (Rahskala/Bahamut) in mid-2010 for a never-finished Windows Sidebar gadget. I no longer play FFXI so I'm releasing this code into the public domain. It's only a *little* bit half-assed. - -VanaDate --------- - -Creating a `VanaDate` object will initialize it with the current date. You can pass in a JavaScript `Date` to initialize it to some other point in the past or future. - - var now = new VanaDate(); - var oneHourFromNow = new Date(/*etc*/); - var vanaTimeInAnHour = new VanaDate(oneHourFromNow); - -A `VanaDate` has the following properties: - -### Date and time -* `year` -* `month` (0-11) -* `day` (0-29) -* `weekDay` (0-7) -- Vana'diel weeks have eight days -* `hour` (0-23) -* `minute` (0-59) -* `second` (0-59) -* `weekDayName` (string) -- Name of the day, i.e. "Earthsday" -* `earthDate` (`Date`) -- A JavaScript Date object of this instance's point in Earth time. -* `time` (integer) -- Raw number of Vana'diel seconds since midnight on 0001/01/01. - -### Moon phases -* `moonPercent` (0-100) Percentage as shown on the in-game clock. 0 is New, 100 is Full. -* `moonPhase` (0-7) -* `moonPhaseName` (string) -- Name of the moon phase -** 0: New Moon -** 1: Waxing Crescent -** 2: First Quarter Moon -** 3: Waxing Gibbous -** 4: Full Moon -** 5: Waning Gibbous -** 6: Last Quarter Moon -** 7: Waning Crescent - -### Instance methods -* `start()` -- Returns the beginning of the Vana'diel day. -* `next()` -- Returns the next Vana'diel day. -* `previous()` -- Returns the previous Vana'diel day. - -### Usage - - // Get the current Vana'diel time - var now = new VanaDate(); // You can also pass in a JavaScript date object to - // get the Vana'diel time for that point in time. - console.log(now.weekDayName); // "Firesday" - var tomorrow = now.next(); - console.log(tomorrow.weekDayName); // "Earthsday" - -Shop ----- - -The `Shop` class represents a guild shop with hours of operation and a weekly holiday. These include the nine crafting guilds plus the three Tenshodo shops. The `FFXI.shops` contains singleton objects for each shop: - -* fishing -* woodworking -* smithing -* goldsmithing -* clothcraft -* leathercraft -* bonecraft -* alchemy -* cooking -* tenshodoj *(Jeuno)* -* tenshodob *(Bastok)* -* tenshodon *(Norg)* - -### Methods - -All of these methods act on the current Vana'diel time and take an optional `VanaTime` parameter to get info on a different time instead. - -* `isOpen()` (boolean) -* `isHoliday()` (boolean) -* `nextOpen()` (`VanaDate`) -- The time the shop will next be open. -* `nextClose()` (`VanaDate`) -- The time the shop will next close. - -### Usage - - // Get info for the fishing guild shop - var fishing = FFXI.shops.fishing; - console.log(fishing.isOpen()); // true - console.log(fishing.isOpen(tomorrow)); // false - console.log(fishing.isHoliday(tomorrow)); // true - var opensAfterHolidayAt = fishing.nextOpen(tomorrow); - -Route ------ -A `Route` represents a single leg of an airship or ferry trip. A route has three phases: Boarding, traveling, and inactive. - - |-------------------|-----------------|---------------|------------ etc... - (1) Boarding (2) Traveling (3) Inactive (1) Boarding - -1. The ship arrives at the dock and players can get on. -2. The ship departs, leaving the dock. -3. The ship arrives at its destination. - -Even though each of the 3 nations has a single *in-game airship* traveling between it and Jeuno, it is defined as two separate routes: One for each direction of travel. - -**Note**: I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? - -`FFXI.routes` has the following trips defined: - -#### Airships -* jeunoToBastok -* bastokToJeuno -* jeunoToWindurst -* windurstToJeuno -* jeunoToSandoria -* sandoriaToJeuno -* jeunoToKazham -* kazhamToJeuno - -#### Manaclippers -* bibikiToPuronogo -* puronogoToBibiki -* reefTour -* rockTour - -#### Ferries -These have identical schedules in both directions, so there's only one route for each path. - -* selbinaMhaura -* alZahbiMhaura -* alZahbiNashmau - -### Methods - -As with `Shop`s, all of these methods act on the current Vana'diel time, and take an optional `VanaTime` parameter which makes them act on that time instead. - -* `isBoarding()` (boolean) -* `nextBoarding()` (`VanaDate`) -- When the next boarding phase (1) starts. -* `nextDeparture()` (`VanaDate`) -- When the next traveling phase (2) starts. -* `nextPhase()` (`VanaDate`) -- The next boarding or traveling phase (1 or 2). - -### Usage - - // What Earth time does the airship from Jeuno to Windurst leave? - var leavesAt = FFXI.routes.jeunoToWindurst.nextDeparture(); - console.log(leavesAt.earthDate.toString()); // Thu Feb 24 2011 15:29:25 GMT-0600 (Central Standard Time) - +VanaTime +======== + +VanaTime is a JavaScript library that tracks FFXI game time. It was written by me (Rahskala/Bahamut) in mid-2010 for a never-finished Windows Sidebar gadget. I no longer play FFXI so I'm releasing this code into the public domain. It's only a *little* bit half-assed. + +VanaDate +-------- + +Creating a `VanaDate` object will initialize it with the current date. You can pass in a JavaScript `Date` to initialize it to some other point in the past or future. + + var now = new VanaDate(); + var oneHourFromNow = new Date(/*etc*/); + var vanaTimeInAnHour = new VanaDate(oneHourFromNow); + +A `VanaDate` has the following properties: + +### Date and time +* `year` +* `month` (0-11) +* `day` (0-29) +* `weekDay` (0-7) Vana'diel weeks have eight days +* `hour` (0-23) +* `minute` (0-59) +* `second` (0-59) +* `weekDayName` (string) Name of the day, i.e. "Earthsday" +* `earthDate` (`Date`) A JavaScript Date object of this instance's point in Earth time. +* `time` (integer) Raw number of Vana'diel seconds since midnight on 0001/01/01. + +### Moon phases +* `moonPercent` (0-100) Percentage as shown on the in-game clock. 0 is New, 100 is Full. +* `moonPhase` (0-7) +* `moonPhaseName` (string) Name of the moon phase. + +#### Moon phase names +* 0: New Moon +* 1: Waxing Crescent +* 2: First Quarter Moon +* 3: Waxing Gibbous +* 4: Full Moon +* 5: Waning Gibbous +* 6: Last Quarter Moon +* 7: Waning Crescent + +### Instance methods +* `start()` -- Returns the beginning of the Vana'diel day. +* `next()` -- Returns the next Vana'diel day. +* `previous()` -- Returns the previous Vana'diel day. + +### Usage + + // Get the current Vana'diel time + var now = new VanaDate(); // You can also pass in a JavaScript date object to + // get the Vana'diel time for that point in time. + console.log(now.weekDayName); // "Firesday" + var tomorrow = now.next(); + console.log(tomorrow.weekDayName); // "Earthsday" + +Shop +---- + +The `Shop` class represents a guild shop with hours of operation and a weekly holiday. These include the nine crafting guilds plus the three Tenshodo shops. The `FFXI.shops` contains singleton objects for each shop: + +* fishing +* woodworking +* smithing +* goldsmithing +* clothcraft +* leathercraft +* bonecraft +* alchemy +* cooking +* tenshodoj *(Jeuno)* +* tenshodob *(Bastok)* +* tenshodon *(Norg)* + +### Methods + +All of these methods act on the current Vana'diel time and take an optional `VanaTime` parameter to get info on a different time instead. + +* `isOpen()` (boolean) +* `isHoliday()` (boolean) +* `nextOpen()` (`VanaDate`) The time the shop will next be open. +* `nextClose()` (`VanaDate`) The time the shop will next close. + +### Usage + + // Get info for the fishing guild shop + var fishing = FFXI.shops.fishing; + console.log(fishing.isOpen()); // true + console.log(fishing.isOpen(tomorrow)); // false + console.log(fishing.isHoliday(tomorrow)); // true + var opensAfterHolidayAt = fishing.nextOpen(tomorrow); + +Route +----- +A `Route` represents a single leg of an airship or ferry trip. A route has three phases: Boarding, traveling, and inactive. + + |-------------------|-----------------|---------------|------------ etc... + (1) Boarding (2) Traveling (3) Inactive (1) Boarding + +1. The ship arrives at the dock and players can get on. +2. The ship departs, leaving the dock. +3. The ship arrives at its destination. + +Even though each of the 3 nations has a single *in-game airship* traveling between it and Jeuno, it is defined as two separate routes: One for each direction of travel. + +**Note**: I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? + +`FFXI.routes` has the following trips defined: + +#### Airships +* jeunoToBastok +* bastokToJeuno +* jeunoToWindurst +* windurstToJeuno +* jeunoToSandoria +* sandoriaToJeuno +* jeunoToKazham +* kazhamToJeuno + +#### Manaclippers +* bibikiToPuronogo +* puronogoToBibiki +* reefTour +* rockTour + +#### Ferries +These have identical schedules in both directions, so there's only one route for each path. + +* selbinaMhaura +* alZahbiMhaura +* alZahbiNashmau + +### Methods + +As with `Shop`s, all of these methods act on the current Vana'diel time, and take an optional `VanaTime` parameter which makes them act on that time instead. + +* `isBoarding()` (boolean) +* `nextBoarding()` (`VanaDate`) When the next boarding phase (1) starts. +* `nextDeparture()` (`VanaDate`) When the next traveling phase (2) starts. +* `nextPhase()` (`VanaDate`) The next boarding or traveling phase (1 or 2). + +### Usage + + // What Earth time does the airship from Jeuno to Windurst leave? + var leavesAt = FFXI.routes.jeunoToWindurst.nextDeparture(); + console.log(leavesAt.earthDate.toString()); // Thu Feb 24 2011 15:29:25 GMT-0600 (Central Standard Time) +
brantb/VanaTime
74a4c41f6dcae14e2c8d47dd972d596f416d1b30
Fixed markdown, again
diff --git a/README.md b/README.md index 7b166eb..c83232f 100644 --- a/README.md +++ b/README.md @@ -1,145 +1,146 @@ VanaTime ======== VanaTime is a JavaScript library that tracks FFXI game time. It was written by me (Rahskala/Bahamut) in mid-2010 for a never-finished Windows Sidebar gadget. I no longer play FFXI so I'm releasing this code into the public domain. It's only a *little* bit half-assed. VanaDate -------- Creating a `VanaDate` object will initialize it with the current date. You can pass in a JavaScript `Date` to initialize it to some other point in the past or future. var now = new VanaDate(); var oneHourFromNow = new Date(/*etc*/); var vanaTimeInAnHour = new VanaDate(oneHourFromNow); A `VanaDate` has the following properties: ### Date and time * `year` * `month` (0-11) * `day` (0-29) * `weekDay` (0-7) -- Vana'diel weeks have eight days * `hour` (0-23) * `minute` (0-59) * `second` (0-59) * `weekDayName` (string) -- Name of the day, i.e. "Earthsday" * `earthDate` (`Date`) -- A JavaScript Date object of this instance's point in Earth time. * `time` (integer) -- Raw number of Vana'diel seconds since midnight on 0001/01/01. ### Moon phases * `moonPercent` (0-100) Percentage as shown on the in-game clock. 0 is New, 100 is Full. * `moonPhase` (0-7) * `moonPhaseName` (string) -- Name of the moon phase ** 0: New Moon ** 1: Waxing Crescent ** 2: First Quarter Moon ** 3: Waxing Gibbous ** 4: Full Moon ** 5: Waning Gibbous ** 6: Last Quarter Moon ** 7: Waning Crescent ### Instance methods * `start()` -- Returns the beginning of the Vana'diel day. * `next()` -- Returns the next Vana'diel day. * `previous()` -- Returns the previous Vana'diel day. ### Usage // Get the current Vana'diel time var now = new VanaDate(); // You can also pass in a JavaScript date object to // get the Vana'diel time for that point in time. console.log(now.weekDayName); // "Firesday" var tomorrow = now.next(); console.log(tomorrow.weekDayName); // "Earthsday" Shop ---- The `Shop` class represents a guild shop with hours of operation and a weekly holiday. These include the nine crafting guilds plus the three Tenshodo shops. The `FFXI.shops` contains singleton objects for each shop: * fishing * woodworking * smithing * goldsmithing * clothcraft * leathercraft * bonecraft * alchemy * cooking * tenshodoj *(Jeuno)* * tenshodob *(Bastok)* * tenshodon *(Norg)* ### Methods All of these methods act on the current Vana'diel time and take an optional `VanaTime` parameter to get info on a different time instead. * `isOpen()` (boolean) * `isHoliday()` (boolean) * `nextOpen()` (`VanaDate`) -- The time the shop will next be open. * `nextClose()` (`VanaDate`) -- The time the shop will next close. ### Usage // Get info for the fishing guild shop var fishing = FFXI.shops.fishing; console.log(fishing.isOpen()); // true console.log(fishing.isOpen(tomorrow)); // false console.log(fishing.isHoliday(tomorrow)); // true var opensAfterHolidayAt = fishing.nextOpen(tomorrow); Route ----- A `Route` represents a single leg of an airship or ferry trip. A route has three phases: Boarding, traveling, and inactive. |-------------------|-----------------|---------------|------------ etc... (1) Boarding (2) Traveling (3) Inactive (1) Boarding 1. The ship arrives at the dock and players can get on. 2. The ship departs, leaving the dock. 3. The ship arrives at its destination. Even though each of the 3 nations has a single *in-game airship* traveling between it and Jeuno, it is defined as two separate routes: One for each direction of travel. -**Note** I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? +**Note**: I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? `FFXI.routes` has the following trips defined: #### Airships * jeunoToBastok * bastokToJeuno * jeunoToWindurst * windurstToJeuno * jeunoToSandoria * sandoriaToJeuno * jeunoToKazham * kazhamToJeuno + #### Manaclippers * bibikiToPuronogo * puronogoToBibiki * reefTour * rockTour + #### Ferries These have identical schedules in both directions, so there's only one route for each path. * selbinaMhaura * alZahbiMhaura * alZahbiNashmau ### Methods As with `Shop`s, all of these methods act on the current Vana'diel time, and take an optional `VanaTime` parameter which makes them act on that time instead. * `isBoarding()` (boolean) * `nextBoarding()` (`VanaDate`) -- When the next boarding phase (1) starts. * `nextDeparture()` (`VanaDate`) -- When the next traveling phase (2) starts. * `nextPhase()` (`VanaDate`) -- The next boarding or traveling phase (1 or 2). ### Usage // What Earth time does the airship from Jeuno to Windurst leave? var leavesAt = FFXI.routes.jeunoToWindurst.nextDeparture(); console.log(leavesAt.earthDate.toString()); // Thu Feb 24 2011 15:29:25 GMT-0600 (Central Standard Time) - \ No newline at end of file
brantb/VanaTime
81d9ca7afdd658f1cd8e772e27ab2601ba0a8efb
God dammit, markdown.
diff --git a/README.md b/README.md index f8e3489..7b166eb 100644 --- a/README.md +++ b/README.md @@ -1,143 +1,145 @@ VanaTime ======== VanaTime is a JavaScript library that tracks FFXI game time. It was written by me (Rahskala/Bahamut) in mid-2010 for a never-finished Windows Sidebar gadget. I no longer play FFXI so I'm releasing this code into the public domain. It's only a *little* bit half-assed. VanaDate -------- Creating a `VanaDate` object will initialize it with the current date. You can pass in a JavaScript `Date` to initialize it to some other point in the past or future. var now = new VanaDate(); var oneHourFromNow = new Date(/*etc*/); var vanaTimeInAnHour = new VanaDate(oneHourFromNow); A `VanaDate` has the following properties: ### Date and time * `year` * `month` (0-11) * `day` (0-29) * `weekDay` (0-7) -- Vana'diel weeks have eight days * `hour` (0-23) * `minute` (0-59) * `second` (0-59) * `weekDayName` (string) -- Name of the day, i.e. "Earthsday" * `earthDate` (`Date`) -- A JavaScript Date object of this instance's point in Earth time. * `time` (integer) -- Raw number of Vana'diel seconds since midnight on 0001/01/01. ### Moon phases * `moonPercent` (0-100) Percentage as shown on the in-game clock. 0 is New, 100 is Full. * `moonPhase` (0-7) * `moonPhaseName` (string) -- Name of the moon phase ** 0: New Moon ** 1: Waxing Crescent ** 2: First Quarter Moon ** 3: Waxing Gibbous ** 4: Full Moon ** 5: Waning Gibbous ** 6: Last Quarter Moon ** 7: Waning Crescent ### Instance methods * `start()` -- Returns the beginning of the Vana'diel day. * `next()` -- Returns the next Vana'diel day. * `previous()` -- Returns the previous Vana'diel day. ### Usage // Get the current Vana'diel time var now = new VanaDate(); // You can also pass in a JavaScript date object to // get the Vana'diel time for that point in time. console.log(now.weekDayName); // "Firesday" var tomorrow = now.next(); console.log(tomorrow.weekDayName); // "Earthsday" Shop ---- The `Shop` class represents a guild shop with hours of operation and a weekly holiday. These include the nine crafting guilds plus the three Tenshodo shops. The `FFXI.shops` contains singleton objects for each shop: * fishing * woodworking * smithing * goldsmithing * clothcraft * leathercraft * bonecraft * alchemy * cooking * tenshodoj *(Jeuno)* * tenshodob *(Bastok)* * tenshodon *(Norg)* ### Methods All of these methods act on the current Vana'diel time and take an optional `VanaTime` parameter to get info on a different time instead. * `isOpen()` (boolean) * `isHoliday()` (boolean) * `nextOpen()` (`VanaDate`) -- The time the shop will next be open. * `nextClose()` (`VanaDate`) -- The time the shop will next close. ### Usage // Get info for the fishing guild shop var fishing = FFXI.shops.fishing; console.log(fishing.isOpen()); // true console.log(fishing.isOpen(tomorrow)); // false console.log(fishing.isHoliday(tomorrow)); // true var opensAfterHolidayAt = fishing.nextOpen(tomorrow); Route ----- A `Route` represents a single leg of an airship or ferry trip. A route has three phases: Boarding, traveling, and inactive. |-------------------|-----------------|---------------|------------ etc... (1) Boarding (2) Traveling (3) Inactive (1) Boarding 1. The ship arrives at the dock and players can get on. 2. The ship departs, leaving the dock. 3. The ship arrives at its destination. Even though each of the 3 nations has a single *in-game airship* traveling between it and Jeuno, it is defined as two separate routes: One for each direction of travel. **Note** I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? `FFXI.routes` has the following trips defined: -* Airships -** jeunoToBastok -** bastokToJeuno -** jeunoToWindurst -** windurstToJeuno -** jeunoToSandoria -** sandoriaToJeuno -** jeunoToKazham -** kazhamToJeuno -* Manaclippers -** bibikiToPuronogo -** puronogoToBibiki -** reefTour -** rockTour -* Ferries (These have identical schedules in both directions, so there's only one route for each path) -** selbinaMhaura -** alZahbiMhaura -** alZahbiNashmau +#### Airships +* jeunoToBastok +* bastokToJeuno +* jeunoToWindurst +* windurstToJeuno +* jeunoToSandoria +* sandoriaToJeuno +* jeunoToKazham +* kazhamToJeuno +#### Manaclippers +* bibikiToPuronogo +* puronogoToBibiki +* reefTour +* rockTour +#### Ferries +These have identical schedules in both directions, so there's only one route for each path. + +* selbinaMhaura +* alZahbiMhaura +* alZahbiNashmau ### Methods As with `Shop`s, all of these methods act on the current Vana'diel time, and take an optional `VanaTime` parameter which makes them act on that time instead. * `isBoarding()` (boolean) * `nextBoarding()` (`VanaDate`) -- When the next boarding phase (1) starts. * `nextDeparture()` (`VanaDate`) -- When the next traveling phase (2) starts. * `nextPhase()` (`VanaDate`) -- The next boarding or traveling phase (1 or 2). ### Usage // What Earth time does the airship from Jeuno to Windurst leave? var leavesAt = FFXI.routes.jeunoToWindurst.nextDeparture(); console.log(leavesAt.earthDate.toString()); // Thu Feb 24 2011 15:29:25 GMT-0600 (Central Standard Time) \ No newline at end of file
brantb/VanaTime
e9e4e4f97b6b5fc644589a159f52b97b556b53af
Added some docs
diff --git a/README b/README new file mode 100644 index 0000000..f8e3489 --- /dev/null +++ b/README @@ -0,0 +1,143 @@ +VanaTime +======== + +VanaTime is a JavaScript library that tracks FFXI game time. It was written by me (Rahskala/Bahamut) in mid-2010 for a never-finished Windows Sidebar gadget. I no longer play FFXI so I'm releasing this code into the public domain. It's only a *little* bit half-assed. + +VanaDate +-------- + +Creating a `VanaDate` object will initialize it with the current date. You can pass in a JavaScript `Date` to initialize it to some other point in the past or future. + + var now = new VanaDate(); + var oneHourFromNow = new Date(/*etc*/); + var vanaTimeInAnHour = new VanaDate(oneHourFromNow); + +A `VanaDate` has the following properties: + +### Date and time +* `year` +* `month` (0-11) +* `day` (0-29) +* `weekDay` (0-7) -- Vana'diel weeks have eight days +* `hour` (0-23) +* `minute` (0-59) +* `second` (0-59) +* `weekDayName` (string) -- Name of the day, i.e. "Earthsday" +* `earthDate` (`Date`) -- A JavaScript Date object of this instance's point in Earth time. +* `time` (integer) -- Raw number of Vana'diel seconds since midnight on 0001/01/01. + +### Moon phases +* `moonPercent` (0-100) Percentage as shown on the in-game clock. 0 is New, 100 is Full. +* `moonPhase` (0-7) +* `moonPhaseName` (string) -- Name of the moon phase +** 0: New Moon +** 1: Waxing Crescent +** 2: First Quarter Moon +** 3: Waxing Gibbous +** 4: Full Moon +** 5: Waning Gibbous +** 6: Last Quarter Moon +** 7: Waning Crescent + +### Instance methods +* `start()` -- Returns the beginning of the Vana'diel day. +* `next()` -- Returns the next Vana'diel day. +* `previous()` -- Returns the previous Vana'diel day. + +### Usage + + // Get the current Vana'diel time + var now = new VanaDate(); // You can also pass in a JavaScript date object to + // get the Vana'diel time for that point in time. + console.log(now.weekDayName); // "Firesday" + var tomorrow = now.next(); + console.log(tomorrow.weekDayName); // "Earthsday" + +Shop +---- + +The `Shop` class represents a guild shop with hours of operation and a weekly holiday. These include the nine crafting guilds plus the three Tenshodo shops. The `FFXI.shops` contains singleton objects for each shop: + +* fishing +* woodworking +* smithing +* goldsmithing +* clothcraft +* leathercraft +* bonecraft +* alchemy +* cooking +* tenshodoj *(Jeuno)* +* tenshodob *(Bastok)* +* tenshodon *(Norg)* + +### Methods + +All of these methods act on the current Vana'diel time and take an optional `VanaTime` parameter to get info on a different time instead. + +* `isOpen()` (boolean) +* `isHoliday()` (boolean) +* `nextOpen()` (`VanaDate`) -- The time the shop will next be open. +* `nextClose()` (`VanaDate`) -- The time the shop will next close. + +### Usage + + // Get info for the fishing guild shop + var fishing = FFXI.shops.fishing; + console.log(fishing.isOpen()); // true + console.log(fishing.isOpen(tomorrow)); // false + console.log(fishing.isHoliday(tomorrow)); // true + var opensAfterHolidayAt = fishing.nextOpen(tomorrow); + +Route +----- +A `Route` represents a single leg of an airship or ferry trip. A route has three phases: Boarding, traveling, and inactive. + + |-------------------|-----------------|---------------|------------ etc... + (1) Boarding (2) Traveling (3) Inactive (1) Boarding + +1. The ship arrives at the dock and players can get on. +2. The ship departs, leaving the dock. +3. The ship arrives at its destination. + +Even though each of the 3 nations has a single *in-game airship* traveling between it and Jeuno, it is defined as two separate routes: One for each direction of travel. + +**Note** I never bothered figuring out how many seconds airships spend in the boarding phase, so it's set to zero. Useful, eh? + +`FFXI.routes` has the following trips defined: + +* Airships +** jeunoToBastok +** bastokToJeuno +** jeunoToWindurst +** windurstToJeuno +** jeunoToSandoria +** sandoriaToJeuno +** jeunoToKazham +** kazhamToJeuno +* Manaclippers +** bibikiToPuronogo +** puronogoToBibiki +** reefTour +** rockTour +* Ferries (These have identical schedules in both directions, so there's only one route for each path) +** selbinaMhaura +** alZahbiMhaura +** alZahbiNashmau + +### Methods + +As with `Shop`s, all of these methods act on the current Vana'diel time, and take an optional `VanaTime` parameter which makes them act on that time instead. + +* `isBoarding()` (boolean) +* `nextBoarding()` (`VanaDate`) -- When the next boarding phase (1) starts. +* `nextDeparture()` (`VanaDate`) -- When the next traveling phase (2) starts. +* `nextPhase()` (`VanaDate`) -- The next boarding or traveling phase (1 or 2). + +### Usage + + // What Earth time does the airship from Jeuno to Windurst leave? + var leavesAt = FFXI.routes.jeunoToWindurst.nextDeparture(); + console.log(leavesAt.earthDate.toString()); // Thu Feb 24 2011 15:29:25 GMT-0600 (Central Standard Time) + + \ No newline at end of file
brantb/VanaTime
d13cf0a67b448035c96d62e0e8aea0a6c7ed7c8f
fixed line endings, I think
diff --git a/vanatime.js b/vanatime.js index e0a69c4..a9b8ac6 100644 --- a/vanatime.js +++ b/vanatime.js @@ -1,327 +1,327 @@ -// VanaTime.js: A JavaScript library for Final Fantasy XI timekeeping. - -(function (window) { - //////////////// - // Constants - // Earth time : 2002/06/23 16:00 GMT - // Vana'diel time : 0898/02/01 00:00 - var VANA_BIRTH = new Date(); - VANA_BIRTH.setUTCFullYear(2002, 5, 23); - VANA_BIRTH.setUTCHours(15, 0, 0, 0); - var VANA_SECS_SINCE_YEAR_0 = (((898 * 360) + 30) * 24 * 60 * 60); - var EARTH_TIME_YEAR_0 = new Date(VANA_BIRTH.getTime() - (VANA_SECS_SINCE_YEAR_0 * 1000) / 25); - - var VANA_SECS_PER_YEAR = 360 * 24 * 60 * 60; // 360 days per year - var VANA_SECS_PER_MONTH = 30 * 24 * 60 * 60; // 30 days per month - var VANA_SECS_PER_WEEK = 8 * 24 * 60 * 60; // Eight Days a Week - var VANA_SECS_PER_DAY = 24 * 60 * 60; // 24 hours per day - var VANA_SECS_PER_HOUR = 60 * 60; // 60 minutes per hour - - //////////////////// - // Utility functions - function getSecs(hours, minutes) { - return (hours * VANA_SECS_PER_HOUR) + (minutes * 60); - } - // makeClass - By John Resig (MIT Licensed) - function makeClass() { - return function (args) { - if (this instanceof arguments.callee) { - if (typeof this.init == "function") - this.init.apply(this, (args && args.callee) ? args : arguments); - } else - return new arguments.callee(arguments); - }; - } - - ///////////////////////////////////////////////////////////////////////////// - // FFXI Class - // Singleton with arrays containing shops, routes, translatable strings, etc. - var FFXI = makeClass(); - FFXI.prototype.init = function () { - /////////////////////// - // Translatable strings - var _translations = { - guilds: ["Fishing", "Woodworking", "Smithing", "Goldsmithing", "Clothcraft", - "Leathercraft", "Bonecraft", "Alchemy", "Cooking", - "Tenshodo (Jeuno)", "Tenshodo (Bastok)", "Tenshodo (Norg)"], - routes: ["Jeuno-Bastok", "Bastok-Jeuno", "Jeuno-Windurst", "Windurst-Jeuno", - "Jeuno-San d'Oria", "San d'Oria-Jeuno", "Jeuno-Kazham", "Kazham-Jeuno", - "Selbina-Mhaura", "Al Zahbi-Mhaura", "Al Zahbi-Nashmau", - "Bibiki-Puronogo", "Puronogo-Bibiki", - "Maliyakaleya Reef Tour", "Dhalmel Rock Tour"] - }; - - ////////////// - // Shop class - // Represents a shop with hours of operation and a weekly holiday. - // nextOpen(), et al assume a shop is always closed at 00:00 and - // 23:59, which is currently true for all of them. - var Shop = makeClass(); - Shop.prototype = { - init: function (id, holiday, open, close) { - this.name = _translations.guilds[id]; - this.holiday = holiday; - this.open = open; - this.close = close; - }, - isOpen: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - var time = getSecs(vanaDate.hour, vanaDate.minute); - return (!this.isHoliday(vanaDate) - && getSecs(this.open, 0) <= time - && getSecs(this.close, 0) > time); - }, - isHoliday: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - return (this.holiday == vanaDate.weekDay); - }, - nextOpen: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - var nextOpen; - var time = getSecs(vanaDate.hour, vanaDate.minute); - var openAt = getSecs(this.open, 0); - //var closeAt = getSecs(this.close, 0); - - if (time < openAt) { - nextOpen = vanaDate.start().time + openAt - } else { - nextOpen = vanaDate.next().start().time + openAt; - } - - return new VanaDate(nextOpen); - }, - nextClose: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - var nextClose; - var time = getSecs(vanaDate.hour, vanaDate.minute); - var closeAt = (getSecs(this.close, 0)); - if (time < closeAt) { - nextClose = vanaDate.start().time + closeAt; - } else { - nextClose = vanaDate.next().start().time + closeAt; - } - return new VanaDate(nextClose); - } - } - ////////////// - // Route class - // Represents a one-directional route between two destinations via airship or boat. - // Times are measured in Vana'diel seconds. - // A route has 3 phases: Boarding, traveling, and inactive. - // Cycle measures Vana'diel seconds between boardings. - // Boarding begins at midnight+offset. - var Route = makeClass(); - Route.prototype = { - init: function (id, boarding, travel, cycle, offset) { - this.name = _translations.routes[id]; - this.boarding = boarding; - this.travel = travel; - this.cycle = cycle; - this.offset = offset; - }, - nextBoarding: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - - // get the first boarding of the day - var nextBoardingAt = vanaDate.start().time + this.offset; - while (nextBoardingAt < vanaDate.time) { - nextBoardingAt = nextBoardingAt + this.cycle; - } - return new VanaDate(nextBoardingAt); - }, - nextDeparture: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - // get the first departure of the day - var nextDepartureAt = vanaDate.start().time + this.offset + this.boarding; - while (nextDepartureAt < vanaDate.time) { - nextDepartureAt = nextDepartureAt + this.cycle; - } - return new VanaDate(nextDepartureAt); - }, - isBoarding: function (vanaDate) { - if (typeof (vanaDate) == 'undefined') { - vanaDate = new VanaDate(); - } - - // Find the beginning of the most recent bording phase - var nextBoard = this.nextBoarding().time; - var lastBoard = nextBoard - this.cycle; - var lastBoardEnd = lastBoard + this.boarding; - return (vanaDate.time < lastBoardEnd && vanaDate.time > lastBoard); - }, - nextPhase: function (vanaDate) { - // returns the next time the craft will start boarding or depart - if (this.isBoarding(vanaDate)) { - return this.nextDeparture(vanaDate); - } else { - return this.nextBoarding(vanaDate); - } - } - }; - - var airBoard = 0; // TODO: How many seconds does an airship spend boarding? - var airCycle = getSecs(6, 0); // airships arrive every 6 hours (4 times per day) - var airTravel = airCycle - airBoard; - var ferryCycle = getSecs(8, 0); // ferries arrive every 8 hours (3 times per day) - - //////////////////////////// - // FFXI class public members - this.translations = _translations; - this.shops = { - fishing: new Shop(0, 5, 3, 18), - woodworking: new Shop(1, 0, 6, 21), - smithing: new Shop(2, 2, 8, 23), - goldsmithing: new Shop(3, 4, 8, 23), - clothcraft: new Shop(4, 0, 6, 21), - leathercraft: new Shop(5, 4, 3, 18), - bonecraft: new Shop(6, 3, 8, 23), - alchemy: new Shop(7, 6, 8, 23), - cooking: new Shop(8, 7, 5, 20), - tenshodoj: new Shop(9, 1, 1, 23), - tenshodob: new Shop(10, 4, 1, 23), - tenshodon: new Shop(11, 7, 1, 23) - }; - this.routes = { - // Airships - // TODO: Verify that these times are accurate - jeunoToBastok: new Route(0, airBoard, airTravel, airCycle, getSecs(3, 11)), - bastokToJeuno: new Route(1, airBoard, airTravel, airCycle, getSecs(0, 13)), - jeunoToWindurst: new Route(2, airBoard, airTravel, airCycle, getSecs(1, 41)), - windurstToJeuno: new Route(3, airBoard, airTravel, airCycle, getSecs(4, 47)), - jeunoToSandoria: new Route(4, airBoard, airTravel, airCycle, getSecs(0, 11)), - sandoriaToJeuno: new Route(5, airBoard, airTravel, airCycle, getSecs(3, 10)), - jeunoToKazham: new Route(6, airBoard, airTravel, airCycle, getSecs(4, 49)), - kazhamToJeuno: new Route(7, airBoard, airTravel, airCycle, getSecs(1, 48)), - // Ferries have identical schedules in both directions, so we only need one for each route - selbinaMhaura: new Route(8, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(6, 40)), - alZahbiMhaura: new Route(9, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(2, 40)), - alZahbiNashmau: new Route(10, getSecs(3, 0), getSecs(5, 0), ferryCycle, 0), - // Manaclipper - bibikiToPuronogo: new Route(11, getSecs(1, 0), getSecs(3, 0), getSecs(12, 0), getSecs(4, 50)), - puronogoToBibiki: new Route(12, getSecs(0, 45), getSecs(3, 55), getSecs(12, 0), getSecs(0, 10)), - reefTour: new Route(13, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(12, 10)), - rockTour: new Route(14, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(0, 10)) - }; - - }; - - ///////////////////////////////////////////////////////////////////// - // VanaDate class - // Represents a fixed point in time. - // Constructor takes either a JavaScript Date representing Earth time, - // or a number of Vana'diel seconds since Year 0. - var VanaDate = makeClass(); - this.VanaDate = VanaDate; - VanaDate.prototype = { - init: function (date) { - // vTime is the number of Vana'diel seconds since 0000/01/01 - var vTime, eTime; - - if (typeof (date) == 'number') { - vTime = Math.round(date); - eTime = new Date(EARTH_TIME_YEAR_0.getTime() + Math.round(vTime * 1000 / 25)); - } else { - if (date instanceof Date) { - eTime = date; - } else { - eTime = new Date(); - } - - var eMilliSinceVanaEpoch = eTime.getTime() - EARTH_TIME_YEAR_0.getTime(); - vTime = Math.round(eMilliSinceVanaEpoch / 1000 * 25); - } - - // Calculate the individual parts of the date - this.earthDate = eTime; - this.time = vTime; // number of vana'diel seconds since midnight 0000/01/01 - this.year = Math.floor(vTime / VANA_SECS_PER_YEAR); - this.month = Math.floor((vTime % VANA_SECS_PER_YEAR) / VANA_SECS_PER_MONTH); - this.day = Math.floor((vTime % VANA_SECS_PER_MONTH) / VANA_SECS_PER_DAY); - this.weekDay = Math.floor((vTime % VANA_SECS_PER_WEEK) / VANA_SECS_PER_DAY); - this.hour = Math.floor((vTime % VANA_SECS_PER_DAY) / VANA_SECS_PER_HOUR); - this.minute = Math.floor((vTime % VANA_SECS_PER_HOUR) / 60); - this.second = Math.floor(vTime % 60); - this.weekDayName = VanaDate.dayNames[this.weekDay]; - - // Calculate phase of the moon. - var daysPerCycle = 84; - // This formula was borrowed from the MithraPride clock. I have no fucking clue what is going on here. - // The value ranges from -100 (full) to 0 (new) to 100 (full again). - var moonPercent = ((((Math.floor(vTime / VANA_SECS_PER_DAY) + 26) % daysPerCycle) - (daysPerCycle / 2)) / (daysPerCycle / 2)) * 100; - - // There are gaps in the ranges here, but it still works because the moon phase only changes - // at the beginning of a new day rather than continuously over time. - if (moonPercent >= 7 && moonPercent <= 38) { - moonPhase = 1; // Waxing Crescent - } else if (moonPercent >= 40 && moonPercent <= 55) { - moonPhase = 2; // First Quarter Moon - } else if (moonPercent >= 57 && moonPercent <= 88) { - moonPhase = 3; // Waxing Gibbous - } else if (moonPercent >= 90 || moonPercent <= -95) { - moonPhase = 4; // Full Moon - } else if (moonPercent >= -93 && moonPercent <= -62) { - moonPhase = 5; // Waning Gibbous - } else if (moonPercent >= -60 && moonPercent <= -45) { - moonPhase = 6; // Last Quarter Moon - } else if (moonPercent >= -43 && moonPercent <= -12) { - moonPhase = 7; // Waning Crescent - } else { - moonPhase = 0; // New Moon - } - this.moonPhase = moonPhase; - this.moonPhaseName = VanaDate.moonPhases[moonPhase]; - this.moonPercent = Math.round(Math.abs(moonPercent)); - - // Calculate when this day starts and ends in earth time - var vSecSinceDayStart = (vTime % VANA_SECS_PER_DAY); - var eMilliSinceDayStart = Math.floor(vSecSinceDayStart * 1000 / 25); - this.dayStart = new Date(eTime.getTime() - eMilliSinceDayStart); - - var vSecUntilDayEnd = VANA_SECS_PER_DAY - (vTime % VANA_SECS_PER_DAY); - var eMilliUntilDayEnd = Math.floor(vSecUntilDayEnd * 1000 / 25); - this.dayEnd = new Date(eTime.getTime() + eMilliUntilDayEnd); - }, - start: function () { - var newVTime = this.time - (this.time % VANA_SECS_PER_DAY); - return new VanaDate(newVTime); - }, - next: function (days) { - var numDays = days; - if (typeof (numDays) != 'number') { - day = 1; - } - var newVTime = this.time + (VANA_SECS_PER_DAY * numDays); - return new VanaDate(newVTime); - }, - previous: function (days) { - var numDays = dayNum; - if (typeof (numDays) != 'number') { - day = 1; - } - - var newVTime = this.time - (VANA_SECS_PER_DAY * numDays); - return new VanaDate(newVTime); - } - }; - VanaDate.dayNames = ["Firesday", "Earthsday", "Watersday", "Windsday", - "Iceday", "Lightningday", "Lightsday", "Darksday"]; - VanaDate.moonPhases = ["New Moon", "Waxing Crescent", "First Quarter Moon", "Waxing Gibbous", - "Full Moon", "Waning Gibbous", "Last Quarter Moon", "Waning Crescent"]; - - - // Create an FFXI object and put VanaDate class in the global scope - window.FFXI = new FFXI(window); - window.VanaDate = VanaDate; -})(window); +// VanaTime.js: A JavaScript library for Final Fantasy XI timekeeping. + +(function (window) { + //////////////// + // Constants + // Earth time : 2002/06/23 16:00 GMT + // Vana'diel time : 0898/02/01 00:00 + var VANA_BIRTH = new Date(); + VANA_BIRTH.setUTCFullYear(2002, 5, 23); + VANA_BIRTH.setUTCHours(15, 0, 0, 0); + var VANA_SECS_SINCE_YEAR_0 = (((898 * 360) + 30) * 24 * 60 * 60); + var EARTH_TIME_YEAR_0 = new Date(VANA_BIRTH.getTime() - (VANA_SECS_SINCE_YEAR_0 * 1000) / 25); + + var VANA_SECS_PER_YEAR = 360 * 24 * 60 * 60; // 360 days per year + var VANA_SECS_PER_MONTH = 30 * 24 * 60 * 60; // 30 days per month + var VANA_SECS_PER_WEEK = 8 * 24 * 60 * 60; // Eight Days a Week + var VANA_SECS_PER_DAY = 24 * 60 * 60; // 24 hours per day + var VANA_SECS_PER_HOUR = 60 * 60; // 60 minutes per hour + + //////////////////// + // Utility functions + function getSecs(hours, minutes) { + return (hours * VANA_SECS_PER_HOUR) + (minutes * 60); + } + // makeClass - By John Resig (MIT Licensed) + function makeClass() { + return function (args) { + if (this instanceof arguments.callee) { + if (typeof this.init == "function") + this.init.apply(this, (args && args.callee) ? args : arguments); + } else + return new arguments.callee(arguments); + }; + } + + ///////////////////////////////////////////////////////////////////////////// + // FFXI Class + // Singleton with arrays containing shops, routes, translatable strings, etc. + var FFXI = makeClass(); + FFXI.prototype.init = function () { + /////////////////////// + // Translatable strings + var _translations = { + guilds: ["Fishing", "Woodworking", "Smithing", "Goldsmithing", "Clothcraft", + "Leathercraft", "Bonecraft", "Alchemy", "Cooking", + "Tenshodo (Jeuno)", "Tenshodo (Bastok)", "Tenshodo (Norg)"], + routes: ["Jeuno-Bastok", "Bastok-Jeuno", "Jeuno-Windurst", "Windurst-Jeuno", + "Jeuno-San d'Oria", "San d'Oria-Jeuno", "Jeuno-Kazham", "Kazham-Jeuno", + "Selbina-Mhaura", "Al Zahbi-Mhaura", "Al Zahbi-Nashmau", + "Bibiki-Puronogo", "Puronogo-Bibiki", + "Maliyakaleya Reef Tour", "Dhalmel Rock Tour"] + }; + + ////////////// + // Shop class + // Represents a shop with hours of operation and a weekly holiday. + // nextOpen(), et al assume a shop is always closed at 00:00 and + // 23:59, which is currently true for all of them. + var Shop = makeClass(); + Shop.prototype = { + init: function (id, holiday, open, close) { + this.name = _translations.guilds[id]; + this.holiday = holiday; + this.open = open; + this.close = close; + }, + isOpen: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + var time = getSecs(vanaDate.hour, vanaDate.minute); + return (!this.isHoliday(vanaDate) + && getSecs(this.open, 0) <= time + && getSecs(this.close, 0) > time); + }, + isHoliday: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + return (this.holiday == vanaDate.weekDay); + }, + nextOpen: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + var nextOpen; + var time = getSecs(vanaDate.hour, vanaDate.minute); + var openAt = getSecs(this.open, 0); + //var closeAt = getSecs(this.close, 0); + + if (time < openAt) { + nextOpen = vanaDate.start().time + openAt + } else { + nextOpen = vanaDate.next().start().time + openAt; + } + + return new VanaDate(nextOpen); + }, + nextClose: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + var nextClose; + var time = getSecs(vanaDate.hour, vanaDate.minute); + var closeAt = (getSecs(this.close, 0)); + if (time < closeAt) { + nextClose = vanaDate.start().time + closeAt; + } else { + nextClose = vanaDate.next().start().time + closeAt; + } + return new VanaDate(nextClose); + } + } + ////////////// + // Route class + // Represents a one-directional route between two destinations via airship or boat. + // Times are measured in Vana'diel seconds. + // A route has 3 phases: Boarding, traveling, and inactive. + // Cycle measures Vana'diel seconds between boardings. + // Boarding begins at midnight+offset. + var Route = makeClass(); + Route.prototype = { + init: function (id, boarding, travel, cycle, offset) { + this.name = _translations.routes[id]; + this.boarding = boarding; + this.travel = travel; + this.cycle = cycle; + this.offset = offset; + }, + nextBoarding: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + + // get the first boarding of the day + var nextBoardingAt = vanaDate.start().time + this.offset; + while (nextBoardingAt < vanaDate.time) { + nextBoardingAt = nextBoardingAt + this.cycle; + } + return new VanaDate(nextBoardingAt); + }, + nextDeparture: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + // get the first departure of the day + var nextDepartureAt = vanaDate.start().time + this.offset + this.boarding; + while (nextDepartureAt < vanaDate.time) { + nextDepartureAt = nextDepartureAt + this.cycle; + } + return new VanaDate(nextDepartureAt); + }, + isBoarding: function (vanaDate) { + if (typeof (vanaDate) == 'undefined') { + vanaDate = new VanaDate(); + } + + // Find the beginning of the most recent bording phase + var nextBoard = this.nextBoarding().time; + var lastBoard = nextBoard - this.cycle; + var lastBoardEnd = lastBoard + this.boarding; + return (vanaDate.time < lastBoardEnd && vanaDate.time > lastBoard); + }, + nextPhase: function (vanaDate) { + // returns the next time the craft will start boarding or depart + if (this.isBoarding(vanaDate)) { + return this.nextDeparture(vanaDate); + } else { + return this.nextBoarding(vanaDate); + } + } + }; + + var airBoard = 0; // TODO: How many seconds does an airship spend boarding? + var airCycle = getSecs(6, 0); // airships arrive every 6 hours (4 times per day) + var airTravel = airCycle - airBoard; + var ferryCycle = getSecs(8, 0); // ferries arrive every 8 hours (3 times per day) + + //////////////////////////// + // FFXI class public members + this.translations = _translations; + this.shops = { + fishing: new Shop(0, 5, 3, 18), + woodworking: new Shop(1, 0, 6, 21), + smithing: new Shop(2, 2, 8, 23), + goldsmithing: new Shop(3, 4, 8, 23), + clothcraft: new Shop(4, 0, 6, 21), + leathercraft: new Shop(5, 4, 3, 18), + bonecraft: new Shop(6, 3, 8, 23), + alchemy: new Shop(7, 6, 8, 23), + cooking: new Shop(8, 7, 5, 20), + tenshodoj: new Shop(9, 1, 1, 23), + tenshodob: new Shop(10, 4, 1, 23), + tenshodon: new Shop(11, 7, 1, 23) + }; + this.routes = { + // Airships + // TODO: Verify that these times are accurate + jeunoToBastok: new Route(0, airBoard, airTravel, airCycle, getSecs(3, 11)), + bastokToJeuno: new Route(1, airBoard, airTravel, airCycle, getSecs(0, 13)), + jeunoToWindurst: new Route(2, airBoard, airTravel, airCycle, getSecs(1, 41)), + windurstToJeuno: new Route(3, airBoard, airTravel, airCycle, getSecs(4, 47)), + jeunoToSandoria: new Route(4, airBoard, airTravel, airCycle, getSecs(0, 11)), + sandoriaToJeuno: new Route(5, airBoard, airTravel, airCycle, getSecs(3, 10)), + jeunoToKazham: new Route(6, airBoard, airTravel, airCycle, getSecs(4, 49)), + kazhamToJeuno: new Route(7, airBoard, airTravel, airCycle, getSecs(1, 48)), + // Ferries have identical schedules in both directions, so we only need one for each route + selbinaMhaura: new Route(8, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(6, 40)), + alZahbiMhaura: new Route(9, getSecs(1, 20), getSecs(6, 40), ferryCycle, getSecs(2, 40)), + alZahbiNashmau: new Route(10, getSecs(3, 0), getSecs(5, 0), ferryCycle, 0), + // Manaclipper + bibikiToPuronogo: new Route(11, getSecs(1, 0), getSecs(3, 0), getSecs(12, 0), getSecs(4, 50)), + puronogoToBibiki: new Route(12, getSecs(0, 45), getSecs(3, 55), getSecs(12, 0), getSecs(0, 10)), + reefTour: new Route(13, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(12, 10)), + rockTour: new Route(14, getSecs(0, 40), getSecs(4, 0), getSecs(24, 0), getSecs(0, 10)) + }; + + }; + + ///////////////////////////////////////////////////////////////////// + // VanaDate class + // Represents a fixed point in time. + // Constructor takes either a JavaScript Date representing Earth time, + // or a number of Vana'diel seconds since Year 0. + var VanaDate = makeClass(); + this.VanaDate = VanaDate; + VanaDate.prototype = { + init: function (date) { + // vTime is the number of Vana'diel seconds since 0000/01/01 + var vTime, eTime; + + if (typeof (date) == 'number') { + vTime = Math.round(date); + eTime = new Date(EARTH_TIME_YEAR_0.getTime() + Math.round(vTime * 1000 / 25)); + } else { + if (date instanceof Date) { + eTime = date; + } else { + eTime = new Date(); + } + + var eMilliSinceVanaEpoch = eTime.getTime() - EARTH_TIME_YEAR_0.getTime(); + vTime = Math.round(eMilliSinceVanaEpoch / 1000 * 25); + } + + // Calculate the individual parts of the date + this.earthDate = eTime; + this.time = vTime; // number of vana'diel seconds since midnight 0000/01/01 + this.year = Math.floor(vTime / VANA_SECS_PER_YEAR); + this.month = Math.floor((vTime % VANA_SECS_PER_YEAR) / VANA_SECS_PER_MONTH); + this.day = Math.floor((vTime % VANA_SECS_PER_MONTH) / VANA_SECS_PER_DAY); + this.weekDay = Math.floor((vTime % VANA_SECS_PER_WEEK) / VANA_SECS_PER_DAY); + this.hour = Math.floor((vTime % VANA_SECS_PER_DAY) / VANA_SECS_PER_HOUR); + this.minute = Math.floor((vTime % VANA_SECS_PER_HOUR) / 60); + this.second = Math.floor(vTime % 60); + this.weekDayName = VanaDate.dayNames[this.weekDay]; + + // Calculate phase of the moon. + var daysPerCycle = 84; + // This formula was borrowed from the MithraPride clock. I have no fucking clue what is going on here. + // The value ranges from -100 (full) to 0 (new) to 100 (full again). + var moonPercent = ((((Math.floor(vTime / VANA_SECS_PER_DAY) + 26) % daysPerCycle) - (daysPerCycle / 2)) / (daysPerCycle / 2)) * 100; + + // There are gaps in the ranges here, but it still works because the moon phase only changes + // at the beginning of a new day rather than continuously over time. + if (moonPercent >= 7 && moonPercent <= 38) { + moonPhase = 1; // Waxing Crescent + } else if (moonPercent >= 40 && moonPercent <= 55) { + moonPhase = 2; // First Quarter Moon + } else if (moonPercent >= 57 && moonPercent <= 88) { + moonPhase = 3; // Waxing Gibbous + } else if (moonPercent >= 90 || moonPercent <= -95) { + moonPhase = 4; // Full Moon + } else if (moonPercent >= -93 && moonPercent <= -62) { + moonPhase = 5; // Waning Gibbous + } else if (moonPercent >= -60 && moonPercent <= -45) { + moonPhase = 6; // Last Quarter Moon + } else if (moonPercent >= -43 && moonPercent <= -12) { + moonPhase = 7; // Waning Crescent + } else { + moonPhase = 0; // New Moon + } + this.moonPhase = moonPhase; + this.moonPhaseName = VanaDate.moonPhases[moonPhase]; + this.moonPercent = Math.round(Math.abs(moonPercent)); + + // Calculate when this day starts and ends in earth time + var vSecSinceDayStart = (vTime % VANA_SECS_PER_DAY); + var eMilliSinceDayStart = Math.floor(vSecSinceDayStart * 1000 / 25); + this.dayStart = new Date(eTime.getTime() - eMilliSinceDayStart); + + var vSecUntilDayEnd = VANA_SECS_PER_DAY - (vTime % VANA_SECS_PER_DAY); + var eMilliUntilDayEnd = Math.floor(vSecUntilDayEnd * 1000 / 25); + this.dayEnd = new Date(eTime.getTime() + eMilliUntilDayEnd); + }, + start: function () { + var newVTime = this.time - (this.time % VANA_SECS_PER_DAY); + return new VanaDate(newVTime); + }, + next: function (days) { + var numDays = days; + if (typeof (numDays) != 'number') { + day = 1; + } + var newVTime = this.time + (VANA_SECS_PER_DAY * numDays); + return new VanaDate(newVTime); + }, + previous: function (days) { + var numDays = dayNum; + if (typeof (numDays) != 'number') { + day = 1; + } + + var newVTime = this.time - (VANA_SECS_PER_DAY * numDays); + return new VanaDate(newVTime); + } + }; + VanaDate.dayNames = ["Firesday", "Earthsday", "Watersday", "Windsday", + "Iceday", "Lightningday", "Lightsday", "Darksday"]; + VanaDate.moonPhases = ["New Moon", "Waxing Crescent", "First Quarter Moon", "Waxing Gibbous", + "Full Moon", "Waning Gibbous", "Last Quarter Moon", "Waning Crescent"]; + + + // Create an FFXI object and put VanaDate class in the global scope + window.FFXI = new FFXI(window); + window.VanaDate = VanaDate; +})(window);
SandyWalsh/FindYourTeammate
00343b247f77868211c8ed65867d0200592ab3d9
Fixed endless loop (last minute tweak)
diff --git a/FindYourTeammate.py b/FindYourTeammate.py index 6e99861..d6a13c0 100644 --- a/FindYourTeammate.py +++ b/FindYourTeammate.py @@ -1,293 +1,293 @@ # Find Your Teammate # (c) Dark Secret Software Inc, 2010 # Distributed under Apache Commons License. import random import unittest import sys from jinja2 import Template, Environment, FileSystemLoader categories = { 'Song' : [ 'Happy Birthday', 'California Gurls', 'Alejandro', 'Break Your Heart', 'Hot and Cold', 'Bad Romance', 'Teenage Dream', 'Dynamite', 'Cooler Than Me', 'Animal', 'Tik Tok' ], 'Movie' : [ 'Despicable Me', 'Diary of a Wimpy Kid', 'Harry Potter', 'Nanny McPhee Returns', 'Percy Jackson', 'Karate Kid', 'The Tooth Fairy', 'Tinkerbell', 'Camp Rock 2', 'Wizards of Waverley Place' ], 'Drink' : [ 'Milk', 'Water', 'Pop', 'Coffee', 'Tea', 'Orange Juice', 'Tomato Juice', 'Apple Juice', 'Fruitopia', 'Shirley Temple' ], 'Sport' : [ 'Soccer', 'Hockey', 'Swimming', 'Basketball', 'Volleyball', 'Dancing', 'Running', 'Ringette', 'Football', 'Tennis', 'Badmiton' ], 'Book' : [ 'Harry Potter', 'Garfield', 'Calvin & Hobbes', 'Indiana Jones', 'Diary of a Wimpy Kid', 'Rainbow Magic', 'Captain Underpants', 'Geronimo Stilton', 'Magic Treehouse', 'Allie Finkle' ], 'Restaurant' : [ 'McDonalds', 'Wendys', 'Pizza Delight', 'Mr Yee', 'Swiss Chalet', 'Monster Pizza', 'KFC', 'Freak Lunchbox', 'Jack Astors', 'Dairy Queen', 'Manchu Wok', 'Montanas', 'Boston Pizza' ], 'Fruit' : [ 'Apple', 'Orange', 'Peach', 'Pear', 'Banana', 'Plum', 'Kiwi', 'Mango' ], 'Color' : [ 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet', 'Black' ], 'Vegetable' : [ 'Potato', 'Carrot', 'Tomato', 'Corn', 'Celery', 'Cucumber', 'Sweet Potato', 'Brocolli', 'Califlower' ], 'Word' : [ 'Apple', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Gamma', 'Hotel', 'India' ], 'Number' : range(1, 10), 'Animal' : [ 'Dolphin', 'Horse', 'Dog', 'Cat', 'Fish', 'Monkey', 'Pig', 'Cow', 'Bunny', 'Snake', 'Tarantula', 'Tiger' ], 'Toy' : [ 'American Girl', 'Basketball', 'Aquasand', 'Stuffed Dog', 'Silly Bandz', 'Dairy Queen Blizzard Maker', 'Wii', 'Barbie' ], } player_names = [ 'Erica', 'Kaleigh', 'Savannah', 'Eryka', 'Brooke', 'Blair', 'Julia', 'Maya', 'Eliza', 'Katlyn', 'Hannah', 'Haylie'] class Player: def __init__(self, name): self.favorites = {} # { category : favorite } self.is_red_herring = {} # { category : bool } self.name = name def fake_code(self): x = {} for category, fake in self.is_red_herring.items(): mark = "" if fake: mark = "*" x[category] = mark return x def __str__(self): return self.name def __repr__(self): return str(self) def get_other_teams(teams, team): other_teams = teams[:] del other_teams[other_teams.index(team)] return other_teams def how_much_in_common(this_team, that_team): in_common = 0 for category, favorite in this_team.favorites.items(): if not that_team.favorites.has_key(category): continue if favorite == that_team.favorites[category]: in_common += 1 return in_common def get_in_common_threshold(number_of_categories): """ Members on the same team will have all in common. But another team might have the same favorite, but they won't have more than 3/4 in common.""" return 3 * (number_of_categories / 4) def has_too_much_in_common(this_team, that_team, number_of_categories): return how_much_in_common(this_team, that_team) > get_in_common_threshold(number_of_categories) def is_overused(other_teams, team, number_of_categories): """ Find out how much we already have in common with this other team. If we have too much, don't permit this candidate.""" for other_team in other_teams: if has_too_much_in_common(team, other_team, number_of_categories): return True return False class Team: def __init__(self, id, members): self.favorites = {} self.id = id self.members = members def __str__(self): return str(self.members) def allocate(): # Populate the player list with Player objects ... players = [Player(player_name) for player_name in player_names] # Start sticking Players on Teams teams = [] player_copy = players[:] # shallow random.shuffle(player_copy) # Assume three players per team and an even multiple of players. while len(player_copy) >= 3: first = player_copy.pop(0) second = player_copy.pop(0) third = player_copy.pop(0) team = Team(id = len(teams), members = [first, second, third]) teams.append(team) # But if we have an odd number remaining stick them on # a random team. while len(player_copy) > 0: - random.choice(teams).members.append(player_copy[0]) + random.choice(teams).members.append(player_copy.pop(0)) # Give each team some things in common # But not given to each individual team member yet # (it could change there) # At this stage we're only storing indices to favorites. # Later we'll use the actual favorite. # We may pick the same favorite as another team, but we'll # be careful not to have the same favorite for too many teams. for category, choices in categories.items(): for team in teams: other_teams = get_other_teams(teams, team) choice_indices = range(len(choices)) random.shuffle(choice_indices) got_one = False for candidate in choice_indices: # Add it before we see if we've over-allocated. # If so, keep trying and overwrite this selection. team.favorites[category] = candidate if not is_overused(other_teams, team, len(categories)): got_one = True break if not got_one: raise Exception("Cannot find an candidate for '%s' that is not overused." % category) # Now place these choices specifically on # each member of each team. for team in teams: for category, choices in categories.items(): favorite = team.favorites[category] for player in team.members: player.favorites[category] = choices[favorite] player.is_red_herring[category] = False return teams def find_all_unused_choices(team, category): used_choices = set() for team in teams: for player in team.members: used_choices.add(player.favorites[category]) all_choices = set(categories[category]) unused_choices = all_choices - used_choices return list(unused_choices) def shake_up(teams): """ Up to this point all the players on a team have *exactly* the same favorites. This function mixes that up a little. We take N (1/3?) of the favorites and change them to something unused by any other player. Each player on the team is ensured to have the remaining favorites all match. The changed onces are marked as "red-herrings" """ for team in teams: topics = categories.keys() random.shuffle(topics) for category in topics[:5]: choices = categories[category] for player in team.members: unused_choices = find_all_unused_choices(teams, category) if len(unused_choices) == 0: continue player.favorites[category] = random.choice(unused_choices) player.is_red_herring[category] = True def show_results(teams): colors = ["Blue", "Yellow", "Red", "Green", "Purple"] all_players = [] for team in teams: for player in team.members: all_players.append(player) context = { "teams" : teams, "colors" : colors, "categories" : categories, } env = Environment(loader = FileSystemLoader('.')) template = env.get_template("Master.html") output = template.render(context) file = open("index.html", "w") file.write(output) file.close() for player in all_players: # TODO: We need to shuffle this up so the output # doesn't list all teams members side-by-side! others = all_players[:] del others[all_players.index(player)] ordered = [player] ordered.extend(others) template = env.get_template("Player.html") context = { "players" : ordered, "categories" : categories} output = template.render(context) file = open("%s.html" % player.name, "w") file.write(output) file.close() class Test(unittest.TestCase): def test_how_much_in_common(self): this_team = Team(1, []) that_team = Team(2, []) this_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(6, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'ff'} self.assertEqual(4, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'cc', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(5, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'c', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(1, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'cc', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(0, how_much_in_common(this_team, that_team)) def test_final_allocation(self): teams = allocate() threshold = get_in_common_threshold(len(categories)) for team in teams: other_teams = get_other_teams(teams, team) for other_team in other_teams: self.assertTrue(how_much_in_common(team, other_team) < threshold) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity=2).run(suite) teams = allocate() shake_up(teams) show_results(teams)
SandyWalsh/FindYourTeammate
34276cdecd1bbf3a27de88d8f08bbfcfe543997d
Comment cleanup
diff --git a/FindYourTeammate.py b/FindYourTeammate.py index 11bf57e..6e99861 100644 --- a/FindYourTeammate.py +++ b/FindYourTeammate.py @@ -1,291 +1,293 @@ # Find Your Teammate # (c) Dark Secret Software Inc, 2010 # Distributed under Apache Commons License. import random import unittest import sys from jinja2 import Template, Environment, FileSystemLoader categories = { 'Song' : [ 'Happy Birthday', 'California Gurls', 'Alejandro', 'Break Your Heart', 'Hot and Cold', 'Bad Romance', 'Teenage Dream', 'Dynamite', 'Cooler Than Me', 'Animal', 'Tik Tok' ], 'Movie' : [ 'Despicable Me', 'Diary of a Wimpy Kid', 'Harry Potter', 'Nanny McPhee Returns', 'Percy Jackson', 'Karate Kid', 'The Tooth Fairy', 'Tinkerbell', 'Camp Rock 2', 'Wizards of Waverley Place' ], 'Drink' : [ 'Milk', 'Water', 'Pop', 'Coffee', 'Tea', 'Orange Juice', 'Tomato Juice', 'Apple Juice', 'Fruitopia', 'Shirley Temple' ], 'Sport' : [ 'Soccer', 'Hockey', 'Swimming', 'Basketball', 'Volleyball', 'Dancing', 'Running', 'Ringette', 'Football', 'Tennis', 'Badmiton' ], 'Book' : [ 'Harry Potter', 'Garfield', 'Calvin & Hobbes', 'Indiana Jones', 'Diary of a Wimpy Kid', 'Rainbow Magic', 'Captain Underpants', 'Geronimo Stilton', 'Magic Treehouse', 'Allie Finkle' ], 'Restaurant' : [ 'McDonalds', 'Wendys', 'Pizza Delight', 'Mr Yee', 'Swiss Chalet', 'Monster Pizza', 'KFC', 'Freak Lunchbox', 'Jack Astors', 'Dairy Queen', 'Manchu Wok', 'Montanas', 'Boston Pizza' ], 'Fruit' : [ 'Apple', 'Orange', 'Peach', 'Pear', 'Banana', 'Plum', 'Kiwi', 'Mango' ], 'Color' : [ 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet', 'Black' ], 'Vegetable' : [ 'Potato', 'Carrot', 'Tomato', 'Corn', 'Celery', 'Cucumber', 'Sweet Potato', 'Brocolli', 'Califlower' ], 'Word' : [ 'Apple', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Gamma', 'Hotel', 'India' ], 'Number' : range(1, 10), 'Animal' : [ 'Dolphin', 'Horse', 'Dog', 'Cat', 'Fish', 'Monkey', 'Pig', 'Cow', 'Bunny', 'Snake', 'Tarantula', 'Tiger' ], 'Toy' : [ 'American Girl', 'Basketball', 'Aquasand', 'Stuffed Dog', 'Silly Bandz', 'Dairy Queen Blizzard Maker', 'Wii', 'Barbie' ], } player_names = [ 'Erica', 'Kaleigh', 'Savannah', 'Eryka', 'Brooke', 'Blair', 'Julia', 'Maya', 'Eliza', 'Katlyn', 'Hannah', 'Haylie'] class Player: def __init__(self, name): self.favorites = {} # { category : favorite } self.is_red_herring = {} # { category : bool } self.name = name def fake_code(self): x = {} for category, fake in self.is_red_herring.items(): mark = "" if fake: mark = "*" x[category] = mark return x def __str__(self): return self.name def __repr__(self): return str(self) def get_other_teams(teams, team): other_teams = teams[:] del other_teams[other_teams.index(team)] return other_teams def how_much_in_common(this_team, that_team): in_common = 0 for category, favorite in this_team.favorites.items(): if not that_team.favorites.has_key(category): continue if favorite == that_team.favorites[category]: in_common += 1 return in_common def get_in_common_threshold(number_of_categories): """ Members on the same team will have all in common. But another team might have the same favorite, but they won't have more than 3/4 in common.""" return 3 * (number_of_categories / 4) def has_too_much_in_common(this_team, that_team, number_of_categories): return how_much_in_common(this_team, that_team) > get_in_common_threshold(number_of_categories) def is_overused(other_teams, team, number_of_categories): """ Find out how much we already have in common with this other team. If we have too much, don't permit this candidate.""" for other_team in other_teams: if has_too_much_in_common(team, other_team, number_of_categories): return True return False class Team: def __init__(self, id, members): self.favorites = {} self.id = id self.members = members def __str__(self): return str(self.members) def allocate(): # Populate the player list with Player objects ... players = [Player(player_name) for player_name in player_names] # Start sticking Players on Teams teams = [] player_copy = players[:] # shallow random.shuffle(player_copy) - # Assume two players per team ... + # Assume three players per team and an even multiple of players. while len(player_copy) >= 3: first = player_copy.pop(0) second = player_copy.pop(0) third = player_copy.pop(0) team = Team(id = len(teams), members = [first, second, third]) teams.append(team) # But if we have an odd number remaining stick them on # a random team. - if len(player_copy) == 1: + while len(player_copy) > 0: random.choice(teams).members.append(player_copy[0]) # Give each team some things in common # But not given to each individual team member yet # (it could change there) # At this stage we're only storing indices to favorites. # Later we'll use the actual favorite. # We may pick the same favorite as another team, but we'll # be careful not to have the same favorite for too many teams. for category, choices in categories.items(): for team in teams: other_teams = get_other_teams(teams, team) choice_indices = range(len(choices)) random.shuffle(choice_indices) got_one = False for candidate in choice_indices: # Add it before we see if we've over-allocated. # If so, keep trying and overwrite this selection. team.favorites[category] = candidate if not is_overused(other_teams, team, len(categories)): got_one = True break if not got_one: raise Exception("Cannot find an candidate for '%s' that is not overused." % category) # Now place these choices specifically on # each member of each team. for team in teams: for category, choices in categories.items(): favorite = team.favorites[category] for player in team.members: player.favorites[category] = choices[favorite] player.is_red_herring[category] = False return teams def find_all_unused_choices(team, category): used_choices = set() for team in teams: for player in team.members: used_choices.add(player.favorites[category]) all_choices = set(categories[category]) unused_choices = all_choices - used_choices return list(unused_choices) def shake_up(teams): """ Up to this point all the players on a team have *exactly* the same favorites. This function mixes that up a little. We take N (1/3?) of the favorites and change them to something unused by any other player. Each player on the team is ensured to have the remaining favorites all match. The changed onces are marked as "red-herrings" """ for team in teams: topics = categories.keys() random.shuffle(topics) for category in topics[:5]: choices = categories[category] for player in team.members: unused_choices = find_all_unused_choices(teams, category) if len(unused_choices) == 0: continue player.favorites[category] = random.choice(unused_choices) player.is_red_herring[category] = True def show_results(teams): colors = ["Blue", "Yellow", "Red", "Green", "Purple"] all_players = [] for team in teams: for player in team.members: all_players.append(player) context = { "teams" : teams, "colors" : colors, "categories" : categories, } env = Environment(loader = FileSystemLoader('.')) template = env.get_template("Master.html") output = template.render(context) file = open("index.html", "w") file.write(output) file.close() for player in all_players: + # TODO: We need to shuffle this up so the output + # doesn't list all teams members side-by-side! others = all_players[:] del others[all_players.index(player)] ordered = [player] ordered.extend(others) template = env.get_template("Player.html") context = { "players" : ordered, "categories" : categories} output = template.render(context) file = open("%s.html" % player.name, "w") file.write(output) file.close() class Test(unittest.TestCase): def test_how_much_in_common(self): this_team = Team(1, []) that_team = Team(2, []) this_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(6, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'ff'} self.assertEqual(4, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'cc', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(5, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'c', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(1, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'cc', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(0, how_much_in_common(this_team, that_team)) def test_final_allocation(self): teams = allocate() threshold = get_in_common_threshold(len(categories)) for team in teams: other_teams = get_other_teams(teams, team) for other_team in other_teams: self.assertTrue(how_much_in_common(team, other_team) < threshold) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity=2).run(suite) teams = allocate() shake_up(teams) show_results(teams)
SandyWalsh/FindYourTeammate
22e32c5b68b5367aeb3b0b92c1c0fbebb546a471
Slight formatting issues
diff --git a/FindYourTeammate.py b/FindYourTeammate.py index 96e0f30..11bf57e 100644 --- a/FindYourTeammate.py +++ b/FindYourTeammate.py @@ -1,289 +1,291 @@ # Find Your Teammate # (c) Dark Secret Software Inc, 2010 -# +# Distributed under Apache Commons License. + import random import unittest import sys + from jinja2 import Template, Environment, FileSystemLoader categories = { 'Song' : [ 'Happy Birthday', 'California Gurls', 'Alejandro', 'Break Your Heart', 'Hot and Cold', 'Bad Romance', 'Teenage Dream', 'Dynamite', 'Cooler Than Me', 'Animal', 'Tik Tok' ], 'Movie' : [ 'Despicable Me', 'Diary of a Wimpy Kid', 'Harry Potter', 'Nanny McPhee Returns', 'Percy Jackson', 'Karate Kid', 'The Tooth Fairy', 'Tinkerbell', 'Camp Rock 2', 'Wizards of Waverley Place' ], 'Drink' : [ 'Milk', 'Water', 'Pop', 'Coffee', 'Tea', 'Orange Juice', 'Tomato Juice', 'Apple Juice', 'Fruitopia', 'Shirley Temple' ], 'Sport' : [ - 'Soccer', 'Hockey', 'Swimming', 'Basketball', 'Volleyball', - 'Dancing', 'Running', 'Ringette', 'Football', 'Tennis', 'Badmiton' + 'Soccer', 'Hockey', 'Swimming', 'Basketball', 'Volleyball', + 'Dancing', 'Running', 'Ringette', 'Football', 'Tennis', 'Badmiton' ], 'Book' : [ - 'Harry Potter', 'Garfield', 'Calvin & Hobbes', 'Indiana Jones', - 'Diary of a Wimpy Kid', 'Rainbow Magic', 'Captain Underpants', - 'Geronimo Stilton', 'Magic Treehouse', 'Allie Finkle' + 'Harry Potter', 'Garfield', 'Calvin & Hobbes', 'Indiana Jones', + 'Diary of a Wimpy Kid', 'Rainbow Magic', 'Captain Underpants', + 'Geronimo Stilton', 'Magic Treehouse', 'Allie Finkle' ], 'Restaurant' : [ 'McDonalds', 'Wendys', 'Pizza Delight', 'Mr Yee', 'Swiss Chalet', 'Monster Pizza', 'KFC', 'Freak Lunchbox', 'Jack Astors', 'Dairy Queen', 'Manchu Wok', 'Montanas', 'Boston Pizza' ], 'Fruit' : [ 'Apple', 'Orange', 'Peach', 'Pear', 'Banana', 'Plum', 'Kiwi', 'Mango' ], 'Color' : [ 'Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet', 'Black' ], 'Vegetable' : [ - 'Potato', 'Carrot', 'Tomato', 'Corn', 'Celery', - 'Cucumber', 'Sweet Potato', 'Brocolli', 'Califlower' + 'Potato', 'Carrot', 'Tomato', 'Corn', 'Celery', + 'Cucumber', 'Sweet Potato', 'Brocolli', 'Califlower' ], 'Word' : [ 'Apple', 'Baker', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Gamma', 'Hotel', 'India' ], 'Number' : range(1, 10), 'Animal' : [ 'Dolphin', 'Horse', 'Dog', 'Cat', 'Fish', 'Monkey', 'Pig', 'Cow', 'Bunny', 'Snake', 'Tarantula', 'Tiger' ], 'Toy' : [ 'American Girl', 'Basketball', 'Aquasand', 'Stuffed Dog', 'Silly Bandz', 'Dairy Queen Blizzard Maker', 'Wii', 'Barbie' ], } player_names = [ 'Erica', 'Kaleigh', 'Savannah', 'Eryka', 'Brooke', 'Blair', 'Julia', 'Maya', 'Eliza', 'Katlyn', 'Hannah', 'Haylie'] class Player: def __init__(self, name): self.favorites = {} # { category : favorite } self.is_red_herring = {} # { category : bool } self.name = name def fake_code(self): x = {} for category, fake in self.is_red_herring.items(): mark = "" if fake: mark = "*" x[category] = mark return x def __str__(self): return self.name def __repr__(self): return str(self) def get_other_teams(teams, team): other_teams = teams[:] del other_teams[other_teams.index(team)] return other_teams def how_much_in_common(this_team, that_team): in_common = 0 for category, favorite in this_team.favorites.items(): if not that_team.favorites.has_key(category): continue if favorite == that_team.favorites[category]: in_common += 1 return in_common def get_in_common_threshold(number_of_categories): """ Members on the same team will have all in common. But another team might have the same favorite, but they won't have more than 3/4 in common.""" return 3 * (number_of_categories / 4) def has_too_much_in_common(this_team, that_team, number_of_categories): return how_much_in_common(this_team, that_team) > get_in_common_threshold(number_of_categories) def is_overused(other_teams, team, number_of_categories): """ Find out how much we already have in common with this other team. If we have too much, don't permit this candidate.""" for other_team in other_teams: if has_too_much_in_common(team, other_team, number_of_categories): return True return False class Team: def __init__(self, id, members): self.favorites = {} self.id = id self.members = members def __str__(self): return str(self.members) def allocate(): # Populate the player list with Player objects ... players = [Player(player_name) for player_name in player_names] # Start sticking Players on Teams teams = [] player_copy = players[:] # shallow random.shuffle(player_copy) # Assume two players per team ... while len(player_copy) >= 3: first = player_copy.pop(0) second = player_copy.pop(0) third = player_copy.pop(0) team = Team(id = len(teams), members = [first, second, third]) teams.append(team) # But if we have an odd number remaining stick them on # a random team. if len(player_copy) == 1: random.choice(teams).members.append(player_copy[0]) # Give each team some things in common # But not given to each individual team member yet # (it could change there) # At this stage we're only storing indices to favorites. # Later we'll use the actual favorite. # We may pick the same favorite as another team, but we'll # be careful not to have the same favorite for too many teams. for category, choices in categories.items(): for team in teams: other_teams = get_other_teams(teams, team) choice_indices = range(len(choices)) random.shuffle(choice_indices) got_one = False for candidate in choice_indices: # Add it before we see if we've over-allocated. # If so, keep trying and overwrite this selection. team.favorites[category] = candidate if not is_overused(other_teams, team, len(categories)): got_one = True break if not got_one: raise Exception("Cannot find an candidate for '%s' that is not overused." % category) # Now place these choices specifically on # each member of each team. for team in teams: for category, choices in categories.items(): favorite = team.favorites[category] for player in team.members: player.favorites[category] = choices[favorite] player.is_red_herring[category] = False return teams def find_all_unused_choices(team, category): used_choices = set() for team in teams: for player in team.members: used_choices.add(player.favorites[category]) all_choices = set(categories[category]) unused_choices = all_choices - used_choices return list(unused_choices) def shake_up(teams): """ Up to this point all the players on a team have *exactly* the same favorites. This function mixes that up a little. We take N (1/3?) of the favorites and change them to something unused by any other player. Each player on the team is ensured to have the remaining favorites all match. The changed onces are marked as "red-herrings" """ for team in teams: topics = categories.keys() random.shuffle(topics) for category in topics[:5]: choices = categories[category] for player in team.members: unused_choices = find_all_unused_choices(teams, category) if len(unused_choices) == 0: continue player.favorites[category] = random.choice(unused_choices) player.is_red_herring[category] = True def show_results(teams): colors = ["Blue", "Yellow", "Red", "Green", "Purple"] all_players = [] for team in teams: for player in team.members: all_players.append(player) context = { "teams" : teams, "colors" : colors, "categories" : categories, } env = Environment(loader = FileSystemLoader('.')) template = env.get_template("Master.html") output = template.render(context) file = open("index.html", "w") file.write(output) file.close() for player in all_players: others = all_players[:] del others[all_players.index(player)] ordered = [player] ordered.extend(others) template = env.get_template("Player.html") context = { "players" : ordered, "categories" : categories} output = template.render(context) file = open("%s.html" % player.name, "w") file.write(output) file.close() class Test(unittest.TestCase): def test_how_much_in_common(self): this_team = Team(1, []) that_team = Team(2, []) this_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(6, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'ff'} self.assertEqual(4, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'a', 2 : 'b', 3 : 'cc', 4 : 'd', 5 : 'e', 6 : 'f'} self.assertEqual(5, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'c', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(1, how_much_in_common(this_team, that_team)) that_team.favorites = {1 : 'aa', 2 : 'bb', 3 : 'cc', 4 : 'dd', 5 : 'ee', 6 : 'ff'} self.assertEqual(0, how_much_in_common(this_team, that_team)) def test_final_allocation(self): teams = allocate() threshold = get_in_common_threshold(len(categories)) for team in teams: other_teams = get_other_teams(teams, team) for other_team in other_teams: self.assertTrue(how_much_in_common(team, other_team) < threshold) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(Test) unittest.TextTestRunner(verbosity=2).run(suite) teams = allocate() shake_up(teams) show_results(teams)
SandyWalsh/FindYourTeammate
afcefcc53df574212397ef115715efd337a68d54
Added README
diff --git a/README b/README new file mode 100644 index 0000000..5eb75d0 --- /dev/null +++ b/README @@ -0,0 +1,2 @@ +Built using Python 2.6+ +Requires Jinja for output ... http://jinja.pocoo.org/ \ No newline at end of file
walker/wlk_rsscloud
8d46ffbbfb6fc12dbfe1f6219e78dae35563e478
Incremented version number, minor changes, specified CURL neede
diff --git a/README.txt b/README.txt index ce38922..3f42cfc 100644 --- a/README.txt +++ b/README.txt @@ -1,7 +1,7 @@ This is a plugin for Textpattern built by Walker Hamilton (http://walkerhamilton.com) that enables the use of RSSCloud. Portions of this plugin are based on the plugin initially implemented by Joseph Scott (http://josephscott.org/). You should really use PubSubHubBub and not RSSCloud, but, since Worpress had this thing running, I figured Textpattern should have the ability too. To install, grab the current version of the compressed plugin (wlk_rsscloud.txt) and paste into the plugin field in Textpattern. As long as it's been installed & activated, you're ready to go. -This has been tested with 4.2.0 only. \ No newline at end of file +This has been tested with 4.2.0 only. It requires CURL. \ No newline at end of file diff --git a/wlk_rsscloud.php b/wlk_rsscloud.php index 99d55b1..d965390 100644 --- a/wlk_rsscloud.php +++ b/wlk_rsscloud.php @@ -1,490 +1,490 @@ <?php -$plugin['version'] = '0.2'; +$plugin['version'] = '0.2.1'; $plugin['author'] = 'Walker Hamilton'; $plugin['author_uri'] = 'http://walkerhamilton.com'; $plugin['description'] = 'A down and dirty RSSCloud plugin.'; $plugin['type'] = 1; if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events $plugin['flags'] = PLUGIN_LIFECYCLE_NOTIFY; @include_once(dirname(dirname(__FILE__)).'/zem_tpl.php'); if(0) { ?> # --- BEGIN PLUGIN HELP --- h2. About -p. This is down and dirty RSSCloud plugin. +p. This is down and dirty RSSCloud plugin. It requires CURL. h2. Installation and Use p. If you've installed and activated it, you're ready to go. h2. Thanks p. Some of the code is heavily based on work by Joseph Scott (http://josephscott.org/) on the Wordpress plugin. # --- END PLUGIN HELP --- <?php } # --- BEGIN PLUGIN CODE --- register_callback('wlk_rsscloud_head', 'rss_head'); register_callback('wlk_rsscloud_notification_activation', 'pretext'); if(@txpinterface == 'admin') { register_callback('wlk_rsscloud_install', 'plugin_lifecycle.wlk_rsscloud', 'installed'); register_callback('wlk_rsscloud_delete', 'plugin_lifecycle.wlk_rsscloud', 'deleted'); register_callback('wlk_rsscloud_language', 'admin_side', 'pagetop'); register_callback('wlk_rsscloud_schedule', 'article', 'edit'); } function wlk_rsscloud_schedule() { $rc = new WlkRssCloudClass(); $rc->schedule_post_notifications(); } function wlk_rsscloud_head() { return WlkRssCloudClass::head(); } function wlk_rsscloud_notification_activation() { if(isset($_GET['rsscloud']) && $_GET['rsscloud']=='notify') { $rc = new WlkRssCloudClass(); $rc->hub_process_notification_request(); exit(); } } function wlk_rsscloud_install() { WlkRssCloudClass::install(); } function wlk_rsscloud_delete() { WlkRssCloudClass::delete(); } function wlk_rsscloud_feeds() { $rc = new WlkRssCloudClass(); return $rc->feedDD(); } function wlk_rsscloud_failures() { global $prefs; $vals = array( 5 => 5, 10 => 10, 15 => 15, 20 => 20 ); $name = 'wlk_rsscloud_max_failures'; return selectInput($name, $vals, $prefs['wlk_rsscloud_max_failures'], '', '', $name); } function wlk_rsscloud_language() { $rc = new WlkRssCloudClass(); } // class WlkRssCloudClass { var $vars = array( 'notifications_instant' => true, 'user_agent' => 'Textpattern/RSSCloud 0.2', 'max_failures' => 5, 'timeout' => 3 ); function __construct() { global $prefs, $textarray; if($prefs['language']=='en-us') { $textarray['wlk_rsscloud'] = 'RSSCloud'; $textarray['rsscloud_standard'] = 'Standard feeds'; $textarray['rsscloud_both'] = 'Both standard feeds & the custom feed'; $textarray['rsscloud_custom_only'] = 'Custom feed only'; $textarray['wlk_rsscloud_notifications_instant'] = 'Instant notifications? ("No" requires wlk_cron)'; $textarray['wlk_rsscloud_max_failures'] = 'Max # of failures'; $textarray['wlk_rsscloud_feeds'] = 'Set type of feeds in use'; $textarray['wlk_rsscloud_timeout'] = 'Timeout'; $textarray['wlk_rsscloud_user_agent'] = 'User-agent'; $textarray['wlk_rsscloud_custom_url'] = 'Custom feed URL'; } if(isset($prefs['wlk_rsscloud_notifications_instant']) && !empty($prefs['wlk_rsscloud_notifications_instant'])) { $this->vars['notifications_instant'] = (bool)$prefs['wlk_rsscloud_notifications_instant']; } if(isset($prefs['wlk_rsscloud_custom_url']) && !empty($prefs['wlk_rsscloud_custom_url'])) { $this->vars['custom_url'] = $prefs['wlk_rsscloud_custom_url']; } } function WlkRssCloudClass() { $this->__construct(); } function feedDD() { global $prefs; $vals = array( 'standard' => gTxt('rsscloud_standard'), 'both' => gTxt('rsscloud_both'), 'custom_only' => gTxt('rsscloud_custom_only'), ); $name = 'wlk_rsscloud_feeds'; return selectInput($name, $vals, $prefs['wlk_rsscloud_feeds'], '', '', $name); } /* Needed HTTP Stuff - Should really create a #2 library plugin for this*/ function remote_post($url, $args = array()) { $defaults = array( 'method' => 'post', 'body' => array(), 'options' => array('path'=>'/', 'port' => 80) ); if(isset($args['options'])) { $final_options = array_merge($defaults['options'], $args['options']); } else { $final_options = $defaults['options']; } $final_args = array_merge($defaults, $args); $final_args['options'] = $final_options; $args = $final_args; $result = array(); // TODO: Should really make fopen, fsockopen, & exthttp work... if(function_exists('curl_init') && function_exists('curl_exec')) { $curl = curl_init(str_replace('//', '/', $url.$args['options']['path'])); curl_setopt($curl, CURLOPT_USERAGENT, $this->vars['user_agent']); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $final_args['body']); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_TIMEOUT, $this->vars['timeout']); $result['response'] = curl_exec($curl); $result['code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); } // else if(function_exists('fsockopen')) { // return $this->_fsock_post('http', $final_args['url'], $final_args['options']['port'], $final_args['options']['path'], $final_args['body']); // } else if(function_exists('http_request')) { // return http_request($final_args['method'}, $final_args['url'], $final_args['body'], $final_args['options']); // } } // function _fsock_post($type,$host,$port='80',$path='/',$data='') { // $_err = 'lib sockets::'.__FUNCTION__.'(): '; // switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port'); // if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1); // // $fp = fsockopen($host,$port,$errno,$errstr,$timeout=30); // if(!$fp) die($_err.$errstr.$errno); else { // fwrite($fp, "POST $path HTTP/1.1\r\n"); // fwrite($fp, "Host: $host\r\n"); // fwrite($fp, "User-Agent: ".$this->vars['user_agent']."\r\n"); // fwrite($fp, "Content-type: application/x-www-form-urlencoded\r\n"); // fwrite($fp, "Content-length: ".strlen($str)."\r\n"); // fwrite($fp, "Connection: close\r\n\r\n"); // fwrite($fp, $str."\r\n\r\n"); // // while(!feof($fp)) $d .= fgets($fp,4096); // fclose($fp); // } // return $d; // } function head() { $cloud = parse_url(hu.'?rsscloud=notify'); if(isset($cloud['port']) && !empty($cloud['port'])) { $port = (int)$cloud['port']; } else { $port = 80; } if(isset($cloud['path']) && isset($cloud['query'])) { $path = $cloud['path']."?".$cloud['query']; } else if(isset($cloud['query'])) { $path = "/?".$cloud['query']; } else { $path = ''; } if(isset($cloud['host'])) { $host = strtolower($cloud['host']); } else { $host = $_SERVER['HTTP_HOST']; } return "<cloud domain='".$host."' port='".$port."' path='".$path."' registerProcedure='' protocol='http-post' />"."\n"; } function notify_result($success, $msg) { header('Content-Type: text/xml'); echo "<?xml version='1.0'"."?".">"."\n"; echo "<notifyResult success='{$success}' msg='{$msg}' />\n"; exit; } function schedule_post_notifications() { if($this->vars['notifications_instant'] && function_exists('wlk_cron_single_event')) { // TODO: create wlk_cron Plugin wlk_cron_single_event(time(), 'send_post_notifications_action'); } else { $this->send_post_notifications(); } } function send_post_notifications() { global $prefs; $send_ud = false; if(!empty($_POST) && isset($_POST['ID'])) { if(is_numeric($_POST['ID'])) { $a = safe_row('Status', 'textpattern', 'ID='.intval($id)); if ($a) { if($uExpires and time() > $uExpires and !$prefs['publish_expired_articles']) { $send_ud = false; return; } if(($a['Status']!=4 || $a['Status']!=5) && ($_POST['Status']==4 || $_POST['Status']==5)) { // status changed to published $send_ud = true; } else { // status didn't change to published $send_ud = false; return; } } else { $send_ud = false; } } else if((!is_numeric($_POST['ID']) || empty($_POST['ID'])) && ($_POST['Status']==4 || $_POST['Status']==5)) { if(!$this->expired($_POST) && $this->published($_POST)) { $send_ud = true; } else if(!$this->expired($_POST) && !$this->published($_POST)) { // TODO: Set cron $send_ud = false; return; } } else { // error! $send_ud = false; return; } } if($send_ud) { $urls = array(); if($prefs['wlk_rsscloud_feeds']=='custom_only' || $prefs['wlk_rsscloud_feeds']=='both') { $urls[] = $prefs['custom_url']; } if($prefs['wlk_rsscloud_feeds']=='both' || $prefs['wlk_rsscloud_feeds']=='standard') { // get the section, category, & "All" $frs = safe_column("name", "txp_section", "in_rss != '1'"); if(isset($_POST['Section']) && in_array($_POST['Section'], $frs)) { // can't send that section } else { // construct the feed URLs // add to the URLs array $urls[] = hu.'rss/'; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section']; } if(isset($_POST['Category1']) && !empty($_POST['Category1'])) { $urls[] = hu.'rss/?category='.$_POST['Category1']; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section'].'&category='.$_POST['Category1']; } } if(isset($_POST['Category2']) && !empty($_POST['Category2'])) { $urls[] = hu.'rss/?category='.$_POST['Category2']; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section'].'&category='.$_POST['Category2']; } } } } if(!empty($urls)) { $feed_condition_arr = array(); foreach($urls as $url) { $feed_condition_arr[] = 'feed_url="'.addslashes($url).'"'; } $feed_conditions = implode(' OR ', $feed_condition_arr); $notify = safe_rows('*', 'txp_rsscloud_notifications', '('.$feed_conditions.') AND status="active"'); foreach($notify as $n) { if($n['status'] == 'active') { if ($n['protocol'] == 'http-post') { $url = parse_url($n['notify_url']); if(isset($url['port']) && !empty($url['port'])) { $port = $url['port']; } else { $port = 80; } $result = $this->remote_post($n['notify_url'], array('method' => 'POST', 'port' => $port, 'body' => array('url' => $n['feed_url']))); $need_update = false; if($result['code']!=200) { $n['fail_count'] = $n['fail_count']+1; safe_update('txp_rsscloud_notifications', 'fail_count="'.$n['fail_count'].'"', 'id="'.$n['id'].'"'); } if($n['fail_count'] > $this->vars['max_failures']) { safe_update('txp_rsscloud_notifications', 'status="suspended"', 'id="'.$n['id'].'"'); } } } } // foreach } } } function published($post) { $when_ts = time(); if(isset($post['reset_time'])) { return true; } else { if (!is_numeric($post['year']) || !is_numeric($post['month']) || !is_numeric($post['day']) || !is_numeric($post['hour']) || !is_numeric($post['minute']) || !is_numeric($post['second']) ) { return false; } $ts = strtotime($post['year'].'-'.$post['month'].'-'.$post['day'].' '.$post['hour'].':'.$post['minute'].':'.$post['second']); if ($ts === false || $ts === -1) { return false; } $when = $when_ts = $ts - tz_offset($ts); if($when<=time()) return true; else return false; } } function expired($post) { if(isset($post['exp_year']) && !empty($post['exp_year'])) { if(empty($post['exp_month'])) $post['exp_month']=1; if(empty($post['exp_day'])) $post['exp_day']=1; if(empty($post['exp_hour'])) $post['exp_hour']=0; if(empty($post['exp_minute'])) $post['exp_minute']=0; if(empty($post['exp_second'])) $post['exp_second']=0; $ts = strtotime($post['exp_year'].'-'.$post['exp_month'].'-'.$post['exp_day'].' '.$post['exp_hour'].':'.$post['exp_minute'].':'.$post['exp_second']); $expires = $ts - tz_offset($ts); if($expires<=time()) return true; else return false; } else { return false; } } function hub_process_notification_request() { global $prefs; // Must provide at least one URL to get notifications about if(isset($_POST['url1']) && empty($_POST['url1'])) $this->notify_result('false', 'No feed for url1.'); // Only support http-post $protocol = 'http-post'; if(isset($_POST['protocol']) && !empty($_POST['protocol']) && strtolower($_POST['protocol'])!=='http-post') $this->notify_result('false', 'Only http-post notifications are supported at this time.'); // Assume port 80 $port = 80; if(isset($_POST['port']) && !empty($_POST['port'])) { $port = (int)$_POST['port']; } // Path is required if((isset($_POST['path']) && empty($_POST['path'])) || !isset($_POST['path'])) { $this->notify_result('false', 'No path provided.'); } else if(isset($_POST['path'])) { $path = $_POST['path']; } // Process each URL request: url1, url2, url3 ... urlN $i = 1; while(isset($_POST['url'.$i])) { $feed_url = $_POST['url'.$i]; if(!preg_match('|url\d+|', $feed_url)) { } else if(!in_array($this->vars['custom_rss'], $feed_url) && $prefs['rsscloud_feeds']=='custom_only') { } else if(!in_array($this->vars['custom_rss'], $feed_url) && $prefs['rsscloud_feeds']=='both' && strpos($feed_url, 'rss')===false) { } else if($prefs['rsscloud_feeds']=='standard' && strpos($feed_url, 'rss')===false) { // Only allow requests for the RSS feed } else { // $rss2_url = get_bloginfo('rss2_url'); $notify_url = $_SERVER['REMOTE_ADDR'].':'.$port.$path; $notify = safe_row('*', 'txp_rsscloud_notifications', 'feed_url="'.$feed_url.'" AND notify_url="'.$notify_url.'" AND failure<"'.addslashes($this->vars['max_failures']).'" AND status="active"'); if(empty($notify)) { // Attempt a notification to see if it will work $result = $this->remote_post($notify_url, array('method'=>'POST', 'timeout'=>$this->vars['timeout'], 'user-agent'=>$this->vars['user_agent'], 'port'=>$port, 'body'=>array('url' => $_POST['url'.$i]))); if(isset($result->errors['http_request_failed'][0])) $this->notify_result('false', 'Error testing notification URL : '.$result->errors['http_request_failed'][0]); if($result['response']['code'] != 200) $this->notify_result('false', 'Error testing notification URL.'); // Passed all the tests, add this to the list of notifications for $status = 'active'; $failure_count = 0; safe_insert('txp_rsscloud_notifications', '(feed_url, notify_url, protocol, status, fail_count) VALUES ("'.addslashes($feed_url).'", "'.addslashes($notify_url).'", "'.addslashes($protocol).'", "'.addslashes($status).'", "'.addslashes($failure_count).'")'); $this->notify_result('true', 'Registration successful.'); } else { // already registered for pings $this->notify_result('true', 'Registration for that feed/notify URL already exists.'); } } $i++; } } // function hub_notify /* Install Goes Here */ function install() { safe_query('DELETE FROM '.safe_pfx('txp_prefs').' WHERE name LIKE "wlk_rsscloud_%"'); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_notifications_instant',val = '1',type = '1',event = 'wlk_rsscloud',html = 'yesnoradio',position = '10',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_max_failures',val = '0',type = '1',event = 'wlk_rsscloud',html = 'wlk_rsscloud_failures',position = '20',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_timeout',val = '3',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '30',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_user_agent',val = 'Textpattern/RSS Cloud 0.2',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '40',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_feeds',val = 'standard',type = '1',event = 'wlk_rsscloud',html = 'wlk_rsscloud_feeds',position = '50',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_custom_url',val = '',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '60',user_name = ''"); safe_query("CREATE TABLE IF NOT EXISTS `".safe_pfx('txp_rsscloud_notifications')."` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `feed_url` VARCHAR( 255 ) NOT NULL , `notify_url` VARCHAR( 255 ) NOT NULL , `protocol` VARCHAR( 20 ) NOT NULL DEFAULT 'http-post', `status` VARCHAR( 20 ) NOT NULL DEFAULT 'active', `fail_count` TINYINT( 4 ) NOT NULL DEFAULT '0', INDEX ( `feed_url` ) ) ENGINE = MYISAM"); } function delete() { safe_delete('txp_prefs',"name LIKE 'wlk_rsscloud_%'"); safe_query('DROP TABLE IF EXISTS `'.safe_pfx('txp_rsscloud_notifications').'`'); } } # --- END PLUGIN CODE --- ?> \ No newline at end of file diff --git a/wlk_rsscloud.txt b/wlk_rsscloud.txt index baf172c..766a592 100644 --- a/wlk_rsscloud.txt +++ b/wlk_rsscloud.txt @@ -1,326 +1,327 @@ -# wlk_rsscloud v0.2 +# wlk_rsscloud v0.2.1 # A down and dirty RSSCloud plugin. # Walker Hamilton # http://walkerhamilton.com # ...................................................................... # This is a plugin for Textpattern - http://textpattern.com/ # To install: textpattern > admin > plugins # Paste the following text into the 'Install plugin' box: # ...................................................................... -YToxMDp7czo3OiJ2ZXJzaW9uIjtzOjM6IjAuMiI7czo2OiJhdXRob3IiO3M6MTU6IldhbGtl -ciBIYW1pbHRvbiI7czoxMDoiYXV0aG9yX3VyaSI7czoyNToiaHR0cDovL3dhbGtlcmhhbWls -dG9uLmNvbSI7czoxMToiZGVzY3JpcHRpb24iO3M6MzM6IkEgZG93biBhbmQgZGlydHkgUlNT -Q2xvdWQgcGx1Z2luLiI7czo0OiJ0eXBlIjtpOjE7czo1OiJmbGFncyI7aToyO3M6NDoibmFt -ZSI7cz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lOREVYICggIGBmZWVkX3VybGAgKQoJCSkgRU5HSU5FID0g +TVlJU0FNIik7Cgl9CgoJZnVuY3Rpb24gZGVsZXRlKCkgewoJCXNhZmVfZGVsZXRlKCd0eHBf +cHJlZnMnLCJuYW1lIExJS0UgJ3dsa19yc3NjbG91ZF8lJyIpOwoJCXNhZmVfcXVlcnkoJ0RS +T1AgVEFCTEUgSUYgRVhJU1RTIGAnLnNhZmVfcGZ4KCd0eHBfcnNzY2xvdWRfbm90aWZpY2F0 +aW9ucycpLidgJyk7Cgl9Cn0KIjtzOjM6Im1kNSI7czozMjoiZDkyZGMyOTU4YzkzOWRmNmM3 +NGU1OWQ2YjIwMzA1ZGEiO30= \ No newline at end of file
walker/wlk_rsscloud
57e6b4c27f01553c1b7fa3cf7a97229710b273a4
Added new compressed
diff --git a/wlk_rsscloud.txt b/wlk_rsscloud.txt index 332c93a..baf172c 100644 --- a/wlk_rsscloud.txt +++ b/wlk_rsscloud.txt @@ -1,331 +1,326 @@ # wlk_rsscloud v0.2 # A down and dirty RSSCloud plugin. # Walker Hamilton # http://walkerhamilton.com # ...................................................................... # This is a plugin for Textpattern - http://textpattern.com/ # To install: textpattern > admin > plugins # Paste the following text into the 'Install plugin' box: # ...................................................................... YToxMDp7czo3OiJ2ZXJzaW9uIjtzOjM6IjAuMiI7czo2OiJhdXRob3IiO3M6MTU6IldhbGtl ciBIYW1pbHRvbiI7czoxMDoiYXV0aG9yX3VyaSI7czoyNToiaHR0cDovL3dhbGtlcmhhbWls dG9uLmNvbSI7czoxMToiZGVzY3JpcHRpb24iO3M6MzM6IkEgZG93biBhbmQgZGlydHkgUlNT Q2xvdWQgcGx1Z2luLiI7czo0OiJ0eXBlIjtpOjE7czo1OiJmbGFncyI7aToyO3M6NDoibmFt ZSI7czoxMjoid2xrX3Jzc2Nsb3VkIjtzOjQ6ImhlbHAiO3M6MzM3OiIJPGgyPkFib3V0PC9o Mj4KCgk8cD5UaGlzIGlzIGRvd24gYW5kIGRpcnR5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ZBUkNI +QVIoIDI1NSApIE5PVCBOVUxMICwKCQkJYHByb3RvY29sYCBWQVJDSEFSKCAyMCApIE5PVCBO +VUxMIERFRkFVTFQgICdodHRwLXBvc3QnLAoJCQlgc3RhdHVzYCBWQVJDSEFSKCAyMCApIE5P +VCBOVUxMIERFRkFVTFQgICdhY3RpdmUnLAoJCQlgZmFpbF9jb3VudGAgVElOWUlOVCggNCAp +IE5PVCBOVUxMIERFRkFVTFQgICcwJywKCQkJSU5ERVggKCAgYGZlZWRfdXJsYCApCgkJKSBF +TkdJTkUgPSBNWUlTQU0iKTsKCX0KCglmdW5jdGlvbiBkZWxldGUoKSB7CgkJc2FmZV9kZWxl +dGUoJ3R4cF9wcmVmcycsIm5hbWUgTElLRSAnd2xrX3Jzc2Nsb3VkXyUnIik7CgkJc2FmZV9x +dWVyeSgnRFJPUCBUQUJMRSBJRiBFWElTVFMgYCcuc2FmZV9wZngoJ3R4cF9yc3NjbG91ZF9u +b3RpZmljYXRpb25zJykuJ2AnKTsKCX0KfQoiO3M6MzoibWQ1IjtzOjMyOiJkOTJkYzI5NThj +OTM5ZGY2Yzc0ZTU5ZDZiMjAzMDVkYSI7fQ== \ No newline at end of file
walker/wlk_rsscloud
6e8da3d5b9992ad223bb8b8cfe1858242f0f45a1
Fixed RSS Feed header
diff --git a/wlk_rsscloud.php b/wlk_rsscloud.php index 0dffe9d..99d55b1 100644 --- a/wlk_rsscloud.php +++ b/wlk_rsscloud.php @@ -1,476 +1,490 @@ <?php $plugin['version'] = '0.2'; $plugin['author'] = 'Walker Hamilton'; $plugin['author_uri'] = 'http://walkerhamilton.com'; $plugin['description'] = 'A down and dirty RSSCloud plugin.'; $plugin['type'] = 1; if (!defined('PLUGIN_LIFECYCLE_NOTIFY')) define('PLUGIN_LIFECYCLE_NOTIFY', 0x0002); // This plugin wants to receive "plugin_lifecycle.{$plugin['name']}" events $plugin['flags'] = PLUGIN_LIFECYCLE_NOTIFY; @include_once(dirname(dirname(__FILE__)).'/zem_tpl.php'); if(0) { ?> # --- BEGIN PLUGIN HELP --- h2. About p. This is down and dirty RSSCloud plugin. h2. Installation and Use p. If you've installed and activated it, you're ready to go. h2. Thanks p. Some of the code is heavily based on work by Joseph Scott (http://josephscott.org/) on the Wordpress plugin. # --- END PLUGIN HELP --- <?php } # --- BEGIN PLUGIN CODE --- register_callback('wlk_rsscloud_head', 'rss_head'); register_callback('wlk_rsscloud_notification_activation', 'pretext'); if(@txpinterface == 'admin') { register_callback('wlk_rsscloud_install', 'plugin_lifecycle.wlk_rsscloud', 'installed'); register_callback('wlk_rsscloud_delete', 'plugin_lifecycle.wlk_rsscloud', 'deleted'); register_callback('wlk_rsscloud_language', 'admin_side', 'pagetop'); register_callback('wlk_rsscloud_schedule', 'article', 'edit'); } function wlk_rsscloud_schedule() { $rc = new WlkRssCloudClass(); $rc->schedule_post_notifications(); } function wlk_rsscloud_head() { return WlkRssCloudClass::head(); } function wlk_rsscloud_notification_activation() { if(isset($_GET['rsscloud']) && $_GET['rsscloud']=='notify') { $rc = new WlkRssCloudClass(); $rc->hub_process_notification_request(); exit(); } } function wlk_rsscloud_install() { WlkRssCloudClass::install(); } function wlk_rsscloud_delete() { WlkRssCloudClass::delete(); } function wlk_rsscloud_feeds() { $rc = new WlkRssCloudClass(); return $rc->feedDD(); } function wlk_rsscloud_failures() { global $prefs; $vals = array( 5 => 5, 10 => 10, 15 => 15, 20 => 20 ); $name = 'wlk_rsscloud_max_failures'; return selectInput($name, $vals, $prefs['wlk_rsscloud_max_failures'], '', '', $name); } function wlk_rsscloud_language() { $rc = new WlkRssCloudClass(); } // class WlkRssCloudClass { var $vars = array( 'notifications_instant' => true, 'user_agent' => 'Textpattern/RSSCloud 0.2', 'max_failures' => 5, 'timeout' => 3 ); function __construct() { global $prefs, $textarray; if($prefs['language']=='en-us') { $textarray['wlk_rsscloud'] = 'RSSCloud'; $textarray['rsscloud_standard'] = 'Standard feeds'; $textarray['rsscloud_both'] = 'Both standard feeds & the custom feed'; $textarray['rsscloud_custom_only'] = 'Custom feed only'; $textarray['wlk_rsscloud_notifications_instant'] = 'Instant notifications? ("No" requires wlk_cron)'; $textarray['wlk_rsscloud_max_failures'] = 'Max # of failures'; $textarray['wlk_rsscloud_feeds'] = 'Set type of feeds in use'; $textarray['wlk_rsscloud_timeout'] = 'Timeout'; $textarray['wlk_rsscloud_user_agent'] = 'User-agent'; $textarray['wlk_rsscloud_custom_url'] = 'Custom feed URL'; } if(isset($prefs['wlk_rsscloud_notifications_instant']) && !empty($prefs['wlk_rsscloud_notifications_instant'])) { $this->vars['notifications_instant'] = (bool)$prefs['wlk_rsscloud_notifications_instant']; } - if(isset($prefs['wlk_rsscloud_max_failures']) && !empty($prefs['wlk_rsscloud_max_failures'])) { $this->vars['max_failures'] = (int)$prefs['wlk_rsscloud_max_failures']; } - if(isset($prefs['wlk_rsscloud_timeout']) && !empty($prefs['wlk_rsscloud_timeout'])) { $this->vars['timeout'] = (int)$prefs['wlk_rsscloud_timeout']; } - if(isset($prefs['wlk_rsscloud_user_agent']) && !empty($prefs['wlk_rsscloud_user_agent'])) { $this->vars['user_agent'] = $prefs['wlk_rsscloud_user_agent']; } if(isset($prefs['wlk_rsscloud_custom_url']) && !empty($prefs['wlk_rsscloud_custom_url'])) { $this->vars['custom_url'] = $prefs['wlk_rsscloud_custom_url']; } } function WlkRssCloudClass() { $this->__construct(); } function feedDD() { global $prefs; $vals = array( 'standard' => gTxt('rsscloud_standard'), 'both' => gTxt('rsscloud_both'), 'custom_only' => gTxt('rsscloud_custom_only'), ); $name = 'wlk_rsscloud_feeds'; return selectInput($name, $vals, $prefs['wlk_rsscloud_feeds'], '', '', $name); } /* Needed HTTP Stuff - Should really create a #2 library plugin for this*/ function remote_post($url, $args = array()) { $defaults = array( 'method' => 'post', 'body' => array(), 'options' => array('path'=>'/', 'port' => 80) ); if(isset($args['options'])) { $final_options = array_merge($defaults['options'], $args['options']); } else { $final_options = $defaults['options']; } $final_args = array_merge($defaults, $args); $final_args['options'] = $final_options; $args = $final_args; $result = array(); // TODO: Should really make fopen, fsockopen, & exthttp work... if(function_exists('curl_init') && function_exists('curl_exec')) { $curl = curl_init(str_replace('//', '/', $url.$args['options']['path'])); curl_setopt($curl, CURLOPT_USERAGENT, $this->vars['user_agent']); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $final_args['body']); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_TIMEOUT, $this->vars['timeout']); $result['response'] = curl_exec($curl); $result['code'] = curl_getinfo($curl, CURLINFO_HTTP_CODE); curl_close($curl); } // else if(function_exists('fsockopen')) { // return $this->_fsock_post('http', $final_args['url'], $final_args['options']['port'], $final_args['options']['path'], $final_args['body']); // } else if(function_exists('http_request')) { // return http_request($final_args['method'}, $final_args['url'], $final_args['body'], $final_args['options']); // } } // function _fsock_post($type,$host,$port='80',$path='/',$data='') { // $_err = 'lib sockets::'.__FUNCTION__.'(): '; // switch($type) { case 'http': $type = ''; case 'ssl': continue; default: die($_err.'bad $type'); } if(!ctype_digit($port)) die($_err.'bad port'); // if(!empty($data)) foreach($data AS $k => $v) $str .= urlencode($k).'='.urlencode($v).'&'; $str = substr($str,0,-1); // // $fp = fsockopen($host,$port,$errno,$errstr,$timeout=30); // if(!$fp) die($_err.$errstr.$errno); else { // fwrite($fp, "POST $path HTTP/1.1\r\n"); // fwrite($fp, "Host: $host\r\n"); // fwrite($fp, "User-Agent: ".$this->vars['user_agent']."\r\n"); // fwrite($fp, "Content-type: application/x-www-form-urlencoded\r\n"); // fwrite($fp, "Content-length: ".strlen($str)."\r\n"); // fwrite($fp, "Connection: close\r\n\r\n"); // fwrite($fp, $str."\r\n\r\n"); // // while(!feof($fp)) $d .= fgets($fp,4096); // fclose($fp); // } // return $d; // } function head() { $cloud = parse_url(hu.'?rsscloud=notify'); - $cloud['port'] = (int) $cloud['port']; - if(empty( $cloud['port'])) { $cloud['port'] = 80; } + if(isset($cloud['port']) && !empty($cloud['port'])) { + $port = (int)$cloud['port']; + } else { + $port = 80; + } + + if(isset($cloud['path']) && isset($cloud['query'])) { + $path = $cloud['path']."?".$cloud['query']; + } else if(isset($cloud['query'])) { + $path = "/?".$cloud['query']; + } else { + $path = ''; + } - $cloud['path'] .= "?{$cloud['query']}"; - $cloud['host'] = strtolower( $cloud['host'] ); + if(isset($cloud['host'])) { + $host = strtolower($cloud['host']); + } else { + $host = $_SERVER['HTTP_HOST']; + } - return "<cloud domain='{$cloud['host']}' port='{$cloud['port']}' path='{$cloud['path']}' registerProcedure='' protocol='http-post' />"."\n"; + return "<cloud domain='".$host."' port='".$port."' path='".$path."' registerProcedure='' protocol='http-post' />"."\n"; } function notify_result($success, $msg) { header('Content-Type: text/xml'); echo "<?xml version='1.0'"."?".">"."\n"; echo "<notifyResult success='{$success}' msg='{$msg}' />\n"; exit; } function schedule_post_notifications() { if($this->vars['notifications_instant'] && function_exists('wlk_cron_single_event')) { // TODO: create wlk_cron Plugin wlk_cron_single_event(time(), 'send_post_notifications_action'); } else { $this->send_post_notifications(); } } function send_post_notifications() { global $prefs; $send_ud = false; if(!empty($_POST) && isset($_POST['ID'])) { if(is_numeric($_POST['ID'])) { $a = safe_row('Status', 'textpattern', 'ID='.intval($id)); if ($a) { if($uExpires and time() > $uExpires and !$prefs['publish_expired_articles']) { $send_ud = false; return; } if(($a['Status']!=4 || $a['Status']!=5) && ($_POST['Status']==4 || $_POST['Status']==5)) { // status changed to published $send_ud = true; } else { // status didn't change to published $send_ud = false; return; } } else { $send_ud = false; } } else if((!is_numeric($_POST['ID']) || empty($_POST['ID'])) && ($_POST['Status']==4 || $_POST['Status']==5)) { if(!$this->expired($_POST) && $this->published($_POST)) { $send_ud = true; } else if(!$this->expired($_POST) && !$this->published($_POST)) { // TODO: Set cron $send_ud = false; return; } } else { // error! $send_ud = false; return; } } if($send_ud) { $urls = array(); if($prefs['wlk_rsscloud_feeds']=='custom_only' || $prefs['wlk_rsscloud_feeds']=='both') { $urls[] = $prefs['custom_url']; } if($prefs['wlk_rsscloud_feeds']=='both' || $prefs['wlk_rsscloud_feeds']=='standard') { // get the section, category, & "All" $frs = safe_column("name", "txp_section", "in_rss != '1'"); if(isset($_POST['Section']) && in_array($_POST['Section'], $frs)) { // can't send that section } else { // construct the feed URLs // add to the URLs array $urls[] = hu.'rss/'; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section']; } if(isset($_POST['Category1']) && !empty($_POST['Category1'])) { $urls[] = hu.'rss/?category='.$_POST['Category1']; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section'].'&category='.$_POST['Category1']; } } if(isset($_POST['Category2']) && !empty($_POST['Category2'])) { $urls[] = hu.'rss/?category='.$_POST['Category2']; if(isset($_POST['Section']) && !empty($_POST['Section'])) { $urls[] = hu.'rss/?section='.$_POST['Section'].'&category='.$_POST['Category2']; } } } } if(!empty($urls)) { $feed_condition_arr = array(); foreach($urls as $url) { $feed_condition_arr[] = 'feed_url="'.addslashes($url).'"'; } $feed_conditions = implode(' OR ', $feed_condition_arr); $notify = safe_rows('*', 'txp_rsscloud_notifications', '('.$feed_conditions.') AND status="active"'); foreach($notify as $n) { if($n['status'] == 'active') { if ($n['protocol'] == 'http-post') { $url = parse_url($n['notify_url']); - $port = 80; - if(!empty($url['port'])) { $port = $url['port']; } + if(isset($url['port']) && !empty($url['port'])) { + $port = $url['port']; + } else { + $port = 80; + } $result = $this->remote_post($n['notify_url'], array('method' => 'POST', 'port' => $port, 'body' => array('url' => $n['feed_url']))); $need_update = false; if($result['code']!=200) { $n['fail_count'] = $n['fail_count']+1; safe_update('txp_rsscloud_notifications', 'fail_count="'.$n['fail_count'].'"', 'id="'.$n['id'].'"'); } if($n['fail_count'] > $this->vars['max_failures']) { safe_update('txp_rsscloud_notifications', 'status="suspended"', 'id="'.$n['id'].'"'); } } } } // foreach } } } function published($post) { $when_ts = time(); if(isset($post['reset_time'])) { return true; } else { if (!is_numeric($post['year']) || !is_numeric($post['month']) || !is_numeric($post['day']) || !is_numeric($post['hour']) || !is_numeric($post['minute']) || !is_numeric($post['second']) ) { return false; } $ts = strtotime($post['year'].'-'.$post['month'].'-'.$post['day'].' '.$post['hour'].':'.$post['minute'].':'.$post['second']); if ($ts === false || $ts === -1) { return false; } $when = $when_ts = $ts - tz_offset($ts); if($when<=time()) return true; else return false; } } function expired($post) { if(isset($post['exp_year']) && !empty($post['exp_year'])) { if(empty($post['exp_month'])) $post['exp_month']=1; if(empty($post['exp_day'])) $post['exp_day']=1; if(empty($post['exp_hour'])) $post['exp_hour']=0; if(empty($post['exp_minute'])) $post['exp_minute']=0; if(empty($post['exp_second'])) $post['exp_second']=0; $ts = strtotime($post['exp_year'].'-'.$post['exp_month'].'-'.$post['exp_day'].' '.$post['exp_hour'].':'.$post['exp_minute'].':'.$post['exp_second']); $expires = $ts - tz_offset($ts); if($expires<=time()) return true; else return false; } else { return false; } } function hub_process_notification_request() { global $prefs; // Must provide at least one URL to get notifications about if(isset($_POST['url1']) && empty($_POST['url1'])) $this->notify_result('false', 'No feed for url1.'); // Only support http-post $protocol = 'http-post'; if(isset($_POST['protocol']) && !empty($_POST['protocol']) && strtolower($_POST['protocol'])!=='http-post') $this->notify_result('false', 'Only http-post notifications are supported at this time.'); // Assume port 80 $port = 80; if(isset($_POST['port']) && !empty($_POST['port'])) { $port = (int)$_POST['port']; } // Path is required if((isset($_POST['path']) && empty($_POST['path'])) || !isset($_POST['path'])) { $this->notify_result('false', 'No path provided.'); } else if(isset($_POST['path'])) { $path = $_POST['path']; } // Process each URL request: url1, url2, url3 ... urlN $i = 1; while(isset($_POST['url'.$i])) { $feed_url = $_POST['url'.$i]; if(!preg_match('|url\d+|', $feed_url)) { } else if(!in_array($this->vars['custom_rss'], $feed_url) && $prefs['rsscloud_feeds']=='custom_only') { } else if(!in_array($this->vars['custom_rss'], $feed_url) && $prefs['rsscloud_feeds']=='both' && strpos($feed_url, 'rss')===false) { } else if($prefs['rsscloud_feeds']=='standard' && strpos($feed_url, 'rss')===false) { // Only allow requests for the RSS feed } else { // $rss2_url = get_bloginfo('rss2_url'); $notify_url = $_SERVER['REMOTE_ADDR'].':'.$port.$path; $notify = safe_row('*', 'txp_rsscloud_notifications', 'feed_url="'.$feed_url.'" AND notify_url="'.$notify_url.'" AND failure<"'.addslashes($this->vars['max_failures']).'" AND status="active"'); if(empty($notify)) { // Attempt a notification to see if it will work $result = $this->remote_post($notify_url, array('method'=>'POST', 'timeout'=>$this->vars['timeout'], 'user-agent'=>$this->vars['user_agent'], 'port'=>$port, 'body'=>array('url' => $_POST['url'.$i]))); if(isset($result->errors['http_request_failed'][0])) $this->notify_result('false', 'Error testing notification URL : '.$result->errors['http_request_failed'][0]); if($result['response']['code'] != 200) $this->notify_result('false', 'Error testing notification URL.'); // Passed all the tests, add this to the list of notifications for $status = 'active'; $failure_count = 0; safe_insert('txp_rsscloud_notifications', '(feed_url, notify_url, protocol, status, fail_count) VALUES ("'.addslashes($feed_url).'", "'.addslashes($notify_url).'", "'.addslashes($protocol).'", "'.addslashes($status).'", "'.addslashes($failure_count).'")'); $this->notify_result('true', 'Registration successful.'); } else { // already registered for pings $this->notify_result('true', 'Registration for that feed/notify URL already exists.'); } } $i++; } } // function hub_notify /* Install Goes Here */ function install() { safe_query('DELETE FROM '.safe_pfx('txp_prefs').' WHERE name LIKE "wlk_rsscloud_%"'); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_notifications_instant',val = '1',type = '1',event = 'wlk_rsscloud',html = 'yesnoradio',position = '10',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_max_failures',val = '0',type = '1',event = 'wlk_rsscloud',html = 'wlk_rsscloud_failures',position = '20',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_timeout',val = '3',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '30',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_user_agent',val = 'Textpattern/RSS Cloud 0.2',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '40',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_feeds',val = 'standard',type = '1',event = 'wlk_rsscloud',html = 'wlk_rsscloud_feeds',position = '50',user_name = ''"); safe_insert('txp_prefs',"prefs_id = '1',name = 'wlk_rsscloud_custom_url',val = '',type = '1',event = 'wlk_rsscloud',html = 'text_input',position = '60',user_name = ''"); safe_query("CREATE TABLE IF NOT EXISTS `".safe_pfx('txp_rsscloud_notifications')."` ( `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , `feed_url` VARCHAR( 255 ) NOT NULL , `notify_url` VARCHAR( 255 ) NOT NULL , `protocol` VARCHAR( 20 ) NOT NULL DEFAULT 'http-post', `status` VARCHAR( 20 ) NOT NULL DEFAULT 'active', `fail_count` TINYINT( 4 ) NOT NULL DEFAULT '0', INDEX ( `feed_url` ) ) ENGINE = MYISAM"); } function delete() { safe_delete('txp_prefs',"name LIKE 'wlk_rsscloud_%'"); safe_query('DROP TABLE IF EXISTS `'.safe_pfx('txp_rsscloud_notifications').'`'); } } # --- END PLUGIN CODE --- ?> \ No newline at end of file diff --git a/wlk_rsscloud.txt b/wlk_rsscloud.txt index 3c92253..332c93a 100644 --- a/wlk_rsscloud.txt +++ b/wlk_rsscloud.txt @@ -1,330 +1,331 @@ -# wlk_rsscloud v0.2 -# A down and dirty RSSCloud plugin. -# Walker Hamilton -# http://walkerhamilton.com - -# ...................................................................... -# This is a plugin for Textpattern - http://textpattern.com/ -# To install: textpattern > admin > plugins -# Paste the following text into the 'Install plugin' box: -# ...................................................................... - +# wlk_rsscloud v0.2 +# A down and dirty RSSCloud plugin. +# Walker Hamilton +# http://walkerhamilton.com + +# ...................................................................... +# This is a plugin for Textpattern - http://textpattern.com/ +# To install: textpattern > admin > plugins +# Paste the following text into the 'Install plugin' box: +# ...................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X3VybGAgVkFSQ0hBUiggMjU1 +ICkgTk9UIE5VTEwgLAoJCQlgcHJvdG9jb2xgIFZBUkNIQVIoIDIwICkgTk9UIE5VTEwgREVG +QVVMVCAgJ2h0dHAtcG9zdCcsCgkJCWBzdGF0dXNgIFZBUkNIQVIoIDIwICkgTk9UIE5VTEwg +REVGQVVMVCAgJ2FjdGl2ZScsCgkJCWBmYWlsX2NvdW50YCBUSU5ZSU5UKCA0ICkgTk9UIE5V +TEwgREVGQVVMVCAgJzAnLAoJCQlJTkRFWCAoICBgZmVlZF91cmxgICkKCQkpIEVOR0lORSA9 +IE1ZSVNBTSIpOwoJfQoKCWZ1bmN0aW9uIGRlbGV0ZSgpIHsKCQlzYWZlX2RlbGV0ZSgndHhw +X3ByZWZzJywibmFtZSBMSUtFICd3bGtfcnNzY2xvdWRfJSciKTsKCQlzYWZlX3F1ZXJ5KCdE +Uk9QIFRBQkxFIElGIEVYSVNUUyBgJy5zYWZlX3BmeCgndHhwX3Jzc2Nsb3VkX25vdGlmaWNh +dGlvbnMnKS4nYCcpOwoJfQp9CiI7czozOiJtZDUiO3M6MzI6ImVlN2QxOWMzZDMyZmJmNmVm +MjNkYzM4Y2JjNjcyYTZkIjt9 \ No newline at end of file
walker/wlk_rsscloud
66cd4070ae0375691b1458badfdd10f3d65c99a9
Minor tweaks
diff --git a/README.txt b/README.txt new file mode 100644 index 0000000..ce38922 --- /dev/null +++ b/README.txt @@ -0,0 +1,7 @@ +This is a plugin for Textpattern built by Walker Hamilton (http://walkerhamilton.com) that enables the use of RSSCloud. Portions of this plugin are based on the plugin initially implemented by Joseph Scott (http://josephscott.org/). You should really use PubSubHubBub and not RSSCloud, but, since Worpress had this thing running, I figured Textpattern should have the ability too. + +To install, grab the current version of the compressed plugin (wlk_rsscloud.txt) and paste into the plugin field in Textpattern. + +As long as it's been installed & activated, you're ready to go. + +This has been tested with 4.2.0 only. \ No newline at end of file
josegomez/GOLang-Samples
e545f966faa38e48c3dd956e82089a22888613ba
adding Hello Golang
diff --git a/golang-hello.go b/golang-hello.go new file mode 100644 index 0000000..e7d5295 --- /dev/null +++ b/golang-hello.go @@ -0,0 +1,13 @@ +package main + +import ( + "fmt" +) + + +func main() { + fmt.Printf("Hello GOLang\nYou are awesome!") +} + +// Reformatted by jose Wed Sep 29 11:08:25 EDT 2010 +
jri/deepamehta3-importer
6f7f79f1798aff4d8c6dd7491b631294305a4c04
Adapt to upcoming DeepaMehta 4.0.3
diff --git a/.gitignore b/.gitignore index cd82fc7..c238cd0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ .DS_Store commit-message.txt + target/ +runner/ +deepamehta-db/ diff --git a/README.md b/README.md index 4a63eec..445c768 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,48 @@ -DeepaMehta 3 Importer +DeepaMehta 4 Importer ===================== -This plugin demonstrates DeepaMehta 3's file upload facility to developers. It is a scaffold without actual functionality. It is here for educational purposes only. +This plugin demonstrates DeepaMehta 4's file upload facility to developers. It is a scaffold without actual functionality. It is here for educational purposes only. -DeepaMehta 3 is a platform for collaboration and knowledge management. -<http://github.com/jri/deepamehta3> +DeepaMehta 4 is a platform for collaboration and knowledge management. +<http://github.com/jri/deepamehta> Installing ---------- Perform the installation via the Apache Felix shell (the terminal window that opens while starting DeepaMehta): -1. Download and start the DeepaMehta 3 Importer plugin: +1. Download and start the DeepaMehta 4 Importer plugin: - start http://www.deepamehta.de/maven2/de/deepamehta/deepamehta3-importer/0.4.2/deepamehta3-importer-0.4.2.jar + start http://www.deepamehta.de/maven2/de/deepamehta/deepamehta-importer/0.4.2/deepamehta-importer-0.4.2.jar - When using the `lb` command you should now see the DeepaMehta 3 Importer plugin as *Active*. + When using the `lb` command you should now see the DeepaMehta 4 Importer plugin as *Active*. 2. Open the DeepaMehta browser window (resp. press reload): - <http://localhost:8080/de.deepamehta.3-client/index.html> + <http://localhost:8080/de.deepamehta.webclient/index.html> Version History --------------- +**4.0.3** -- Upcoming + +* Compatible with DeepaMehta 4.0.3 + **v0.4.2** -- Nov 25, 2010 * Compatible with DeepaMehta 3 v0.4.3 **v0.4.1** -- Oct 16, 2010 * Compatible with DeepaMehta 3 v0.4.1 **v0.4** -- Aug 4, 2010 * Compatible with DeepaMehta 3 v0.4 ------------ Jörg Richter -Nov 25, 2010 +Aug 7, 2011 diff --git a/pom.xml b/pom.xml index 927521c..8c764bb 100644 --- a/pom.xml +++ b/pom.xml @@ -1,33 +1,32 @@ <project> <modelVersion>4.0.0</modelVersion> - <name>DeepaMehta 3 Importer</name> + <name>DeepaMehta 4 Importer</name> <groupId>de.deepamehta</groupId> - <artifactId>deepamehta3-importer</artifactId> - <version>0.4.3-SNAPSHOT</version> + <artifactId>deepamehta-importer</artifactId> + <version>4.0.3-SNAPSHOT</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> - <artifactId>deepamehta3-plugin-parent</artifactId> - <version>0.4.5-SNAPSHOT</version> + <artifactId>deepamehta-plugin-parent</artifactId> + <version>4.0.3-SNAPSHOT</version> </parent> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <configuration> <instructions> <Bundle-Activator> de.deepamehta.plugins.importer.ImporterPlugin </Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> - </project> diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java index 55c1fcb..2cf2f26 100644 --- a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -1,62 +1,62 @@ package de.deepamehta.plugins.importer; -import de.deepamehta.core.model.ClientContext; -import de.deepamehta.core.model.CommandParams; -import de.deepamehta.core.model.CommandResult; +import de.deepamehta.core.service.ClientContext; +import de.deepamehta.core.service.CommandParams; +import de.deepamehta.core.service.CommandResult; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.util.UploadedFile; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Logger; public class ImporterPlugin extends Plugin { // ---------------------------------------------------------------------------------------------- Instance Variables private Logger logger = Logger.getLogger(getClass().getName()); // -------------------------------------------------------------------------------------------------- Public Methods // ************************ // *** Overriding Hooks *** // ************************ @Override public CommandResult executeCommandHook(String command, CommandParams params, ClientContext clientContext) { - if (command.equals("deepamehta3-importer.start")) { + if (command.equals("deepamehta-importer.start")) { UploadedFile file = null; try { file = params.getFile("file"); logger.info("### Importing " + file); importFile(file); return new CommandResult("message", "OK"); } catch (Exception e) { throw new RuntimeException("Importing " + file + " failed", e); } } return null; } // ------------------------------------------------------------------------------------------------- Private Methods private void importFile(UploadedFile file) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); StringBuilder builder = new StringBuilder(); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); logger.info("### First 5 lines:\n" + builder); } } diff --git a/src/main/resources/plugin.properties b/src/main/resources/plugin.properties index 98cb33a..66d4826 100644 --- a/src/main/resources/plugin.properties +++ b/src/main/resources/plugin.properties @@ -1 +1 @@ -clientSidePluginFile = dm3_importer.js +clientSidePluginFile = importer_plugin.js diff --git a/src/main/resources/web/script/dm3_importer.js b/src/main/resources/web/script/importer_plugin.js similarity index 60% rename from src/main/resources/web/script/dm3_importer.js rename to src/main/resources/web/script/importer_plugin.js index ea63221..f8b8685 100644 --- a/src/main/resources/web/script/dm3_importer.js +++ b/src/main/resources/web/script/importer_plugin.js @@ -1,20 +1,18 @@ -function dm3_importer() { +function importer_plugin() { // ------------------------------------------------------------------------------------------------ Overriding Hooks this.init = function() { - dm3c.add_to_special_menu({label: "Import..."}) - } - - this.handle_special_command = function(label) { - if (label == "Import...") { - dm3c.show_upload_dialog("deepamehta3-importer.start", show_result) - } + dm4c.toolbar.special_menu.add_item({label: "Import...", handler: do_import}) } // ----------------------------------------------------------------------------------------------- Private Functions + function do_import() { + dm4c.upload_dialog.show("deepamehta-importer.start", show_result) + } + function show_result(result) { alert("import result=" + JSON.stringify(result)) } }
jri/deepamehta3-importer
31516369d00d0e9119d2ca016f5ac2d08701f2f8
Adapt to current version of deepamehta3-core
diff --git a/pom.xml b/pom.xml index 13e957f..927521c 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,33 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> <version>0.4.3-SNAPSHOT</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> - <artifactId>deepamehta3-parent</artifactId> - <version>${parent-version}</version> + <artifactId>deepamehta3-plugin-parent</artifactId> + <version>0.4.5-SNAPSHOT</version> </parent> - <dependencies> - <dependency> - <groupId>de.deepamehta</groupId> - <artifactId>deepamehta3-core</artifactId> - <version>${core-version}</version> - </dependency> - </dependencies> - <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> - <extensions>true</extensions> <configuration> <instructions> - <Private-Package> - de.deepamehta.plugins.importer - </Private-Package> - <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> + <Bundle-Activator> + de.deepamehta.plugins.importer.ImporterPlugin + </Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project> diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java index 4516222..55c1fcb 100644 --- a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -1,73 +1,62 @@ package de.deepamehta.plugins.importer; import de.deepamehta.core.model.ClientContext; -import de.deepamehta.core.model.DataField; -import de.deepamehta.core.model.Topic; -import de.deepamehta.core.model.TopicType; +import de.deepamehta.core.model.CommandParams; +import de.deepamehta.core.model.CommandResult; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.util.UploadedFile; -import org.codehaus.jettison.json.JSONArray; -import org.codehaus.jettison.json.JSONException; -import org.codehaus.jettison.json.JSONObject; - import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; import java.util.logging.Logger; public class ImporterPlugin extends Plugin { - // -------------------------------------------------------------------------------------------------- Static Methods - // ---------------------------------------------------------------------------------------------- Instance Variables private Logger logger = Logger.getLogger(getClass().getName()); + // -------------------------------------------------------------------------------------------------- Public Methods + // ************************ // *** Overriding Hooks *** // ************************ @Override - public JSONObject executeCommandHook(String command, Map params, ClientContext clientContext) { + public CommandResult executeCommandHook(String command, CommandParams params, ClientContext clientContext) { if (command.equals("deepamehta3-importer.start")) { UploadedFile file = null; try { - file = (UploadedFile) params.get("file"); + file = params.getFile("file"); logger.info("### Importing " + file); importFile(file); - // - JSONObject result = new JSONObject(); - result.put("message", "OK"); - return result; - } catch (Throwable e) { - throw new RuntimeException("Error while importing " + file, e); + return new CommandResult("message", "OK"); + } catch (Exception e) { + throw new RuntimeException("Importing " + file + " failed", e); } } return null; } // ------------------------------------------------------------------------------------------------- Private Methods private void importFile(UploadedFile file) throws Exception { - BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getFile()))); + BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); StringBuilder builder = new StringBuilder(); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); logger.info("### First 5 lines:\n" + builder); } }
jri/deepamehta3-importer
ea2dc307a8f5b459e4a82f0fd976c1dcc07fb535
Fix: class ClientContext imported.
diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java index 6ab18dc..4516222 100644 --- a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -1,72 +1,73 @@ package de.deepamehta.plugins.importer; +import de.deepamehta.core.model.ClientContext; import de.deepamehta.core.model.DataField; import de.deepamehta.core.model.Topic; import de.deepamehta.core.model.TopicType; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.util.UploadedFile; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class ImporterPlugin extends Plugin { // -------------------------------------------------------------------------------------------------- Static Methods // ---------------------------------------------------------------------------------------------- Instance Variables private Logger logger = Logger.getLogger(getClass().getName()); // ************************ // *** Overriding Hooks *** // ************************ @Override public JSONObject executeCommandHook(String command, Map params, ClientContext clientContext) { if (command.equals("deepamehta3-importer.start")) { UploadedFile file = null; try { file = (UploadedFile) params.get("file"); logger.info("### Importing " + file); importFile(file); // JSONObject result = new JSONObject(); result.put("message", "OK"); return result; } catch (Throwable e) { throw new RuntimeException("Error while importing " + file, e); } } return null; } // ------------------------------------------------------------------------------------------------- Private Methods private void importFile(UploadedFile file) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getFile()))); StringBuilder builder = new StringBuilder(); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); logger.info("### First 5 lines:\n" + builder); } }
jri/deepamehta3-importer
b1fb3b469360bf1dddece49eaa9f53968391c04c
1) Adapted to current version of deepamehta3-core (new class ClientContext). 2) Version number changed from 0.4.2 to 0.4.3-SNAPSHOT.
diff --git a/pom.xml b/pom.xml index 59e0c66..13e957f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4.2</version> + <version>0.4.3-SNAPSHOT</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project> diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java index d4e18a5..6ab18dc 100644 --- a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -1,72 +1,72 @@ package de.deepamehta.plugins.importer; import de.deepamehta.core.model.DataField; import de.deepamehta.core.model.Topic; import de.deepamehta.core.model.TopicType; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.util.UploadedFile; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class ImporterPlugin extends Plugin { // -------------------------------------------------------------------------------------------------- Static Methods // ---------------------------------------------------------------------------------------------- Instance Variables private Logger logger = Logger.getLogger(getClass().getName()); // ************************ // *** Overriding Hooks *** // ************************ @Override - public JSONObject executeCommandHook(String command, Map params, Map<String, String> clientContext) { + public JSONObject executeCommandHook(String command, Map params, ClientContext clientContext) { if (command.equals("deepamehta3-importer.start")) { UploadedFile file = null; try { file = (UploadedFile) params.get("file"); logger.info("### Importing " + file); importFile(file); // JSONObject result = new JSONObject(); result.put("message", "OK"); return result; } catch (Throwable e) { throw new RuntimeException("Error while importing " + file, e); } } return null; } // ------------------------------------------------------------------------------------------------- Private Methods private void importFile(UploadedFile file) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getFile()))); StringBuilder builder = new StringBuilder(); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); logger.info("### First 5 lines:\n" + builder); } }
jri/deepamehta3-importer
5b55f4b10cc21a512e6b9e8dc27f0a82097aca04
DeepaMehta 3 v0.4.3 release: POM Version number updated. README updated.
diff --git a/README.md b/README.md index 65a48ea..4a63eec 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,44 @@ -DeepaMehta 3 -============ +DeepaMehta 3 Importer +===================== -DeepaMehta 3 is a platform for collaboration and knowledge management. +This plugin demonstrates DeepaMehta 3's file upload facility to developers. It is a scaffold without actual functionality. It is here for educational purposes only. -Technologically DeepaMehta is made of Java, Neo4j, Apache Lucene, Apache Felix, Jersey, Javascript/AJAX, jQuery, jQuery-UI, and HTML5 Canvas. +DeepaMehta 3 is a platform for collaboration and knowledge management. +<http://github.com/jri/deepamehta3> -DeepaMehta 3 is a complete rewrite of DeepaMehta 2. -DeepaMehta 3 is highly modularized software. The main module and installation instructions: -<http://github.com/jri/deepamehta3> +Installing +---------- + +Perform the installation via the Apache Felix shell (the terminal window that opens while starting DeepaMehta): + +1. Download and start the DeepaMehta 3 Importer plugin: + + start http://www.deepamehta.de/maven2/de/deepamehta/deepamehta3-importer/0.4.2/deepamehta3-importer-0.4.2.jar + + When using the `lb` command you should now see the DeepaMehta 3 Importer plugin as *Active*. + +2. Open the DeepaMehta browser window (resp. press reload): + <http://localhost:8080/de.deepamehta.3-client/index.html> + + +Version History +--------------- + +**v0.4.2** -- Nov 25, 2010 + +* Compatible with DeepaMehta 3 v0.4.3 + +**v0.4.1** -- Oct 16, 2010 + +* Compatible with DeepaMehta 3 v0.4.1 + +**v0.4** -- Aug 4, 2010 + +* Compatible with DeepaMehta 3 v0.4 ------------ Jörg Richter -Oct 16, 2010 +Nov 25, 2010 diff --git a/pom.xml b/pom.xml index e1b66da..59e0c66 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4.2-SNAPSHOT</version> + <version>0.4.2</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project>
jri/deepamehta3-importer
2a0f712845ad4eb288af4f694f289eb067dff8aa
1) Adapted to current version of deepamehta3-client. 2) POM updated: version number changed from 0.4.1 to 0.4.2-SNAPSHOT.
diff --git a/pom.xml b/pom.xml index 6470530..e1b66da 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4.1</version> + <version>0.4.2-SNAPSHOT</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project> diff --git a/src/main/resources/web/script/dm3_importer.js b/src/main/resources/web/script/dm3_importer.js index 6430b4f..ea63221 100644 --- a/src/main/resources/web/script/dm3_importer.js +++ b/src/main/resources/web/script/dm3_importer.js @@ -1,20 +1,20 @@ function dm3_importer() { // ------------------------------------------------------------------------------------------------ Overriding Hooks this.init = function() { - $("#special-select").append($("<option>").text("Import...")) + dm3c.add_to_special_menu({label: "Import..."}) } - this.handle_special_command = function(command) { - if (command == "Import...") { + this.handle_special_command = function(label) { + if (label == "Import...") { dm3c.show_upload_dialog("deepamehta3-importer.start", show_result) } } // ----------------------------------------------------------------------------------------------- Private Functions function show_result(result) { alert("import result=" + JSON.stringify(result)) } }
jri/deepamehta3-importer
262e5875129e775ece1d02a3fc9c761778a52a7d
v0.4.1: version bumped. README updated.
diff --git a/README.md b/README.md index 9d2d89f..65a48ea 100644 --- a/README.md +++ b/README.md @@ -1,71 +1,17 @@ DeepaMehta 3 ============ -DeepaMehta is a platform for collaboration and knowledge management. +DeepaMehta 3 is a platform for collaboration and knowledge management. -Technologically DeepaMehta is made of Java, Neo4j, Lucene, Javascript/AJAX, jQuery, jQuery-UI, and HTML 5 Canvas. -All DeepaMehta modules are OSGi bundles. -DeepaMehta 3 is a complete rewrite of DeepaMehta 2. - -<http://www.deepamehta.de> - - -Requirements ------------- - -*To be written* - - -Installation ------------- - -*To be written* - - -Running -------- - -*To be written* +Technologically DeepaMehta is made of Java, Neo4j, Apache Lucene, Apache Felix, Jersey, Javascript/AJAX, jQuery, jQuery-UI, and HTML5 Canvas. +DeepaMehta 3 is a complete rewrite of DeepaMehta 2. -Updating --------- - -*To be written* - - -Version History ---------------- - -**v0.4** -- upcoming - -* Fundamental under the hood technology/architectural changes -* CouchDB is replaced by Neo4j -* Java-based middle-tier with REST interface -* All DeepaMehta modules are OSGi bundles - -**v0.3** -- Mar 5, 2010 - -* Persistent topicmaps (plugin *DM3 Topicmaps*) -* Type editor (plugin *DM3 Type Editor*) -* Icon picker (plugin *DM3 Icons*) -* New topic type "To Do" (plugin *DM3 Project*) -* More flexible plugin developer framework - -**v0.2** -- Dec 1, 2009 - -* Framework for plugin developers -* Autocompletion facility -* Topics have icons -* jQuery UI based GUI -* 7 general purpose plugins (*DM3 Time*, *DM3 Workspaces*, *DM3 Contacts*, *DM3 Email*, *DM3 Import*, *DM3 Accounts*, *DM3 Typing*) and 1 custom application (*Poemspace*) available - -**v0.1** -- Sep 15, 2009 - -* Basic functionality (Creating notes, edit, delete. Relate notes to other notes, navigate alongside relations. Attach files to notes. Fulltext searching in notes, also in attachments. Graphical network display of related notes.) +DeepaMehta 3 is highly modularized software. The main module and installation instructions: +<http://github.com/jri/deepamehta3> ------------ Jörg Richter -May 24, 2010 +Oct 16, 2010 diff --git a/pom.xml b/pom.xml index 9629ee5..6470530 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4.1-SNAPSHOT</version> + <version>0.4.1</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project>
jri/deepamehta3-importer
50bcf44bafdab0ed3aa7746e90947d82011f0e81
1) Adapted to current version of deepamehta3-client. 2) version number bumped to 0.4.1-SNAPSHOT.
diff --git a/pom.xml b/pom.xml index 0bae6ec..9629ee5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4</version> + <version>0.4.1-SNAPSHOT</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project> diff --git a/src/main/resources/web/script/dm3_importer.js b/src/main/resources/web/script/dm3_importer.js index 0f28a84..6430b4f 100644 --- a/src/main/resources/web/script/dm3_importer.js +++ b/src/main/resources/web/script/dm3_importer.js @@ -1,32 +1,20 @@ function dm3_importer() { - - - /**************************************************************************************************/ - /**************************************** Overriding Hooks ****************************************/ - /**************************************************************************************************/ - - + // ------------------------------------------------------------------------------------------------ Overriding Hooks this.init = function() { $("#special-select").append($("<option>").text("Import...")) } this.handle_special_command = function(command) { if (command == "Import...") { - show_upload_dialog("deepamehta3-importer.start", show_result) + dm3c.show_upload_dialog("deepamehta3-importer.start", show_result) } } - - - /************************************************************************************************/ - /**************************************** Custom Methods ****************************************/ - /************************************************************************************************/ - - + // ----------------------------------------------------------------------------------------------- Private Functions function show_result(result) { alert("import result=" + JSON.stringify(result)) } }
jri/deepamehta3-importer
29c0cebfd826da4c9cd97eb37ff2da68aaa971d4
version dependencies are set via properties in the parent pom
diff --git a/pom.xml b/pom.xml index 6f3317d..0bae6ec 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> <version>0.4</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> - <version>0.4</version> + <version>${parent-version}</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> - <version>0.4</version> + <version>${core-version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project>
jri/deepamehta3-importer
17593c5f9ea3c37dace12a5d65c0efb9271a32f1
v0.4 release: bumped version number.
diff --git a/pom.xml b/pom.xml index 2129009..6f3317d 100644 --- a/pom.xml +++ b/pom.xml @@ -1,43 +1,43 @@ <project> <modelVersion>4.0.0</modelVersion> <name>DeepaMehta 3 Importer</name> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-importer</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> <packaging>bundle</packaging> <parent> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-parent</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </parent> <dependencies> <dependency> <groupId>de.deepamehta</groupId> <artifactId>deepamehta3-core</artifactId> - <version>0.4-SNAPSHOT</version> + <version>0.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.felix</groupId> <artifactId>maven-bundle-plugin</artifactId> <extensions>true</extensions> <configuration> <instructions> <Private-Package> de.deepamehta.plugins.importer </Private-Package> <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> </instructions> </configuration> </plugin> </plugins> </build> </project>
jri/deepamehta3-importer
c07bcd2ac21fd4d978c13109a11dee2fb7d9a904
Adapted to current version of DeepaMehta 3 Core.
diff --git a/src/main/resources/plugin.properties b/src/main/resources/plugin.properties index 6296a2b..98cb33a 100644 --- a/src/main/resources/plugin.properties +++ b/src/main/resources/plugin.properties @@ -1 +1 @@ -clientSidePlugin = dm3_importer.js +clientSidePluginFile = dm3_importer.js
jri/deepamehta3-importer
5843f1c629e60bec2a81103c8f68891743d5345c
Adapted to current version of DeepaMehta 3 Core.
diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java index 0e935fb..d4e18a5 100644 --- a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -1,71 +1,72 @@ package de.deepamehta.plugins.importer; import de.deepamehta.core.model.DataField; import de.deepamehta.core.model.Topic; import de.deepamehta.core.model.TopicType; import de.deepamehta.core.service.Plugin; import de.deepamehta.core.util.UploadedFile; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONException; import org.codehaus.jettison.json.JSONObject; import java.io.BufferedReader; +import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; public class ImporterPlugin extends Plugin { // -------------------------------------------------------------------------------------------------- Static Methods // ---------------------------------------------------------------------------------------------- Instance Variables private Logger logger = Logger.getLogger(getClass().getName()); // ************************ // *** Overriding Hooks *** // ************************ @Override public JSONObject executeCommandHook(String command, Map params, Map<String, String> clientContext) { if (command.equals("deepamehta3-importer.start")) { UploadedFile file = null; try { file = (UploadedFile) params.get("file"); logger.info("### Importing " + file); importFile(file); // JSONObject result = new JSONObject(); result.put("message", "OK"); return result; } catch (Throwable e) { throw new RuntimeException("Error while importing " + file, e); } } return null; } // ------------------------------------------------------------------------------------------------- Private Methods private void importFile(UploadedFile file) throws Exception { - BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); + BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getFile()))); StringBuilder builder = new StringBuilder(); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); builder.append(reader.readLine() + "\n"); logger.info("### First 5 lines:\n" + builder); } }
jri/deepamehta3-importer
517852436d8c7a03d5d8ff3253b73746cf1b74d3
The server response is now received. Import not yet functional.
diff --git a/src/main/resources/web/script/dm3_importer.js b/src/main/resources/web/script/dm3_importer.js index fc58bd6..0f28a84 100644 --- a/src/main/resources/web/script/dm3_importer.js +++ b/src/main/resources/web/script/dm3_importer.js @@ -1,32 +1,32 @@ function dm3_importer() { /**************************************************************************************************/ /**************************************** Overriding Hooks ****************************************/ /**************************************************************************************************/ this.init = function() { $("#special-select").append($("<option>").text("Import...")) } this.handle_special_command = function(command) { if (command == "Import...") { - var result = show_upload_dialog("deepamehta3-importer.start") - show_result(result) + show_upload_dialog("deepamehta3-importer.start", show_result) } } /************************************************************************************************/ /**************************************** Custom Methods ****************************************/ /************************************************************************************************/ function show_result(result) { + alert("import result=" + JSON.stringify(result)) } }
jri/deepamehta3-importer
7121f5fb6db0f87e642b0b17c3ce2188f9fda1e1
Importer plugin for DeepaMehta 3: creates a bunch of topics and relations by importing a text file. Not yet functional.
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cd82fc7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +commit-message.txt +target/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..9d2d89f --- /dev/null +++ b/README.md @@ -0,0 +1,71 @@ + +DeepaMehta 3 +============ + +DeepaMehta is a platform for collaboration and knowledge management. + +Technologically DeepaMehta is made of Java, Neo4j, Lucene, Javascript/AJAX, jQuery, jQuery-UI, and HTML 5 Canvas. +All DeepaMehta modules are OSGi bundles. +DeepaMehta 3 is a complete rewrite of DeepaMehta 2. + +<http://www.deepamehta.de> + + +Requirements +------------ + +*To be written* + + +Installation +------------ + +*To be written* + + +Running +------- + +*To be written* + + +Updating +-------- + +*To be written* + + +Version History +--------------- + +**v0.4** -- upcoming + +* Fundamental under the hood technology/architectural changes +* CouchDB is replaced by Neo4j +* Java-based middle-tier with REST interface +* All DeepaMehta modules are OSGi bundles + +**v0.3** -- Mar 5, 2010 + +* Persistent topicmaps (plugin *DM3 Topicmaps*) +* Type editor (plugin *DM3 Type Editor*) +* Icon picker (plugin *DM3 Icons*) +* New topic type "To Do" (plugin *DM3 Project*) +* More flexible plugin developer framework + +**v0.2** -- Dec 1, 2009 + +* Framework for plugin developers +* Autocompletion facility +* Topics have icons +* jQuery UI based GUI +* 7 general purpose plugins (*DM3 Time*, *DM3 Workspaces*, *DM3 Contacts*, *DM3 Email*, *DM3 Import*, *DM3 Accounts*, *DM3 Typing*) and 1 custom application (*Poemspace*) available + +**v0.1** -- Sep 15, 2009 + +* Basic functionality (Creating notes, edit, delete. Relate notes to other notes, navigate alongside relations. Attach files to notes. Fulltext searching in notes, also in attachments. Graphical network display of related notes.) + + +------------ +Jörg Richter +May 24, 2010 diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..2129009 --- /dev/null +++ b/pom.xml @@ -0,0 +1,43 @@ +<project> + + <modelVersion>4.0.0</modelVersion> + + <name>DeepaMehta 3 Importer</name> + <groupId>de.deepamehta</groupId> + <artifactId>deepamehta3-importer</artifactId> + <version>0.4-SNAPSHOT</version> + <packaging>bundle</packaging> + + <parent> + <groupId>de.deepamehta</groupId> + <artifactId>deepamehta3-parent</artifactId> + <version>0.4-SNAPSHOT</version> + </parent> + + <dependencies> + <dependency> + <groupId>de.deepamehta</groupId> + <artifactId>deepamehta3-core</artifactId> + <version>0.4-SNAPSHOT</version> + </dependency> + </dependencies> + + <build> + <plugins> + <plugin> + <groupId>org.apache.felix</groupId> + <artifactId>maven-bundle-plugin</artifactId> + <extensions>true</extensions> + <configuration> + <instructions> + <Private-Package> + de.deepamehta.plugins.importer + </Private-Package> + <Bundle-Activator>de.deepamehta.plugins.importer.ImporterPlugin</Bundle-Activator> + </instructions> + </configuration> + </plugin> + </plugins> + </build> + +</project> diff --git a/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java new file mode 100644 index 0000000..0e935fb --- /dev/null +++ b/src/main/java/de/deepamehta/plugins/importer/ImporterPlugin.java @@ -0,0 +1,71 @@ +package de.deepamehta.plugins.importer; + +import de.deepamehta.core.model.DataField; +import de.deepamehta.core.model.Topic; +import de.deepamehta.core.model.TopicType; +import de.deepamehta.core.service.Plugin; +import de.deepamehta.core.util.UploadedFile; + +import org.codehaus.jettison.json.JSONArray; +import org.codehaus.jettison.json.JSONException; +import org.codehaus.jettison.json.JSONObject; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Logger; + + + +public class ImporterPlugin extends Plugin { + + // -------------------------------------------------------------------------------------------------- Static Methods + + // ---------------------------------------------------------------------------------------------- Instance Variables + + private Logger logger = Logger.getLogger(getClass().getName()); + + + + // ************************ + // *** Overriding Hooks *** + // ************************ + + + + @Override + public JSONObject executeCommandHook(String command, Map params, Map<String, String> clientContext) { + if (command.equals("deepamehta3-importer.start")) { + UploadedFile file = null; + try { + file = (UploadedFile) params.get("file"); + logger.info("### Importing " + file); + importFile(file); + // + JSONObject result = new JSONObject(); + result.put("message", "OK"); + return result; + } catch (Throwable e) { + throw new RuntimeException("Error while importing " + file, e); + } + } + return null; + } + + // ------------------------------------------------------------------------------------------------- Private Methods + + private void importFile(UploadedFile file) throws Exception { + BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream())); + StringBuilder builder = new StringBuilder(); + builder.append(reader.readLine() + "\n"); + builder.append(reader.readLine() + "\n"); + builder.append(reader.readLine() + "\n"); + builder.append(reader.readLine() + "\n"); + builder.append(reader.readLine() + "\n"); + logger.info("### First 5 lines:\n" + builder); + } +} diff --git a/src/main/resources/plugin.properties b/src/main/resources/plugin.properties new file mode 100644 index 0000000..6296a2b --- /dev/null +++ b/src/main/resources/plugin.properties @@ -0,0 +1 @@ +clientSidePlugin = dm3_importer.js diff --git a/src/main/resources/web/script/dm3_importer.js b/src/main/resources/web/script/dm3_importer.js new file mode 100644 index 0000000..fc58bd6 --- /dev/null +++ b/src/main/resources/web/script/dm3_importer.js @@ -0,0 +1,32 @@ +function dm3_importer() { + + + + /**************************************************************************************************/ + /**************************************** Overriding Hooks ****************************************/ + /**************************************************************************************************/ + + + + this.init = function() { + $("#special-select").append($("<option>").text("Import...")) + } + + this.handle_special_command = function(command) { + if (command == "Import...") { + var result = show_upload_dialog("deepamehta3-importer.start") + show_result(result) + } + } + + + + /************************************************************************************************/ + /**************************************** Custom Methods ****************************************/ + /************************************************************************************************/ + + + + function show_result(result) { + } +}
timurvafin/tumblr-dashboard-rss-sinatra-app
b1f4c42d5747f8ef32881faa2135b2224050f9eb
Use 1.9.2
diff --git a/.rvmrc b/.rvmrc index 46e6d7e..bc05402 100644 --- a/.rvmrc +++ b/.rvmrc @@ -1 +1 @@ -rvm use ree-1.8.7-2010.02@tumblr-dashboard-rss-sinatra-app +rvm use ruby-1.9.2-p0@tumblr-dashboard-rss-sinatra-app diff --git a/config.ru b/config.ru index 3112760..7aaffd7 100644 --- a/config.ru +++ b/config.ru @@ -1,2 +1,4 @@ -require 'app/tumbler_rss' +$LOAD_PATH.unshift(File.dirname(__FILE__) + '/app') + +require 'tumbler_rss' run Sinatra::Application
timurvafin/tumblr-dashboard-rss-sinatra-app
dfbddab0851b8f73de226c5a24b4f08448e7108a
Added index page
diff --git a/app/tumbler_rss.rb b/app/tumbler_rss.rb index 6d6bb68..f9b0744 100644 --- a/app/tumbler_rss.rb +++ b/app/tumbler_rss.rb @@ -1,8 +1,12 @@ require 'rubygems' require 'bundler/setup' require 'sinatra' require 'tumblr_dashboard_rss' +get '/' do + File.read(File.join('public', 'index.html')) +end + get '/:email/:password' do Tumblr::DashboardRSS.new(params[:email], params[:password], params).to_rss end \ No newline at end of file diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..8129e78 --- /dev/null +++ b/public/index.html @@ -0,0 +1,26 @@ +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> +<html> + <head> + <title>Tumbler RSS generator</title> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <style type="text/css"> + body { text-align:center;font-family:helvetica,arial;font-size:22px;color:#888;margin:20px} + #c {margin:0 auto;width:600px;text-align:left} + </style> + </head> + <body> + <h1>Tumbler RSS generator</h1> + + <div id="c"> + <ul> + <li>No auth</li> + <li>No cache</li> + <li> + <a href="http://github.com/timurvafin/tumblr-dashboard-rss-sinatra-app">Open</a> + <a href="http://github.com/timurvafin/tumblr-dashboard-rss">Source</a> + </li> + <li>http://tumblr-dashboard.heroku.com/:email/:password</li> + </ul> + </div> + </body> +</html>
timurvafin/tumblr-dashboard-rss-sinatra-app
fdeeb5b373835846195d13a2ac2695c79ca629d0
Added config.ru for rackup
diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..3112760 --- /dev/null +++ b/config.ru @@ -0,0 +1,2 @@ +require 'app/tumbler_rss' +run Sinatra::Application
tuxsoul/wiki-httpbl
b3115321dc0d93578fbb4ab58e737fe8a79a4cd7
* Delete: "config.httpbl.php" * Rename: "core.httpbl.php" to "httpbl.core.php" * Rename: "object.httpbl.php" to "httpbl.object.php" * Add: "$wgWikiHttpBLKey", set key access to Http:BL (Project Honey Pot) * Add: "$wgWikiHttpBLTrap", set quicklink (url trap) * Add: "$wgWikiHttpBLTrapWord", set word to work whith quicklink * Update: README, README-ES
diff --git a/CHANGELOG b/CHANGELOG index 0478535..dd27291 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,22 +1,36 @@ ================================================================================ CHANGELOG ================================================================================ +-------------------------------------------------------------------------------- +2008-02-01 - v0.2.2 +-------------------------------------------------------------------------------- +Whith this release you can configure Http:BL from "LocalSettings.php", for more +easy install and future updates. + +* Delete: "config.httpbl.php" +* Rename: "core.httpbl.php" to "httpbl.core.php" +* Rename: "object.httpbl.php" to "httpbl.object.php" +* Add: "$wgWikiHttpBLKey", set key access to Http:BL (Project Honey Pot) +* Add: "$wgWikiHttpBLTrap", set quicklink (url trap) +* Add: "$wgWikiHttpBLTrapWord", set word to work whith quicklink +* Update: README, README-ES + -------------------------------------------------------------------------------- 2008-01-31 - v0.1.1 -------------------------------------------------------------------------------- * Fix bug #1: "wiki-httpbl stop others extensions using the same wgHook ...." -* Change $wgHook['ParserBeforeTidy'] to $wgHook['ParserAfterTidy'] -* Change version to v0.1.1 +* Change: $wgHook['ParserBeforeTidy'] to $wgHook['ParserAfterTidy'] +* Change: version to v0.1.1 -------------------------------------------------------------------------------- 2008-01-20 - v0.1 -------------------------------------------------------------------------------- * Core version '0.1' * First version of this extension * Detect spammer's using http:bl from 'Project Honey Pot' * Can redirect spammer to one address trap * Use one word with address trap * Insert three or more address trap in the html code ================================================================================ diff --git a/README b/README index d0eb7c8..2a7560b 100644 --- a/README +++ b/README @@ -1,83 +1,81 @@ = Introduction = Please visit the following websites where you can find more information: Project Honey Pot website http://www.projecthoneypot.org/?rf=39586 Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ = Contact = Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com E-mail: <[email protected]> = Bugs = If you find any bugs or have any idea for a feature can be usefull to this extension, you can leave it in the bugtrack: http://code.google.com/p/wiki-httpbl/issues/list = License = GNU General Public License v2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html = Requirements = * Key from "Project Honey Pot" * Quicklink from "Project Honey Pot" * Mediawiki version 1.6 + * PHP4 + = Features = * Use Http:BL to detect spammer's * Ability to redirect into a trap if the visitor is a spammer * Ability to insert addresses traps in the html code of Mediawiki = Details = * First download and decompresses the file extension of this * Rename the directory the this extension to "wiki-httpbl" - * Inside the directory "wiki-httpbl" there is a file named - "config.httpbl.php", which is necessary to change the following: - - * Enter your "key" from Project Honey Pot - * Enter a QuickLink or trap, to redirect the spammer's - * Enter a word random, to anything, is only to show the Links to spammer's - traps - * Upload the "wiki-httpbl" to the directory of extensions you wiki, which is called "extensions" * Open the file named "LocalSettings.php" which is located in the Root directory of your site, after adding the following two lines to End of the file: - # Include Http:bl - include ( './extensions/wiki-httpbl/httpbl.php' ); + ##### Include Http:bl + # Key of access to Http:BL (Project Honey Pot) + $wgWikiHttpBLKey = '------------'; + # QuickLink (Project Honey Pot) + $wgWikiHttpBLTrap = ''; + # Word to work whith Quicklink (url trap) + $wgWikiHttpBLTrapWord = 'mediawiki'; + include( './extensions/wiki-httpbl/httpbl.php' ); * Save the file and enters your website to see if it is not showing any Error Lastly and can only wait to block the spammer's coming to you Website. = Donation = Please consider helping through donations, for more information visit the following link: Donate http://tinyurl.com/2zhdhg Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ Cheers :-). diff --git a/README-ES b/README-ES index eeee7bd..b010ba1 100644 --- a/README-ES +++ b/README-ES @@ -1,84 +1,82 @@ = Introducción = Por favor visita los siguientes sitios web, en donde encontrarás más información: Project Honey Pot website http://www.projecthoneypot.org/?rf=39586 Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ = Contacto = Autor: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com E-mail: <[email protected]> = Bugs = Si encuentras algún bug o tienes alguna idea para una característica que creas que le puede ser útil a esta extensión, puedes dejarla en el bugtrack: http://code.google.com/p/wiki-httpbl/issues/list = Licencia = GNU General Public License v2 http://www.gnu.org/licenses/old-licenses/gpl-2.0.html = Requerimientos = * Key de "Project Honey Pot" * Quicklink de "Project Honey Pot" * Mediawiki versión 1.6 + * PHP4 + = Características = * Usa Http:BL para detectar spammer's * Posibilidad de redireccionar hacia una trampa si el visitante es un spammer * Posibilidad de insertar direcciones de trampas en el código html de mediawiki = Detalles = * Primero descarga y descomprime el archivo de esta extensión * Renombra el directorio de la extensión a "wiki-httpbl" - * Dentro del directorio de "wiki-httpbl" hay un archivo nombrado - "config.httpbl.php", en el cual es necesario cambiar lo siguiente: - - * Ingresa tú "key" de Project Honey Pot - * Ingresa un QuickLink o trampa, para redireccionar a los spammer's - * Ingresa una palabra aleatoria, la que sea, solo es para mostrar los - enlaces que llevan a trampas para spammer's - * Sube el directorio "wiki-httpbl" al directorio de extensiones de tú wiki, el cual tiene el nombre de "extensions" * Abre el archivo nombrado "LocalSettings.php" el cual esta ubicado en el directorio raíz de tú sitio web, despúes agrega las siguientes dos lineas al final del archivo: - # Include Http:bl - include ( './extensions/wiki-httpbl/httpbl.php' ); + ##### Include Http:bl + # Key of access to Http:BL (Project Honey Pot) + $wgWikiHttpBLKey = '------------'; + # QuickLink (Project Honey Pot) + $wgWikiHttpBLTrap = ''; + # Word to work whith Quicklink (url trap) + $wgWikiHttpBLTrapWord = 'mediawiki'; + include( './extensions/wiki-httpbl/httpbl.php' ); * Salva el archivo y entra a tú sitio web para ver si no se muestra algún error Por último ya solo queda esperar para bloquear a los spammer's que lleguen a tú sitio web. = Donaciones = Por favor considera el ayudar mediante donaciones, para más información visita el siguiente enlace: Donación http://tinyurl.com/2zhdhg Extension wiki-httpbl http://code.google.com/p/wiki-httpbl/ Saludos :-). diff --git a/config.httpbl.php b/config.httpbl.php deleted file mode 100644 index 5c643c9..0000000 --- a/config.httpbl.php +++ /dev/null @@ -1,49 +0,0 @@ -<?php -/* -Implementation of API from "Project Honey Pot" -http://www.projecthoneypot.org/httpbl_api - -Author: Mario Oyorzabal Salgado -Blog: http://blog.tuxsoul.com/ -E-mail: <[email protected]> -Web: http://code.google.com/p/wiki-httpbl/ -Donate: http://tinyurl.com/2zhdhg - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation; either version 2 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program; if not, write to the Free Software -Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. -*/ - -// you can't execute directly this file -// you are lost ? -if (!defined('HTTPBL_CWD')) { - die ('You are lost ?'); -} - -////////// Configuration -////////// You can edit all values ;-) - -///// Key to access dnsbl service from "Project Honey Pot" -///// All Access Keys are 12-characters in length, lower case, and contain only alpha characters (no numbers) -///// You need a key ?, register here: http://www.projecthoneypot.org?rf=39586 -define('HTTPBL_KEY', '------------'); - -////////// Url to honeypot trap for redirect malicious visitors -///// If you have install a trap or you can get this in "Project Honey Pot" -> "QuickLink" -///// This value is important to catch more spammers ;-) -define('HTTPBL_TRAP', ''); - -///// Is important change this value to any word, for have usefull url trap's -define('HTTPBL_TRAP_WORD', 'mediawiki'); - -?> diff --git a/core.httpbl.php b/httpbl.core.php similarity index 88% rename from core.httpbl.php rename to httpbl.core.php index f2b6574..e3f2fd0 100644 --- a/core.httpbl.php +++ b/httpbl.core.php @@ -1,182 +1,186 @@ <?php /* Implementation of API from "Project Honey Pot" http://www.projecthoneypot.org/httpbl_api Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com/ E-mail: <[email protected]> Web: http://code.google.com/p/wiki-httpbl/ Donate: http://tinyurl.com/2zhdhg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // can't execute directly this file // you are lost ? if (!defined('HTTPBL_CWD')) { die ('You are lost ?'); } // main class object class coreHttpBL { + // config values + var $key, $url, $word; + var $coreHttpBLIp; var $coreHttpBLError; var $coreHttpBLConfVersion; var $coreHttpBLConfDnsbl; var $coreHttpBLConfDays; function coreHttpBL () { // set flag error to cero $this->coreHttpBLError = 0; // config // version of this core - $this->coreHttpBLConfVersion = '0.1'; + $this->coreHttpBLConfVersion = '0.2'; // spammer days since last activity $this->coreHttpBLConfDays = '15'; // define query to dnsbl $this->coreHttpBLConfDnsbl = '{key}.{ip}.dnsbl.httpbl.org'; } // return version of this core function coreHttpBLVersion () { return $this->coreHttpBLConfVersion; } // start the search to spammer's function coreHttpBLStart () { // detect ip $this->coreHttpBLDetectIp(); // reverse-octet ip address // change data of query $host = $this->coreHttpBLDnsblPrepareQuery(); // make query and get response $response = $this->coreHttpBLDnsblQuery($host); // Is spammer ? if($this->coreHttpBLIsSpammer($response) == 1) { // Get the trap $this->coreHttpBLShowTrap(); } } // try to detect the remote ip function coreHttpBLDetectIP () { $ip = $_SERVER['REMOTE_ADDR']; // only for test // $ip = '127.1.1.1'; $this->coreHttpBLIp = $ip; } // change data of query to dnsbl function coreHttpBLDnsblPrepareQuery () { // reverse-octet ip format $reverseIp = implode('.', array_reverse(explode('.', $this->coreHttpBLIp))); // prepare query to dnsbl $string = $this->coreHttpBLConfDnsbl; - $string = ereg_replace('{key}', HTTPBL_KEY, $string); + $string = ereg_replace('{key}', $this->key, $string); $string = ereg_replace('{ip}', $reverseIp, $string); return $string; } // make the query to dnsbl server function coreHttpBLDnsblQuery ($host) { $response = gethostbyname($host); if($response == $host) $this->coreHttpBLError = 1; return $response; } // is spammer ? function coreHttpBLIsSpammer ($response) { if($this->coreHttpBLError == 0) { $data = explode('.', $response); $spammer = 0; // the first octect always is 127 if((int)$data[0] == 127) { // spammer days since last activity if((int)$data[1] <= $this->coreHttpBLConfDays) { // only check the type of spammer if((int)$data[3] > 0) { $spammer = 1; } } } else $this->coreHttpBLError = 1; return $spammer; } return 0; } // redirect to the trap function coreHttpBLShowTrap () { if($this->coreHttpBLError == 0) { - // FIXME: HTTPBL_TRAP is set correctly ? - if(strlen(HTTPBL_TRAP) > 0) { - header('Location: ' . HTTPBL_TRAP); + // FIXME: $this->url is set correctly ? + if(strlen($this->url) > 0) { + header('Location: ' . $this->url); die(); } } } // return url to trap in html // FIXME: Need more work here :) function coreHttpBLGetUrlTrap () { - $text = '<!-- begin links ' . HTTPBL_TRAP_WORD . ' -->'; + $text = '<!-- begin links ' . $this->word . ' -->'; - // FIXME: HTTPBL_TRAP is set correctly ? - if(strlen(HTTPBL_TRAP) > 0) { + // FIXME: $this->url is set correctly ? + if(strlen($this->url) > 0) { $url = array ( '<a href="{url}"><!-- {word} --></a>', '<a href="{url}" style="display: none;">{word}</a>', '<div style="display: none;"><a href="{url}">{word}</a></div>', '<a href="{url}"></a>', '<!-- <a href="{url}">{word}</a> -->', '<div style="position: absolute; top: -250px; left: -250px;"><a href="{url}">{word}</a></div>', '<a href="{url}"><span style="display: none;">{word}</span></a>', ); for($x = 0; $x <= 2; $x++) { $temp = $url[rand(0, 6)]; - $temp = ereg_replace('{url}', HTTPBL_TRAP, $temp); - $temp = ereg_replace('{word}', HTTPBL_TRAP_WORD, $temp); + $temp = ereg_replace('{url}', $this->url, $temp); + $temp = ereg_replace('{word}', $this->word, $temp); $text .= $temp; } - $text .= '<!-- end links '. HTTPBL_TRAP_WORD . ' -->'; + $text .= '<!-- end links '. $this->word . ' -->'; } return $text; } } + ?> diff --git a/object.httpbl.php b/httpbl.object.php similarity index 86% rename from object.httpbl.php rename to httpbl.object.php index a5cb2ea..8568966 100644 --- a/object.httpbl.php +++ b/httpbl.object.php @@ -1,76 +1,77 @@ <?php /* Implementation of API from "Project Honey Pot" http://www.projecthoneypot.org/httpbl_api Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com/ E-mail: <[email protected]> Web: http://code.google.com/p/wiki-httpbl/ Donate: http://tinyurl.com/2zhdhg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // can't execute directly this file // you are lost ? if (!defined('HTTPBL_CWD')) { die('You are lost ?'); } -// include config file -include (HTTPBL_CWD . '/config.httpbl.php'); - // include core file -include (HTTPBL_CWD . '/core.httpbl.php'); +include (HTTPBL_CWD . '/httpbl.core.php'); // main class object class objectHttpBL extends coreHttpBL { - // load configuration - function httpbl () { - - } - // start the search to spammer's - function httpblStart () { + function httpblStart (&$data) { + // set the key to access 'Project Honey Pot' + $this->key = $data[0]; + $this->url = $data[1]; + $this->word = $data[2]; + $this->coreHttpBLStart(); } // get url to trap - function httpblGetUrlTrap () { + function httpblGetUrlTrap (&$url, &$word) { + $this->url = $url; + $this->word = $word; + return $this->coreHttpBLGetUrlTrap(); } // return information from this code function httpblInfo ($type) { $description = 'This code implement the API from "Project Honey Pot", to detect Spammers, Harvesters'; $description .= ' and other malicious visitors. Consider donate to this extension'; $values = array ( 'name' => 'Http:BL', 'version' => $this->coreHttpBLVersion(), 'author' => 'Mario Oyorzabal Salgado', 'description' => $description, 'url' => 'http://code.google.com/p/wiki-httpbl/', ); if (isset($values[$type])) return $values[$type]; else return 'Null'; } } + ?> diff --git a/httpbl.php b/httpbl.php index e4899af..750b350 100644 --- a/httpbl.php +++ b/httpbl.php @@ -1,69 +1,77 @@ <?php /* Implementation of API from "Project Honey Pot" http://www.projecthoneypot.org/httpbl_api Author: Mario Oyorzabal Salgado Blog: http://blog.tuxsoul.com/ E-mail: <[email protected]> Web: http://code.google.com/p/wiki-httpbl/ Donate: http://tinyurl.com/2zhdhg This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ // Check to run with mediawiki if (!defined('MEDIAWIKI')) { die ('You are lost ?'); } // Extension version, not core version, is other stuff -$httpblExtensionVersion = "1"; +$httpblExtensionVersion = "2"; // Define path of extension define('HTTPBL_CWD', dirname(__FILE__)); // Include class to work dnsbl of httpbl -include(HTTPBL_CWD . '/object.httpbl.php'); +include(HTTPBL_CWD . '/httpbl.object.php'); // Instance object $httpbl = new objectHttpBL(); // Execute httpbl filter function httpbl_mediawiki_start () { - global $httpbl; - $httpbl->httpblStart(); + global $httpbl, $wgWikiHttpBLKey, $wgWikiHttpBLTrap, $wgWikiHttpBLTrapWord; + + $data = array ( + $wgWikiHttpBLKey, + $wgWikiHttpBLTrap, + $wgWikiHttpBLTrapWord + ); + + $httpbl->httpblStart($data); } // Execute httpbl text function httpbl_mediawiki_text (&$parser, &$text) { - global $httpbl; - $text = $httpbl->httpblGetUrlTrap() . $text; + global $httpbl, $wgWikiHttpBLTrap, $wgWikiHttpBLTrapWord; + + $text = $httpbl->httpblGetUrlTrap($wgWikiHttpBLTrap, $wgWikiHttpBLTrapWord) . $text; return true; } // Extension info $wgExtensionCredits['other'][] = array( 'name' => $httpbl->httpblInfo('name'), 'version' => $httpbl->httpblInfo('version') . '.' . $httpblExtensionVersion, 'author' => $httpbl->httpblInfo('author'), 'description' => $httpbl->httpblInfo('description'), 'url' => $httpbl->httpblInfo('url'), ); $wgHooks['ParserAfterTidy'][] = 'httpbl_mediawiki_text'; $wgExtensionFunctions[] = 'httpbl_mediawiki_start'; ?>