'),
+ '#description' => t('The list of tags which are allowed in feeds, i.e., which will not be removed by Drupal.')
+ );
+
+ $form['aggregator_summary_items'] = array(
+ '#type' => 'select', '#title' => t('Items shown in sources and categories pages') ,
+ '#default_value' => variable_get('aggregator_summary_items', 3), '#options' => $items,
+ '#description' => t('The number of items which will be shown with each feed or category in the feed and category summary pages.')
+ );
+
+ $form['aggregator_clear'] = array(
+ '#type' => 'select', '#title' => t('Discard news items older than'),
+ '#default_value' => variable_get('aggregator_clear', 9676800), '#options' => $period,
+ '#description' => t('Older news items will be automatically discarded. Requires crontab.')
+ );
+
+ $form['aggregator_category_selector'] = array(
+ '#type' => 'radios', '#title' => t('Category selection type'), '#default_value' => variable_get('aggregator_category_selector', 'check'),
+ '#options' => array('checkboxes' => t('checkboxes'), 'select' => t('multiple selector')),
+ '#description' => t('The type of category selection widget which is shown on categorization pages. Checkboxes are easier to use; a multiple selector is good for working with large numbers of categories.')
+ );
+ return $form;
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function aggregator_perm() {
+ return array('administer news feeds', 'access news feeds');
+}
+
+/**
+ * Implementation of hook_cron().
+ *
+ * Checks news feeds for updates once their refresh interval has elapsed.
+ */
+function aggregator_cron() {
+ $result = db_query('SELECT * FROM {aggregator_feed} WHERE checked + refresh < %d', time());
+ while ($feed = db_fetch_array($result)) {
+ aggregator_refresh($feed);
+ }
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Generates blocks for the latest news items in each category and feed.
+ */
+function aggregator_block($op, $delta = 0, $edit = array()) {
+ if (user_access('access news feeds')) {
+ if ($op == 'list') {
+ $result = db_query('SELECT cid, title FROM {aggregator_category} ORDER BY title');
+ while ($category = db_fetch_object($result)) {
+ $block['category-'. $category->cid]['info'] = t('%title category latest items', array('%title' => theme('placeholder', $category->title)));
+ }
+ $result = db_query('SELECT fid, title FROM {aggregator_feed} ORDER BY fid');
+ while ($feed = db_fetch_object($result)) {
+ $block['feed-'. $feed->fid]['info'] = t('%title feed latest items', array('%title' => theme('placeholder', $feed->title)));
+ }
+ }
+ else if ($op == 'configure') {
+ list($type, $id) = explode('-', $delta);
+ if ($type == 'category') {
+ $value = db_result(db_query('SELECT block FROM {aggregator_category} WHERE cid = %d', $id));
+ }
+ else {
+ $value = db_result(db_query('SELECT block FROM {aggregator_feed} WHERE fid = %d', $id));
+ }
+ $form['block'] = array('#type' => 'select', '#title' => t('Number of news items in block'), '#default_value' => $value, '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)));
+ return $form;
+ }
+ else if ($op == 'save') {
+ list($type, $id) = explode('-', $delta);
+ if ($type == 'category') {
+ $value = db_query('UPDATE {aggregator_category} SET block = %d WHERE cid = %d', $edit['block'], $id);
+ }
+ else {
+ $value = db_query('UPDATE {aggregator_feed} SET block = %d WHERE fid = %d', $edit['block'], $id);
+ }
+ }
+ else if ($op == 'view') {
+ list($type, $id) = explode('-', $delta);
+ switch ($type) {
+ case 'feed':
+ if ($feed = db_fetch_object(db_query('SELECT fid, title, block FROM {aggregator_feed} WHERE fid = %d', $id))) {
+ $block['subject'] = check_plain($feed->title);
+ $result = db_query_range('SELECT * FROM {aggregator_item} WHERE fid = %d ORDER BY timestamp DESC, iid DESC', $feed->fid, 0, $feed->block);
+ $block['content'] = ''. l(t('more'), 'aggregator/sources/'. $feed->fid, array('title' => t('View this feed\'s recent news.'))) .'
';
+ }
+ break;
+
+ case 'category':
+ if ($category = db_fetch_object(db_query('SELECT cid, title, block FROM {aggregator_category} WHERE cid = %d', $id))) {
+ $block['subject'] = check_plain($category->title);
+ $result = db_query_range('SELECT i.* FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON ci.iid = i.iid WHERE ci.cid = %d ORDER BY i.timestamp DESC, i.iid DESC', $category->cid, 0, $category->block);
+ $block['content'] = ''. l(t('more'), 'aggregator/categories/'. $category->cid, array('title' => t('View this category\'s recent news.'))) .'
';
+ }
+ break;
+ }
+ $items = array();
+ while ($item = db_fetch_object($result)) {
+ $items[] = theme('aggregator_block_item', $item);
+ }
+ $block['content'] = theme('item_list', $items) . $block['content'];
+ }
+ return $block;
+ }
+}
+
+/**
+ * Generate a form to add/edit/delete aggregator categories.
+ */
+ function aggregator_form_category($edit = array()) {
+ $form['title'] = array('#type' => 'textfield',
+ '#title' => t('Title'),
+ '#default_value' => $edit['title'],
+ '#maxlength' => 64,
+ '#required' => TRUE,
+ );
+ $form['description'] = array('#type' => 'textarea',
+ '#title' => t('Description'),
+ '#default_value' => $edit['description'],
+ );
+ $form['submit'] = array('#type' => 'submit', '#value' =>t('Submit'));
+
+ if ($edit['cid']) {
+ $form['delete'] = array('#type' => 'submit', '#value' =>t('Delete'));
+ $form['cid'] = array('#type' => 'hidden', '#value' => $edit['cid']);
+ }
+
+ return drupal_get_form('aggregator_form_category', $form);
+}
+
+/**
+ * Validate aggregator_form_feed form submissions.
+ */
+function aggregator_form_category_validate($form_id, $form_values) {
+ if ($_POST['op'] == t('Submit')) {
+ // Check for duplicate titles
+ if (isset($form_values['cid'])) {
+ $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s' AND cid != %d", $form_values['title'], $form_values['cid']));
+ }
+ else {
+ $category = db_fetch_object(db_query("SELECT cid FROM {aggregator_category} WHERE title = '%s'", $form_values['title']));
+ }
+ if ($category) {
+ form_set_error('title', t('A category named %category already exists. Please enter a unique title.', array('%category' => theme('placeholder', $form_values['title']))));
+ }
+ }
+}
+
+/**
+ * Process aggregator_form_category form submissions.
+ * @todo Add delete confirmation dialog.
+ */
+function aggregator_form_category_submit($form_id, $form_values) {
+ if ($_POST['op'] == t('Delete')) {
+ $title = $form_values['title'];
+ // Unset the title:
+ unset($form_values['title']);
+ }
+ aggregator_save_category($form_values);
+ menu_rebuild();
+ if (isset($form_values['cid'])) {
+ if (isset($form_values['title'])) {
+ drupal_set_message(t('The category %category has been updated.', array('%category' => theme('placeholder', $form_values['title']))));
+ if (arg(0) == 'admin') {
+ return 'admin/aggregator/';
+ }
+ else {
+ return 'aggregator/categories/'. $form_values['cid'];
+ }
+ }
+ else {
+ watchdog('aggregator', t('Category %category deleted.', array('%category' => theme('placeholder', $title))));
+ drupal_set_message(t('The category %category has been deleted.', array('%category' => theme('placeholder', $title))));
+ if (arg(0) == 'admin') {
+ return 'admin/aggregator/';
+ }
+ else {
+ return 'aggregator/categories/';
+ }
+ }
+ }
+ else {
+ watchdog('aggregator', t('Category %category added.', array('%category' => theme('placeholder', $form_values['title']))), WATCHDOG_NOTICE, l(t('view'), 'admin/aggregator'));
+ drupal_set_message(t('The category %category has been added.', array('%category' => theme('placeholder', $form_values['title']))));
+ }
+}
+
+/**
+ * Add/edit/delete aggregator categories.
+ */
+function aggregator_save_category($edit) {
+ if ($edit['cid'] && $edit['title']) {
+ db_query("UPDATE {aggregator_category} SET title = '%s', description = '%s' WHERE cid = %d", $edit['title'], $edit['description'], $edit['cid']);
+ }
+ else if ($edit['cid']) {
+ db_query('DELETE FROM {aggregator_category} WHERE cid = %d', $edit['cid']);
+ }
+ else if ($edit['title']) {
+ // A single unique id for bundles and feeds, to use in blocks
+ $next_id = db_next_id('{aggregator_category}_cid');
+ db_query("INSERT INTO {aggregator_category} (cid, title, description, block) VALUES (%d, '%s', '%s', 5)", $next_id, $edit['title'], $edit['description']);
+ }
+}
+
+/**
+ * Generate a form to add/edit feed sources.
+ */
+function aggregator_form_feed($edit = array()) {
+ $period = drupal_map_assoc(array(900, 1800, 3600, 7200, 10800, 21600, 32400, 43200, 64800, 86400, 172800, 259200, 604800, 1209600, 2419200), 'format_interval');
+
+ if ($edit['refresh'] == '') {
+ $edit['refresh'] = 3600;
+ }
+
+ $form['title'] = array('#type' => 'textfield',
+ '#title' => t('Title'),
+ '#default_value' => $edit['title'],
+ '#maxlength' => 64,
+ '#description' => t('The name of the feed; typically the name of the web site you syndicate content from.'),
+ '#required' => TRUE,
+ );
+ $form['url'] = array('#type' => 'textfield',
+ '#title' => t('URL'),
+ '#default_value' => $edit['url'],
+ '#maxlength' => 255,
+ '#description' => t('The fully-qualified URL of the feed.'),
+ '#required' => TRUE,
+ );
+ $form['refresh'] = array('#type' => 'select',
+ '#title' => t('Update interval'),
+ '#default_value' => $edit['refresh'],
+ '#options' => $period,
+ '#description' => t('The refresh interval indicating how often you want to update this feed. Requires crontab.'),
+ );
+
+ // Handling of categories:
+ $options = array();
+ $values = array();
+ $categories = db_query('SELECT c.cid, c.title, f.fid FROM {aggregator_category} c LEFT JOIN {aggregator_category_feed} f ON c.cid = f.cid AND f.fid = %d ORDER BY title', $edit['fid']);
+ while ($category = db_fetch_object($categories)) {
+ $options[$category->cid] = $category->title;
+ if ($category->fid) $values[] = check_plain($category->cid);
+ }
+ if ($options) {
+ $form['category'] = array('#type' => 'checkboxes',
+ '#title' => t('Categorize news items'),
+ '#default_value' => $values,
+ '#options' => $options,
+ '#description' => t('New items in this feed will be automatically filed in the checked categories as they are received.'),
+ );
+ }
+ $form['submit'] = array('#type' => 'submit', '#value' =>t('Submit'));
+
+ if ($edit['fid']) {
+ $form['delete'] = array('#type' => 'submit', '#value' =>t('Delete'));
+ $form['fid'] = array('#type' => 'hidden', '#value' => $edit['fid']);
+ }
+
+ return drupal_get_form('aggregator_form_feed', $form);
+}
+
+/**
+ * Validate aggregator_form_feed form submissions.
+ */
+function aggregator_form_feed_validate($form_id, $form_values) {
+ if ($_POST['op'] == t('Submit')) {
+ // Check for duplicate titles
+ if (isset($form_values['fid'])) {
+ $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE (title = '%s' OR url='%s') AND fid != %d", $form_values['title'], $form_values['url'], $form_values['fid']);
+ }
+ else {
+ $result = db_query("SELECT title, url FROM {aggregator_feed} WHERE title = '%s' OR url='%s'", $form_values['title'], $form_values['url']);
+ }
+ while ($feed = db_fetch_object($result)) {
+ if (strcasecmp($feed->title, $form_values['title']) == 0) {
+ form_set_error('title', t('A feed named %feed already exists. Please enter a unique title.', array('%feed' => theme('placeholder', $form_values['title']))));
+ }
+ }
+ }
+}
+
+/**
+ * Process aggregator_form_feed form submissions.
+ * @todo Add delete confirmation dialog.
+ */
+function aggregator_form_feed_submit($form_id, $form_values) {
+ if ($_POST['op'] == t('Delete')) {
+ $title = $form_values['title'];
+ // Unset the title:
+ unset($form_values['title']);
+ }
+ aggregator_save_feed($form_values);
+ menu_rebuild();
+ if (isset($form_values['fid'])) {
+ if (isset($form_values['title'])) {
+ drupal_set_message(t('The feed %feed has been updated.', array('%feed' => theme('placeholder', $form_values['title']))));
+ if (arg(0) == 'admin') {
+ return 'admin/aggregator/';
+ }
+ else {
+ return 'aggregator/sources/'. $form_values['fid'];
+ }
+ }
+ else {
+ watchdog('aggregator', t('Feed %feed deleted.', array('%feed' => theme('placeholder', $title))));
+ drupal_set_message(t('The feed %feed has been deleted.', array('%feed' => theme('placeholder', $title))));
+ if (arg(0) == 'admin') {
+ return 'admin/aggregator/';
+ }
+ else {
+ return 'aggregator/sources/';
+ }
+ }
+ }
+ else {
+ watchdog('aggregator', t('Feed %feed added.', array('%feed' => theme('placeholder', $form_values['title']))), WATCHDOG_NOTICE, l(t('view'), 'admin/aggregator'));
+ drupal_set_message(t('The feed %feed has been added.', array('%feed' => theme('placeholder', $form_values['title']))));
+ }
+}
+
+/**
+ * Add/edit/delete an aggregator feed.
+ */
+function aggregator_save_feed($edit) {
+ if ($edit['fid']) {
+ // An existing feed is being modified, delete the category listings.
+ db_query('DELETE FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
+ }
+ if ($edit['fid'] && $edit['title']) {
+ db_query("UPDATE {aggregator_feed} SET title = '%s', url = '%s', refresh = %d WHERE fid = %d", $edit['title'], $edit['url'], $edit['refresh'], $edit['fid']);
+ }
+ else if ($edit['fid']) {
+ $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
+ while ($item = db_fetch_object($result)) {
+ $items[] = "iid = $item->iid";
+ }
+ if ($items) {
+ db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
+ }
+ db_query('DELETE FROM {aggregator_feed} WHERE fid = %d', $edit['fid']);
+ db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $edit['fid']);
+ }
+ else if ($edit['title']) {
+ // A single unique id for bundles and feeds, to use in blocks.
+ $edit['fid'] = db_next_id('{aggregator_feed}_fid');
+ db_query("INSERT INTO {aggregator_feed} (fid, title, url, refresh, block) VALUES (%d, '%s', '%s', %d, 5)", $edit['fid'], $edit['title'], $edit['url'], $edit['refresh']);
+ }
+ if ($edit['title']) {
+ // The feed is being saved, save the categories as well.
+ if ($edit['category']) {
+ foreach ($edit['category'] as $cid => $value) {
+ if ($value) {
+ db_query('INSERT INTO {aggregator_category_feed} (fid, cid) VALUES (%d, %d)', $edit['fid'], $cid);
+ }
+ }
+ }
+ }
+}
+
+function aggregator_remove($feed) {
+ $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
+ while ($item = db_fetch_object($result)) {
+ $items[] = "iid = $item->iid";
+ }
+ if ($items) {
+ db_query('DELETE FROM {aggregator_category_item} WHERE '. implode(' OR ', $items));
+ }
+ db_query('DELETE FROM {aggregator_item} WHERE fid = %d', $feed['fid']);
+ db_query("UPDATE {aggregator_feed} SET checked = 0, etag = '', modified = 0 WHERE fid = %d", $feed['fid']);
+ drupal_set_message(t('The news items from %site have been removed.', array('%site' => theme('placeholder', $feed['title']))));
+}
+
+/**
+ * Call-back function used by the XML parser.
+ */
+function aggregator_element_start($parser, $name, $attributes) {
+ global $item, $element, $tag, $items, $channel;
+
+ switch ($name) {
+ case 'IMAGE':
+ case 'TEXTINPUT':
+ case 'CONTENT':
+ case 'SUMMARY':
+ case 'TAGLINE':
+ case 'SUBTITLE':
+ case 'LOGO':
+ case 'INFO':
+ $element = $name;
+ break;
+ case 'ID':
+ if ($element != 'ITEM') {
+ $element = $name;
+ }
+ case 'LINK':
+ if ($attributes['REL'] == 'alternate') {
+ if ($element == 'ITEM') {
+ $items[$item]['LINK'] = $attributes['HREF'];
+ }
+ else {
+ $channel['LINK'] = $attributes['HREF'];
+ }
+ }
+ break;
+ case 'ITEM':
+ $element = $name;
+ $item += 1;
+ break;
+ case 'ENTRY':
+ $element = 'ITEM';
+ $item += 1;
+ break;
+ }
+
+ $tag = $name;
+}
+
+/**
+ * Call-back function used by the XML parser.
+ */
+function aggregator_element_end($parser, $name) {
+ global $element;
+
+ switch ($name) {
+ case 'IMAGE':
+ case 'TEXTINPUT':
+ case 'ITEM':
+ case 'ENTRY':
+ case 'CONTENT':
+ case 'INFO':
+ $element = '';
+ break;
+ case 'ID':
+ if ($element == 'ID') {
+ $element = '';
+ }
+ }
+}
+
+/**
+ * Call-back function used by the XML parser.
+ */
+function aggregator_element_data($parser, $data) {
+ global $channel, $element, $items, $item, $image, $tag;
+
+ switch ($element) {
+ case 'ITEM':
+ $items[$item][$tag] .= $data;
+ break;
+ case 'IMAGE':
+ case 'LOGO':
+ $image[$tag] .= $data;
+ break;
+ case 'LINK':
+ if ($data) {
+ $items[$item][$tag] .= $data;
+ }
+ break;
+ case 'CONTENT':
+ $items[$item]['CONTENT'] .= $data;
+ break;
+ case 'SUMMARY':
+ $items[$item]['SUMMARY'] .= $data;
+ break;
+ case 'TAGLINE':
+ case 'SUBTITLE':
+ $channel['DESCRIPTION'] .= $data;
+ break;
+ case 'INFO':
+ case 'ID':
+ case 'TEXTINPUT':
+ // The sub-element is not supported. However, we must recognize
+ // it or its contents will end up in the item array.
+ break;
+ default:
+ $channel[$tag] .= $data;
+ }
+}
+
+/**
+ * Checks a news feed for new items.
+ */
+function aggregator_refresh($feed) {
+ global $channel, $image;
+
+ // Generate conditional GET headers.
+ $headers = array();
+ if ($feed['etag']) {
+ $headers['If-None-Match'] = $feed['etag'];
+ }
+ if ($feed['modified']) {
+ $headers['If-Modified-Since'] = gmdate('D, d M Y H:i:s', $feed['modified']) .' GMT';
+ }
+
+ // Request feed.
+ $result = drupal_http_request($feed['url'], $headers);
+
+ // Process HTTP response code.
+ switch ($result->code) {
+ case 304:
+ db_query('UPDATE {aggregator_feed} SET checked = %d WHERE fid = %d', time(), $feed['fid']);
+ drupal_set_message(t('There is no new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
+ break;
+ case 301:
+ $feed['url'] = $result->redirect_url;
+ watchdog('aggregator', t('Updated URL for feed %title to %url.', array('%title' => theme('placeholder', $feed['title']), '%url' => theme('placeholder', $feed['url']))));
+
+ case 200:
+ case 302:
+ case 307:
+ // Filter the input data:
+ if (aggregator_parse_feed($result->data, $feed)) {
+
+ if ($result->headers['Last-Modified']) {
+ $modified = strtotime($result->headers['Last-Modified']);
+ }
+
+ /*
+ ** Prepare the channel data:
+ */
+
+ foreach ($channel as $key => $value) {
+ $channel[$key] = trim($value);
+ }
+
+ /*
+ ** Prepare the image data (if any):
+ */
+
+ foreach ($image as $key => $value) {
+ $image[$key] = trim($value);
+ }
+
+ if ($image['LINK'] && $image['URL'] && $image['TITLE']) {
+ // Note, we should really use theme_image() here but that only works with local images it won't work with images fetched with a URL unless PHP version > 5
+ $image = '';
+ }
+ else {
+ $image = NULL;
+ }
+
+ /*
+ ** Update the feed data:
+ */
+
+ db_query("UPDATE {aggregator_feed} SET url = '%s', checked = %d, link = '%s', description = '%s', image = '%s', etag = '%s', modified = %d WHERE fid = %d", $feed['url'], time(), $channel['LINK'], $channel['DESCRIPTION'], $image, $result->headers['ETag'], $modified, $feed['fid']);
+
+ /*
+ ** Clear the cache:
+ */
+
+ cache_clear_all();
+
+ watchdog('aggregator', t('There is new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
+ drupal_set_message(t('There is new syndicated content from %site.', array('%site' => theme('placeholder', $feed['title']))));
+ }
+ break;
+ default:
+ watchdog('aggregator', t('The RSS-feed from %site seems to be broken, due to "%error".', array('%site' => theme('placeholder', $feed['title']), '%error' => theme('placeholder', $result->code .' '. $result->error))), WATCHDOG_WARNING);
+ drupal_set_message(t('The RSS-feed from %site seems to be broken, because of error "%error".', array('%site' => theme('placeholder', $feed['title']), '%error' => theme('placeholder', $result->code .' '. $result->error))));
+ }
+}
+
+/**
+ * Parse the W3C date/time format, a subset of ISO 8601. PHP date parsing
+ * functions do not handle this format.
+ * See http://www.w3.org/TR/NOTE-datetime for more information.
+ * Originally from MagpieRSS (http://magpierss.sourceforge.net/).
+ *
+ * @param $date_str A string with a potentially W3C DTF date.
+ * @return A timestamp if parsed successfully or -1 if not.
+ */
+function aggregator_parse_w3cdtf($date_str) {
+ if (preg_match('/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/', $date_str, $match)) {
+ list($year, $month, $day, $hours, $minutes, $seconds) = array($match[1], $match[2], $match[3], $match[4], $match[5], $match[6]);
+ // calc epoch for current date assuming GMT
+ $epoch = gmmktime($hours, $minutes, $seconds, $month, $day, $year);
+ if ($match[10] != 'Z') { // Z is zulu time, aka GMT
+ list($tz_mod, $tz_hour, $tz_min) = array($match[8], $match[9], $match[10]);
+ // zero out the variables
+ if (!$tz_hour) {
+ $tz_hour = 0;
+ }
+ if (!$tz_min) {
+ $tz_min = 0;
+ }
+ $offset_secs = (($tz_hour * 60) + $tz_min) * 60;
+ // is timezone ahead of GMT? then subtract offset
+ if ($tz_mod == '+') {
+ $offset_secs *= -1;
+ }
+ $epoch += $offset_secs;
+ }
+ return $epoch;
+ }
+ else {
+ return FALSE;
+ }
+}
+
+function aggregator_parse_feed(&$data, $feed) {
+ global $items, $image, $channel;
+
+ // Unset the global variables before we use them:
+ unset($GLOBALS['element'], $GLOBALS['item'], $GLOBALS['tag']);
+ $items = array();
+ $image = array();
+ $channel = array();
+
+ // parse the data:
+ $xml_parser = drupal_xml_parser_create($data);
+ xml_set_element_handler($xml_parser, 'aggregator_element_start', 'aggregator_element_end');
+ xml_set_character_data_handler($xml_parser, 'aggregator_element_data');
+
+ if (!xml_parse($xml_parser, $data, 1)) {
+ watchdog('aggregator', t('The RSS-feed from %site seems to be broken, due to an error "%error" on line %line.', array('%site' => theme('placeholder', $feed['title']), '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), WATCHDOG_WARNING);
+ drupal_set_message(t('The RSS-feed from %site seems to be broken, because of error "%error" on line %line.', array('%site' => theme('placeholder', $feed['title']), '%error' => xml_error_string(xml_get_error_code($xml_parser)), '%line' => xml_get_current_line_number($xml_parser))), 'error');
+ return 0;
+ }
+ xml_parser_free($xml_parser);
+
+ /*
+ ** We reverse the array such that we store the first item last,
+ ** and the last item first. In the database, the newest item
+ ** should be at the top.
+ */
+
+ $items = array_reverse($items);
+
+ foreach ($items as $item) {
+ unset($title, $link, $author, $description);
+
+ // Prepare the item:
+ foreach ($item as $key => $value) {
+ $item[$key] = trim($value);
+ }
+
+ /*
+ ** Resolve the item's title. If no title is found, we use
+ ** up to 40 characters of the description ending at a word
+ ** boundary but not splitting potential entities.
+ */
+
+ if ($item['TITLE']) {
+ $title = $item['TITLE'];
+ }
+ else {
+ $title = preg_replace('/^(.*)[^\w;&].*?$/', "\\1", truncate_utf8($item['DESCRIPTION'], 40));
+ }
+
+ /*
+ ** Resolve the items link.
+ */
+
+ if ($item['LINK']) {
+ $link = $item['LINK'];
+ }
+ elseif ($item['GUID'] && (strncmp($item['GUID'], 'http://', 7) == 0)) {
+ $link = $item['GUID'];
+ }
+ else {
+ $link = $feed['link'];
+ }
+
+ /**
+ * Atom feeds have a CONTENT and/or SUMMARY tag instead of a DESCRIPTION tag
+ */
+ if ($item['CONTENT:ENCODED']) {
+ $item['DESCRIPTION'] = $item['CONTENT:ENCODED'];
+ }
+ else if ($item['SUMMARY']) {
+ $item['DESCRIPTION'] = $item['SUMMARY'];
+ }
+
+ /*
+ ** Try to resolve and parse the item's publication date. If no
+ ** date is found, we use the current date instead.
+ */
+
+ if ($item['PUBDATE']) $date = $item['PUBDATE']; // RSS 2.0
+ else if ($item['DC:DATE']) $date = $item['DC:DATE']; // Dublin core
+ else if ($item['DCTERMS:ISSUED']) $date = $item['DCTERMS:ISSUED']; // Dublin core
+ else if ($item['DCTERMS:CREATED']) $date = $item['DCTERMS:CREATED']; // Dublin core
+ else if ($item['DCTERMS:MODIFIED']) $date = $item['DCTERMS:MODIFIED']; // Dublin core
+ else if ($item['ISSUED']) $date = $item['ISSUED']; // Atom XML
+ else if ($item['CREATED']) $date = $item['CREATED']; // Atom XML
+ else if ($item['MODIFIED']) $date = $item['MODIFIED']; // Atom XML
+ else $date = 'now';
+
+ $timestamp = strtotime($date); // As of PHP 5.1.0, strtotime returns FALSE on failure instead of -1.
+ if ($timestamp <= 0) {
+ $timestamp = aggregator_parse_w3cdtf($date); // Returns FALSE on failure
+ if (!$timestamp) {
+ $timestamp = time(); // better than nothing
+ }
+ }
+
+ /*
+ ** Save this item. Try to avoid duplicate entries as much as
+ ** possible. If we find a duplicate entry, we resolve it and
+ ** pass along it's ID such that we can update it if needed.
+ */
+
+ if ($link && $link != $feed['link'] && $link != $feed['url']) {
+ $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND link = '%s'", $feed['fid'], $link));
+ }
+ else {
+ $entry = db_fetch_object(db_query("SELECT iid FROM {aggregator_item} WHERE fid = %d AND title = '%s'", $feed['fid'], $title));
+ }
+
+ aggregator_save_item(array('iid' => $entry->iid, 'fid' => $feed['fid'], 'timestamp' => $timestamp, 'title' => $title, 'link' => $link, 'author' => $item['AUTHOR'], 'description' => $item['DESCRIPTION']));
+ }
+
+ /*
+ ** Remove all items that are older than flush item timer:
+ */
+
+ $age = time() - variable_get('aggregator_clear', 9676800);
+ $result = db_query('SELECT iid FROM {aggregator_item} WHERE fid = %d AND timestamp < %d', $feed['fid'], $age);
+
+ if (db_num_rows($result)) {
+ $items = array();
+ while ($item = db_fetch_object($result)) {
+ $items[] = $item->iid;
+ }
+ db_query('DELETE FROM {aggregator_category_item} WHERE iid IN ('. implode(', ', $items) .')');
+ db_query('DELETE FROM {aggregator_item} WHERE fid = %d AND timestamp < %d', $feed['fid'], $age);
+ }
+
+ return 1;
+}
+
+function aggregator_save_item($edit) {
+ if ($edit['iid'] && $edit['title']) {
+ db_query("UPDATE {aggregator_item} SET title = '%s', link = '%s', author = '%s', description = '%s' WHERE iid = %d", $edit['title'], $edit['link'], $edit['author'], $edit['description'], $edit['iid']);
+ }
+ else if ($edit['iid']) {
+ db_query('DELETE FROM {aggregator_item} WHERE iid = %d', $edit['iid']);
+ db_query('DELETE FROM {aggregator_category_item} WHERE iid = %d', $edit['iid']);
+ }
+ else if ($edit['title'] && $edit['link']) {
+ $edit['iid'] = db_next_id('{aggregator_item}_iid');
+ db_query("INSERT INTO {aggregator_item} (iid, fid, title, link, author, description, timestamp) VALUES (%d, %d, '%s', '%s', '%s', '%s', %d)", $edit['iid'], $edit['fid'], $edit['title'], $edit['link'], $edit['author'], $edit['description'], $edit['timestamp']);
+ // file the items in the categories indicated by the feed
+ $categories = db_query('SELECT cid FROM {aggregator_category_feed} WHERE fid = %d', $edit['fid']);
+ while ($category = db_fetch_object($categories)) {
+ db_query('INSERT INTO {aggregator_category_item} (cid, iid) VALUES (%d, %d)', $category->cid, $edit['iid']);
+ }
+ }
+}
+
+function aggregator_get_feed($fid) {
+ return db_fetch_array(db_query('SELECT * FROM {aggregator_feed} WHERE fid = %d', $fid));
+}
+
+function aggregator_get_category($cid) {
+ return db_fetch_array(db_query('SELECT * FROM {aggregator_category} WHERE cid = %d', $cid));
+}
+
+function aggregator_view() {
+ $result = db_query('SELECT f.*, COUNT(i.iid) AS items FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.url, f.refresh, f.checked, f.link, f.description, f.etag, f.modified, f.image, f.block ORDER BY f.title');
+
+ $output .= ''. t('Feed overview') .'
';
+
+ $header = array(t('Title'), t('Items'), t('Last update'), t('Next update'), array('data' => t('Operations'), 'colspan' => '3'));
+ $rows = array();
+ while ($feed = db_fetch_object($result)) {
+ $rows[] = array(l($feed->title, "aggregator/sources/$feed->fid"), format_plural($feed->items, '1 item', '%count items'), ($feed->checked ? t('%time ago', array('%time' => format_interval(time() - $feed->checked))) : t('never')), ($feed->checked ? t('%time left', array('%time' => format_interval($feed->checked + $feed->refresh - time()))) : t('never')), l(t('edit'), "admin/aggregator/edit/feed/$feed->fid"), l(t('remove items'), "admin/aggregator/remove/$feed->fid"), l(t('update items'), "admin/aggregator/update/$feed->fid"));
+ }
+ $output .= theme('table', $header, $rows);
+
+ $result = db_query('SELECT c.cid, c.title, count(ci.iid) as items FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid GROUP BY c.cid, c.title ORDER BY title');
+
+ $output .= ''. t('Category overview') .'
';
+
+ $header = array(t('Title'), t('Items'), t('Operations'));
+ $rows = array();
+ while ($category = db_fetch_object($result)) {
+ $rows[] = array(l($category->title, "aggregator/categories/$category->cid"), format_plural($category->items, '1 item', '%count items'), l(t('edit'), "admin/aggregator/edit/category/$category->cid"));
+ }
+ $output .= theme('table', $header, $rows);
+
+ return $output;
+}
+
+/**
+ * Menu callback; removes all items from a feed, then redirects to the overview page.
+ */
+function aggregator_admin_remove_feed($feed) {
+ aggregator_remove(aggregator_get_feed($feed));
+ drupal_goto('admin/aggregator');
+}
+
+/**
+ * Menu callback; refreshes a feed, then redirects to the overview page.
+ */
+function aggregator_admin_refresh_feed($feed) {
+ aggregator_refresh(aggregator_get_feed($feed));
+ drupal_goto('admin/aggregator');
+}
+
+/**
+ * Menu callback; displays the aggregator administration page.
+ */
+function aggregator_admin_overview() {
+ return aggregator_view();
+}
+
+/**
+ * Menu callback; displays the most recent items gathered from any feed.
+ */
+function aggregator_page_last() {
+ return _aggregator_page_list('SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_item} i INNER JOIN {aggregator_feed} f ON i.fid = f.fid ORDER BY i.timestamp DESC, i.iid DESC', arg(1));
+}
+
+/**
+ * Menu callback; displays all the items captured from a particular feed.
+ */
+function aggregator_page_source() {
+ $feed = db_fetch_object(db_query('SELECT * FROM {aggregator_feed} WHERE fid = %d', arg(2)));
+ $info = theme('aggregator_feed', $feed);
+
+ return _aggregator_page_list('SELECT * FROM {aggregator_item} WHERE fid = '. $feed->fid .' ORDER BY timestamp DESC, iid DESC', arg(3), $info);
+}
+
+/**
+ * Menu callback; displays all the items aggregated in a particular category.
+ */
+function aggregator_page_category() {
+ $category = db_fetch_object(db_query('SELECT cid, title FROM {aggregator_category} WHERE cid = %d', arg(2)));
+
+ return _aggregator_page_list('SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_category_item} c LEFT JOIN {aggregator_item} i ON c.iid = i.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE cid = '. $category->cid .' ORDER BY timestamp DESC, iid DESC', arg(3));
+}
+
+/**
+ * Prints an aggregator page listing a number of feed items. Various
+ * menu callbacks use this function to print their feeds.
+ */
+function _aggregator_page_list($sql, $op, $header = '') {
+ $categorize = (user_access('administer news feeds') && ($op == 'categorize'));
+
+ $output = '';
+
+ $form['header'] = array('#value' => $header);
+ $output .= $form['header']['#value'];
+
+ $result = pager_query($sql, 20);
+ $categories = array();
+ while ($item = db_fetch_object($result)) {
+ $form['items'][$item->iid] = array('#value' => theme('aggregator_page_item', $item));
+ $output .= $form['items'][$item->iid]['#value'];
+ $form['categories'][$item->iid] = array();
+
+ if ($categorize) {
+
+ $categories_result = db_query('SELECT c.cid, c.title, ci.iid FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid AND ci.iid = %d', $item->iid);
+ $selected = array();
+ while ($category = db_fetch_object($categories_result)) {
+ if (!$done) {
+ $categories[$category->cid] = check_plain($category->title);
+ }
+ if ($category->iid) {
+ $selected[] = $category->cid;
+ }
+ }
+ $done = true;
+ $form['categories'][$item->iid] = array(
+ '#type' => variable_get('aggregator_category_selector', 'checkboxes'),
+ '#default_value' => $selected, '#options' => $categories,
+ '#size' => 10, '#multiple' => true
+ );
+ }
+ }
+ $output .= '
';
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Save categories'));
+ $form['pager'] = array('#value' => theme('pager', NULL, 20, 0));
+ $output .= $form['pager']['#value'];
+
+ // arg(1) is undefined if we are at the top aggregator URL
+ // is there a better way to do this?
+ if (!arg(1)) {
+ $form['feed_icon'] = array('#value' => theme('feed_icon', url('aggregator/rss')));
+ }
+ elseif (arg(1) == 'categories' && arg(2) && !arg(3)) {
+ $form['feed_icon'] = array('#value' => theme('feed_icon', url('aggregator/rss/' . arg(2))));
+ }
+ $output .= $form['feed_icon']['#value'];
+
+ return ($categorize) ? drupal_get_form('aggregator_page_list', $form) : $output;
+}
+
+function theme_aggregator_page_list($form) {
+ $output = '';
+ $output .= form_render($form['header']);
+ $rows = array();
+ if ($form['items']) {
+ foreach (element_children($form['items']) as $key) {
+ if (is_array($form['items'][$key])) {
+ $rows[] = array(form_render($form['items'][$key]), array('data' => form_render($form['categories'][$key]), 'class' => 'categorize-item'));
+ }
+ }
+ }
+ $output .= theme('table', array('', t('Categorize')), $rows);
+ $output .= form_render($form['submit']);
+ $output .= '
';
+ $output .= form_render($form);
+ return $output;
+}
+
+function aggregator_page_list_validate($form_id, &$form) {
+ if (!user_access('administer news feeds')) {
+ form_error($form, t('You are not allowed to categorize this feed item.'));
+ }
+}
+
+function aggregator_page_list_submit($form_id, $form_values) {
+ foreach ($form_values as $iid => $selection) {
+ db_query('DELETE FROM {aggregator_category_item} WHERE iid = %d', $iid);
+ foreach ($selection as $cid) {
+ if ($cid) {
+ db_query('INSERT INTO {aggregator_category_item} (cid, iid) VALUES (%d, %d)', $cid, $iid);
+ }
+ }
+ }
+ drupal_set_message(t('The categories have been saved.'));
+}
+
+/**
+ * Menu callback; displays all the feeds used by the aggregator.
+ */
+function aggregator_page_sources() {
+ $result = db_query('SELECT f.fid, f.title, f.description, f.image, MAX(i.timestamp) AS last FROM {aggregator_feed} f LEFT JOIN {aggregator_item} i ON f.fid = i.fid GROUP BY f.fid, f.title, f.description, f.image ORDER BY last DESC, f.title');
+ $output = "\n";
+ while ($feed = db_fetch_object($result)) {
+ $output .= '
'. check_plain($feed->title) ."
\n";
+
+ // Most recent items:
+ $list = array();
+ if (variable_get('aggregator_summary_items', 3)) {
+ $items = db_query_range('SELECT i.title, i.timestamp, i.link FROM {aggregator_item} i WHERE i.fid = %d ORDER BY i.timestamp DESC', $feed->fid, 0, variable_get('aggregator_summary_items', 3));
+ while ($item = db_fetch_object($items)) {
+ $list[] = theme('aggregator_summary_item', $item);
+ }
+ }
+ $output .= theme('item_list', $list);
+ $output .= '
'. theme('links', array(l(t('more'), 'aggregator/sources/'. $feed->fid))) ."
\n";
+ }
+ $output .= theme('xml_icon', url('aggregator/opml'));
+ $output .= '
';
+ return $output;
+}
+
+/**
+ * Menu callback; generate an RSS 0.92 feed of aggregator items or categories.
+ */
+function aggregator_page_rss() {
+ // arg(2) is the passed cid, only select for that category
+ $result = NULL;
+ if (arg(2)) {
+ $category = db_fetch_object(db_query('SELECT cid, title FROM {aggregator_category} WHERE cid = %d', arg(2)));
+ $url = '/categories/' . $category->cid;
+ $title = ' ' . t('in category') . ' ' . $category->title;
+ $sql = 'SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_category_item} c LEFT JOIN {aggregator_item} i ON c.iid = i.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE cid = %d ORDER BY timestamp DESC, iid DESC';
+ $result = db_query_range($sql, $category->cid, 0, variable_get('feed_default_items', 10));
+ }
+ // or, get the default aggregator items
+ else {
+ $sql = 'SELECT i.*, f.title AS ftitle, f.link AS flink FROM {aggregator_item} i INNER JOIN {aggregator_feed} f ON i.fid = f.fid ORDER BY i.timestamp DESC, i.iid DESC';
+ $result = db_query_range($sql, 0, variable_get('feed_default_items', 10));
+ }
+
+ while ($item = db_fetch_object($result)) {
+ switch (variable_get('feed_item_length', 'teaser')) {
+ case 'teaser':
+ $teaser = node_teaser($item->description);
+ if ($teaser != $item->description) {
+ $teaser .= ''. t('read more') ."
\n";
+ }
+ $item->description = $teaser;
+ break;
+ case 'title':
+ $item->description = '';
+ break;
+ }
+ $items .= format_rss_item($item->ftitle . ': ' . $item->title, $item->link, $item->description, array('pubDate' => date('r', $item->timestamp)));
+ }
+
+ $output .= "\n";
+ $output .= "\n";
+ $output .= format_rss_channel(variable_get('site_name', t('Drupal')) . ' ' . t('aggregator'), url('aggregator' . $url, NULL, NULL, TRUE), variable_get('site_name', t('Drupal')) . ' - ' . t('aggregated feeds') . $title, $items, 'en');
+ $output .= "\n";
+
+ drupal_set_header('Content-Type: application/rss+xml; charset=utf-8');
+ print $output;
+}
+
+/**
+ * Menu callback; generates an OPML representation of all feeds.
+ */
+function aggregator_page_opml($cid = NULL) {
+ if ($cid) {
+ $result = db_query('SELECT f.title, f.url FROM {aggregator_feed} f LEFT JOIN {aggregator_category_feed} c on f.fid = c.fid WHERE c.cid = %d ORDER BY title', $cid);
+ }
+ else {
+ $result = db_query('SELECT * FROM {aggregator_feed} ORDER BY title');
+ }
+
+ $output = "\n";
+ $output .= "\n";
+ $output .= "\n";
+ $output .= ''. check_plain(variable_get('site_name', 'Drupal')) ."\n";
+ $output .= ''. gmdate('r') ."\n";
+ $output .= "\n";
+ $output .= "\n";
+
+ while ($feed = db_fetch_object($result)) {
+ $output .= '\n";
+ }
+
+ $output .= "\n";
+ $output .= "\n";
+
+ drupal_set_header('Content-Type: text/xml; charset=utf-8');
+ print $output;
+}
+
+/**
+ * Menu callback; displays all the categories used by the aggregator.
+ */
+function aggregator_page_categories() {
+ $result = db_query('SELECT c.cid, c.title, c.description FROM {aggregator_category} c LEFT JOIN {aggregator_category_item} ci ON c.cid = ci.cid LEFT JOIN {aggregator_item} i ON ci.iid = i.iid GROUP BY c.cid, c.title, c.description');
+ $output = "\n";
+
+ while ($category = db_fetch_object($result)) {
+ $output .= '
'. check_plain($category->title) ."
\n";
+ if (variable_get('aggregator_summary_items', 3)) {
+ $list = array();
+ $items = db_query_range('SELECT i.title, i.timestamp, i.link, f.title as feed_title, f.link as feed_link FROM {aggregator_category_item} ci LEFT JOIN {aggregator_item} i ON i.iid = ci.iid LEFT JOIN {aggregator_feed} f ON i.fid = f.fid WHERE ci.cid = %d ORDER BY i.timestamp DESC', $category->cid, 0, variable_get('aggregator_summary_items', 3));
+ while ($item = db_fetch_object($items)) {
+ $list[] = theme('aggregator_summary_item', $item);
+ }
+ $output .= theme('item_list', $list);
+ }
+ $output .= '
'. theme('links', array(l(t('more'), 'aggregator/categories/'. $category->cid))) ."
\n";
+ }
+ $output .= '
';
+
+ return $output;
+}
+
+/**
+ * Format a news feed.
+ *
+ * @ingroup themeable
+ */
+function theme_aggregator_feed($feed) {
+ $output = '';
+ $output .= theme('feed_icon', $feed->url) ."\n";
+ $output .= $feed->image;
+ $output .= '
'. aggregator_filter_xss($feed->description) ."
\n";
+ $output .= '
'. t('URL:') .' '. l($feed->link, $feed->link, array(), NULL, NULL, TRUE) ."
\n";
+
+ if ($feed->checked) {
+ $updated = t('%time ago', array('%time' => format_interval(time() - $feed->checked)));
+ }
+ else {
+ $updated = t('never');
+ }
+
+ if (user_access('administer news feeds')) {
+ $updated = l($updated, 'admin/aggregator');
+ }
+
+ $output .= '
'. t('Updated:') . " $updated
";
+ $output .= "
\n";
+
+ return $output;
+}
+
+/**
+ * Format an individual feed item for display in the block.
+ *
+ * @ingroup themeable
+ */
+function theme_aggregator_block_item($item, $feed = 0) {
+ global $user;
+
+ if ($user->uid && module_exist('blog') && user_access('edit own blog')) {
+ if ($image = theme('image', 'misc/blog.png', t('blog it'), t('blog it'))) {
+ $output .= ''. l($image, 'node/add/blog', array('title' => t('Comment on this news item in your personal blog.'), 'class' => 'blog-it'), "iid=$item->iid", NULL, FALSE, TRUE) .'
';
+ }
+ }
+
+ // Display the external link to the item.
+ $output .= ''. check_plain($item->title) ."\n";
+
+ return $output;
+}
+
+/**
+ * Return a themed item heading for summary pages located at "aggregator/sources"
+ * and "aggregator/categories".
+ *
+ * @param $item The item object from the aggregator module.
+ * @return A string containing the output.
+ *
+ * @ingroup themeable
+ */
+function theme_aggregator_summary_item($item) {
+ $output = ''. check_plain($item->title) .' '. t('%age old', array('%age' => format_interval(time() - $item->timestamp))) .'';
+ if ($item->feed_link) {
+ $output .= ', '. check_plain($item->feed_title) .'';
+ }
+ return $output ."\n";
+}
+
+/**
+ * Format an individual feed item for display on the aggregator page.
+ *
+ * @ingroup themeable
+ */
+function theme_aggregator_page_item($item) {
+
+ $source = '';
+ if ($item->ftitle && $item->fid) {
+ $source = l($item->ftitle, "aggregator/sources/$item->fid", array('class' => 'feed-item-source')) . ' -';
+ }
+
+ if (date('Ymd', $item->timestamp) == date('Ymd')) {
+ $source_date = t('%ago ago', array('%ago' => format_interval(time() - $item->timestamp)));
+ }
+ else {
+ $source_date = format_date($item->timestamp, 'custom', variable_get('date_format_medium', 'D, Y-m-d H:i'));
+ }
+
+ $output .= "\n";
+ $output .= '
\n";
+ $output .= "
$source $source_date
\n";
+
+ if ($item->description) {
+ $output .= '
'. aggregator_filter_xss($item->description) ."
\n";
+ }
+
+ $result = db_query('SELECT c.title, c.cid FROM {aggregator_category_item} ci LEFT JOIN {aggregator_category} c ON ci.cid = c.cid WHERE ci.iid = %d ORDER BY c.title', $item->iid);
+ $categories = array();
+ while ($category = db_fetch_object($result)) {
+ $categories[] = l($category->title, 'aggregator/categories/'. $category->cid);
+ }
+ if ($categories) {
+ $output .= '
'. t('Categories') .': '. implode(', ', $categories) ."
\n";
+ }
+
+ $output .= "
\n";
+
+ return $output;
+}
+
+/**
+ * Safely render HTML content, as allowed.
+ */
+function aggregator_filter_xss($value) {
+ return filter_xss($value, preg_split('/\s+|<|>/', variable_get("aggregator_allowed_html_tags", '
-
-
-
'), -1, PREG_SPLIT_NO_EMPTY));
+}
+
+/**
+ * Helper function for drupal_map_assoc.
+ */
+function _aggregator_items($count) {
+ return format_plural($count, '1 item', '%count items');
+}
diff --git a/modules/archive.module b/modules/archive.module
new file mode 100644
index 0000000..d015cb5
--- /dev/null
+++ b/modules/archive.module
@@ -0,0 +1,291 @@
+'. t('The archive page allows content to be viewed by date. It also provides a monthly calendar view that users can use to navigate through content.') .'
';
+ $output .= ''. t('To view the archive by date, select the date in the calendar. Administrators can enable the browse archives block in block administration to allow users to browse by calendar. Clicking on a date in the monthly calendar view shows the content for that date. Users can navigate to different months using arrows beside the month\'s name in the calendar display. The current date will be highlighted in the calendar.') .'
';
+ $output .= t('You can
+
+', array('%archive' => url('archive'), '%admin-block' => url('admin/block')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Archive page.', array('%archive' => 'http://drupal.org/handbook/modules/archive/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Displays a calendar for navigating older content.');
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function archive_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array('path' => 'archive',
+ 'title' => t('archives'),
+ 'access' => user_access('access content'),
+ 'callback' => 'archive_page',
+ 'type' => MENU_SUGGESTED_ITEM);
+ }
+ return $items;
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Generates a calendar for the current month, with links to the archives
+ * for each day.
+ */
+function archive_block($op = 'list', $delta = 0) {
+ if ($op == 'list') {
+ $blocks[0]['info'] = t('Calendar to browse archives');
+ return $blocks;
+ }
+ else if ($op == 'view' && user_access('access content')) {
+ $block['subject'] = t('Browse archives');
+ $block['content'] = archive_calendar();
+ return $block;
+ }
+}
+
+/**
+ * Generates a monthly calendar, for display in the archive block.
+ */
+function archive_calendar() {
+ global $user;
+
+ // Extract today's date:
+ $start_of_today = mktime(0, 0, 0, date('n', time()), date('d', time()), date('Y', time())) + $user->timezone;
+ $end_of_today = mktime(23, 59, 59, date('n', time()), date('d', time()), date('Y', time())) + $user->timezone;
+
+ // Extract the requested date:
+ if (arg(0) == 'archive' && arg(3)) {
+ $year = arg(1);
+ $month = arg(2);
+ $day = arg(3);
+
+ $requested = mktime(0, 0, 0, $month, $day, $year) + $user->timezone;
+ }
+ else {
+ $year = date('Y', time());
+ $month = date('n', time());
+ $day = date('d', time());
+
+ $requested = $end_of_today + $user->timezone;
+ }
+
+ $start_of_month = mktime(0, 0, 0, $month, 1, $year);
+
+ // Extract first day of the month:
+ $first = date('w', $start_of_month);
+
+ // Extract last day of the month:
+ $last = date('t', $start_of_month);
+
+ $end_of_month = mktime(23, 59, 59, $month, $last, $year);
+
+ $cache = cache_get("archive:calendar:$day-$month-$year");
+
+ if (!empty($cache)) {
+ return $cache->data;
+ }
+
+ // Calculate previous and next months dates and check for shorter months (28/30 days)
+ $prevmonth = mktime(23, 59, 59, $month - 1, 1, $year);
+ $prev = mktime(23, 59, 59, $month - 1, min(date('t', $prevmonth), $day), $year);
+ $nextmonth = mktime(23, 59, 59, $month + 1, 1, $year);
+ $next = mktime(23, 59, 59, $month + 1, min(date('t', $nextmonth), $day), $year);
+
+ $sql = 'SELECT n.nid, n.created FROM {node} n WHERE n.status = 1 AND n.created > %d AND n.created < %d ORDER BY n.created';
+ $sql = db_rewrite_sql($sql);
+ $result = db_query($sql, $start_of_month, $end_of_month);
+
+ $days_with_posts = array();
+ while ($day_with_post = db_fetch_object($result)) {
+ $daynum = date('j', $day_with_post->created + $user->timezone);
+ if (isset($days_with_posts[$daynum])) {
+ $days_with_posts[$daynum]++;
+ }
+ else {
+ $days_with_posts[$daynum] = 1;
+ }
+ }
+
+ // Generate calendar header:
+ $output .= "\n\n";
+ $output .= '';
+ $output .= '
\n";
+ $output .= ' '. l('«', 'archive/'. date('Y/m/d', $prev), array('title' => t('Previous month'))) .' '. format_date($requested, 'custom', 'F') . date(' Y', $requested) .' '. ($nextmonth <= time() ? l('»', 'archive/'. date('Y/m/d', $next), array('title' => t('Next month'))) : ' ') ."\n";
+
+ // First day of week (0 => Sunday, 1 => Monday, ...)
+ $weekstart = variable_get('date_first_day', 0);
+
+ // Last day of week
+ ($weekstart - 1 == -1) ? $lastday = 6 : $lastday = $weekstart - 1;
+
+ // Generate the days of the week:
+ $firstcolumn = mktime(0, 0, 0, 3, 20 + $weekstart, 1994);
+
+ $output .= " \n";
+
+ // Initialize temporary variables:
+ $nday = 1;
+ $sday = $first;
+
+ // Loop through all the days of the month:
+ while ($nday <= $last) {
+ // Set up blank days for first week of the month (allowing individual blank day styling):
+ if ($first != $weekstart) {
+ $blankdays = ($first - $weekstart + 7) % 7;
+ $output .= " " . str_repeat(" | \n", $blankdays);
+ $first = $weekstart;
+ }
+ // Start every week on a new line:
+ if ($sday == $weekstart) {
+ $output .= "
\n";
+ }
+
+ // Print one cell:
+ $date = mktime(0, 0, 0, $month, $nday, $year) + $user->timezone;
+ if (isset($days_with_posts[$nday])) {
+ $daytext = l($nday, "archive/$year/$month/$nday", array("title" => format_plural($days_with_posts[$nday], "1 post", "%count posts")));
+ $dayclass = 'day-link';
+ }
+ else {
+ $daytext = $nday;
+ $dayclass = 'day-normal';
+ }
+ if ($date == $requested) {
+ $output .= " $daytext | \n";
+ }
+ else if ($date == $start_of_today) {
+ $output .= " $daytext | \n";
+ }
+ else if ($date > $end_of_today) {
+ $output .= " $daytext | \n";
+ }
+ else {
+ $output .= " $daytext | \n";
+ }
+
+ // Start every week on a new line:
+ if ($sday == $lastday) {
+ $output .= "
\n";
+ }
+
+ // Update temporary variables:
+ $sday++;
+ $sday = $sday % 7;
+ $nday++;
+ }
+
+ // Complete the calendar (allowing individual blank day styling):
+ if ($sday != $weekstart) {
+ $end = (7 - $sday + $weekstart) % 7;
+ $output .= str_repeat(" | \n", $end) . "\n";
+ }
+
+ $output .= "
\n\n";
+
+ cache_set("archive:calendar:$day-$month-$year", $output, CACHE_TEMPORARY);
+
+ return $output;
+}
+
+/**
+ * Menu callback; lists all nodes posted on a given date.
+ */
+function archive_page($year = 0, $month = 0, $day = 0) {
+ global $user;
+
+ $date = mktime(0, 0, 0, $month, $day, $year) - $user->timezone;
+ $date_end = mktime(0, 0, 0, $month, $day + 1, $year) - $user->timezone;
+
+ // Display form.
+ $output = archive_browse_form($year, $month, $day);
+
+ if ($year && $month && $day) {
+ // Fetch nodes for the selected date, if one was specified.
+ $sql = 'SELECT n.nid, n.created FROM {node} n WHERE n.status = 1 AND n.created > %d AND n.created < %d ORDER BY n.created';
+ $sql = db_rewrite_sql($sql);
+ $result = db_query_range($sql, $date, $date_end, 0, 20);
+ if (db_num_rows($result) > 0) {
+ while ($nid = db_fetch_object($result)) {
+ $output .= node_view(node_load($nid->nid), 1);
+ }
+ }
+ else {
+ $output .= theme('box', t('No posts found.'), '');
+ }
+ }
+ else {
+ $output .= theme('box', t('No posts found.'), '');
+ }
+
+ return $output;
+}
+
+/**
+ * Generate a form that retrieves archives for a certain date.
+ */
+function archive_browse_form($year, $month, $day) {
+ // Prepare the values of the form fields.
+ $years = drupal_map_assoc(range(2000, date('Y')));
+ $months = array(1 => t('January'), 2 => t('February'), 3 => t('March'), 4 => t('April'), 5 => t('May'), 6 => t('June'), 7 => t('July'), 8 => t('August'), 9 => t('September'), 10 => t('October'), 11 => t('November'), 12 => t('December'));
+ $days = drupal_map_assoc(range(1, 31));
+
+ $form['year'] = array('#type' => 'select',
+ '#default_value' => ($year ? $year : date('Y')),
+ '#options' => $years,
+ );
+ $form['month'] = array('#type' => 'select',
+ '#default_value' => ($month ? $month : date('m')),
+ '#options' => $months,
+ );
+ $form['day'] = array('#type' => 'select',
+ '#default_value' => ($day ? $day : date('d')),
+ '#options' => $days,
+ );
+ $form['show'] = array('#type' => 'submit',
+ '#value' => t('Show'),
+ );
+
+ return drupal_get_form('archive_browse_form', $form);
+}
+
+/**
+ * Process archive browse form submission.
+ */
+function archive_browse_form_submit($form_id, $form_values) {
+ return('archive/'. $form_values['year'] .'/'. $form_values['month'] .'/'. $form_values['day']);
+}
+
+/**
+ * Form theme function; displays the archive date navigation form inline.
+ */
+function theme_archive_browse_form($form) {
+ $output = '' . form_render($form) . '
';
+ return $output;
+}
diff --git a/modules/block.module b/modules/block.module
new file mode 100644
index 0000000..c4ea29d
--- /dev/null
+++ b/modules/block.module
@@ -0,0 +1,660 @@
+'. t('Blocks are boxes of content that may be rendered into certain regions of your web pages, for example, into sidebars. Blocks are usually generated automatically by modules (e.g., Recent Forum Topics), but administrators can also define custom blocks.') .'
';
+ $output .= ''. t('The region each block appears in depends on both which theme you are using (some themes allow greater control over block placement than others), and on the settings in the block administration section.') .'
';
+ $output .= ''. t('The block administration screen lets you specify the vertical placement of the blocks within a region. You do this by assigning a weight to each block. Lighter blocks (those having a smaller weight) "float up" towards the top of the region; heavier ones "sink".') .'
';
+ $output .= t('A block\'s visibility depends on:
+
+- Its enabled checkbox. Disabled blocks are never shown.
+- Its throttle checkbox. Throttled blocks are hidden during high server loads.
+- Its page visibility settings. Blocks can be configured to be visible/hidden on certain pages.
+- Its custom visibility settings. Blocks can be configured to be visible only when specific conditions are true.
+- Its user visibility settings. Administrators can choose to let users decide whether to show/hide certain blocks.
+- Its function. Some dynamic blocks, such as those generated by modules, will be displayed only on certain pages.
+
+');
+ $output .= ''. t('Module blocks') .'
';
+ $output .= ''. t('Some modules generate blocks that become available when the modules are enabled. These blocks can be administered via the blocks administration page.
', array('%admin-block' => url('admin/block'))) .'';
+ $output .= ''. t('Administrator defined blocks') .'
';
+ $output .= ''. t('Administrators can also define custom blocks. These blocks consist of a title, a description, and a body which can be as long as you wish. Block content can be in any of the input formats supported for other content.') .'
';
+ $output .= t('You can
+
+', array('%admin-block' => url('admin/block'), '%admin-block-add' => url('admin/block/add')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Block page.', array('%block' => 'http://drupal.org/handbook/modules/block/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Controls the boxes that are displayed around the main content.');
+ case 'admin/block':
+ return t("
+Blocks are boxes of content that may be rendered into certain regions of your web pages, for example, into sidebars. They are usually generated automatically by modules, but administrators can create blocks manually.
+Only enabled blocks are shown. You can position blocks by specifying which area of the page they should appear in (e.g., a sidebar). Highlighted labels on this page show the regions into which blocks can be rendered. You can specify where within a region a block will appear by adjusting its weight.
+If you want certain blocks to disable themselves temporarily during high server loads, check the 'Throttle' box. You can configure the auto-throttle on the throttle configuration page after having enabled the throttle module.
+You can configure the behaviour of each block (for example, specifying on which pages and for what users it will appear) by clicking the 'configure' link for each block.
+", array('%throttle' => url('admin/settings/throttle')));
+ case 'admin/block/add':
+ return t('Here you can create a new block. Once you have created this block you must make it active and give it a place on the page using blocks. The title is used when displaying the block. The description is used in the "block" column on the blocks page.
', array('%overview' => url('admin/block')));
+ }
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function block_perm() {
+ return array('administer blocks', 'use PHP for block visibility');
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function block_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array('path' => 'admin/block', 'title' => t('blocks'),
+ 'access' => user_access('administer blocks'),
+ 'callback' => 'block_admin_display');
+ $items[] = array('path' => 'admin/block/list', 'title' => t('list'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
+ $items[] = array('path' => 'admin/block/configure', 'title' => t('configure block'),
+ 'access' => user_access('administer blocks'),
+ 'callback' => 'block_admin_configure',
+ 'type' => MENU_CALLBACK);
+ $items[] = array('path' => 'admin/block/delete', 'title' => t('delete block'),
+ 'access' => user_access('administer blocks'),
+ 'callback' => 'block_box_delete',
+ 'type' => MENU_CALLBACK);
+ $items[] = array('path' => 'admin/block/add', 'title' => t('add block'),
+ 'access' => user_access('administer blocks'),
+ 'callback' => 'block_box_add',
+ 'type' => MENU_LOCAL_TASK);
+ foreach (list_themes() as $key => $theme) {
+ if ($theme->status) {
+ if ($key == variable_get('theme_default', 'bluemarine')) {
+ $items[] = array('path' => 'admin/block/list/' . $key, 'title' => t('%key settings', array('%key' => $key)),
+ 'access' => user_access('administer blocks'), 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
+ }
+ else {
+ $items[] = array('path' => 'admin/block/list/' . $key, 'title' => t('%key settings', array('%key' => $key)),
+ 'access' => user_access('administer blocks'), 'type' => MENU_LOCAL_TASK);
+ }
+ }
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Generates the administrator-defined blocks for display.
+ */
+function block_block($op = 'list', $delta = 0, $edit = array()) {
+ switch ($op) {
+ case 'list':
+ $blocks = array();
+
+ $result = db_query('SELECT bid, title, info FROM {boxes} ORDER BY title');
+ while ($block = db_fetch_object($result)) {
+ $blocks[$block->bid]['info'] = $block->info ? check_plain($block->info) : check_plain($block->title);
+ }
+ return $blocks;
+
+ case 'configure':
+ $box = block_box_get($delta);
+ if (filter_access($box['format'])) {
+ return block_box_form($box);
+ }
+ break;
+
+ case 'save':
+ block_box_save($edit, $delta);
+ break;
+
+ case 'view':
+ $block = db_fetch_object(db_query('SELECT * FROM {boxes} WHERE bid = %d', $delta));
+ $data['subject'] = check_plain($block->title);
+ $data['content'] = check_markup($block->body, $block->format, FALSE);
+ return $data;
+ }
+}
+
+/**
+ * Update the 'blocks' DB table with the blocks currently exported by modules.
+ *
+ * @return
+ * Blocks currently exported by modules.
+ */
+function _block_rehash() {
+ global $theme_key;
+
+ init_theme();
+
+ $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s'", $theme_key);
+ while ($old_block = db_fetch_object($result)) {
+ $old_blocks[$old_block->module][$old_block->delta] = $old_block;
+ }
+
+ db_query("DELETE FROM {blocks} WHERE theme = '%s'", $theme_key);
+
+ foreach (module_list() as $module) {
+ $module_blocks = module_invoke($module, 'block', 'list');
+ if ($module_blocks) {
+ foreach ($module_blocks as $delta => $block) {
+ $block['module'] = $module;
+ $block['delta'] = $delta;
+ // If previously written to database, load values.
+ if ($old_blocks[$module][$delta]) {
+ $block['status'] = $old_blocks[$module][$delta]->status;
+ $block['weight'] = $old_blocks[$module][$delta]->weight;
+ $block['region'] = $old_blocks[$module][$delta]->region;
+ $block['visibility'] = $old_blocks[$module][$delta]->visibility;
+ $block['pages'] = $old_blocks[$module][$delta]->pages;
+ $block['custom'] = $old_blocks[$module][$delta]->custom;
+ $block['throttle'] = $old_blocks[$module][$delta]->throttle;
+ }
+ // Otherwise, use any set values, or else substitute defaults.
+ else {
+ $properties = array('status' => 0, 'weight' => 0, 'region' => 'left', 'pages' => '', 'custom' => 0);
+ foreach ($properties as $property => $default) {
+ if (!isset($block[$property])) {
+ $block[$property] = $default;
+ }
+ }
+ }
+
+ // Reinsert blocks into table
+ db_query("INSERT INTO {blocks} (module, delta, theme, status, weight, region, visibility, pages, custom, throttle) VALUES ('%s', '%s', '%s', %d, %d, '%s', %d, '%s', %d, %d)",
+ $block['module'], $block['delta'], $theme_key, $block['status'], $block['weight'], $block['region'], $block['visibility'], $block['pages'], $block['custom'], $block['throttle']);
+ $blocks[] = $block;
+ }
+ }
+ }
+
+ return $blocks;
+}
+
+/**
+ * Generate main block administration form.
+ */
+function block_admin_display() {
+ global $theme_key, $custom_theme;
+
+ // If non-default theme configuration has been selected, set the custom theme.
+ if (arg(3)) {
+ $custom_theme = arg(3);
+ }
+ else {
+ $custom_theme = variable_get('theme_default', 'bluemarine');
+ }
+ init_theme();
+
+ // Fetch and sort blocks
+ $blocks = _block_rehash();
+ usort($blocks, '_block_compare');
+
+ $throttle = module_exist('throttle');
+ $block_regions = system_region_list($theme_key);
+
+ // Build form tree
+ $form['#action'] = arg(3) ? url('admin/block/list/' . $theme_key) : url('admin/block');
+ $form['#tree'] = TRUE;
+ foreach ($blocks as $i => $block) {
+ $form[$i]['module'] = array('#type' => 'value', '#value' => $block['module']);
+ $form[$i]['delta'] = array('#type' => 'value', '#value' => $block['delta']);
+ $form[$i]['info'] = array('#value' => $block['info']);
+ $form[$i]['status'] = array('#type' => 'checkbox', '#default_value' => $block['status']);
+ $form[$i]['theme'] = array('#type' => 'hidden', '#value' => $theme_key);
+ $form[$i]['weight'] = array('#type' => 'weight', '#default_value' => $block['weight']);
+ $form[$i]['region'] = array('#type' => 'select',
+ '#default_value' => isset($block['region']) ? $block['region'] : system_default_region($theme_key),
+ '#options' => $block_regions,
+ );
+
+ if ($throttle) {
+ $form[$i]['throttle'] = array('#type' => 'checkbox', '#default_value' => $block['throttle']);
+ }
+ $form[$i]['configure'] = array('#value' => l(t('configure'), 'admin/block/configure/'. $block['module'] .'/'. $block['delta']));
+ if ($block['module'] == 'block') {
+ $form[$i]['delete'] = array('#value' => l(t('delete'), 'admin/block/delete/'. $block['delta']));
+ }
+ }
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Save blocks'));
+
+ return drupal_get_form('block_admin_display', $form);
+}
+
+/**
+ * Helper function for sorting blocks on admin/block.
+ *
+ * Active blocks are sorted by region, then by weight.
+ * Disabled blocks are sorted by name.
+ */
+function _block_compare($a, $b) {
+ $status = $b['status'] - $a['status'];
+ // Separate enabled from disabled.
+ if ($status) {
+ return $status;
+ }
+ // Enabled blocks
+ if ($a['status']) {
+ $place = strcmp($a['region'], $b['region']);
+ return $place ? $place : ($a['weight'] - $b['weight']);
+ }
+ // Disabled blocks
+ else {
+ return strcmp($a['info'], $b['info']);
+ }
+}
+
+/**
+ * Process main block administration form submission.
+ */
+function block_admin_display_submit($form_id, $form_values) {
+ foreach ($form_values as $block) {
+ db_query("UPDATE {blocks} SET status = %d, weight = %d, region = '%s', throttle = %d WHERE module = '%s' AND delta = '%s' AND theme = '%s'", $block['status'], $block['weight'], $block['region'], $block['throttle'], $block['module'], $block['delta'], $block['theme']);
+ }
+ drupal_set_message(t('The block settings have been updated.'));
+ cache_clear_all();
+}
+
+/**
+ * Theme main block administration form submission.
+ *
+ * Note: the blocks are already sorted in the right order,
+ * grouped by status, region and weight.
+ */
+function theme_block_admin_display($form) {
+ global $theme_key;
+
+ $throttle = module_exist('throttle');
+ $block_regions = system_region_list($theme_key);
+
+ // Highlight regions on page to provide visual reference.
+ foreach ($block_regions as $key => $value) {
+ drupal_set_content($key, '' . $value . '
');
+ }
+
+ // Build rows
+ $rows = array();
+ $last_region = '';
+ $last_status = 1;
+ foreach (element_children($form) as $i) {
+ $block = $form[$i];
+ // Only take form elements that are blocks.
+ if (is_array($block['info'])) {
+ // Fetch values
+ $region = $block['region']['#default_value'];
+ $status = $block['status']['#default_value'];
+
+ // Output region header
+ if ($status && $region != $last_region) {
+ $region_title = t('%region', array('%region' => drupal_ucfirst($block_regions[$region])));
+ $rows[] = array(array('data' => $region_title, 'class' => 'region', 'colspan' => ($throttle ? 7 : 6)));
+ $last_region = $region;
+ }
+ // Output disabled header
+ elseif ($status != $last_status) {
+ $rows[] = array(array('data' => t('Disabled'), 'class' => 'region', 'colspan' => ($throttle ? 7 : 6)));
+ $last_status = $status;
+ }
+
+ // Generate block row
+ $row = array(
+ array('data' => form_render($block['info']), 'class' => 'block'),
+ form_render($block['status']) . form_render($block['theme']),
+ form_render($block['weight']),
+ form_render($block['region'])
+ );
+ if ($throttle) {
+ $row[] = form_render($block['throttle']);
+ }
+ $row[] = form_render($block['configure']);
+ $row[] = $block['delete'] ? form_render($block['delete']) : '';
+ $rows[] = $row;
+ }
+ }
+
+ // Finish table
+ $header = array(t('Block'), t('Enabled'), t('Weight'), t('Placement'));
+ if ($throttle) {
+ $header[] = t('Throttle');
+ }
+ $header[] = array('data' => t('Operations'), 'colspan' => 2);
+
+ $output = theme('table', $header, $rows, array('id' => 'blocks'));
+ $output .= form_render($form['submit']);
+ // Also render the form_id as there is no form_render($form) call (as form_render does not appear to handle the
+ // multi-dimensional block form array very well).
+ $output .= form_render($form['form_id']);
+
+ return $output;
+}
+
+function block_box_get($bid) {
+ return db_fetch_array(db_query('SELECT * FROM {boxes} WHERE bid = %d', $bid));
+}
+
+/**
+ * Menu callback; displays the block configuration form.
+ */
+function block_admin_configure($module = NULL, $delta = 0) {
+
+ $form['module'] = array('#type' => 'value', '#value' => $module);
+ $form['delta'] = array('#type' => 'value', '#value' => $delta);
+
+ $edit = db_fetch_array(db_query("SELECT pages, visibility, custom FROM {blocks} WHERE module = '%s' AND delta = '%s'", $module, $delta));
+
+ // Module-specific block configurations.
+ if ($settings = module_invoke($module, 'block', 'configure', $delta)) {
+ $form['block_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Block specific settings'),
+ '#collapsible' => true,
+ );
+
+ foreach ($settings as $k => $v) {
+ $form['block_settings'][$k] = $v;
+ }
+ }
+
+ // Get the block subject for the page title.
+ $info = module_invoke($module, 'block', 'list');
+ drupal_set_title(t("'%name' block", array('%name' => $info[$delta]['info'])));
+
+ // Standard block configurations.
+
+ $form['user_vis_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('User specific visibility settings'),
+ '#collapsible' => true,
+ );
+ $form['user_vis_settings']['custom'] = array(
+ '#type' => 'radios',
+ '#title' => t('Custom visibility settings'),
+ '#options' => array(t('Users cannot control whether or not they see this block.'), t('Show this block by default, but let individual users hide it.'), t('Hide this block by default but let individual users show it.')),
+ '#description' => t('Allow individual users to customize the visibility of this block in their account settings.'),
+ '#default_value' => $edit['custom'],
+ );
+ $form['page_vis_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Page specific visibility settings'),
+ '#collapsible' => true,
+ );
+ $access = user_access('use PHP for block visibility');
+
+ if ($edit['visibility'] == 2 && !$access) {
+ $form['page_vis_settings'] = array();
+ $form['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
+ $form['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $edit['pages']);
+ }
+ else {
+ $options = array(t('Show on every page except the listed pages.'), t('Show on only the listed pages.'));
+ $description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are '%blog' for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => theme('placeholder', 'blog'), '%blog-wildcard' => theme('placeholder', 'blog/*'), '%front' => theme('placeholder', '')));
+
+ if ($access) {
+ $options[] = t('Show if the following PHP code returns TRUE
(PHP-mode, experts only).');
+ $description .= t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', array('%php' => theme('placeholder', '')));
+ }
+ $form['page_vis_settings']['visibility'] = array(
+ '#type' => 'radios',
+ '#title' => t('Show block on specific pages'),
+ '#options' => $options,
+ '#default_value' => $edit['visibility'],
+ );
+ $form['page_vis_settings']['pages'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Pages'),
+ '#default_value' => $edit['pages'],
+ '#description' => $description,
+ );
+ }
+
+ $form['submit'] = array(
+ '#type' => 'submit',
+ '#value' => t('Save block'),
+ );
+
+ return drupal_get_form('block_admin_configure', $form);
+}
+
+function block_admin_configure_validate($form_id, $form_values) {
+ if ($form_values['module'] == 'block') {
+ if (empty($form_values['info']) || db_num_rows(db_query("SELECT bid FROM {boxes} WHERE bid != %d AND info = '%s'", $form_values['delta'], $form_values['info']))) {
+ form_set_error('info', t('Please ensure that each block description is unique.'));
+ }
+ }
+}
+
+function block_admin_configure_submit($form_id, $form_values) {
+ if (!form_get_errors()) {
+ db_query("UPDATE {blocks} SET visibility = %d, pages = '%s', custom = %d WHERE module = '%s' AND delta = '%s'", $form_values['visibility'], $form_values['pages'], $form_values['custom'], $form_values['module'], $form_values['delta']);
+ module_invoke($form_values['module'], 'block', 'save', $form_values['delta'], $form_values);
+ drupal_set_message(t('The block configuration has been saved.'));
+ cache_clear_all();
+ return 'admin/block';
+ }
+}
+
+/**
+ * Menu callback; displays the block creation form.
+ */
+function block_box_add() {
+ $form = block_box_form();
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Save block'));
+
+ return drupal_get_form('block_box_add', $form);
+}
+
+function block_box_add_validate($form_id, $form_values) {
+ if (empty($form_values['info']) || db_num_rows(db_query("SELECT info FROM {boxes} WHERE info = '%s'", $form_values['info']))) {
+ form_set_error('info', t('Please ensure that each block description is unique.'));
+ }
+}
+
+function block_box_add_submit($form_id, $form_values) {
+ if (!form_get_errors()) {
+ if (block_box_save($form_values)) {
+ drupal_set_message(t('The block has been created.'));
+ return 'admin/block';
+ }
+ }
+}
+
+/**
+ * Menu callback; confirm deletion of custom blocks.
+ */
+function block_box_delete($bid = 0) {
+ $box = block_box_get($bid);
+ $form['info'] = array('#type' => 'hidden', '#value' => $box['info'] ? $box['info'] : $box['title']);
+ $form['bid'] = array('#type' => 'hidden', '#value' => $bid);
+
+ return confirm_form('block_box_delete_confirm', $form, t('Are you sure you want to delete the block %name?', array('%name' => theme('placeholder', $box['info']))), 'admin/block', '', t('Delete'), t('Cancel'));
+}
+
+/**
+ * Deletion of custom blocks.
+ */
+function block_box_delete_confirm_submit($form_id, $form_values) {
+ db_query('DELETE FROM {boxes} WHERE bid = %d', $form_values['bid']);
+ drupal_set_message(t('The block %name has been removed.', array('%name' => theme('placeholder', $form_values['info']))));
+ cache_clear_all();
+ return 'admin/block';
+};
+
+function block_box_form($edit = array()) {
+ $form['info'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Block description'),
+ '#default_value' => $edit['info'],
+ '#maxlength' => 64,
+ '#description' => t('A brief description of your block. Used on the block overview page.', array('%overview' => url('admin/block'))),
+ '#required' => TRUE,
+ '#weight' => -19,
+ );
+ $form['title'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Block title'),
+ '#default_value' => $edit['title'],
+ '#maxlength' => 64,
+ '#description' => t('The title of the block as shown to the user.'),
+ '#weight' => -18,
+ );
+ $form['body_filter']['#weight'] = -17;
+ $form['body_filter']['body'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Block body'),
+ '#default_value' => $edit['body'],
+ '#rows' => 15,
+ '#description' => t('The content of the block as shown to the user.'),
+ '#weight' => -17,
+ );
+ $form['body_filter']['format'] = filter_form($edit['format'], -16);
+
+ return $form;
+}
+
+function block_box_save($edit, $delta = NULL) {
+ if (!filter_access($edit['format'])) {
+ $edit['format'] = FILTER_FORMAT_DEFAULT;
+ }
+
+ if (isset($delta)) {
+ db_query("UPDATE {boxes} SET title = '%s', body = '%s', info = '%s', format = %d WHERE bid = %d", $edit['title'], $edit['body'], $edit['info'], $edit['format'], $delta);
+ }
+ else {
+ db_query("INSERT INTO {boxes} (title, body, info, format) VALUES ('%s', '%s', '%s', %d)", $edit['title'], $edit['body'], $edit['info'], $edit['format']);
+ }
+ return true;
+}
+
+/**
+ * Implementation of hook_user().
+ *
+ * Allow users to decide which custom blocks to display when they visit
+ * the site.
+ */
+function block_user($type, $edit, &$user, $category = NULL) {
+ switch ($type) {
+ case 'form':
+ if ($category == 'account') {
+ $result = db_query('SELECT * FROM {blocks} WHERE status = 1 AND custom != 0 ORDER BY weight, module, delta');
+ $form['block'] = array('#type' => 'fieldset', '#title' => t('Block configuration'), '#weight' => 3, '#collapsible' => TRUE, '#tree' => TRUE);
+ while ($block = db_fetch_object($result)) {
+ $data = module_invoke($block->module, 'block', 'list');
+ if ($data[$block->delta]['info']) {
+ $return = TRUE;
+ $form['block'][$block->module][$block->delta] = array('#type' => 'checkbox', '#title' => $data[$block->delta]['info'], '#default_value' => isset($user->block[$block->module][$block->delta]) ? $user->block[$block->module][$block->delta] : ($block->custom == 1));
+ }
+ }
+
+ if ($return) {
+ return $form;
+ }
+ }
+
+ break;
+ case 'validate':
+ if (!$edit['block']) {
+ $edit['block'] = array();
+ }
+ return $edit;
+ }
+}
+
+/**
+ * Return all blocks in the specified region for the current user.
+ *
+ * @param $region
+ * The name of a region.
+ *
+ * @return
+ * An array of block objects, indexed with module_delta.
+ * If you are displaying your blocks in one or two sidebars, you may check
+ * whether this array is empty to see how many columns are going to be
+ * displayed.
+ *
+ * @todo
+ * Add a proper primary key (bid) to the blocks table so we don't have
+ * to mess around with this module_delta construct.
+ * Currently, the blocks table has no primary key defined!
+ */
+function block_list($region) {
+ global $user, $theme_key;
+
+ static $blocks = array();
+
+ if (!count($blocks)) {
+ $result = db_query("SELECT * FROM {blocks} WHERE theme = '%s' AND status = 1 ORDER BY region, weight, module", $theme_key);
+ while ($block = db_fetch_object($result)) {
+ if (!isset($blocks[$block->region])) {
+ $blocks[$block->region] = array();
+ }
+ // Use the user's block visibility setting, if necessary
+ if ($block->custom != 0) {
+ if ($user->uid && isset($user->block[$block->module][$block->delta])) {
+ $enabled = $user->block[$block->module][$block->delta];
+ }
+ else {
+ $enabled = ($block->custom == 1);
+ }
+ }
+ else {
+ $enabled = TRUE;
+ }
+
+ // Match path if necessary
+ if ($block->pages) {
+ if ($block->visibility < 2) {
+ $path = drupal_get_path_alias($_GET['q']);
+ $regexp = '/^('. preg_replace(array('/(\r\n?|\n)/', '/\\\\\*/', '/(^|\|)\\\\($|\|)/'), array('|', '.*', '\1'. preg_quote(variable_get('site_frontpage', 'node'), '/') .'\2'), preg_quote($block->pages, '/')) .')$/';
+ $page_match = !($block->visibility xor preg_match($regexp, $path));
+ }
+ else {
+ $page_match = drupal_eval($block->pages);
+ }
+ }
+ else {
+ $page_match = TRUE;
+ }
+
+ if ($enabled && $page_match) {
+ // Check the current throttle status and see if block should be displayed
+ // based on server load.
+ if (!($block->throttle && (module_invoke('throttle', 'status') > 0))) {
+ $array = module_invoke($block->module, 'block', 'view', $block->delta);
+ if (isset($array) && is_array($array)) {
+ foreach ($array as $k => $v) {
+ $block->$k = $v;
+ }
+ }
+ }
+ if (isset($block->content) && $block->content) {
+ $blocks[$block->region]["{$block->module}_{$block->delta}"] = $block;
+ }
+ }
+ }
+ }
+ // Create an empty array if there were no entries
+ if (!isset($blocks[$region])) {
+ $blocks[$region] = array();
+ }
+ return $blocks[$region];
+}
+
+
diff --git a/modules/blog.module b/modules/blog.module
new file mode 100644
index 0000000..d0e35a8
--- /dev/null
+++ b/modules/blog.module
@@ -0,0 +1,305 @@
+ array('name' => t('blog entry'), 'base' => 'blog'));
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function blog_perm() {
+ return array('edit own blog');
+}
+
+/**
+ * Implementation of hook_access().
+ */
+function blog_access($op, $node) {
+ global $user;
+
+ if ($op == 'create') {
+ return user_access('edit own blog') && $user->uid;
+ }
+
+ if ($op == 'update' || $op == 'delete') {
+ if (user_access('edit own blog') && ($user->uid == $node->uid)) {
+ return TRUE;
+ }
+ }
+}
+
+/**
+ * Implementation of hook_user().
+ */
+function blog_user($type, &$edit, &$user) {
+ if ($type == 'view' && user_access('edit own blog', $user)) {
+ $items[] = array('title' => t('Blog'),
+ 'value' => l(t('view recent blog entries'), "blog/$user->uid", array('title' => t("Read %username's latest blog entries.", array('%username' => $user->name)))),
+ 'class' => 'blog',
+ );
+ return array(t('History') => $items);
+ }
+}
+
+/**
+ * Implementation of hook_help().
+ */
+function blog_help($section) {
+ switch ($section) {
+ case 'admin/help#blog':
+ $output = ''. t('The blog module allows registered users to maintain an online weblog (commonly known as a blog), often referred to as an online journal or diary. Blogs are made up of individual posts that are time stamped and are typically viewed by date as you would a diary. Blogs often contain links to webpages users have read and/or agree/disagree with.') .'
';
+ $output .= ''. t('The blog module adds a user blogs navigation link to the site, which takes any visitor to a page that displays the most recent blog entries from all the users on the site. The navigation menu has a create a blog entry link (which takes you to a submission form) and a view personal blog link (which displays your blog entries as other people will see them). The blog module also creates a recent blog posts block that can be enabled.') .'
';
+ $output .= ''. t('If a user has the ability to post blogs, then the import module (news aggregator) will display a blog-it link next to each news item in its lists. Clicking on this takes the user to the blog submission form, with the title, a link to the item, and a link to the source into the body text already in the text box, ready for the user to add a comment or explanation. This actively encourages people to add blog entries about things they see and hear elsewhere in the website and from your syndicated partner sites.') .'
';
+ $output .= t('You can
+
+', array('%user' => url('user'), '%node-add-blog' => url('node/add/blog'), '%admin-node-configure-types-blog' => url('admin/settings/content-types/blog'), '%admin-settings-blogapi' => url('admin/settings/blogapi'), '%admin-block' => url('admin/block')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Blog page.', array('%blog' => 'http://drupal.org/handbook/modules/blog/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Enables keeping an easily and regularly updated web page or a blog.');
+ case 'node/add#blog':
+ return t("A blog is a regularly updated journal or diary made up of individual posts shown in reversed chronological order. A blog is tightly coupled to the author so each user will have his 'own' blog.");
+ }
+}
+
+/**
+ * Displays an RSS feed containing recent blog entries of a given user.
+ */
+function blog_feed_user($uid = 0) {
+ global $user;
+
+ if ($uid) {
+ $account = user_load(array('uid' => $uid, 'status' => 1));
+ }
+ else {
+ $account = $user;
+ }
+
+ $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, r.teaser, n.created, u.name, u.uid FROM {node} n INNER JOIN {node_revisions} r ON n.vid = r.vid INNER JOIN {users} u ON n.uid = u.uid WHERE n.type = 'blog' AND u.uid = %d AND n.status = 1 ORDER BY n.created DESC"), $uid, 0, variable_get('feed_default_items', 10));
+ $channel['title'] = $account->name ."'s blog";
+ $channel['link'] = url("blog/$uid", NULL, NULL, TRUE);
+ $channel['description'] = $term->description;
+ node_feed($result, $channel);
+}
+
+/**
+ * Displays an RSS feed containing recent blog entries of all users.
+ */
+function blog_feed_last() {
+ $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, r.teaser, n.created, u.name, u.uid FROM {node} n INNER JOIN {node_revisions} r ON n.vid = r.vid INNER JOIN {users} u ON n.uid = u.uid WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), 0, variable_get('feed_default_items', 10));
+ $channel['title'] = variable_get('site_name', 'drupal') .' blogs';
+ $channel['link'] = url('blog', NULL, NULL, TRUE);
+ $channel['description'] = $term->description;
+ node_feed($result, $channel);
+}
+
+/**
+ * Menu callback; displays a Drupal page containing recent blog entries.
+ */
+function blog_page($a = NULL, $b = NULL) {
+
+ if (is_numeric($a)) { // $a is a user ID
+ if ($b == 'feed') {
+ return blog_feed_user($a);
+ }
+ else {
+ return blog_page_user($a);
+ }
+ }
+ else if ($a == 'feed') {
+ return blog_feed_last();
+ }
+ else {
+ return blog_page_last();
+ }
+}
+
+/**
+ * Displays a Drupal page containing recent blog entries of a given user.
+ */
+function blog_page_user($uid) {
+ global $user;
+
+ $account = user_load(array((is_numeric($uid) ? 'uid' : 'name') => $uid, 'status' => 1));
+
+ if ($account->uid) {
+ drupal_set_title($title = t("%name's blog", array('%name' => $account->name)));
+
+ if (($account->uid == $user->uid) && user_access('edit own blog')) {
+ $output = '- '. l(t('Post new blog entry.'), "node/add/blog") .'
';
+ }
+ else if ($account->uid == $user->uid) {
+ $output = '- '. t('You are not allowed to post a new blog entry.') .'
';
+ }
+
+ if ($output) {
+ $output = '';
+ }
+ else {
+ $output = '';
+ }
+
+ $result = pager_query(db_rewrite_sql("SELECT n.nid, n.sticky, n.created FROM {node} n WHERE type = 'blog' AND n.uid = %d AND n.status = 1 ORDER BY n.sticky DESC, n.created DESC"), variable_get('default_nodes_main', 10), 0, NULL, $account->uid);
+ while ($node = db_fetch_object($result)) {
+ $output .= node_view(node_load($node->nid), 1);
+ }
+ $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
+ $output .= theme('feed_icon', url("blog/$account->uid/feed"));
+
+ drupal_add_link(array('rel' => 'alternate',
+ 'type' => 'application/rss+xml',
+ 'title' => t('RSS - %title', array('%title' => $title)),
+ 'href' => url("blog/$account->uid/feed")));
+ return $output;
+ }
+ else {
+ drupal_not_found();
+ }
+}
+
+/**
+ * Displays a Drupal page containing recent blog entries of all users.
+ */
+function blog_page_last() {
+ global $user;
+
+ $output = '';
+
+ $result = pager_query(db_rewrite_sql("SELECT n.nid, n.created FROM {node} n WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), variable_get('default_nodes_main', 10));
+
+ while ($node = db_fetch_object($result)) {
+ $output .= node_view(node_load($node->nid), 1);
+ }
+ $output .= theme('pager', NULL, variable_get('default_nodes_main', 10));
+ $output .= theme('feed_icon', url('blog/feed'));
+
+ drupal_add_link(array('rel' => 'alternate',
+ 'type' => 'application/rss+xml',
+ 'title' => t('RSS - blogs'),
+ 'href' => url("blog/feed")));
+ return $output;
+}
+
+/**
+ * Implementation of hook_form().
+ */
+function blog_form(&$node) {
+ global $nid;
+ $iid = $_GET['iid'];
+
+
+ if (empty($node->body)) {
+ /*
+ ** If the user clicked a "blog it" link, we load the data from the
+ ** database and quote it in the blog:
+ */
+
+ if ($nid && $blog = node_load($nid)) {
+ $node->body = ''. $blog->body .' ['. l($blog->name, "node/$nid") .']';
+ }
+
+ if ($iid && $item = db_fetch_object(db_query('SELECT i.*, f.title as ftitle, f.link as flink FROM {aggregator_item} i, {aggregator_feed} f WHERE i.iid = %d AND i.fid = f.fid', $iid))) {
+ $node->title = $item->title;
+ // Note: $item->description has been validated on aggregation.
+ $node->body = ''. check_plain($item->title) .' - '. $item->description .' ['. check_plain($item->ftitle) ."]\n";
+ }
+
+ }
+
+ $form['title'] = array('#type' => 'textfield', '#title' => t('Title'), '#required' => TRUE, '#default_value' => $node->title, '#weight' => -5);
+ $form['body_filter']['body'] = array('#type' => 'textarea', '#title' => t('Body'), '#default_value' => $node->body, '#rows' => 20, '#required' => TRUE);
+ $form['body_filter']['filter'] = filter_form($node->format);
+ return $form;
+}
+
+/**
+ * Implementation of hook_view().
+ */
+function blog_view(&$node, $teaser = FALSE, $page = FALSE) {
+ if ($page) {
+ // Breadcrumb navigation
+ $breadcrumb[] = array('path' => 'blog', 'title' => t('blogs'));
+ $breadcrumb[] = array('path' => 'blog/'. $node->uid, 'title' => t("%name's blog", array('%name' => $node->name)));
+ $breadcrumb[] = array('path' => 'node/'. $node->nid);
+ menu_set_location($breadcrumb);
+ }
+ $node = node_prepare($node, $teaser);
+}
+
+/**
+ * Implementation of hook_link().
+ */
+function blog_link($type, $node = 0, $main = 0) {
+ $links = array();
+
+ if ($type == 'node' && $node->type == 'blog') {
+ if (arg(0) != 'blog' || arg(1) != $node->uid) {
+ $links[] = l(t("%username's blog", array('%username' => $node->name)), "blog/$node->uid", array('title' => t("Read %username's latest blog entries.", array('%username' => $node->name))));
+ }
+ }
+
+ return $links;
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function blog_menu($may_cache) {
+ global $user;
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array('path' => 'node/add/blog', 'title' => t('blog entry'),
+ 'access' => user_access('edit own blog'));
+ $items[] = array('path' => 'blog', 'title' => t('blogs'),
+ 'callback' => 'blog_page',
+ 'access' => user_access('access content'),
+ 'type' => MENU_SUGGESTED_ITEM);
+ $items[] = array('path' => 'blog/'. $user->uid, 'title' => t('my blog'),
+ 'access' => user_access('edit own blog'),
+ 'type' => MENU_DYNAMIC_ITEM);
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Displays the most recent 10 blog titles.
+ */
+function blog_block($op = 'list', $delta = 0) {
+ global $user;
+ if ($op == 'list') {
+ $block[0]['info'] = t('Recent blog posts');
+ return $block;
+ }
+ else if ($op == 'view') {
+ if (user_access('access content')) {
+ $result = db_query_range(db_rewrite_sql("SELECT n.nid, n.title, n.created FROM {node} n WHERE n.type = 'blog' AND n.status = 1 ORDER BY n.created DESC"), 0, 10);
+ if (db_num_rows($result)) {
+ $block['content'] = node_title_list($result);
+ $block['content'] .= ''. l(t('more'), 'blog', array('title' => t('Read the latest blog entries.'))) .'
';
+ $block['subject'] = t('Recent blog posts');
+ return $block;
+ }
+ }
+ }
+}
+
+
diff --git a/modules/blogapi.module b/modules/blogapi.module
new file mode 100644
index 0000000..59d641d
--- /dev/null
+++ b/modules/blogapi.module
@@ -0,0 +1,737 @@
+'. t('The blog API module enables a post to be posted to a site via external GUI applications. Many users prefer to use external tools to improve their ability to read and post responses in a customized way. The blog api provides users the freedom to use the blogging tools they want but still have the blogging server of choice.') .'';
+ $output .= ''. t('When this module is enabled and configured you can use programs like Ecto to create and publish posts from your desktop. Blog API module supports several XML-RPC based blogging APIs such as the Blogger API, MetaWeblog API, and most of the Movable Type API. Any desktop blogging tools or other services (e.g. Flickr\'s "post to blog") that support these APIs should work with this site.', array('%external-http-ecto-kung-foo-tv' => 'http://ecto.kung-foo.tv/', '%-' => url('http://www.blogger.com/developers/api/1_docs/'), '%external-http-www-xmlrpc-com-metaWeblogApi' => 'http://www.xmlrpc.com/metaWeblogApi', '%external-http-www-movabletype-org-docs-mtmanual_programmatic-html' => 'http://www.movabletype.org/docs/mtmanual_programmatic.html', '%external-http-www-flickr-com' => 'http://www.flickr.com')) .'
';
+ $output .= ''. t('This module also allows site administrators to configure which content types can be posted via the external applications. So, for instance, users can post forum topics as well as blog posts. Where supported, the external applications will display each content type as a separate "blog".') .'
';
+ $output .= t('You can
+
+', array('%file-xmlrpc' => 'xmlrpc.php', '%admin-settings-blogapi' => url('admin/settings/blogapi')));
+ $output .= ''. t('For more information please read the configuration and customization handbook BlogApi page.', array('%blogapi' => 'http://drupal.org/handbook/modules/blogapi/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Allows users to post content using applications that support XML-RPC blog APIs.');
+ }
+}
+
+/**
+ * Implementation of hook_xmlrpc().
+ */
+function blogapi_xmlrpc() {
+ return array(
+ array(
+ 'blogger.getUsersBlogs',
+ 'blogapi_blogger_get_users_blogs',
+ array('array', 'string', 'string', 'string'),
+ t('Returns a list of weblogs to which an author has posting privileges.')),
+ array(
+ 'blogger.getUserInfo',
+ 'blogapi_blogger_get_user_info',
+ array('struct', 'string', 'string', 'string'),
+ t('Returns information about an author in the system.')),
+ array(
+ 'blogger.newPost',
+ 'blogapi_blogger_new_post',
+ array('string', 'string', 'string', 'string', 'string', 'string', 'boolean'),
+ t('Creates a new post, and optionally publishes it.')),
+ array(
+ 'blogger.editPost',
+ 'blogapi_blogger_edit_post',
+ array('boolean', 'string', 'string', 'string', 'string', 'string', 'boolean'),
+ t('Updates the information about an existing post.')),
+ array(
+ 'blogger.getPost',
+ 'blogapi_blogger_get_post',
+ array('struct', 'string', 'string', 'string', 'string'),
+ t('Returns information about a specific post.')),
+ array(
+ 'blogger.deletePost',
+ 'blogapi_blogger_delete_post',
+ array('boolean', 'string', 'string', 'string', 'string', 'boolean'),
+ t('Deletes a post.')),
+ array(
+ 'blogger.getRecentPosts',
+ 'blogapi_blogger_get_recent_posts',
+ array('array', 'string', 'string', 'string', 'string', 'int'),
+ t('Returns a list of the most recent posts in the system.')),
+ array(
+ 'metaWeblog.newPost',
+ 'blogapi_metaweblog_new_post',
+ array('string', 'string', 'string', 'string', 'struct', 'boolean'),
+ t('Creates a new post, and optionally publishes it.')),
+ array(
+ 'metaWeblog.editPost',
+ 'blogapi_metaweblog_edit_post',
+ array('boolean', 'string', 'string', 'string', 'struct', 'boolean'),
+ t('Updates information about an existing post.')),
+ array(
+ 'metaWeblog.getPost',
+ 'blogapi_metaweblog_get_post',
+ array('struct', 'string', 'string', 'string'),
+ t('Returns information about a specific post.')),
+ array(
+ 'metaWeblog.newMediaObject',
+ 'blogapi_metaweblog_new_media_object',
+ array('string', 'string', 'string', 'string', 'struct'),
+ t('Uploads a file to your webserver.')),
+ array(
+ 'metaWeblog.getCategories',
+ 'blogapi_metaweblog_get_category_list',
+ array('struct', 'string', 'string', 'string'),
+ t('Returns a list of all categories to which the post is assigned.')),
+ array(
+ 'metaWeblog.getRecentPosts',
+ 'blogapi_metaweblog_get_recent_posts',
+ array('array', 'string', 'string', 'string', 'int'),
+ t('Returns a list of the most recent posts in the system.')),
+ array(
+ 'mt.getRecentPostTitles',
+ 'blogapi_mt_get_recent_post_titles',
+ array('array', 'string', 'string', 'string', 'int'),
+ t('Returns a bandwidth-friendly list of the most recent posts in the system.')),
+ array(
+ 'mt.getCategoryList',
+ 'blogapi_mt_get_category_list',
+ array('array', 'string', 'string', 'string'),
+ t('Returns a list of all categories defined in the weblog.')),
+ array(
+ 'mt.getPostCategories',
+ 'blogapi_mt_get_post_categories',
+ array('array', 'string', 'string', 'string'),
+ t('Returns a list of all categories to which the post is assigned.')),
+ array(
+ 'mt.setPostCategories',
+ 'blogapi_mt_set_post_categories',
+ array('boolean', 'string', 'string', 'string', 'array'),
+ t('Sets the categories for a post.')),
+ array(
+ 'mt.supportedMethods',
+ 'xmlrpc_server_list_methods',
+ array('array'),
+ t('Retrieve information about the XML-RPC methods supported by the server.')),
+ array(
+ 'mt.supportedTextFilters',
+ 'blogapi_mt_supported_text_filters',
+ array('array'),
+ t('Retrieve information about the text formatting plugins supported by the server.')),
+ array(
+ 'mt.getTrackbackPings',
+ 'blogapi_mt_get_trackback_pings',
+ array('array', 'string'),
+ t('Retrieve the list of TrackBack pings posted to a particular entry. This could be used to programmatically retrieve the list of pings for a particular entry, then iterate through each of those pings doing the same, until one has built up a graph of the web of entries referencing one another on a particular topic.')),
+ array(
+ 'mt.publishPost',
+ 'blogap_mti_publish_post',
+ array('boolean', 'string', 'string', 'string'),
+ t('Publish (rebuild) all of the static files related to an entry from your weblog. Equivalent to saving an entry in the system (but without the ping).')));
+}
+
+/**
+ * Blogging API callback. Finds the URL of a user's blog.
+ */
+
+function blogapi_blogger_get_users_blogs($appid, $username, $password) {
+
+ $user = blogapi_validate_user($username, $password);
+ if ($user->uid) {
+ $types = _blogapi_get_node_types();
+ $structs = array();
+ foreach ($types as $type) {
+ $structs[] = array('url' => url('blog/' . $user->uid, NULL, NULL, true), 'blogid' => $type, 'blogName' => $user->name . ": " . $type);
+ }
+ return $structs;
+ }
+ else {
+ return blogapi_error($user);
+ }
+}
+
+/**
+ * Blogging API callback. Returns profile information about a user.
+ */
+function blogapi_blogger_get_user_info($appkey, $username, $password) {
+ $user = blogapi_validate_user($username, $password);
+
+ if ($user->uid) {
+ $name = explode(' ', $user->realname ? $user->realname : $user->name, 2);
+ return array(
+ 'userid' => $user->uid,
+ 'lastname' => $name[1],
+ 'firstname' => $name[0],
+ 'nickname' => $user->name,
+ 'email' => $user->mail,
+ 'url' => url('blog/' . $user->uid, NULL, NULL, true));
+ }
+ else {
+ return blogapi_error($user);
+ }
+}
+
+/**
+ * Blogging API callback. Inserts a new blog post as a node.
+ */
+function blogapi_blogger_new_post($appkey, $blogid, $username, $password, $content, $publish) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $edit = array();
+ $edit['type'] = _blogapi_blogid($blogid);
+ // get the node type defaults
+ $node_type_default = variable_get('node_options_'. $edit['type'], array('status', 'promote'));
+ $edit['uid'] = $user->uid;
+ $edit['name'] = $user->name;
+ $edit['promote'] = in_array('promote', $node_type_default);
+ $edit['comment'] = variable_get('comment_'. $edit['type'], 2);
+ $edit['moderate'] = in_array('moderate', $node_type_default);
+ $edit['revision'] = in_array('revision', $node_type_default);
+ $edit['format'] = FILTER_FORMAT_DEFAULT;
+ $edit['status'] = $publish;
+
+ // check for bloggerAPI vs. metaWeblogAPI
+ if (is_array($content)) {
+ $edit['title'] = $content['title'];
+ $edit['body'] = $content['description'];
+ _blogapi_mt_extra($edit, $content);
+ }
+ else {
+ $edit['title'] = blogapi_blogger_title($content);
+ $edit['body'] = $content;
+ }
+
+ if (!node_access('create', $edit['type'])) {
+ return blogapi_error(t('You do not have permission to create the type of post you wanted to create.'));
+ }
+
+ if (user_access('administer nodes') && !isset($edit['date'])) {
+ $edit['date'] = format_date(time(), 'custom', 'Y-m-d H:i:s O');
+ }
+
+ node_validate($edit);
+ if ($errors = form_get_errors()) {
+ return blogapi_error(implode("\n", $errors));
+ }
+
+ $node = node_submit($edit);
+ node_save($node);
+ if ($node->nid) {
+ watchdog('content', t('%type: added %title using blog API.', array('%type' => ''. t($node->type) .'', '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
+ // blogger.newPost returns a string so we cast the nid to a string by putting it in double quotes:
+ return "$node->nid";
+ }
+
+ return blogapi_error(t('Error storing post.'));
+}
+
+/**
+ * Blogging API callback. Modifies the specified blog node.
+ */
+function blogapi_blogger_edit_post($appkey, $postid, $username, $password, $content, $publish) {
+
+ $user = blogapi_validate_user($username, $password);
+
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $node = node_load($postid);
+ if (!$node) {
+ return blogapi_error(message_na());
+ }
+ // Let the teaser be re-generated.
+ unset($node->teaser);
+
+ if (!node_access('update', $node)) {
+ return blogapi_error(t('You do not have permission to update this post.'));
+ }
+
+ $node->status = $publish;
+
+ // check for bloggerAPI vs. metaWeblogAPI
+ if (is_array($content)) {
+ $node->title = $content['title'];
+ $node->body = $content['description'];
+ _blogapi_mt_extra($node, $content);
+ }
+ else {
+ $node->title = blogapi_blogger_title($content);
+ $node->body = $content;
+ }
+
+ node_validate($node);
+ if ($errors = form_get_errors()) {
+ return blogapi_error(implode("\n", $errors));
+ }
+
+ if (user_access('administer nodes') && !isset($edit['date'])) {
+ $node->date = format_date($node->created, 'custom', 'Y-m-d H:i:s O');
+ }
+ $node = node_submit($node);
+ node_save($node);
+ if ($node->nid) {
+ watchdog('content', t('%type: updated %title using blog API.', array('%type' => ''. t($node->type) .'', '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), "node/$node->nid"));
+ return true;
+ }
+
+ return blogapi_error(t('Error storing post.'));
+}
+
+/**
+ * Blogging API callback. Returns a specified blog node.
+ */
+function blogapi_blogger_get_post($appkey, $postid, $username, $password) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $node = node_load($postid);
+
+ return _blogapi_get_post($node, true);
+}
+
+/**
+ * Blogging API callback. Removes the specified blog node.
+ */
+function blogapi_blogger_delete_post($appkey, $postid, $username, $password, $publish) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ node_delete($postid);
+ return true;
+}
+
+/**
+ * Blogging API callback. Returns the latest few postings in a user's blog. $bodies TRUE
+ *
+ * returns a bandwidth-friendly list.
+ */
+function blogapi_blogger_get_recent_posts($appkey, $blogid, $username, $password, $number_of_posts, $bodies = TRUE) {
+ // Remove unused appkey (from bloggerAPI).
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $type = _blogapi_blogid($blogid);
+ if ($bodies) {
+ $result = db_query_range("SELECT n.nid, n.title, r.body, n.created, u.name FROM {node} n, {node_revisions} r, {users} u WHERE n.uid = u.uid AND n.vid = r.vid AND n.type = '%s' AND n.uid = %d ORDER BY n.created DESC", $type, $user->uid, 0, $number_of_posts);
+ }
+ else {
+ $result = db_query_range("SELECT n.nid, n.title, n.created, u.name FROM {node} n, {users} u WHERE n.uid = u.uid AND n.type = '%s' AND n.uid = %d ORDER BY n.created DESC", $type, $user->uid, 0, $number_of_posts);
+ }
+ $blogs = array ();
+ while ($blog = db_fetch_object($result)) {
+ $blogs[] = _blogapi_get_post($blog, $bodies);
+ }
+ return $blogs;
+}
+
+function blogapi_metaweblog_new_post($blogid, $username, $password, $content, $publish) {
+ return blogapi_blogger_new_post('0123456789ABCDEF', $blogid, $username, $password, $content, $publish);
+}
+
+function blogapi_metaweblog_edit_post($postid, $username, $password, $content, $publish) {
+ return blogapi_blogger_edit_post('0123456789ABCDEF', $postid, $username, $password, $content, $publish);
+}
+
+function blogapi_metaweblog_get_post($postid, $username, $password) {
+ return blogapi_blogger_get_post('01234567890ABCDEF', $postid, $username, $password);
+}
+
+/**
+ * Blogging API callback. Inserts a file into Drupal.
+ */
+function blogapi_metaweblog_new_media_object($blogid, $username, $password, $file) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $name = basename($file['name']);
+ $data = $file['bits'];
+
+ if (!$data) {
+ return blogapi_error(t('No file sent.'));
+ }
+
+ if (!$file = file_save_data($data, $name)) {
+ return blogapi_error(t('Error storing file.'));
+ }
+
+ // Return the successful result.
+ return array('url' => file_create_url($file), 'struct');
+}
+/**
+ * Blogging API callback. Returns a list of the taxonomy terms that can be
+ * associated with a blog node.
+ */
+function blogapi_metaweblog_get_category_list($blogid, $username, $password) {
+ $type = _blogapi_blogid($blogid);
+ $vocabularies = module_invoke('taxonomy', 'get_vocabularies', $type, 'vid');
+ $categories = array();
+ if ($vocabularies) {
+ foreach ($vocabularies as $vocabulary) {
+ $terms = module_invoke('taxonomy', 'get_tree', $vocabulary->vid, 0, -1);
+ foreach ($terms as $term) {
+ $term_name = $term->name;
+ foreach (module_invoke('taxonomy', 'get_parents', $term->tid, 'tid') as $parent) {
+ $term_name = $parent->name . '/' . $term_name;
+ }
+ $categories[] = array('categoryName' => $term_name, 'categoryId' => $term->tid);
+ }
+ }
+ }
+ return $categories;
+}
+
+function blogapi_metaweblog_get_recent_posts($blogid, $username, $password, $number_of_posts) {
+ return blogapi_blogger_get_recent_posts('0123456789ABCDEF', $blogid, $username, $password, $number_of_posts, TRUE);
+}
+
+// see above
+function blogapi_mt_get_recent_post_titles($blogid, $username, $password, $number_of_posts) {
+ return blogapi_blogger_get_recent_posts('0123456789ABCDEF', $blogid, $username, $password, $number_of_posts, FALSE);
+}
+
+/* **** */
+function blogapi_mt_get_category_list($blogid, $username, $password) {
+ return blogapi_metaweblog_get_category_list($blogid, $username, $password);
+}
+
+/**
+ * Blogging API callback. Returns a list of the taxonomy terms that are
+ * assigned to a particular node.
+ */
+function blogapi_mt_get_post_categories($postid, $username, $password) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $terms = module_invoke('taxonomy', 'node_get_terms', $postid, 'tid');
+ $categories = array();
+ foreach ($terms as $term) {
+ $term_name = $term->name;
+ foreach (module_invoke('taxonomy', 'get_parents', $term->tid, 'tid') as $parent) {
+ $term_name = $parent->name . '/' . $term_name;
+ }
+ $categories[] = array('categoryName' => $term_name, 'categoryId' => $term->tid, 'isPrimary' => true);
+ }
+ return $categories;
+}
+
+/**
+ * Blogging API callback. Assigns taxonomy terms to a particular node.
+ */
+function blogapi_mt_set_post_categories($postid, $username, $password, $categories) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+
+ $node = node_load($postid);
+ $node->taxonomy = array();
+ foreach ($categories as $category) {
+ $node->taxonomy[] = $category['categoryId'];
+ }
+ node_save($node);
+ return TRUE;
+}
+
+/**
+ * Blogging API callback. Sends a list of available input formats.
+ */
+function blogapi_mt_supported_text_filters() {
+ // NOTE: we're only using anonymous' formats because the MT spec
+ // does not allow for per-user formats.
+ $formats = filter_formats();
+
+ $filters = array();
+ foreach ($formats as $format) {
+ $filter['key'] = $format->format;
+ $filter['label'] = $format->name;
+ $filters[] = $filter;
+ }
+
+ return $filters;
+}
+
+/**
+ * Blogging API callback. Can not be implemented without support from
+ * trackback module.
+ */
+function blogapi_mt_get_trackback_pings() {
+ return blogapi_error(t('Not implemented.'));
+}
+
+/**
+ * Blogging API callback. Publishes the given node
+ */
+function blogap_mti_publish_post($postid, $username, $password) {
+ $user = blogapi_validate_user($username, $password);
+ if (!$user->uid) {
+ return blogapi_error($user);
+ }
+ $node = node_load($postid);
+ if (!$node) {
+ return blogapi_error(t('Invalid post.'));
+ }
+
+ $node->status = 1;
+ if (!node_access('update', $node)) {
+ return blogapi_error(t('You do not have permission to update this post.'));
+ }
+
+ node_save($node);
+
+ return true;
+}
+
+/**
+ * Prepare an error message for returning to the XMLRPC caller.
+ */
+function blogapi_error($message) {
+ static $xmlrpcusererr;
+ if (!is_array($message)) {
+ $message = array($message);
+ }
+
+ $message = implode(' ', $message);
+
+ return xmlrpc_error($xmlrpcusererr + 1, strip_tags($message));
+}
+
+/**
+ * Ensure that the given user has permission to edit a blog.
+ */
+function blogapi_validate_user($username, $password) {
+ global $user;
+
+ $user = user_authenticate($username, $password);
+
+ if ($user->uid) {
+ if (user_access('edit own blog', $user)) {
+ return $user;
+ }
+ else {
+ return t("You either tried to edit somebody else's blog or you don't have permission to edit your own blog.");
+ }
+ }
+ else {
+ return t('Wrong username or password.');
+ }
+}
+
+/**
+ * For the blogger API, extract the node title from the contents field.
+ */
+function blogapi_blogger_title(&$contents) {
+ if (eregi('([^<]*)', $contents, $title)) {
+ $title = strip_tags($title[0]);
+ $contents = ereg_replace('[^<]*', '', $contents);
+ }
+ else {
+ list($title, $contents) = explode("\n", $contents, 2);
+ }
+ return $title;
+}
+
+function blogapi_settings() {
+ $form['blogapi_engine'] = array(
+ '#type' => 'select', '#title' => t('XML-RPC Engine'), '#default_value' => variable_get('blogapi_engine', 0),
+ '#options' => array(0 => 'Blogger', 1 => 'MetaWeblog', 2 => 'Movabletype'),
+ '#description' => t('RSD or Really-Simple-Discovery is a mechanism which allows external blogger tools to discover the APIs they can use to interact with Drupal. Here you can set the preferred method for blogger tools to interact with your site. The common XML-RPC engines are Blogger, MetaWeblog and Movabletype. If you are not sure which is the correct setting, choose Blogger.')
+ );
+
+ $node_types = node_get_types();
+ $defaults = isset($node_types['blog']) ? array('blog' => 1) : array();
+ $form['blogapi_node_types'] = array(
+ '#type' => 'checkboxes', '#title' => t('Blog types'), '#required' => TRUE,
+ '#default_value' => variable_get('blogapi_node_types', $defaults), '#options' => $node_types,
+ '#description' => t('Select the content types for which you wish to enable posting via blogapi. Each type will appear as a different "blog" in the client application (if supported).')
+ );
+
+ return $form;
+}
+
+function blogapi_menu($may_cache) {
+ $items = array();
+
+ if (drupal_is_front_page()) {
+ drupal_add_link(array('rel' => 'EditURI',
+ 'type' => 'application/rsd+xml',
+ 'title' => t('RSD'),
+ 'href' => url('blogapi/rsd', NULL, NULL, TRUE)));
+ }
+
+ if ($may_cache) {
+ $items[] = array('path' => 'blogapi', 'title' => t('RSD'), 'callback' => 'blogapi_blogapi', 'access' => user_access('access content'), 'type' => MENU_CALLBACK);
+ }
+
+ return $items;
+}
+
+function blogapi_blogapi() {
+ switch (arg(1)) {
+ case 'rsd':
+ blogapi_rsd();
+ break;
+ default:
+ drupal_not_found();
+ break;
+ }
+}
+
+function blogapi_rsd() {
+ global $base_url;
+
+ $xmlrpc = $base_url .'/'. 'xmlrpc.php';
+ $base = url('', NULL, NULL, TRUE);
+ $blogid = 1; # until we figure out how to handle multiple bloggers
+
+ drupal_set_header('Content-Type: application/rsd+xml; charset=utf-8');
+ print <<<__RSD__
+
+
+
+ Drupal
+ http://drupal.org/
+ $base
+
+
+
+
+
+
+
+__RSD__;
+}
+
+/**
+ * Handles extra information sent by clients according to MovableType's spec.
+ */
+function _blogapi_mt_extra(&$node, $struct) {
+ if (is_array($node)) {
+ $was_array = true;
+ $node = (object)$node;
+ }
+
+ // mt_allow_comments
+ if (array_key_exists('mt_allow_comments', $struct)) {
+ switch ($struct['mt_allow_comments']) {
+ case 0:
+ $node->comment = COMMENT_NODE_DISABLED;
+ break;
+ case 1:
+ $node->comment = COMMENT_NODE_READ_WRITE;
+ break;
+ case 2:
+ $node->comment = COMMENT_NODE_READ_ONLY;
+ break;
+ }
+ }
+
+ // merge the 3 body sections (description, mt_excerpt, mt_text_more) into
+ // one body
+ if ($struct['mt_excerpt']) {
+ $node->body = $struct['mt_excerpt'] .''.$node->body;
+ }
+ if ($struct['mt_text_more']) {
+ $node->body = $node->body . '' . $struct['mt_text_more'];
+ }
+
+ // mt_tb_ping_urls
+ if (function_exists('trackback_send')) {
+ if (is_array($struct['mt_tb_ping_urls'])) {
+ foreach ($struct['mt_tb_ping_urls'] as $tb_ping_url) {
+ $node->tb_url = $tb_ping_url->getVal();
+ trackback_send($node);
+ unset($node->tb_url); // make sure we don't ping twice
+ }
+ }
+ else {
+ $node->tb_url = $struct['mt_tb_ping_urls'];
+ }
+ }
+
+ // mt_convert_breaks
+ if ($struct['mt_convert_breaks']) {
+ $node->format = $struct['mt_convert_breaks'];
+ }
+
+ // dateCreated
+ if ($struct['dateCreated']) {
+ $node->date = format_date(mktime($struct['dateCreated']->hour, $struct['dateCreated']->minute, $struct['dateCreated']->second, $struct['dateCreated']->month, $struct['dateCreated']->day, $struct['dateCreated']->year), 'custom', 'Y-m-d H:i:s O');
+ }
+
+ if ($was_array) {
+ $node = (array)$node;
+ }
+}
+
+function _blogapi_get_post($node, $bodies = true) {
+ $xmlrpcval = array (
+ 'userid' => $node->name,
+ 'dateCreated' => xmlrpc_date($node->created),
+ 'title' => $node->title,
+ 'postid' => $node->nid,
+ 'link' => url('node/'.$node->nid, NULL, NULL, true),
+ 'permaLink' => url('node/'.$node->nid, NULL, NULL, true),
+ );
+ if ($bodies) {
+ if ($node->comment = 1) {
+ $comment = 2;
+ }
+ if ($node->comment = 2) {
+ $comment = 1;
+ }
+
+ $xmlrpcval['content'] = "$node->title$node->body";
+ $xmlrpcval['description'] = $node->body;
+ // Add MT specific fields
+ $xmlrpcval['mt_allow_comments'] = $comment;
+ $xmlrpcval['mt_convert_breaks'] = $node->format;
+ }
+
+ return $xmlrpcval;
+}
+
+function _blogapi_blogid($id) {
+ if (is_numeric($id)) {
+ return 'blog';
+ }
+ else {
+ return $id;
+ }
+}
+
+function _blogapi_get_node_types() {
+ $available_types = array_keys(array_filter(variable_get('blogapi_node_types', array('blog' => 1))));
+ $types = array();
+ foreach (node_get_types() as $type => $name) {
+ if (node_access('create', $type) && in_array($type, $available_types)) {
+ $types[] = $type;
+ }
+ }
+
+ return $types;
+}
+
diff --git a/modules/book.module b/modules/book.module
new file mode 100644
index 0000000..1667b92
--- /dev/null
+++ b/modules/book.module
@@ -0,0 +1,1026 @@
+ array('name' => t('book page'), 'base' => 'book'));
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function book_perm() {
+ return array('outline posts in books', 'create book pages', 'create new books', 'edit book pages', 'edit own book pages', 'see printer-friendly version');
+}
+
+/**
+ * Implementation of hook_access().
+ */
+function book_access($op, $node) {
+ global $user;
+
+ if ($op == 'create') {
+ // Only registered users can create book pages. Given the nature
+ // of the book module this is considered to be a good/safe idea.
+ return user_access('create book pages');
+ }
+
+ if ($op == 'update') {
+ // Only registered users can update book pages. Given the nature
+ // of the book module this is considered to be a good/safe idea.
+ // One can only update a book page if there are no suggested updates
+ // of that page waiting for approval. That is, only updates that
+ // don't overwrite the current or pending information are allowed.
+
+ if ((user_access('edit book pages') && !$node->moderate) || ($node->uid == $user->uid && user_access('edit own book pages'))) {
+ return TRUE;
+ }
+ else {
+ // do nothing. node-access() will determine further access
+ }
+ }
+}
+
+/**
+ * Implementation of hook_link().
+ */
+function book_link($type, $node = 0, $main = 0) {
+
+ $links = array();
+
+ if ($type == 'node' && isset($node->parent)) {
+ if (!$main) {
+ if (book_access('create', $node)) {
+ $links[] = l(t('add child page'), "node/add/book/parent/$node->nid");
+ }
+ if (user_access('see printer-friendly version')) {
+ $links[] = l(t('printer-friendly version'),
+ 'book/export/html/'. $node->nid,
+ array('title' => t('Show a printer-friendly version of this book page and its sub-pages.')));
+ }
+ }
+ }
+
+ return $links;
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function book_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array(
+ 'path' => 'node/add/book',
+ 'title' => t('book page'),
+ 'access' => user_access('create book pages'));
+ $items[] = array(
+ 'path' => 'admin/node/book',
+ 'title' => t('books'),
+ 'callback' => 'book_admin',
+ 'access' => user_access('administer nodes'),
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => -1);
+ $items[] = array(
+ 'path' => 'admin/node/book/list',
+ 'title' => t('list'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK);
+ $items[] = array(
+ 'path' => 'admin/node/book/orphan',
+ 'title' => t('orphan pages'),
+ 'callback' => 'book_admin_orphan',
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 8);
+ $items[] = array(
+ 'path' => 'book',
+ 'title' => t('books'),
+ 'callback' => 'book_render',
+ 'access' => user_access('access content'),
+ 'type' => MENU_SUGGESTED_ITEM);
+ $items[] = array(
+ 'path' => 'book/export',
+ 'callback' => 'book_export',
+ 'access' => user_access('access content'),
+ 'type' => MENU_CALLBACK);
+ }
+ else {
+ // To avoid SQL overhead, check whether we are on a node page and whether the
+ // user is allowed to outline posts in books.
+ if (arg(0) == 'node' && is_numeric(arg(1)) && user_access('outline posts in books')) {
+ // Only add the outline-tab for non-book pages:
+ $result = db_query(db_rewrite_sql("SELECT n.nid FROM {node} n WHERE n.nid = %d AND n.type != 'book'"), arg(1));
+ if (db_num_rows($result) > 0) {
+ $items[] = array(
+ 'path' => 'node/'. arg(1) .'/outline',
+ 'title' => t('outline'),
+ 'callback' => 'book_outline',
+ 'callback arguments' => array(arg(1)),
+ 'access' => user_access('outline posts in books'),
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 2);
+ }
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Displays the book table of contents in a block when the current page is a
+ * single-node view of a book node.
+ */
+function book_block($op = 'list', $delta = 0) {
+ $block = array();
+ if ($op == 'list') {
+ $block[0]['info'] = t('Book navigation');
+ return $block;
+ }
+ else if ($op == 'view') {
+ // Only display this block when the user is browsing a book:
+ if (arg(0) == 'node' && is_numeric(arg(1))) {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), arg(1));
+ if (db_num_rows($result) > 0) {
+ $node = db_fetch_object($result);
+
+ $path = book_location($node);
+ $path[] = $node;
+
+ $expand = array();
+ foreach ($path as $key => $node) {
+ $expand[] = $node->nid;
+ }
+
+ $block['subject'] = check_plain($path[0]->title);
+ $block['content'] = book_tree($expand[0], 5, $expand);
+ }
+ }
+
+ return $block;
+ }
+}
+
+/**
+ * Implementation of hook_load().
+ */
+function book_load($node) {
+ $book = db_fetch_object(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
+ return $book;
+}
+
+/**
+ * Implementation of hook_insert().
+ */
+function book_insert($node) {
+ db_query("INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->vid, $node->parent, $node->weight);
+}
+
+/**
+ * Implementation of hook_update().
+ */
+function book_update($node) {
+ if ($node->revision) {
+ db_query("INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)", $node->nid, $node->vid, $node->parent, $node->weight);
+ }
+ else {
+ db_query("UPDATE {book} SET parent = %d, weight = %d WHERE vid = %d", $node->parent, $node->weight, $node->vid);
+ }
+}
+
+/**
+ * Implementation of hook_delete().
+ */
+function book_delete(&$node) {
+ db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+}
+
+/**
+ * Implementation of hook_submit().
+ */
+function book_submit(&$node) {
+ global $user;
+ // Set default values for non-administrators.
+ if (!user_access('administer nodes')) {
+ $node->weight = 0;
+ $node->revision = 1;
+ $book->uid = $user->uid;
+ $book->name = $user->uid ? $user->name : '';
+ }
+}
+
+/**
+ * Implementation of hook_form().
+ */
+function book_form(&$node) {
+ if ($node->nid && !$node->parent && !user_access('create new books')) {
+ $form['parent'] = array('#type' => 'value', '#value' => $node->parent);
+ }
+ else {
+ $form['parent'] = array('#type' => 'select',
+ '#title' => t('Parent'),
+ '#default_value' => ($node->parent ? $node->parent : arg(4)),
+ '#options' => book_toc($node->nid),
+ '#weight' => -4,
+ '#description' => user_access('create new books') ? t('The parent section in which to place this page. Note that each page whose parent is <top-level> is an independent, top-level book.') : t('The parent that this page belongs in.'),
+ );
+ }
+
+ $form['title'] = array('#type' => 'textfield',
+ '#title' => t('Title'),
+ '#required' => TRUE,
+ '#default_value' => $node->title,
+ '#weight' => -5,
+ );
+ $form['body_filter']['body'] = array('#type' => 'textarea',
+ '#title' => t('Body'),
+ '#default_value' => $node->body,
+ '#rows' => 20,
+ '#required' => TRUE,
+ );
+ $form['body_filter']['format'] = filter_form($node->format);
+
+ $form['log'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Log message'),
+ '#default_value' => $node->log,
+ '#weight' => 5,
+ '#description' => t('An explanation of the additions or updates being made to help other authors understand your motivations.'),
+ );
+
+ if (user_access('administer nodes')) {
+ $form['weight'] = array('#type' => 'weight',
+ '#title' => t('Weight'),
+ '#default_value' => $node->weight,
+ '#delta' => 15,
+ '#weight' => 5,
+ '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
+ );
+ }
+ else {
+ // If a regular user updates a book page, we create a new revision
+ // authored by that user:
+ $form['revision'] = array('#type' => 'hidden', '#value' => 1);
+ }
+
+ return $form;
+}
+
+/**
+ * Implementation of function book_outline()
+ * Handles all book outline operations.
+ */
+function book_outline($nid) {
+ $node = node_load($nid);
+ $page = book_load($node);
+
+ $form['parent'] = array('#type' => 'select',
+ '#title' => t('Parent'),
+ '#default_value' => $page->parent,
+ '#options' => book_toc($node->nid),
+ '#description' => t('The parent page in the book.'),
+ );
+ $form['weight'] = array('#type' => 'weight',
+ '#title' => t('Weight'),
+ '#default_value' => $page->weight,
+ '#delta' => 15,
+ '#description' => t('Pages at a given level are ordered first by weight and then by title.'),
+ );
+ $form['log'] = array('#type' => 'textarea',
+ '#title' => t('Log message'),
+ '#default_value' => $node->log,
+ '#description' => t('An explanation to help other authors understand your motivations to put this post into the book.'),
+ );
+
+ $form['nid'] = array('#type' => 'value', '#value' => $nid);
+ if ($page->nid) {
+ $form['update'] = array('#type' => 'submit',
+ '#value' => t('Update book outline'),
+ );
+ $form['remove'] = array('#type' => 'submit',
+ '#value' => t('Remove from book outline'),
+ );
+ }
+ else {
+ $form['add'] = array('#type' => 'submit', '#value' => t('Add to book outline'));
+ }
+
+ drupal_set_title(check_plain($node->title));
+ return drupal_get_form('book_outline', $form);
+}
+
+/**
+ * Handles book outline form submissions.
+ */
+function book_outline_submit($form_id, $form_values) {
+ $op = $_POST['op'];
+ $node = node_load($form_values['nid']);
+
+ switch ($op) {
+ case t('Add to book outline'):
+ db_query('INSERT INTO {book} (nid, vid, parent, weight) VALUES (%d, %d, %d, %d)', $node->nid, $node->vid, $form_values['parent'], $form_values['weight']);
+ db_query("UPDATE {node_revisions} SET log = '%s' WHERE vid = %d", $form_values['log'], $node->vid);
+ drupal_set_message(t('The post has been added to the book.'));
+ break;
+ case t('Update book outline'):
+ db_query('UPDATE {book} SET parent = %d, weight = %d WHERE vid = %d', $form_values['parent'], $form_values['weight'], $node->vid);
+ db_query("UPDATE {node_revisions} SET log = '%s' WHERE vid = %d", $form_values['log'], $node->vid);
+ drupal_set_message(t('The book outline has been updated.'));
+ break;
+ case t('Remove from book outline'):
+ db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+ drupal_set_message(t('The post has been removed from the book.'));
+ break;
+ }
+ return "node/$node->nid";
+}
+
+/**
+ * Given a node, this function returns an array of 'book node' objects
+ * representing the path in the book tree from the root to the
+ * parent of the given node.
+ *
+ * @param node - a book node object for which to compute the path
+ *
+ * @return - an array of book node objects representing the path of
+ * nodes root to parent of the given node. Returns an empty array if
+ * the node does not exist or is not part of a book hierarchy.
+ *
+ */
+function book_location($node, $nodes = array()) {
+ $parent = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), $node->parent));
+ if (isset($parent->title)) {
+ $nodes = book_location($parent, $nodes);
+ $nodes[] = $parent;
+ }
+ return $nodes;
+}
+
+/**
+ * Accumulates the nodes up to the root of the book from the given node in the $nodes array.
+ */
+function book_location_down($node, $nodes = array()) {
+ $last_direct_child = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND b.parent = %d ORDER BY b.weight DESC, n.title DESC'), $node->nid));
+ if ($last_direct_child) {
+ $nodes[] = $last_direct_child;
+ $nodes = book_location_down($last_direct_child, $nodes);
+ }
+ return $nodes;
+}
+
+/**
+ * Fetches the node object of the previous page of the book.
+ */
+function book_prev($node) {
+ // If the parent is zero, we are at the start of a book so there is no previous.
+ if ($node->parent == 0) {
+ return NULL;
+ }
+
+ // Previous on the same level:
+ $direct_above = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 AND n.moderate = 0 AND (b.weight < %d OR (b.weight = %d AND n.title < '%s')) ORDER BY b.weight DESC, n.title DESC"), $node->parent, $node->weight, $node->weight, $node->title));
+ if ($direct_above) {
+ // Get last leaf of $above.
+ $path = book_location_down($direct_above);
+
+ return $path ? (count($path) > 0 ? array_pop($path) : NULL) : $direct_above;
+ }
+ else {
+ // Direct parent:
+ $prev = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d AND n.status = 1 AND n.moderate = 0'), $node->parent));
+ return $prev;
+ }
+}
+
+/**
+ * Fetches the node object of the next page of the book.
+ */
+function book_next($node) {
+ // get first direct child
+ $child = db_fetch_object(db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 AND n.moderate = 0 ORDER BY b.weight ASC, n.title ASC'), $node->nid));
+ if ($child) {
+ return $child;
+ }
+
+ // No direct child: get next for this level or any parent in this book.
+ $path = book_location($node); // Path to top-level node including this one.
+ $path[] = $node;
+
+ while (($leaf = array_pop($path)) && count($path)) {
+ $next = db_fetch_object(db_query(db_rewrite_sql("SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d AND n.status = 1 AND n.moderate = 0 AND (b.weight > %d OR (b.weight = %d AND n.title > '%s')) ORDER BY b.weight ASC, n.title ASC"), $leaf->parent, $leaf->weight, $leaf->weight, $leaf->title));
+ if ($next) {
+ return $next;
+ }
+ }
+}
+
+/**
+ * Returns the content of a given node. If $teaser if true, returns
+ * the teaser rather than full content. Displays the most recently
+ * approved revision of a node (if any) unless we have to display this
+ * page in the context of the moderation queue.
+ */
+function book_content($node, $teaser = FALSE) {
+ // Return the page body.
+ return node_prepare($node, $teaser);
+}
+
+/**
+ * Implementation of hook_view().
+ *
+ * If not displayed on the main page, we render the node as a page in the
+ * book with extra links to the previous and next pages.
+ */
+function book_view(&$node, $teaser = FALSE, $page = FALSE) {
+ $node = node_prepare($node, $teaser);
+}
+
+/**
+ * Implementation of hook_nodeapi().
+ *
+ * Appends book navigation to all nodes in the book.
+ */
+function book_nodeapi(&$node, $op, $teaser, $page) {
+ switch ($op) {
+ case 'view':
+ if (!$teaser) {
+ $book = db_fetch_array(db_query('SELECT * FROM {book} WHERE vid = %d', $node->vid));
+ if ($book) {
+ if ($node->moderate && user_access('administer nodes')) {
+ drupal_set_message(t("The post has been submitted for moderation and won't be accessible until it has been approved."));
+ }
+
+ foreach ($book as $key => $value) {
+ $node->$key = $value;
+ }
+
+ $path = book_location($node);
+ // Construct the breadcrumb:
+ $node->breadcrumb = array(); // Overwrite the trail with a book trail.
+ foreach ($path as $level) {
+ $node->breadcrumb[] = array('path' => 'node/'. $level->nid, 'title' => $level->title);
+ }
+ $node->breadcrumb[] = array('path' => 'node/'. $node->nid);
+
+ $node->body .= theme('book_navigation', $node);
+
+ if ($page) {
+ menu_set_location($node->breadcrumb);
+ }
+ }
+ }
+ break;
+ case 'delete revision':
+ db_query('DELETE FROM {book} WHERE vid = %d', $node->vid);
+ break;
+ case 'delete':
+ db_query('DELETE FROM {book} WHERE nid = %d', $node->nid);
+ break;
+ }
+}
+
+/**
+ * Prepares the links to children (TOC) and forward/backward
+ * navigation for a node presented as a book page.
+ *
+ * @ingroup themeable
+ */
+function theme_book_navigation($node) {
+ $output = '';
+ $links = '';
+
+ if ($node->nid) {
+ $tree = book_tree($node->nid);
+
+ if ($prev = book_prev($node)) {
+ drupal_add_link(array('rel' => 'prev', 'href' => url('node/'. $prev->nid)));
+ $links .= l(t('â¹ ') . $prev->title, 'node/'. $prev->nid, array('class' => 'page-previous', 'title' => t('Go to previous page')));
+ }
+ if ($node->parent) {
+ drupal_add_link(array('rel' => 'up', 'href' => url('node/'. $node->parent)));
+ $links .= l(t('up'), 'node/'. $node->parent, array('class' => 'page-up', 'title' => t('Go to parent page')));
+ }
+ if ($next = book_next($node)) {
+ drupal_add_link(array('rel' => 'next', 'href' => url('node/'. $next->nid)));
+ $links .= l($next->title . t(' âº'), 'node/'. $next->nid, array('class' => 'page-next', 'title' => t('Go to next page')));
+ }
+
+ if (isset($tree) || isset($links)) {
+ $output = '';
+ if (isset($tree)) {
+ $output .= $tree;
+ }
+ if (isset($links)) {
+ $output .= '
'. $links .'
';
+ }
+ $output .= '
';
+ }
+ }
+
+ return $output;
+}
+
+/**
+ * This is a helper function for book_toc().
+ */
+function book_toc_recurse($nid, $indent, $toc, $children, $exclude) {
+ if ($children[$nid]) {
+ foreach ($children[$nid] as $foo => $node) {
+ if (!$exclude || $exclude != $node->nid) {
+ $toc[$node->nid] = $indent .' '. $node->title;
+ $toc = book_toc_recurse($node->nid, $indent .'--', $toc, $children, $exclude);
+ }
+ }
+ }
+
+ return $toc;
+}
+
+/**
+ * Returns an array of titles and nid entries of book pages in table of contents order.
+ */
+function book_toc($exclude = 0) {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 ORDER BY b.weight, n.title'));
+
+ while ($node = db_fetch_object($result)) {
+ if (!$children[$node->parent]) {
+ $children[$node->parent] = array();
+ }
+ $children[$node->parent][] = $node;
+ }
+
+ $toc = array();
+ // If the user has permission to create new books, add the top-level book page to the menu;
+ if (user_access('create new books')) {
+ $toc[0] = '<'. t('top-level') .'>';
+ }
+
+ $toc = book_toc_recurse(0, '', $toc, $children, $exclude);
+
+ return $toc;
+}
+
+/**
+ * This is a helper function for book_tree()
+ */
+function book_tree_recurse($nid, $depth, $children, $unfold = array()) {
+ $output = '';
+ if ($depth > 0) {
+ if (isset($children[$nid])) {
+ foreach ($children[$nid] as $foo => $node) {
+ if (in_array($node->nid, $unfold)) {
+ if ($tree = book_tree_recurse($node->nid, $depth - 1, $children, $unfold)) {
+ $output .= '- ';
+ $output .= l($node->title, 'node/'. $node->nid);
+ $output .= '';
+ $output .= '
';
+ }
+ else {
+ $output .= '- '. l($node->title, 'node/'. $node->nid) .'
';
+ }
+ }
+ else {
+ if ($tree = book_tree_recurse($node->nid, 1, $children)) {
+ $output .= '- '. l($node->title, 'node/'. $node->nid) .'
';
+ }
+ else {
+ $output .= '- '. l($node->title, 'node/'. $node->nid) .'
';
+ }
+ }
+ }
+ }
+ }
+
+ return $output;
+}
+
+/**
+ * Returns an HTML nested list (wrapped in a menu-class div) representing the book nodes
+ * as a tree.
+ */
+function book_tree($parent = 0, $depth = 3, $unfold = array()) {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND n.moderate = 0 ORDER BY b.weight, n.title'));
+
+ while ($node = db_fetch_object($result)) {
+ $list = isset($children[$node->parent]) ? $children[$node->parent] : array();
+ $list[] = $node;
+ $children[$node->parent] = $list;
+ }
+
+ if ($tree = book_tree_recurse($parent, $depth, $children, $unfold)) {
+ return '';
+ }
+}
+
+/**
+ * Menu callback; prints a listing of all books.
+ */
+function book_render() {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = 0 AND n.status = 1 AND n.moderate = 0 ORDER BY b.weight, n.title'));
+
+ $books = array();
+ while ($node = db_fetch_object($result)) {
+ $books[] = l($node->title, 'node/'. $node->nid);
+ }
+
+ return theme('item_list', $books);
+}
+
+/**
+ * Menu callback; Generates various representation of a book page with
+ * all descendants and prints the requested representation to output.
+ *
+ * The function delegates the generation of output to helper functions.
+ * The function name is derived by prepending 'book_export_' to the
+ * given output type. So, e.g., a type of 'html' results in a call to
+ * the function book_export_html().
+ *
+ * @param type
+ * - a string encoding the type of output requested.
+ * The following types are currently supported in book module
+ * html: HTML (printer friendly output)
+ * Other types are supported in contributed modules.
+ * @param nid
+ * - an integer representing the node id (nid) of the node to export
+ *
+ */
+function book_export($type = 'html', $nid = 0) {
+ $type = drupal_strtolower($type);
+ $node_result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.nid = %d'), $nid);
+ if (db_num_rows($node_result) > 0) {
+ $node = db_fetch_object($node_result);
+ }
+ $depth = count(book_location($node)) + 1;
+ $export_function = 'book_export_' . $type;
+
+ if (function_exists($export_function)) {
+ print call_user_func($export_function, $nid, $depth);
+ }
+ else {
+ drupal_set_message(t('Unknown export format.'));
+ drupal_not_found();
+ }
+}
+
+/**
+ * This function is called by book_export() to generate HTML for export.
+ *
+ * The given node is /embedded to its absolute depth in a top level
+ * section/. For example, a child node with depth 2 in the hierarchy
+ * is contained in (otherwise empty) <div> elements
+ * corresponding to depth 0 and depth 1. This is intended to support
+ * WYSIWYG output - e.g., level 3 sections always look like level 3
+ * sections, no matter their depth relative to the node selected to be
+ * exported as printer-friendly HTML.
+ *
+ * @param nid
+ * - an integer representing the node id (nid) of the node to export
+ * @param depth
+ * - an integer giving the depth in the book hierarchy of the node
+ * which is to be exported
+ *
+ * @return
+ * - string containing HTML representing the node and its children in
+ * the book hierarchy
+*/
+function book_export_html($nid, $depth) {
+ if (user_access('see printer-friendly version')) {
+ $node = node_load($nid);
+ for ($i = 1; $i < $depth; $i++) {
+ $content .= "\n";
+ }
+ $content .= book_recurse($nid, $depth, 'book_node_visitor_html_pre', 'book_node_visitor_html_post');
+ for ($i = 1; $i < $depth; $i++) {
+ $content .= "
\n";
+ }
+ return theme('book_export_html', check_plain($node->title), $content);
+ }
+ else {
+ drupal_access_denied();
+ }
+}
+
+/**
+ * How the book's HTML export should be themed
+ *
+ * @ingroup themeable
+ */
+function theme_book_export_html($title, $content) {
+ global $base_url;
+ $html = "\n";
+ $html .= '';
+ $html .= "\n". $title ."\n";
+ $html .= '';
+ $html .= '' . "\n";
+ $html .= "\n";
+ $html .= "\n\n". $content . "\n\n\n";
+ return $html;
+}
+
+/**
+ * Traverses the book tree. Applies the $visit_pre() callback to each
+ * node, is called recursively for each child of the node (in weight,
+ * title order). Finally appends the output of the $visit_post()
+ * callback to the output before returning the generated output.
+ *
+ * @param nid
+ * - the node id (nid) of the root node of the book hierarchy.
+ * @param depth
+ * - the depth of the given node in the book hierarchy.
+ * @param visit_pre
+ * - a function callback to be called upon visiting a node in the tree
+ * @param visit_post
+ * - a function callback to be called after visiting a node in the tree,
+ * but before recursively visiting children.
+ * @return
+ * - the output generated in visiting each node
+ */
+function book_recurse($nid = 0, $depth = 1, $visit_pre, $visit_post) {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND n.nid = %d AND n.moderate = 0 ORDER BY b.weight, n.title'), $nid);
+ while ($page = db_fetch_object($result)) {
+ // Load the node:
+ $node = node_load($page->nid);
+
+ if ($node) {
+ if (function_exists($visit_pre)) {
+ $output .= call_user_func($visit_pre, $node, $depth, $nid);
+ }
+ else {
+ $output .= book_node_visitor_html_pre($node, $depth, $nid);
+ }
+
+ $children = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE n.status = 1 AND b.parent = %d AND n.moderate = 0 ORDER BY b.weight, n.title'), $node->nid);
+ while ($childpage = db_fetch_object($children)) {
+ $childnode = node_load($childpage->nid);
+ if ($childnode->nid != $node->nid) {
+ $output .= book_recurse($childnode->nid, $depth + 1, $visit_pre, $visit_post);
+ }
+ }
+ if (function_exists($visit_post)) {
+ $output .= call_user_func($visit_post, $node, $depth);
+ }
+ else {
+ # default
+ $output .= book_node_visitor_html_post($node, $depth);
+ }
+ }
+ }
+
+ return $output;
+}
+
+/**
+ * Generates printer-friendly HTML for a node. This function
+ * is a 'pre-node' visitor function for book_recurse().
+ *
+ * @param $node
+ * - the node to generate output for.
+ * @param $depth
+ * - the depth of the given node in the hierarchy. This
+ * is used only for generating output.
+ * @param $nid
+ * - the node id (nid) of the given node. This
+ * is used only for generating output.
+ * @return
+ * - the HTML generated for the given node.
+ */
+function book_node_visitor_html_pre($node, $depth, $nid) {
+ // Output the content:
+ if (node_hook($node, 'content')) {
+ $node = node_invoke($node, 'content');
+ }
+ // Allow modules to change $node->body before viewing.
+ node_invoke_nodeapi($node, 'print', $node->body, false);
+
+ $output .= "nid ."\" class=\"section-$depth\">\n";
+ $output .= "
". check_plain($node->title) ."
\n";
+
+ if ($node->body) {
+ $output .= $node->body;
+ }
+ return $output;
+}
+
+/**
+ * Finishes up generation of printer-friendly HTML after visiting a
+ * node. This function is a 'post-node' visitor function for
+ * book_recurse().
+ */
+function book_node_visitor_html_post($node, $depth) {
+ return "\n";
+}
+
+function _book_admin_table($nodes = array()) {
+ $form = array(
+ '#theme' => 'book_admin_table',
+ '#tree' => TRUE,
+ );
+
+ foreach ($nodes as $node) {
+ $form = array_merge($form, _book_admin_table_tree($node, 0));
+ }
+
+ return $form;
+}
+
+function _book_admin_table_tree($node, $depth) {
+ $form = array();
+
+ $form[] = array(
+ 'nid' => array('#type' => 'value', '#value' => $node->nid),
+ 'depth' => array('#type' => 'value', '#value' => $depth),
+ 'title' => array(
+ '#type' => 'textfield',
+ '#default_value' => $node->title,
+ '#maxlength' => 255,
+ ),
+ 'weight' => array(
+ '#type' => 'weight',
+ '#default_value' => $node->weight,
+ '#delta' => 15,
+ ),
+ );
+
+ $children = db_query(db_rewrite_sql('SELECT n.nid, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = %d ORDER BY b.weight, n.title'), $node->nid);
+ while ($child = db_fetch_object($children)) {
+ $form = array_merge($form, _book_admin_table_tree(node_load($child->nid), $depth + 1));
+ }
+
+ return $form;
+}
+
+function theme_book_admin_table($form) {
+ $header = array(t('Title'), t('Weight'), array('data' => t('Operations'), 'colspan' => '3'));
+
+ $rows = array();
+ foreach (element_children($form) as $key) {
+ $nid = $form[$key]['nid']['#value'];
+ $pid = $form[0]['nid']['#value'];
+ if ($pid == $nid) {
+ // Don't return to the parent book page if it is deleted.
+ $pid = '';
+ }
+ $rows[] = array(
+ ''. form_render($form[$key]['title']) .'
',
+ form_render($form[$key]['weight']),
+ l(t('view'), 'node/'. $nid),
+ l(t('edit'), 'node/'. $nid .'/edit'),
+ l(t('delete'), 'node/'. $nid .'/delete', NULL, 'destination=admin/node/book/'. (arg(3) == 'orphan' ? 'orphan' : $pid)),
+ );
+ }
+
+ return theme('table', $header, $rows);
+}
+
+/**
+ * Display an administrative view of the hierarchy of a book.
+ */
+function book_admin_edit($nid) {
+ $node = node_load($nid);
+ if ($node->nid) {
+ drupal_set_title(check_plain($node->title));
+ $form = array();
+
+ $form['table'] = _book_admin_table(array($node));
+ $form['save'] = array(
+ '#type' => 'submit',
+ '#value' => t('Save book pages'),
+ );
+
+ return drupal_get_form('book_admin_edit', $form);
+ }
+ else {
+ drupal_not_found();
+ }
+}
+
+/**
+ * Menu callback; displays a listing of all orphaned book pages.
+ */
+function book_admin_orphan() {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, n.status, b.parent FROM {node} n INNER JOIN {book} b ON n.vid = b.vid'));
+
+ $pages = array();
+ while ($page = db_fetch_object($result)) {
+ $pages[$page->nid] = $page;
+ }
+
+ $orphans = array();
+ if (count($pages)) {
+ foreach ($pages as $page) {
+ if ($page->parent && empty($pages[$page->parent])) {
+ $orphans[] = node_load($page->nid);
+ }
+ }
+ }
+
+ if (count($orphans)) {
+ $form = array();
+
+ $form['table'] = _book_admin_table($orphans);
+ $form['save'] = array(
+ '#type' => 'submit',
+ '#value' => t('Save book pages'),
+ );
+
+ return drupal_get_form('book_admin_edit', $form);
+ }
+ else {
+ return ''. t('There are no orphan pages.') .'
';
+ }
+}
+
+function book_admin_edit_submit($form_id, $form_values) {
+ foreach ($form_values['table'] as $row) {
+ $node = node_load($row['nid']);
+
+ if ($row['title'] != $node->title || $row['weight'] != $node->weight) {
+ $node->title = $row['title'];
+ $node->weight = $row['weight'];
+
+ node_save($node);
+ watchdog('content', t('%type: updated %title.', array('%type' => theme('placeholder', t('book')), '%title' => theme('placeholder', $node->title))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $node->nid));
+ }
+ }
+
+ if (is_numeric(arg(3))) {
+ // Updating pages in a single book.
+ $book = node_load(arg(3));
+ drupal_set_message(t('Updated book %title.', array('%title' => theme('placeholder', $book->title))));
+ }
+ else {
+ // Updating the orphan pages.
+ drupal_set_message(t('Updated orphan book pages.'));
+ }
+}
+
+/**
+ * Menu callback; displays the book administration page.
+ */
+function book_admin($nid = 0) {
+ if ($nid) {
+ return book_admin_edit($nid);
+ }
+ else {
+ return book_admin_overview();
+ }
+}
+
+/**
+ * Returns an administrative overview of all books.
+ */
+function book_admin_overview() {
+ $result = db_query(db_rewrite_sql('SELECT n.nid, n.title, b.weight FROM {node} n INNER JOIN {book} b ON n.vid = b.vid WHERE b.parent = 0 ORDER BY b.weight, n.title'));
+ while ($book = db_fetch_object($result)) {
+ $rows[] = array(l($book->title, "node/$book->nid"), l(t('outline'), "admin/node/book/$book->nid"));
+ }
+ $headers = array(t('Book'), t('Operations'));
+
+ return theme('table', $headers, $rows);
+}
+
+/**
+ * Implementation of hook_help().
+ */
+function book_help($section) {
+ switch ($section) {
+ case 'admin/help#book':
+ $output = ''. t('The book content type is suited for creating structured, multi-page hypertexts such as site resource guides, manuals, and Frequently Asked Questions (FAQs). It permits a document to have chapters, sections, subsections, etc. Authors with suitable permissions can add pages to a collaborative book, placing them into the existing document by adding them to a table of contents menu. ') .'
';
+ $output .= ''. t('Books have additional previous, up, and next navigation elements at the bottom of each page for moving through the text. Additional navigation may be provided by enabling the book navigation block on the block administration page.', array('%admin-block' => url('admin/block'))) .'
';
+ $output .= ''. t('Users can select the printer-friendly version link visible at the bottom of a book page to generate a printer-friendly display of the page and all of its subsections. ') .'
';
+ $output .= ''. t('Administrators can view a book outline, from which is it possible to change the titles of sections, and their weight (thus reordering sections). From this outline, it is also possible to edit and/or delete book pages. Many content types besides pages (for example, blog entries, stories, and polls) can be added to a collaborative book by choosing the outline tab when viewing the post.') .'
';
+ $output .= t('You can
+
+', array('%node-add-book' => url('node/add/book'), '%admin-node-book' => url('admin/node/book'), '%admin-settings-content-types-book-page' => url('admin/settings/content-types/book'), '%admin-block' => url('admin/block'), '%admin-access' => url('admin/access')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Book page.', array('%book' => 'http://drupal.org/handbook/modules/book/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Allows users to collaboratively author a book.');
+ case 'admin/node/book':
+ return t('The book module offers a means to organize content, authored by many users, in an online manual, outline or FAQ.
');
+ case 'admin/node/book/orphan':
+ return t('Pages in a book are like a tree. As pages are edited, reorganized and removed, child pages might be left with no link to the rest of the book. Such pages are referred to as "orphan pages". On this page, administrators can review their books for orphans and reattach those pages as desired.
');
+ case 'node/add#book':
+ return t("A book is a collaborative writing effort: users can collaborate writing the pages of the book, positioning the pages in the right order, and reviewing or modifying pages previously written. So when you have some information to share or when you read a page of the book and you didn't like it, or if you think a certain page could have been written better, you can do something about it.");
+ }
+
+ if (arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'outline') {
+ return t('The outline feature allows you to include posts in the book hierarchy.', array('%book' => url('book')));
+ }
+}
+
+
diff --git a/modules/comment.module b/modules/comment.module
new file mode 100644
index 0000000..d6df750
--- /dev/null
+++ b/modules/comment.module
@@ -0,0 +1,1787 @@
+'. t('The comment module creates a discussion board for each post. Users can post comments to discuss a forum topic, weblog post, story, collaborative book page, etc. The ability to comment is an important part of involving members in a community dialogue.') .'';
+ $output .= ''. t('An administrator can give comment permissions to user groups, and users can (optionally) edit their last comment, assuming no others have been posted since. Attached to each comment board is a control panel for customizing the way that comments are displayed. Users can control the chronological ordering of posts (newest or oldest first) and the number of posts to display on each page. Comments behave like other user submissions. Filters, smileys and HTML that work in nodes will also work with comments. The comment module provides specific features to inform site members when new comments have been posted.') .'
';
+ $output .= t('You can
+
+', array('%admin-access' => url('admin/access'), '%admin-comment-configure' => url('admin/comment/configure')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Comment page.', array('%comment' => 'http://drupal.org/handbook/modules/comment/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Allows users to comment on and discuss published content.');
+ case 'admin/comment':
+ case 'admin/comment/new':
+ return t("Below is a list of the latest comments posted to your site. Click on a subject to see the comment, the author's name to edit the author's user information , \"edit\" to modify the text, and \"delete\" to remove their submission.
");
+ case 'admin/comment/approval':
+ return t("Below is a list of the comments posted to your site that need approval. To approve a comment, click on \"edit\" and then change its \"moderation status\" to Approved. Click on a subject to see the comment, the author's name to edit the author's user information, \"edit\" to modify the text, and \"delete\" to remove their submission.
");
+ case 'admin/comment/configure':
+ case 'admin/comment/configure/settings':
+ return t("Comments can be attached to any node, and their settings are below. The display comes in two types: a \"flat list\" where everything is flush to the left side, and comments come in chronological order, and a \"threaded list\" where replies to other comments are placed immediately below and slightly indented, forming an outline. They also come in two styles: \"expanded\", where you see both the title and the contents, and \"collapsed\" where you only see the title. Preview comment forces a user to look at their comment by clicking on a \"Preview\" button before they can actually add the comment.
");
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function comment_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $access = user_access('administer comments');
+ $items[] = array('path' => 'admin/comment', 'title' => t('comments'),
+ 'callback' => 'comment_admin_overview', 'access' => $access);
+
+ // Tabs:
+ $items[] = array('path' => 'admin/comment/list', 'title' => t('list'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
+ $items[] = array('path' => 'admin/comment/configure', 'title' => t('configure'),
+ 'callback' => 'comment_configure', 'access' => $access, 'type' => MENU_LOCAL_TASK);
+
+ // Subtabs:
+ $items[] = array('path' => 'admin/comment/list/new', 'title' => t('published comments'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
+ $items[] = array('path' => 'admin/comment/list/approval', 'title' => t('approval queue'),
+ 'callback' => 'comment_admin_overview', 'access' => $access,
+ 'callback arguments' => array('approval'),
+ 'type' => MENU_LOCAL_TASK);
+
+ $items[] = array('path' => 'admin/comment/configure/settings', 'title' => t('settings'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK, 'weight' => -10);
+
+ $items[] = array('path' => 'comment/delete', 'title' => t('delete comment'),
+ 'callback' => 'comment_delete', 'access' => $access, 'type' => MENU_CALLBACK);
+
+ $access = user_access('post comments');
+ $items[] = array('path' => 'comment/edit', 'title' => t('edit comment'),
+ 'callback' => 'comment_edit', 'access' => $access, 'type' => MENU_CALLBACK);
+ }
+ else {
+ if (arg(0) == 'comment' && arg(1) == 'reply' && is_numeric(arg(2))) {
+ $node = node_load(arg(2));
+ if ($node->nid) {
+ $items[] = array('path' => 'comment/reply', 'title' => t('reply to comment'),
+ 'callback' => 'comment_reply', 'access' => node_access('view', $node), 'type' => MENU_CALLBACK);
+ }
+ }
+ if ((arg(0) == 'node') && is_numeric(arg(1)) && is_numeric(arg(2))) {
+ $items[] = array('path' => ('node/'. arg(1) .'/'. arg(2)), 'title' => t('view'),
+ 'callback' => 'node_page',
+ 'type' => MENU_CALLBACK);
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function comment_perm() {
+ return array('access comments', 'post comments', 'administer comments', 'post comments without approval');
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Generates a block with the most recent comments.
+ */
+function comment_block($op = 'list', $delta = 0) {
+ if ($op == 'list') {
+ $blocks[0]['info'] = t('Recent comments');
+ return $blocks;
+ }
+ else if ($op == 'view' && user_access('access comments')) {
+ $block['subject'] = t('Recent comments');
+ $block['content'] = theme('comment_block');
+ return $block;
+ }
+}
+
+function theme_comment_block() {
+ $result = db_query_range(db_rewrite_sql('SELECT c.nid, c.subject, c.cid, c.timestamp FROM {comments} c INNER JOIN {node} n ON n.nid = c.nid WHERE n.status = 1 AND c.status = %d ORDER BY c.timestamp DESC', 'c'), COMMENT_PUBLISHED, 0, 10);
+ $items = array();
+ while ($comment = db_fetch_object($result)) {
+ $items[] = l($comment->subject, 'node/'. $comment->nid, NULL, NULL, 'comment-'. $comment->cid) .'
'. t('%time ago', array('%time' => format_interval(time() - $comment->timestamp)));
+ }
+ return theme('item_list', $items);
+}
+
+/**
+ * Implementation of hook_link().
+ */
+function comment_link($type, $node = 0, $main = 0) {
+ $links = array();
+
+ if ($type == 'node' && $node->comment) {
+
+ if ($main) {
+ // Main page: display the number of comments that have been posted.
+
+ if (user_access('access comments')) {
+ $all = comment_num_all($node->nid);
+ $new = comment_num_new($node->nid);
+
+ if ($all) {
+ $links[] = l(format_plural($all, '1 comment', '%count comments'), "node/$node->nid", array('title' => t('Jump to the first comment of this posting.')), NULL, 'comment');
+
+ if ($new) {
+ $links[] = l(format_plural($new, '1 new comment', '%count new comments'), "node/$node->nid", array('title' => t('Jump to the first new comment of this posting.')), NULL, 'new');
+ }
+ }
+ else {
+ if ($node->comment == COMMENT_NODE_READ_WRITE) {
+ if (user_access('post comments')) {
+ $links[] = l(t('add new comment'), "comment/reply/$node->nid", array('title' => t('Add a new comment to this page.')), NULL, 'comment_form');
+ }
+ else {
+ $links[] = theme('comment_post_forbidden', $node->nid);
+ }
+ }
+ }
+ }
+ }
+ else {
+ // Node page: add a "post comment" link if the user is allowed to
+ // post comments, if this node is not read-only, and if the comment form isn't already shown
+
+ if ($node->comment == COMMENT_NODE_READ_WRITE) {
+ if (user_access('post comments')) {
+ if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
+ $links[] = l(t('add new comment'), "comment/reply/$node->nid", array('title' => t('Share your thoughts and opinions related to this posting.')), NULL, 'comment_form');
+ }
+ }
+ else {
+ $links[] = theme('comment_post_forbidden', $node->nid);
+ }
+ }
+ }
+ }
+
+ if ($type == 'comment') {
+ $links = comment_links($node, $main);
+ }
+
+ return $links;
+}
+
+function comment_form_alter($form_id, &$form) {
+ if (isset($form['type'])) {
+ if ($form['type']['#value'] .'_node_settings' == $form_id) {
+ $form['workflow']['comment_'. $form['type']['#value']] = array('#type' => 'radios', '#title' => t('Default comment setting'), '#default_value' => variable_get('comment_'. $form['type']['#value'], COMMENT_NODE_READ_WRITE), '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')), '#description' => t('Users with the administer comments permission will be able to override this setting.'));
+ }
+ if ($form['type']['#value'] .'_node_form' == $form_id) {
+ $node = $form['#node'];
+ if (user_access('administer comments')) {
+ $form['comment_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Comment settings'),
+ '#collapsible' => TRUE,
+ '#collapsed' => TRUE,
+ '#weight' => 30,
+ );
+ $form['comment_settings']['comment'] = array(
+ '#type' => 'radios',
+ '#parents' => array('comment'),
+ '#default_value' => $node->comment,
+ '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
+ );
+ }
+ else {
+ $form['comment_settings']['comment'] = array(
+ '#type' => 'value',
+ '#value' => $node->comment,
+ );
+ }
+ }
+ }
+}
+
+/**
+ * Implementation of hook_nodeapi().
+ *
+ */
+function comment_nodeapi(&$node, $op, $arg = 0) {
+ switch ($op) {
+ case 'load':
+ return db_fetch_array(db_query("SELECT last_comment_timestamp, last_comment_name, comment_count FROM {node_comment_statistics} WHERE nid = %d", $node->nid));
+ break;
+
+ case 'prepare':
+ if (!isset($node->comment)) {
+ $node->comment = variable_get("comment_$node->type", COMMENT_NODE_READ_WRITE);
+ }
+ break;
+
+ case 'insert':
+ db_query('INSERT INTO {node_comment_statistics} (nid, last_comment_timestamp, last_comment_name, last_comment_uid, comment_count) VALUES (%d, %d, NULL, %d, 0)', $node->nid, $node->created, $node->uid);
+ break;
+
+ case 'delete':
+ db_query('DELETE FROM {comments} WHERE nid = %d', $node->nid);
+ db_query('DELETE FROM {node_comment_statistics} WHERE nid = %d', $node->nid);
+ break;
+
+ case 'update index':
+ $text = '';
+ $comments = db_query('SELECT subject, comment, format FROM {comments} WHERE nid = %d AND status = %d', $node->nid, COMMENT_PUBLISHED);
+ while ($comment = db_fetch_object($comments)) {
+ $text .= ''. check_plain($comment->subject) .'
'. check_markup($comment->comment, $comment->format, FALSE);
+ }
+ return $text;
+
+ case 'search result':
+ $comments = db_result(db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = %d', $node->nid));
+ return format_plural($comments, '1 comment', '%count comments');
+
+ case 'rss item':
+ return array(array('key' => 'comments', 'value' => url('node/'. $node->nid, NULL, 'comment', TRUE)));
+ }
+}
+
+/**
+ * Implementation of hook_user().
+ *
+ * Provides signature customization for the user's comments.
+ */
+function comment_user($type, $edit, &$user, $category = NULL) {
+ if ($type == 'form' && $category == 'account') {
+ // when user tries to edit his own data
+ $form['comment_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Comment settings'),
+ '#collapsible' => TRUE,
+ '#weight' => 4);
+ $form['comment_settings']['signature'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Signature'),
+ '#default_value' => $edit['signature'],
+ '#description' => t('Your signature will be publicly displayed at the end of your comments.'));
+
+ return $form;
+ }
+ elseif ($type == 'delete') {
+ db_query('UPDATE {comments} SET uid = 0 WHERE uid = %d', $user->uid);
+ db_query('UPDATE {node_comment_statistics} SET last_comment_uid = 0 WHERE last_comment_uid = %d', $user->uid);
+ }
+}
+
+/**
+ * Menu callback; presents the comment settings page.
+ */
+function comment_configure() {
+ $form['viewing_options'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Viewing options'),
+ '#collapsible' => TRUE,
+ '#collapsed' => TRUE,
+ );
+
+ $form['viewing_options']['comment_default_mode'] = array(
+ '#type' => 'radios',
+ '#title' => t('Default display mode'),
+ '#default_value' => variable_get('comment_default_mode', COMMENT_MODE_THREADED_EXPANDED),
+ '#options' => _comment_get_modes(),
+ '#description' => t('The default view for comments. Expanded views display the body of the comment. Threaded views keep replies together.'),
+ );
+
+ $form['viewing_options']['comment_default_order'] = array(
+ '#type' => 'radios',
+ '#title' => t('Default display order'),
+ '#default_value' => variable_get('comment_default_order', COMMENT_ORDER_NEWEST_FIRST),
+ '#options' => _comment_get_orders(),
+ '#description' => t('The default sorting for new users and anonymous users while viewing comments. These users may change their view using the comment control panel. For registered users, this change is remembered as a persistent user preference.'),
+ );
+
+ $form['viewing_options']['comment_default_per_page'] = array(
+ '#type' => 'select',
+ '#title' => t('Default comments per page'),
+ '#default_value' => variable_get('comment_default_per_page', 50),
+ '#options' => _comment_per_page(),
+ '#description' => t('Default number of comments for each page: more comments are distributed in several pages.'),
+ );
+
+ $form['viewing_options']['comment_controls'] = array(
+ '#type' => 'radios',
+ '#title' => t('Comment controls'),
+ '#default_value' => variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN),
+ '#options' => array(
+ t('Display above the comments'),
+ t('Display below the comments'),
+ t('Display above and below the comments'),
+ t('Do not display')),
+ '#description' => t('Position of the comment controls box. The comment controls let the user change the default display mode and display order of comments.'),
+ );
+
+ $form['posting_settings'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Posting settings'),
+ '#collapsible' => TRUE,
+ '#collapsed' => TRUE,
+ );
+
+ $form['posting_settings']['comment_anonymous'] = array(
+ '#type' => 'radios',
+ '#title' => t('Anonymous commenting'),
+ '#default_value' => variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT),
+ '#options' => array(
+ COMMENT_ANONYMOUS_MAYNOT_CONTACT => t('Anonymous posters may not enter their contact information'),
+ COMMENT_ANONYMOUS_MAY_CONTACT => t('Anonymous posters may leave their contact information'),
+ COMMENT_ANONYMOUS_MUST_CONTACT => t('Anonymous posters must leave their contact information')),
+ '#description' => t('This option is enabled when anonymous users have permission to post comments on the permissions page.', array('%url' => url('admin/access'))),
+ );
+ if (!user_access('post comments', user_load(array('uid' => 0)))) {
+ $form['posting_settings']['comment_anonymous']['#attributes'] = array('disabled' => 'disabled');
+ }
+
+ $form['posting_settings']['comment_subject_field'] = array(
+ '#type' => 'radios',
+ '#title' => t('Comment subject field'),
+ '#default_value' => variable_get('comment_subject_field', 1),
+ '#options' => array(t('Disabled'), t('Enabled')),
+ '#description' => t('Can users provide a unique subject for their comments?'),
+ );
+
+ $form['posting_settings']['comment_preview'] = array(
+ '#type' => 'radios',
+ '#title' => t('Preview comment'),
+ '#default_value' => variable_get('comment_preview', COMMENT_PREVIEW_REQUIRED),
+ '#options' => array(t('Optional'), t('Required')),
+ );
+
+ $form['posting_settings']['comment_form_location'] = array(
+ '#type' => 'radios',
+ '#title' => t('Location of comment submission form'),
+ '#default_value' => variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE),
+ '#options' => array(t('Display on separate page'), t('Display below post or comments')),
+ );
+
+ return system_settings_form('comment_settings_form', $form);
+}
+
+/**
+ * This is *not* a hook_access() implementation. This function is called
+ * to determine whether the current user has access to a particular comment.
+ *
+ * Authenticated users can edit their comments as long they have not been
+ * replied to. This prevents people from changing or revising their
+ * statements based on the replies to their posts.
+ */
+function comment_access($op, $comment) {
+ global $user;
+
+ if ($op == 'edit') {
+ return ($user->uid && $user->uid == $comment->uid && comment_num_replies($comment->cid) == 0) || user_access('administer comments');
+ }
+}
+
+function comment_node_url() {
+ return arg(0) .'/'. arg(1);
+}
+
+function comment_edit($cid) {
+ global $user;
+
+ $comment = db_fetch_object(db_query('SELECT c.*, u.uid, u.name AS registered_name, u.data FROM {comments} c INNER JOIN {users} u ON c.uid = u.uid WHERE c.cid = %d', $cid));
+ $comment = drupal_unpack($comment);
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ if (comment_access('edit', $comment)) {
+ return comment_form((array)$comment);
+ }
+ else {
+ drupal_access_denied();
+ }
+}
+
+function comment_reply($nid, $pid = NULL) {
+ // set the breadcrumb trail
+ $node = node_load($nid);
+ menu_set_location(array(array('path' => "node/$nid", 'title' => $node->title), array('path' => "comment/reply/$nid")));
+
+ $op = isset($_POST['op']) ? $_POST['op'] : '';
+
+ $output = '';
+
+ // or are we merely showing the form?
+ if (user_access('access comments')) {
+
+ if ($op == t('Preview comment')) {
+ if (user_access('post comments')) {
+ $output .= comment_form(array('pid' => $pid, 'nid' => $nid), NULL);
+ }
+ else {
+ drupal_set_message(t('You are not authorized to post comments.'), 'error');
+ drupal_goto("node/$nid");
+ }
+ }
+ else {
+ // if this is a reply to another comment, show that comment first
+ // else, we'll just show the user the node they're commenting on.
+ if ($pid) {
+ if ($comment = db_fetch_object(db_query('SELECT c.*, u.uid, u.name AS registered_name, u.picture, u.data FROM {comments} c INNER JOIN {users} u ON c.uid = u.uid WHERE c.cid = %d AND c.status = %d', $pid, COMMENT_PUBLISHED))) {
+ if ($comment->nid != $nid) {
+ // Attempting to reply to a comment not belonging to the current nid.
+ drupal_set_message(t('The comment you are replying to does not exist.'), 'error');
+ drupal_goto("node/$nid");
+ }
+ $comment = drupal_unpack($comment);
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ $output .= theme('comment_view', $comment);
+ }
+ else {
+ drupal_set_message(t('The comment you are replying to does not exist.'), 'error');
+ drupal_goto("node/$nid");
+ }
+ }
+ else if (user_access('access content')) {
+ $output .= node_view($node);
+ }
+
+ // should we show the reply box?
+ if (node_comment_mode($nid) != COMMENT_NODE_READ_WRITE) {
+ drupal_set_message(t("This discussion is closed: you can't post new comments."), 'error');
+ drupal_goto("node/$nid");
+ }
+ else if (user_access('post comments')) {
+ $output .= comment_form(array('pid' => $pid, 'nid' => $nid), t('Reply'));
+ }
+ else {
+ drupal_set_message(t('You are not authorized to post comments.'), 'error');
+ drupal_goto("node/$nid");
+ }
+ }
+ }
+ else {
+ drupal_set_message(t('You are not authorized to view comments.'), 'error');
+ drupal_goto("node/$nid");
+ }
+
+ return $output;
+}
+
+/**
+ * Accepts a submission of new or changed comment content.
+ *
+ * @param $edit
+ * A comment array.
+ *
+ * @return
+ * If the comment is successfully saved the comment ID is returned. If the comment
+ * is not saved, FALSE is returned.
+ */
+function comment_save($edit) {
+ global $user;
+ if (user_access('post comments') && (user_access('administer comments') || node_comment_mode($edit['nid']) == COMMENT_NODE_READ_WRITE)) {
+ if (!form_get_errors()) {
+ // Check for duplicate comments. Note that we have to use the
+ // validated/filtered data to perform such check.
+ $duplicate = db_result(db_query("SELECT COUNT(cid) FROM {comments} WHERE pid = %d AND nid = %d AND subject = '%s' AND comment = '%s'", $edit['pid'], $edit['nid'], $edit['subject'], $edit['comment']), 0);
+ if ($duplicate != 0) {
+ watchdog('content', t('Comment: duplicate %subject.', array('%subject' => theme('placeholder', $edit['subject']))), WATCHDOG_WARNING);
+ }
+
+ if ($edit['cid']) {
+ // Update the comment in the database.
+ db_query("UPDATE {comments} SET status = %d, timestamp = %d, subject = '%s', comment = '%s', format = %d, uid = %d, name = '%s', mail = '%s', homepage = '%s' WHERE cid = %d", $edit['status'], $edit['timestamp'], $edit['subject'], $edit['comment'], $edit['format'], $edit['uid'], $edit['name'], $edit['mail'], $edit['homepage'], $edit['cid']);
+
+ _comment_update_node_statistics($edit['nid']);
+
+ // Allow modules to respond to the updating of a comment.
+ comment_invoke_comment($edit, 'update');
+
+
+ // Add an entry to the watchdog log.
+ watchdog('content', t('Comment: updated %subject.', array('%subject' => theme('placeholder', $edit['subject']))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $edit['nid'], NULL, NULL, 'comment-'. $edit['cid']));
+ }
+ else {
+ // Add the comment to database.
+ $status = user_access('post comments without approval') ? COMMENT_PUBLISHED : COMMENT_NOT_PUBLISHED;
+ $roles = variable_get('comment_roles', array());
+ $score = 0;
+
+ foreach (array_intersect(array_keys($roles), array_keys($user->roles)) as $rid) {
+ $score = max($roles[$rid], $score);
+ }
+
+ $users = serialize(array(0 => $score));
+
+ // Here we are building the thread field. See the comment
+ // in comment_render().
+ if ($edit['pid'] == 0) {
+ // This is a comment with no parent comment (depth 0): we start
+ // by retrieving the maximum thread level.
+ $max = db_result(db_query('SELECT MAX(thread) FROM {comments} WHERE nid = %d', $edit['nid']));
+
+ // Strip the "/" from the end of the thread.
+ $max = rtrim($max, '/');
+
+ // Finally, build the thread field for this new comment.
+ $thread = int2vancode(vancode2int($max) + 1) .'/';
+ }
+ else {
+ // This is comment with a parent comment: we increase
+ // the part of the thread value at the proper depth.
+
+ // Get the parent comment:
+ $parent = _comment_load($edit['pid']);
+
+ // Strip the "/" from the end of the parent thread.
+ $parent->thread = (string) rtrim((string) $parent->thread, '/');
+
+ // Get the max value in _this_ thread.
+ $max = db_result(db_query("SELECT MAX(thread) FROM {comments} WHERE thread LIKE '%s.%%' AND nid = %d", $parent->thread, $edit['nid']));
+
+ if ($max == '') {
+ // First child of this parent.
+ $thread = $parent->thread .'.'. int2vancode(0) .'/';
+ }
+ else {
+ // Strip the "/" at the end of the thread.
+ $max = rtrim($max, '/');
+
+ // We need to get the value at the correct depth.
+ $parts = explode('.', $max);
+ $parent_depth = count(explode('.', $parent->thread));
+ $last = $parts[$parent_depth];
+
+ // Finally, build the thread field for this new comment.
+ $thread = $parent->thread .'.'. int2vancode(vancode2int($last) + 1) .'/';
+ }
+ }
+
+ $edit['cid'] = db_next_id('{comments}_cid');
+ $edit['timestamp'] = time();
+
+ if ($edit['uid'] == $user->uid) {
+ $edit['name'] = $user->name;
+ }
+
+ db_query("INSERT INTO {comments} (cid, nid, pid, uid, subject, comment, format, hostname, timestamp, status, score, users, thread, name, mail, homepage) VALUES (%d, %d, %d, %d, '%s', '%s', %d, '%s', %d, %d, %d, '%s', '%s', '%s', '%s', '%s')", $edit['cid'], $edit['nid'], $edit['pid'], $edit['uid'], $edit['subject'], $edit['comment'], $edit['format'], $_SERVER['REMOTE_ADDR'], $edit['timestamp'], $status, $score, $users, $thread, $edit['name'], $edit['mail'], $edit['homepage']);
+
+ _comment_update_node_statistics($edit['nid']);
+
+ // Tell the other modules a new comment has been submitted.
+ comment_invoke_comment($edit, 'insert');
+
+ // Add an entry to the watchdog log.
+ watchdog('content', t('Comment: added %subject.', array('%subject' => theme('placeholder', $edit['subject']))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $edit['nid'], NULL, NULL, 'comment-'. $edit['cid']));
+ }
+
+ // Clear the cache so an anonymous user can see his comment being added.
+ cache_clear_all();
+
+ // Explain the approval queue if necessary, and then
+ // redirect the user to the node he's commenting on.
+ if ($status == COMMENT_NOT_PUBLISHED) {
+ drupal_set_message(t('Your comment has been queued for moderation by site administrators and will be published after approval.'));
+ }
+ return $edit['cid'];
+ }
+ else {
+ return FALSE;
+ }
+ }
+ else {
+ $txt = t('Comment: unauthorized comment submitted or comment submitted to a closed node %subject.', array('%subject' => theme('placeholder', $edit['subject'])));
+ watchdog('content', $txt, WATCHDOG_WARNING);
+ drupal_set_message($txt, 'error');
+ return FALSE;
+ }
+}
+
+function comment_links($comment, $return = 1) {
+ global $user;
+
+ $links = array();
+
+ // If we are viewing just this comment, we link back to the node.
+ if ($return) {
+ $links[] = l(t('parent'), comment_node_url(), NULL, NULL, "comment-$comment->cid");
+ }
+
+ if (node_comment_mode($comment->nid) == COMMENT_NODE_READ_WRITE) {
+ if (user_access('administer comments') && user_access('post comments')) {
+ $links[] = l(t('delete'), "comment/delete/$comment->cid");
+ $links[] = l(t('edit'), "comment/edit/$comment->cid");
+ $links[] = l(t('reply'), "comment/reply/$comment->nid/$comment->cid");
+ }
+ else if (user_access('post comments')) {
+ if (comment_access('edit', $comment)) {
+ $links[] = l(t('edit'), "comment/edit/$comment->cid");
+ }
+ $links[] = l(t('reply'), "comment/reply/$comment->nid/$comment->cid");
+ }
+ else {
+ $links[] = theme('comment_post_forbidden', $comment->nid);
+ }
+ }
+
+ return $links;
+}
+
+function comment_render($node, $cid = 0) {
+ global $user;
+
+ $output = '';
+
+ if (user_access('access comments')) {
+ // Pre-process variables.
+ $nid = $node->nid;
+ if (empty($nid)) {
+ $nid = 0;
+ }
+
+ $mode = _comment_get_display_setting('mode');
+ $order = _comment_get_display_setting('sort');
+ $comments_per_page = _comment_get_display_setting('comments_per_page');
+
+ $output .= "\n";
+
+ if ($cid) {
+ // Single comment view.
+ $query = 'SELECT c.cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, c.homepage, u.uid, u.name AS registered_name, u.picture, u.data, c.score, c.users, c.status FROM {comments} c INNER JOIN {users} u ON c.uid = u.uid WHERE c.cid = %d';
+ $query_args = array($cid);
+ if (!user_access('administer comments')) {
+ $query .= ' AND c.status = %d';
+ $query_args[] = COMMENT_PUBLISHED;
+ }
+ $query .= ' GROUP BY c.cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, u.picture, c.homepage, u.uid, u.name, u.picture, u.data, c.score, c.users, c.status';
+ $result = db_query($query, $query_args);
+
+ if ($comment = db_fetch_object($result)) {
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ $output .= theme('comment_view', $comment, module_invoke_all('link', 'comment', $comment, 1));
+ }
+ }
+ else {
+ // Multiple comment view
+ $query_count = 'SELECT COUNT(*) FROM {comments} WHERE nid = %d';
+ $query = 'SELECT c.cid as cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, c.homepage, u.uid, u.name AS registered_name, u.picture, u.data, c.score, c.users, c.thread, c.status FROM {comments} c INNER JOIN {users} u ON c.uid = u.uid WHERE c.nid = %d';
+
+ $query_args = array($nid);
+ if (!user_access('administer comments')) {
+ $query .= ' AND c.status = %d';
+ $query_count .= ' AND status = %d';
+ $query_args[] = COMMENT_PUBLISHED;
+ }
+
+ $query .= ' GROUP BY c.cid, c.pid, c.nid, c.subject, c.comment, c.format, c.timestamp, c.name, c.mail, u.picture, c.homepage, u.uid, u.name, u.picture, u.data, c.score, c.users, c.thread, c.status';
+
+ /*
+ ** We want to use the standard pager, but threads would need every
+ ** comment to build the thread structure, so we need to store some
+ ** extra info.
+ **
+ ** We use a "thread" field to store this extra info. The basic idea
+ ** is to store a value and to order by that value. The "thread" field
+ ** keeps this data in a way which is easy to update and convenient
+ ** to use.
+ **
+ ** A "thread" value starts at "1". If we add a child (A) to this
+ ** comment, we assign it a "thread" = "1.1". A child of (A) will have
+ ** "1.1.1". Next brother of (A) will get "1.2". Next brother of the
+ ** parent of (A) will get "2" and so on.
+ **
+ ** First of all note that the thread field stores the depth of the
+ ** comment: depth 0 will be "X", depth 1 "X.X", depth 2 "X.X.X", etc.
+ **
+ ** Now to get the ordering right, consider this example:
+ **
+ ** 1
+ ** 1.1
+ ** 1.1.1
+ ** 1.2
+ ** 2
+ **
+ ** If we "ORDER BY thread ASC" we get the above result, and this is
+ ** the natural order sorted by time. However, if we "ORDER BY thread
+ ** DESC" we get:
+ **
+ ** 2
+ ** 1.2
+ ** 1.1.1
+ ** 1.1
+ ** 1
+ **
+ ** Clearly, this is not a natural way to see a thread, and users
+ ** will get confused. The natural order to show a thread by time
+ ** desc would be:
+ **
+ ** 2
+ ** 1
+ ** 1.2
+ ** 1.1
+ ** 1.1.1
+ **
+ ** which is what we already did before the standard pager patch. To
+ ** achieve this we simply add a "/" at the end of each "thread" value.
+ ** This way out thread fields will look like depicted below:
+ **
+ ** 1/
+ ** 1.1/
+ ** 1.1.1/
+ ** 1.2/
+ ** 2/
+ **
+ ** we add "/" since this char is, in ASCII, higher than every number,
+ ** so if now we "ORDER BY thread DESC" we get the correct order. Try
+ ** it, it works ;). However this would spoil the "ORDER BY thread ASC"
+ ** Here, we do not need to consider the trailing "/" so we use a
+ ** substring only.
+ */
+
+ if ($order == COMMENT_ORDER_NEWEST_FIRST) {
+ if ($mode == COMMENT_MODE_FLAT_COLLAPSED || $mode == COMMENT_MODE_FLAT_EXPANDED) {
+ $query .= ' ORDER BY c.timestamp DESC';
+ }
+ else {
+ $query .= ' ORDER BY c.thread DESC';
+ }
+ }
+ else if ($order == COMMENT_ORDER_OLDEST_FIRST) {
+ if ($mode == COMMENT_MODE_FLAT_COLLAPSED || $mode == COMMENT_MODE_FLAT_EXPANDED) {
+ $query .= ' ORDER BY c.timestamp';
+ }
+ else {
+
+ /*
+ ** See comment above. Analysis learns that this doesn't cost
+ ** too much. It scales much much better than having the whole
+ ** comment structure.
+ */
+
+ $query .= ' ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))';
+ }
+ }
+
+ // Start a form, for use with comment control.
+ $result = pager_query($query, $comments_per_page, 0, $query_count, $query_args);
+ if (db_num_rows($result) && (variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN) == COMMENT_CONTROLS_ABOVE || variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN) == COMMENT_CONTROLS_ABOVE_BELOW)) {
+ $output .= comment_controls($mode, $order, $comments_per_page);
+ }
+
+ while ($comment = db_fetch_object($result)) {
+ $comment = drupal_unpack($comment);
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ $comment->depth = count(explode('.', $comment->thread)) - 1;
+
+ if ($mode == COMMENT_MODE_FLAT_COLLAPSED) {
+ $output .= theme('comment_flat_collapsed', $comment);
+ }
+ else if ($mode == COMMENT_MODE_FLAT_EXPANDED) {
+ $output .= theme('comment_flat_expanded', $comment);
+ }
+ else if ($mode == COMMENT_MODE_THREADED_COLLAPSED) {
+ $output .= theme('comment_thread_collapsed', $comment);
+ }
+ else if ($mode == COMMENT_MODE_THREADED_EXPANDED) {
+ $output .= theme('comment_thread_expanded', $comment);
+ }
+ }
+
+ $output .= theme('pager', NULL, $comments_per_page, 0);
+
+ if (db_num_rows($result) && (variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN) == COMMENT_CONTROLS_BELOW || variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN) == COMMENT_CONTROLS_ABOVE_BELOW)) {
+ $output .= comment_controls($mode, $order, $comments_per_page);
+ }
+ }
+
+ // If enabled, show new comment form.
+ if (user_access('post comments') && node_comment_mode($nid) == COMMENT_NODE_READ_WRITE && (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_BELOW)) {
+ $output .= comment_form(array('nid' => $nid), t('Post new comment'));
+ }
+ }
+ return $output;
+}
+
+
+/**
+ * Menu callback; delete a comment.
+ */
+function comment_delete($cid) {
+ $comment = db_fetch_object(db_query('SELECT c.*, u.name AS registered_name, u.uid FROM {comments} c INNER JOIN {users} u ON u.uid = c.uid WHERE c.cid = %d', $cid));
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+
+ $output = '';
+
+ // We'll only delete if the user has confirmed the
+ // deletion using the form in our else clause below.
+ if (is_object($comment) && is_numeric($comment->cid) && $_POST['edit']['confirm']) {
+ drupal_set_message(t('The comment and all its replies have been deleted.'));
+
+ // Delete comment and its replies.
+ _comment_delete_thread($comment);
+
+ _comment_update_node_statistics($comment->nid);
+
+ // Clear the cache so an anonymous user sees that his comment was deleted.
+ cache_clear_all();
+
+ drupal_goto("node/$comment->nid");
+ }
+ else if (is_object($comment) && is_numeric($comment->cid)) {
+ $output = confirm_form('comment_confirm_delete',
+ array(),
+ t('Are you sure you want to delete the comment %title?', array('%title' => theme('placeholder', $comment->subject))),
+ 'node/'. $comment->nid,
+ t('Any replies to this comment will be lost. This action cannot be undone.'),
+ t('Delete'),
+ t('Cancel'));
+ }
+ else {
+ drupal_set_message(t('The comment no longer exists.'));
+ }
+
+ return $output;
+}
+
+/**
+ * Comment operations. We offer different update operations depending on
+ * which comment administration page we're on.
+ */
+function comment_operations($action = NULL) {
+ if ($action == 'publish') {
+ $operations = array(
+ 'publish' => array(t('Publish the selected comments'), 'UPDATE {comments} SET status = '. COMMENT_PUBLISHED .' WHERE cid = %d'),
+ 'delete' => array(t('Delete the selected comments'), '')
+ );
+ }
+ else if ($action == 'unpublish') {
+ $operations = array(
+ 'unpublish' => array(t('Unpublish the selected comments'), 'UPDATE {comments} SET status = '. COMMENT_NOT_PUBLISHED .' WHERE cid = %d'),
+ 'delete' => array(t('Delete the selected comments'), '')
+ );
+ }
+ else {
+ $operations = array(
+ 'publish' => array(t('Publish the selected comments'), 'UPDATE {comments} SET status = '. COMMENT_PUBLISHED .' WHERE cid = %d'),
+ 'unpublish' => array(t('Unpublish the selected comments'), 'UPDATE {comments} SET status = '. COMMENT_NOT_PUBLISHED .' WHERE cid = %d'),
+ 'delete' => array(t('Delete the selected comments'), '')
+ );
+ }
+ return $operations;
+}
+
+/**
+ * Menu callback; present an administrative comment listing.
+ */
+function comment_admin_overview($type = 'new') {
+ $edit = $_POST['edit'];
+
+ if ($edit['operation'] == 'delete') {
+ return comment_multiple_delete_confirm();
+ }
+
+ // build an 'Update options' form
+ $form['options'] = array(
+ '#type' => 'fieldset', '#title' => t('Update options'),
+ '#prefix' => '', '#suffix' => '
'
+ );
+ $options = array();
+ foreach (comment_operations(arg(3) == 'approval' ? 'publish' : 'unpublish') as $key => $value) {
+ $options[$key] = $value[0];
+ }
+ $form['options']['operation'] = array('#type' => 'select', '#options' => $options, '#default_value' => 'publish');
+ $form['options']['submit'] = array('#type' => 'submit', '#value' => t('Update'));
+
+ // load the comments that we want to display
+ $status = ($type == 'approval') ? COMMENT_NOT_PUBLISHED : COMMENT_PUBLISHED;
+ $form['header'] = array('#type' => 'value', '#value' => array(
+ NULL,
+ array('data' => t('Subject'), 'field' => 'subject'),
+ array('data' => t('Author'), 'field' => 'name'),
+ array('data' => t('Time'), 'field' => 'timestamp', 'sort' => 'desc'),
+ array('data' => t('Operations'))
+ ));
+ $result = pager_query('SELECT c.subject, c.nid, c.cid, c.comment, c.timestamp, c.status, c.name, c.homepage, u.name AS registered_name, u.uid FROM {comments} c INNER JOIN {users} u ON u.uid = c.uid WHERE c.status = %d'. tablesort_sql($form['header']['#value']), 50, 0, NULL, $status);
+
+ // build a table listing the appropriate comments
+ $destination = drupal_get_destination();
+ while ($comment = db_fetch_object($result)) {
+ $comments[$comment->cid] = '';
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ $form['subject'][$comment->cid] = array('#value' => l($comment->subject, 'node/'. $comment->nid, array('title' => truncate_utf8($comment->comment, 128)), NULL, 'comment-'. $comment->cid));
+ $form['username'][$comment->cid] = array('#value' => theme('username', $comment));
+ $form['timestamp'][$comment->cid] = array('#value' => format_date($comment->timestamp, 'small'));
+ $form['operations'][$comment->cid] = array('#value' => l(t('edit'), 'comment/edit/'. $comment->cid, array(), $destination));
+ }
+ $form['comments'] = array('#type' => 'checkboxes', '#options' => $comments);
+ $form['pager'] = array('#value' => theme('pager', NULL, 50, 0));
+ return drupal_get_form('comment_admin_overview', $form);
+}
+
+/**
+ * We can't execute any 'Update options' if no comments were selected.
+ */
+function comment_admin_overview_validate($form_id, $edit) {
+ $edit['comments'] = array_diff($edit['comments'], array(0));
+ if (count($edit['comments']) == 0) {
+ form_set_error('', t('Please select one or more comments to perform the update on.'));
+ drupal_goto('admin/comment');
+ }
+}
+
+/**
+ * Execute the chosen 'Update option' on the selected comments, such as
+ * publishing, unpublishing or deleting.
+ */
+function comment_admin_overview_submit($form_id, $edit) {
+ $operations = comment_operations();
+ if ($operations[$edit['operation']][1]) {
+ // extract the appropriate database query operation
+ $query = $operations[$edit['operation']][1];
+ foreach ($edit['comments'] as $cid => $value) {
+ if ($value) {
+ // perform the update action, then refresh node statistics
+ db_query($query, $cid);
+ $comment = _comment_load($cid);
+ _comment_update_node_statistics($comment->nid);
+ // Allow modules to respond to the updating of a comment.
+ comment_invoke_comment($comment, $edit['operation']);
+ // Add an entry to the watchdog log.
+ watchdog('content', t('Comment: updated %subject.', array('%subject' => theme('placeholder', $comment->subject))), WATCHDOG_NOTICE, l(t('view'), 'node/'. $comment->nid, NULL, NULL, 'comment-'. $comment->cid));
+ }
+ }
+ cache_clear_all();
+ drupal_set_message(t('The update has been performed.'));
+ drupal_goto('admin/comment');
+ }
+}
+
+function theme_comment_admin_overview($form) {
+ $output = form_render($form['options']);
+ if (isset($form['subject']) && is_array($form['subject'])) {
+ foreach (element_children($form['subject']) as $key) {
+ $row = array();
+ $row[] = form_render($form['comments'][$key]);
+ $row[] = form_render($form['subject'][$key]);
+ $row[] = form_render($form['username'][$key]);
+ $row[] = form_render($form['timestamp'][$key]);
+ $row[] = form_render($form['operations'][$key]);
+ $rows[] = $row;
+ }
+ }
+ else {
+ $rows[] = array(array('data' => t('No comments available.'), 'colspan' => '6'));
+ }
+
+ $output .= theme('table', $form['header']['#value'], $rows);
+ if ($form['pager']['#value']) {
+ $output .= form_render($form['pager']);
+ }
+
+ $output .= form_render($form);
+
+ return $output;
+}
+
+/**
+ * List the selected comments and verify that the admin really wants to delete
+ * them.
+ */
+function comment_multiple_delete_confirm() {
+ $edit = $_POST['edit'];
+
+ $form['comments'] = array('#prefix' => '', '#tree' => TRUE);
+ // array_filter() returns only elements with actual values
+ $comment_counter = 0;
+ foreach (array_filter($edit['comments']) as $cid => $value) {
+ $comment = _comment_load($cid);
+ if (is_object($comment) && is_numeric($comment->cid)) {
+ $subject = db_result(db_query('SELECT subject FROM {comments} WHERE cid = %d', $cid));
+ $form['comments'][$cid] = array('#type' => 'hidden', '#value' => $cid, '#prefix' => '- ', '#suffix' => check_plain($subject) .'
');
+ $comment_counter++;
+ }
+ }
+ $form['operation'] = array('#type' => 'hidden', '#value' => 'delete');
+
+ if (!$comment_counter) {
+ drupal_set_message(t('There do not appear to be any comments to delete or your selected comment was deleted by another administrator.'));
+ drupal_goto('admin/comment');
+ }
+ else {
+ return confirm_form('comment_multiple_delete_confirm', $form,
+ t('Are you sure you want to delete these comments and all their children?'),
+ 'admin/comment', t('This action cannot be undone.'),
+ t('Delete comments'), t('Cancel'));
+ }
+}
+
+/**
+ * Perform the actual comment deletion.
+ */
+function comment_multiple_delete_confirm_submit($form_id, $edit) {
+ if ($edit['confirm']) {
+ foreach ($edit['comments'] as $cid => $value) {
+ $comment = _comment_load($cid);
+ _comment_delete_thread($comment);
+ _comment_update_node_statistics($comment->nid);
+ cache_clear_all();
+ }
+ drupal_set_message(t('The comments have been deleted.'));
+ }
+ drupal_goto('admin/comment');
+}
+
+/**
+*** misc functions: helpers, privates, history
+**/
+
+/**
+ * Load the entire comment by cid.
+ */
+function _comment_load($cid) {
+ return db_fetch_object(db_query('SELECT * FROM {comments} WHERE cid = %d', $cid));
+}
+
+function comment_num_all($nid) {
+ static $cache;
+
+ if (!isset($cache[$nid])) {
+ $cache[$nid] = db_result(db_query('SELECT comment_count FROM {node_comment_statistics} WHERE nid = %d', $nid));
+ }
+ return $cache[$nid];
+}
+
+function comment_num_replies($pid) {
+ static $cache;
+
+ if (!isset($cache[$pid])) {
+ $cache[$pid] = db_result(db_query('SELECT COUNT(cid) FROM {comments} WHERE pid = %d AND status = %d', $pid, COMMENT_PUBLISHED));
+ }
+
+ return $cache[$pid];
+}
+
+/**
+ * get number of new comments for current user and specified node
+ *
+ * @param $nid node-id to count comments for
+ * @param $timestamp time to count from (defaults to time of last user access
+ * to node)
+ */
+function comment_num_new($nid, $timestamp = 0) {
+ global $user;
+
+ if ($user->uid) {
+ // Retrieve the timestamp at which the current user last viewed the
+ // specified node.
+ if (!$timestamp) {
+ $timestamp = node_last_viewed($nid);
+ }
+ $timestamp = ($timestamp > NODE_NEW_LIMIT ? $timestamp : NODE_NEW_LIMIT);
+
+ // Use the timestamp to retrieve the number of new comments.
+ $result = db_result(db_query('SELECT COUNT(c.cid) FROM {node} n INNER JOIN {comments} c ON n.nid = c.nid WHERE n.nid = %d AND timestamp > %d AND c.status = %d', $nid, $timestamp, COMMENT_PUBLISHED));
+
+ return $result;
+ }
+ else {
+ return 0;
+ }
+
+}
+
+function comment_validate($edit) {
+ global $user;
+
+ // Invoke other validation handlers
+ comment_invoke_comment($edit, 'validate');
+
+ if (isset($edit['date'])) {
+ // As of PHP 5.1.0, strtotime returns FALSE upon failure instead of -1.
+ if (strtotime($edit['date']) <= 0) {
+ form_set_error('date', t('You have to specify a valid date.'));
+ }
+ }
+ if (isset($edit['author']) && !$account = user_load(array('name' => $edit['author']))) {
+ form_set_error('author', t('You have to specify a valid author.'));
+ }
+
+ // Check validity of name, mail and homepage (if given)
+ if (!$user->uid || isset($edit['is_anonymous'])) {
+ if (variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT) > COMMENT_ANONYMOUS_MAYNOT_CONTACT) {
+ if ($edit['name']) {
+ $taken = db_result(db_query("SELECT COUNT(uid) FROM {users} WHERE LOWER(name) = '%s'", $edit['name']), 0);
+
+ if ($taken != 0) {
+ form_set_error('name', t('The name you used belongs to a registered user.'));
+ }
+
+ }
+ else if (variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT) == COMMENT_ANONYMOUS_MUST_CONTACT) {
+ form_set_error('name', t('You have to leave your name.'));
+ }
+
+ if ($edit['mail']) {
+ if (!valid_email_address($edit['mail'])) {
+ form_set_error('mail', t('The e-mail address you specified is not valid.'));
+ }
+ }
+ else if (variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT) == COMMENT_ANONYMOUS_MUST_CONTACT) {
+ form_set_error('mail', t('You have to leave an e-mail address.'));
+ }
+
+ if ($edit['homepage']) {
+ if (!valid_url($edit['homepage'], TRUE)) {
+ form_set_error('homepage', t('The URL of your homepage is not valid. Remember that it must be fully qualified, i.e. of the form http://example.com/directory
.'));
+ }
+ }
+ }
+ }
+
+ return $edit;
+}
+
+/*
+** Generate the basic commenting form, for appending to a node or display on a separate page.
+** This is rendered by theme_comment_form.
+*/
+
+function comment_form($edit, $title = NULL) {
+ global $user;
+
+ $op = isset($_POST['op']) ? $_POST['op'] : '';
+
+ if ($user->uid) {
+ if ($edit['cid'] && user_access('administer comments')) {
+ if ($edit['author']) {
+ $author = $edit['author'];
+ }
+ elseif ($edit['name']) {
+ $author = $edit['name'];
+ }
+ else {
+ $author = $edit['registered_name'];
+ }
+
+ if ($edit['status']) {
+ $status = $edit['status'];
+ }
+ else {
+ $status = 0;
+ }
+
+ if ($edit['date']) {
+ $date = $edit['date'];
+ }
+ else {
+ $date = format_date($edit['timestamp'], 'custom', 'Y-m-d H:i O');
+ }
+
+ $form['admin'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Administration'),
+ '#collapsible' => TRUE,
+ '#collapsed' => TRUE,
+ '#weight' => -2,
+ );
+
+ if ($edit['registered_name'] != '') {
+ // The comment is by a registered user
+ $form['admin']['author'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Authored by'),
+ '#size' => 30,
+ '#maxlength' => 60,
+ '#autocomplete_path' => 'user/autocomplete',
+ '#default_value' => $author,
+ '#weight' => -1,
+ );
+ }
+ else {
+ // The comment is by an anonymous user
+ $form['is_anonymous'] = array(
+ '#type' => 'value',
+ '#value' => TRUE,
+ );
+ $form['admin']['name'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Authored by'),
+ '#size' => 30,
+ '#maxlength' => 60,
+ '#default_value' => $author,
+ '#weight' => -1,
+ );
+ $form['admin']['mail'] = array(
+ '#type' => 'textfield',
+ '#title' => t('E-mail'),
+ '#maxlength' => 64,
+ '#size' => 30,
+ '#default_value' => $edit['mail'],
+ '#description' => t('The content of this field is kept private and will not be shown publicly.'),
+ );
+
+ $form['admin']['homepage'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Homepage'),
+ '#maxlength' => 255,
+ '#size' => 30,
+ '#default_value' => $edit['homepage'],
+ );
+ }
+
+ $form['admin']['date'] = array('#type' => 'textfield', '#parents' => array('date'), '#title' => t('Authored on'), '#size' => 20, '#maxlength' => 25, '#default_value' => $date, '#weight' => -1);
+
+ $form['admin']['status'] = array('#type' => 'radios', '#parents' => array('status'), '#title' => t('Status'), '#default_value' => $status, '#options' => array(t('Published'), t('Not published')), '#weight' => -1);
+
+ }
+ else {
+ $form['_author'] = array('#type' => 'item', '#title' => t('Your name'), '#value' => theme('username', $user)
+ );
+ $form['author'] = array('#type' => 'value', '#value' => $user->name);
+ }
+ }
+ else if (variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT) == COMMENT_ANONYMOUS_MAY_CONTACT) {
+ $form['name'] = array('#type' => 'textfield', '#title' => t('Your name'), '#maxlength' => 60, '#size' => 30, '#default_value' => $edit['name'] ? $edit['name'] : variable_get('anonymous', 'Anonymous')
+ );
+
+ $form['mail'] = array('#type' => 'textfield', '#title' => t('E-mail'), '#maxlength' => 64, '#size' => 30, '#default_value' => $edit['mail'], '#description' => t('The content of this field is kept private and will not be shown publicly.')
+ );
+
+ $form['homepage'] = array('#type' => 'textfield', '#title' => t('Homepage'), '#maxlength' => 255, '#size' => 30, '#default_value' => $edit['homepage']);
+ }
+ else if (variable_get('comment_anonymous', COMMENT_ANONYMOUS_MAYNOT_CONTACT) == COMMENT_ANONYMOUS_MUST_CONTACT) {
+ $form['name'] = array('#type' => 'textfield', '#title' => t('Your name'), '#maxlength' => 60, '#size' => 30, '#default_value' => $edit['name'] ? $edit['name'] : variable_get('anonymous', 'Anonymous'), '#required' => TRUE);
+
+ $form['mail'] = array('#type' => 'textfield', '#title' => t('E-mail'), '#maxlength' => 64, '#size' => 30, '#default_value' => $edit['mail'],'#description' => t('The content of this field is kept private and will not be shown publicly.'), '#required' => TRUE);
+
+ $form['homepage'] = array('#type' => 'textfield', '#title' => t('Homepage'), '#maxlength' => 255, '#size' => 30, '#default_value' => $edit['homepage']);
+ }
+
+ if (variable_get('comment_subject_field', 1) == 1) {
+ $form['subject'] = array('#type' => 'textfield', '#title' => t('Subject'), '#maxlength' => 64, '#default_value' => $edit['subject']);
+ }
+
+ $form['comment_filter']['comment'] = array('#type' => 'textarea', '#title' => t('Comment'), '#rows' => 15, '#default_value' => $edit['comment'] ? $edit['comment'] : $user->signature, '#required' => TRUE);
+ $form['comment_filter']['format'] = filter_form($edit['format']);
+
+ $form['cid'] = array('#type' => 'value', '#value' => $edit['cid']);
+ $form['pid'] = array('#type' => 'value', '#value' => $edit['pid']);
+ $form['nid'] = array('#type' => 'value', '#value' => $edit['nid']);
+ $form['uid'] = array('#type' => 'value', '#value' => $edit['uid']);
+
+ $form['preview'] = array('#type' => 'button', '#value' => t('Preview comment'), '#weight' => 19);
+ $form['#token'] = 'comment' . $edit['nid'] . $edit['pid'];
+
+ // Only show post button if preview is optional or if we are in preview mode.
+ // We show the post button in preview mode even if there are form errors so that
+ // optional form elements (e.g., captcha) can be updated in preview mode.
+ if (!form_get_errors() && ((variable_get('comment_preview', COMMENT_PREVIEW_REQUIRED) == COMMENT_PREVIEW_OPTIONAL) || ($op == t('Preview comment')) || ($op == t('Post comment')))) {
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Post comment'), '#weight' => 20);
+ }
+
+ if ($op == t('Preview comment')) {
+ $form['#after_build'] = array('comment_form_add_preview');
+ }
+
+ if ($_REQUEST['destination']) {
+ $form['#attributes']['destination'] = $_REQUEST['destination'];
+ }
+
+ if (empty($edit['cid']) && empty($edit['pid'])) {
+ $form['#action'] = url('comment/reply/'. $edit['nid']);
+ }
+
+ // Graft in extra form additions
+ $form = array_merge($form, comment_invoke_comment($form, 'form'));
+
+ return theme('box', $title, drupal_get_form('comment_form', $form));
+}
+
+function comment_form_add_preview($form, $edit) {
+ global $user;
+
+ drupal_set_title(t('Preview comment'));
+
+ $output = '';
+
+ comment_validate($edit);
+ $comment = (object)_comment_form_submit($edit);
+
+ // Attach the user and time information.
+ if ($edit['author']) {
+ $account = user_load(array('name' => $edit['author']));
+ }
+ elseif ($user->uid && !isset($edit['is_anonymous'])) {
+ $account = $user;
+ }
+ if ($account) {
+ $comment->uid = $account->uid;
+ $comment->name = check_plain($account->name);
+ }
+ $comment->timestamp = $edit['timestamp'] ? $edit['timestamp'] : time();
+
+ // Preview the comment with security check.
+ if (!form_get_errors()) {
+ $output .= theme('comment_view', $comment);
+ }
+ $form['comment_preview'] = array(
+ '#value' => $output,
+ '#weight' => -100,
+ '#prefix' => '',
+ '#suffix' => '
',
+ );
+
+ $output = '';
+
+ if ($edit['pid']) {
+ $comment = db_fetch_object(db_query('SELECT c.*, u.uid, u.name AS registered_name, u.picture, u.data FROM {comments} c INNER JOIN {users} u ON c.uid = u.uid WHERE c.cid = %d AND c.status = %d', $edit['pid'], COMMENT_PUBLISHED));
+ $comment = drupal_unpack($comment);
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ $output .= theme('comment_view', $comment);
+ }
+ else {
+ $form['#suffix'] = node_view(node_load($edit['nid']));
+ $edit['pid'] = 0;
+ }
+
+ $form['comment_preview_below'] = array('#value' => $output, '#weight' => 100);
+
+ return $form;
+}
+
+function comment_form_validate($form_id, $form_values) {
+ comment_validate($form_values);
+}
+
+function _comment_form_submit($form_values) {
+ if (!isset($form_values['date'])) {
+ $form_values['date'] = 'now';
+ }
+ $form_values['timestamp'] = strtotime($form_values['date']);
+ if (isset($form_values['author'])) {
+ $account = user_load(array('name' => $form_values['author']));
+ $form_values['uid'] = $account->uid;
+ $form_values['name'] = $form_values['author'];
+ }
+ // Validate the comment's subject. If not specified, extract
+ // one from the comment's body.
+ if (trim($form_values['subject']) == '') {
+ // The body may be in any format, so we:
+ // 1) Filter it into HTML
+ // 2) Strip out all HTML tags
+ // 3) Convert entities back to plain-text.
+ // Note: format is checked by check_markup().
+ $form_values['subject'] = truncate_utf8(decode_entities(strip_tags(check_markup($form_values['comment'], $form_values['format']))), 29, TRUE);
+ }
+ return $form_values;
+}
+
+function comment_form_submit($form_id, $form_values) {
+ $form_values = _comment_form_submit($form_values);
+ if ($cid = comment_save($form_values)) {
+ return array('node/'. $form_values['nid'], NULL, "comment-$cid");
+ }
+}
+
+/*
+** Renderer or visualization functions this can be optionally
+** overridden by themes.
+*/
+
+function theme_comment_preview($comment, $links = array(), $visible = 1) {
+ $output = '';
+ $output .= theme('comment_view', $comment, $links, $visible);
+ $output .= '
';
+ return $output;
+};
+
+function theme_comment_view($comment, $links = array(), $visible = 1) {
+
+ // Emit selectors:
+ $output = '';
+ if (($comment->new = node_mark($comment->nid, $comment->timestamp)) != MARK_READ) {
+ $output .= "\n";
+ }
+
+ $output .= "\n";
+
+ // Switch to folded/unfolded view of the comment
+ if ($visible) {
+ $comment->comment = check_markup($comment->comment, $comment->format, FALSE);
+
+ // Comment API hook
+ comment_invoke_comment($comment, 'view');
+
+ $output .= theme('comment', $comment, $links);
+ }
+ else {
+ $output .= theme('comment_folded', $comment);
+ }
+
+ return $output;
+}
+
+function comment_controls($mode = COMMENT_MODE_THREADED_EXPANDED, $order = COMMENT_ORDER_NEWEST_FIRST, $comments_per_page = 50) {
+ $form['mode'] = array('#type' => 'select',
+ '#default_value' => $mode,
+ '#options' => _comment_get_modes(),
+ '#weight' => 1,
+ );
+ $form['order'] = array(
+ '#type' => 'select',
+ '#default_value' => $order,
+ '#options' => _comment_get_orders(),
+ '#weight' => 2,
+ );
+ foreach (_comment_per_page() as $i) {
+ $options[$i] = t('%a comments per page', array('%a' => $i));
+ }
+ $form['comments_per_page'] = array('#type' => 'select',
+ '#default_value' => $comments_per_page,
+ '#options' => $options,
+ '#weight' => 3,
+ );
+
+ $form['submit'] = array('#type' => 'submit',
+ '#value' => t('Save settings'),
+ '#weight' => 20,
+ );
+
+ return drupal_get_form('comment_controls', $form);
+}
+
+function theme_comment_controls($form) {
+ $output .= '';
+ $output .= form_render($form);
+ $output .= '
';
+ $output .= ''. t('Select your preferred way to display the comments and click "Save settings" to activate your changes.') .'
';
+ return theme('box', t('Comment viewing options'), $output);
+}
+
+function comment_controls_submit($form_id, $form_values) {
+ global $user;
+
+ $mode = $form_values['mode'];
+ $order = $form_values['order'];
+ $comments_per_page = $form_values['comments_per_page'];
+
+ if ($user->uid) {
+ $user = user_save($user, array('mode' => $mode, 'sort' => $order, 'comments_per_page' => $comments_per_page));
+ }
+ else {
+ $_SESSION['comment_mode'] = $mode;
+ $_SESSION['comment_sort'] = $order;
+ $_SESSION['comment_comments_per_page'] = $comments_per_page;
+ }
+}
+
+function theme_comment($comment, $links = array()) {
+ $output = '';
+ return $output;
+}
+
+function theme_comment_folded($comment) {
+ $output = "\n";
+ return $output;
+}
+
+function theme_comment_flat_collapsed($comment) {
+ return theme('comment_view', $comment, '', 0);
+ return '';
+}
+
+function theme_comment_flat_expanded($comment) {
+ return theme('comment_view', $comment, module_invoke_all('link', 'comment', $comment, 0));
+}
+
+function theme_comment_thread_collapsed($comment) {
+ $output = '\n";
+ $output .= theme('comment_view', $comment, '', 0);
+ $output .= "
\n";
+ return $output;
+}
+
+function theme_comment_thread_expanded($comment) {
+ $output = '';
+ if ($comment->depth) {
+ $output .= '\n";
+ }
+
+ $output .= theme('comment_view', $comment, module_invoke_all('link', 'comment', $comment, 0));
+
+ if ($comment->depth) {
+ $output .= "
\n";
+ }
+ return $output;
+}
+
+function theme_comment_post_forbidden($nid) {
+ global $user;
+ if ($user->uid) {
+ return t("you can't post comments");
+ }
+ else {
+ // we cannot use drupal_get_destination() because these links sometimes appear on /node and taxo listing pages
+ if (variable_get('comment_form_location', COMMENT_FORM_SEPARATE_PAGE) == COMMENT_FORM_SEPARATE_PAGE) {
+ $destination = "destination=". drupal_urlencode("comment/reply/$nid#comment_form");
+ }
+ else {
+ $destination = "destination=". drupal_urlencode("node/$nid#comment_form");
+ }
+
+ if (variable_get('user_register', 1)) {
+ return t('login or register to post comments', array('%login' => url('user/login', $destination), '%register' => check_url(url('user/register', $destination))));
+ }
+ else {
+ return t('login to post comments', array('%login' => check_url(url('user/login', $destination))));
+ }
+ }
+}
+
+function _comment_delete_thread($comment) {
+ if (!is_object($comment) || !is_numeric($comment->cid)) {
+ watchdog('content', t('Can not delete non-existent comment.'), WATCHDOG_WARNING);
+ return;
+ }
+
+ // Delete the comment:
+ db_query('DELETE FROM {comments} WHERE cid = %d', $comment->cid);
+ watchdog('content', t('Comment: deleted %subject.', array('%subject' => theme('placeholder', $comment->subject))));
+
+ comment_invoke_comment($comment, 'delete');
+
+ // Delete the comment's replies
+ $result = db_query('SELECT c.*, u.name AS registered_name, u.uid FROM {comments} c INNER JOIN {users} u ON u.uid = c.uid WHERE pid = %d', $comment->cid);
+ while ($comment = db_fetch_object($result)) {
+ $comment->name = $comment->uid ? $comment->registered_name : $comment->name;
+ _comment_delete_thread($comment);
+ }
+}
+
+/**
+ * Return an array of viewing modes for comment listings.
+ *
+ * We can't use a global variable array because the locale system
+ * is not initialized yet when the comment module is loaded.
+ */
+function _comment_get_modes() {
+ return array(
+ COMMENT_MODE_FLAT_COLLAPSED => t('Flat list - collapsed'),
+ COMMENT_MODE_FLAT_EXPANDED => t('Flat list - expanded'),
+ COMMENT_MODE_THREADED_COLLAPSED => t('Threaded list - collapsed'),
+ COMMENT_MODE_THREADED_EXPANDED => t('Threaded list - expanded')
+ );
+}
+
+/**
+ * Return an array of viewing orders for comment listings.
+ *
+ * We can't use a global variable array because the locale system
+ * is not initialized yet when the comment module is loaded.
+ */
+function _comment_get_orders() {
+ return array(
+ COMMENT_ORDER_NEWEST_FIRST => t('Date - newest first'),
+ COMMENT_ORDER_OLDEST_FIRST => t('Date - oldest first')
+ );
+}
+
+/**
+ * Return an array of "comments per page" settings from which the user
+ * can choose.
+ */
+function _comment_per_page() {
+ return drupal_map_assoc(array(10, 30, 50, 70, 90, 150, 200, 250, 300));
+}
+
+/**
+ * Return a current comment display setting
+ *
+ * $setting can be one of these: 'mode', 'sort', 'comments_per_page'
+ */
+function _comment_get_display_setting($setting) {
+ global $user;
+
+ if ($_GET[$setting]) {
+ $value = $_GET[$setting];
+ }
+ else {
+ // get the setting's site default
+ switch ($setting) {
+ case 'mode':
+ $default = variable_get('comment_default_mode', COMMENT_MODE_THREADED_EXPANDED);
+ break;
+ case 'sort':
+ $default = variable_get('comment_default_order', COMMENT_ORDER_NEWEST_FIRST);
+ break;
+ case 'comments_per_page':
+ $default = variable_get('comment_default_per_page', '50');
+ }
+ if (variable_get('comment_controls', COMMENT_CONTROLS_HIDDEN) == COMMENT_CONTROLS_HIDDEN) {
+ // if comment controls are disabled use site default
+ $value = $default;
+ }
+ else {
+ // otherwise use the user's setting if set
+ if ($user->$setting) {
+ $value = $user->$setting;
+ }
+ else if ($_SESSION['comment_'. $setting]) {
+ $value = $_SESSION['comment_'. $setting];
+ }
+ else {
+ $value = $default;
+ }
+ }
+ }
+ return $value;
+}
+
+/**
+ * Updates the comment statistics for a given node. This should be called any
+ * time a comment is added, deleted, or updated.
+ *
+ * The following fields are contained in the node_comment_statistics table.
+ * - last_comment_timestamp: the timestamp of the last comment for this node or the node create stamp if no comments exist for the node.
+ * - last_comment_name: the name of the anonymous poster for the last comment
+ * - last_comment_uid: the uid of the poster for the last comment for this node or the node authors uid if no comments exists for the node.
+ * - comment_count: the total number of approved/published comments on this node.
+ */
+function _comment_update_node_statistics($nid) {
+ $count = db_result(db_query('SELECT COUNT(cid) FROM {comments} WHERE nid = %d AND status = %d', $nid, COMMENT_PUBLISHED));
+
+ // comments exist
+ if ($count > 0) {
+ $last_reply = db_fetch_object(db_query_range('SELECT cid, name, timestamp, uid FROM {comments} WHERE nid = %d AND status = %d ORDER BY cid DESC', $nid, COMMENT_PUBLISHED, 0, 1));
+ db_query("UPDATE {node_comment_statistics} SET comment_count = %d, last_comment_timestamp = %d, last_comment_name = '%s', last_comment_uid = %d WHERE nid = %d", $count, $last_reply->timestamp, $last_reply->uid ? '' : $last_reply->name, $last_reply->uid, $nid);
+ }
+
+ // no comments
+ else {
+ $node = db_fetch_object(db_query("SELECT uid, created FROM {node} WHERE nid = %d", $nid));
+ db_query("UPDATE {node_comment_statistics} SET comment_count = 0, last_comment_timestamp = %d, last_comment_name = '', last_comment_uid = %d WHERE nid = %d", $node->created, $node->uid, $nid);
+ }
+}
+
+/**
+ * Invoke a hook_comment() operation in all modules.
+ *
+ * @param &$comment
+ * A comment object.
+ * @param $op
+ * A string containing the name of the comment operation.
+ * @return
+ * The returned value of the invoked hooks.
+ */
+function comment_invoke_comment(&$comment, $op) {
+ $return = array();
+ foreach (module_implements('comment') as $name) {
+ $function = $name .'_comment';
+ $result = $function($comment, $op);
+ if (isset($result) && is_array($result)) {
+ $return = array_merge($return, $result);
+ }
+ else if (isset($result)) {
+ $return[] = $result;
+ }
+ }
+ return $return;
+}
+
+/**
+ * Generate vancode.
+ *
+ * Consists of a leading character indicating length, followed by N digits
+ * with a numerical value in base 36. Vancodes can be sorted as strings
+ * without messing up numerical order.
+ *
+ * It goes:
+ * 00, 01, 02, ..., 0y, 0z,
+ * 110, 111, ... , 1zy, 1zz,
+ * 2100, 2101, ..., 2zzy, 2zzz,
+ * 31000, 31001, ...
+ */
+function int2vancode($i = 0) {
+ $num = base_convert((int)$i, 10, 36);
+ $length = strlen($num);
+ return chr($length + ord('0') - 1) . $num;
+}
+
+/**
+ * Decode vancode back to an integer.
+ */
+function vancode2int($c = '00') {
+ return base_convert(substr($c, 1), 36, 10);
+}
diff --git a/modules/contact.module b/modules/contact.module
new file mode 100644
index 0000000..82114bf
--- /dev/null
+++ b/modules/contact.module
@@ -0,0 +1,549 @@
+'. t('The contact module enables the use of both personal and site-wide contact forms, thereby facilitating easy communication within the community. While personal contact forms allow users to contact each other by e-mail, site-wide forms allow community members to contact the site administration from a central location. Users can specify a subject and message in the contact form, and also request that a copy of the e-mail be sent to their own address.') .'';
+ $output .= ''. t("Users can activate/deactivate their personal contact forms in their account settings. Upon activation, a contact tab will appear in their user profiles. Privileged users such as site administrators are able to contact users even if they have chosen not to enable this feature.") .'
';
+ $output .= ''. t('If the menu module is enabled, a menu item linking to the site-wide contact page is added to the navigation block. It is disabled by default, but can be enabled via the menu management page. Links to the contact page may also be added to the primary and secondary links using the same page.', array('%menu-module' => url('admin/menu'))) .'
';
+ $output .= t('Contact module links:') .'';
+ $output .= '- '. t('Default site-wide contact page.', array('%contact-page' => url('contact'))) .'
';
+ $output .= '- '. t('Site-wide contact form category configuration.', array('%configuration-page' => url('admin/contact'))) .'
';
+ $output .= '- '. t('Site-wide contact form general settings.', array('%additional-settings' => url('admin/contact/settings'))) .'
';
+ $output .= '- '. t('Site-wide contact form menu configuration.', array('%menu-configuration' => url('admin/menu'))) .'
';
+ $output .= t('For more information, please read the configuration and customization handbook page for the contact module.', array('%contact' => url('http://drupal.org/handbook/modules/contact/', NULL, NULL, TRUE)));
+ return $output;
+ case 'admin/modules#description':
+ return t('Enables the use of both personal and site-wide contact forms.');
+ case 'admin/contact':
+ $output = t('This page lets you setup your site-wide contact form. To do so, add one or more categories. You can associate different recipients with each category to route e-mails to different people. For example, you can route website feedback to the webmaster and direct product information requests to the sales department. On the settings page, you can customize the information shown above the contact form. This can be useful to provide additional contact information such as your postal address and telephone number.', array('%settings' => url('admin/contact/settings'), '%form' => url('contact')));
+ if (!module_exist('menu')) {
+ $menu_note = t('The menu item can be customized and configured only once the menu module has been enabled.', array('%modules-page' => url('admin/modules')));
+ }
+ else {
+ $menu_note = '';
+ }
+ $output .= ''. t('The contact module also adds a menu item (disabled by default) to the navigation block.', array('%menu-settings' => url('admin/menu'))) .' '. $menu_note .'
';
+ return($output);
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function contact_menu($may_cache) {
+ $items = array();
+ if ($may_cache) {
+ $items[] = array('path' => 'admin/contact',
+ 'title' => t('contact form'),
+ 'callback' => 'contact_admin_categories',
+ 'access' => user_access('administer site configuration'),
+ );
+ $items[] = array('path' => 'admin/contact/category',
+ 'title' => t('categories'),
+ 'callback' => 'contact_admin_categories',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK,
+ );
+ $items[] = array('path' => 'admin/contact/category/list',
+ 'title' => t('list'),
+ 'callback' => 'contact_admin_categories',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK,
+ );
+ $items[] = array('path' => 'admin/contact/category/add',
+ 'title' => t('add category'),
+ 'callback' => 'contact_admin_edit',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 1,
+ );
+ $items[] = array('path' => 'admin/contact/category/edit',
+ 'title' => t('edit contact category'),
+ 'callback' => 'contact_admin_edit',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_CALLBACK,
+ );
+ $items[] = array('path' => 'admin/contact/category/delete',
+ 'title' => t('delete contact'),
+ 'callback' => 'contact_admin_delete',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_CALLBACK,
+ );
+ $items[] = array('path' => 'admin/contact/settings',
+ 'title' => t('settings'),
+ 'callback' => 'contact_admin_settings',
+ 'access' => user_access('administer site configuration'),
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 1,
+ );
+ $items[] = array('path' => 'contact',
+ 'title' => t('contact'),
+ 'callback' => 'contact_mail_page',
+ 'access' => user_access('access content'),
+ 'type' => MENU_SUGGESTED_ITEM,
+ );
+ }
+ else {
+ if (arg(0) == 'user' && is_numeric(arg(1))) {
+ $items[] = array('path' => "user/". arg(1) ."/contact",
+ 'title' => t('contact'),
+ 'callback' => 'contact_mail_user',
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 2,
+ );
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_user().
+ *
+ * Allows the user the option of enabling/disabling his personal contact form.
+ */
+function contact_user($type, $edit, &$user, $category = NULL) {
+ if ($type == 'form' && $category == 'account') {
+ $form['contact'] = array('#type' => 'fieldset',
+ '#title' => t('Contact settings'),
+ '#weight' => 5,
+ '#collapsible' => TRUE,
+ );
+ $form['contact']['contact'] = array('#type' => 'checkbox',
+ '#title' => t('Personal contact form'),
+ '#default_value' => $edit['contact'],
+ '#description' => t('Allow other users to contact you by e-mail via your personal contact form. Note that while your e-mail address is not made public to other members of the community, privileged users such as site administrators are able to contact you even if you choose not to enable this feature.', array('%url' => url("user/$user->uid/contact"))),
+ );
+ return $form;
+ }
+ if ($type == 'validate') {
+ return array('contact' => $edit['contact']);
+ }
+}
+
+/**
+ * Categories/list tab.
+ */
+function contact_admin_categories() {
+ $result = db_query('SELECT cid, category, recipients, selected FROM {contact} ORDER BY weight, category');
+ $rows = array();
+ while ($category = db_fetch_object($result)) {
+ $rows[] = array($category->category, $category->recipients, ($category->selected ? t('Yes') : t('No')), l(t('edit'), 'admin/contact/category/edit/'. $category->cid), l(t('delete'), 'admin/contact/category/delete/'. $category->cid));
+ }
+ $header = array(t('Category'), t('Recipients'), t('Selected'), array('data' => t('Operations'), 'colspan' => 2));
+
+ return theme('table', $header, $rows);
+}
+
+/**
+ * Category edit page.
+ */
+function contact_admin_edit($cid = NULL) {
+ if (arg(3) == "edit" && $cid > 0) {
+ $edit = db_fetch_array(db_query("SELECT * FROM {contact} WHERE cid = %d", $cid));
+ }
+ $form['category'] = array('#type' => 'textfield',
+ '#title' => t('Category'),
+ '#maxlength' => 255,
+ '#default_value' => $edit['category'],
+ '#description' => t("Example: 'website feedback' or 'product information'."),
+ '#required' => TRUE,
+ );
+ $form['recipients'] = array('#type' => 'textarea',
+ '#title' => t('Recipients'),
+ '#default_value' => $edit['recipients'],
+ '#description' => t("Example: 'webmaster@yoursite.com' or 'sales@yoursite.com'. To specify multiple recipients, separate each e-mail address with a comma."),
+ '#required' => TRUE,
+ );
+ $form['reply'] = array('#type' => 'textarea',
+ '#title' => t('Auto-reply'),
+ '#default_value' => $edit['reply'],
+ '#description' => t('Optional auto-reply. Leave empty if you do not want to send the user an auto-reply message.'),
+ );
+ $form['weight'] = array('#type' => 'weight',
+ '#title' => t('Weight'),
+ '#default_value' => $edit['weight'],
+ '#description' => t('When listing categories, those with lighter (smaller) weights get listed before categories with heavier (larger) weights. Categories with equal weights are sorted alphabetically.'),
+ );
+ $form['selected'] = array('#type' => 'select',
+ '#title' => t('Selected'),
+ '#options' => array('0' => t('No'), '1' => t('Yes')),
+ '#default_value' => $edit['selected'],
+ '#description' => t('Set this to Yes if you would like this category to be selected by default.'),
+ );
+ $form['cid'] = array('#type' => 'value',
+ '#value' => $edit['cid'],
+ );
+ $form['submit'] = array('#type' => 'submit',
+ '#value' => t('Submit'),
+ );
+
+ return drupal_get_form('contact_admin_edit', $form);
+}
+
+/**
+ * Validate the contact category edit page form submission.
+ */
+function contact_admin_edit_validate($form_id, $form_values) {
+ if (empty($form_values['category'])) {
+ form_set_error('category', t('You must enter a category.'));
+ }
+ if (empty($form_values['recipients'])) {
+ form_set_error('recipients', t('You must enter one or more recipients.'));
+ }
+ else {
+ $recipients = explode(',', $form_values['recipients']);
+ foreach($recipients as $recipient) {
+ if (!valid_email_address(trim($recipient))) {
+ form_set_error('recipients', t('%recipient is an invalid e-mail address.', array('%recipient' => theme('placeholder', $recipient))));
+ }
+ }
+ }
+}
+
+/**
+ * Process the contact category edit page form submission.
+ */
+function contact_admin_edit_submit($form_id, $form_values) {
+ if ($form_values['selected']) {
+ // Unselect all other contact categories.
+ db_query('UPDATE {contact} SET selected = 0');
+ }
+ $recipients = explode(',', $form_values['recipients']);
+ foreach($recipients as $key=>$recipient) {
+ // E-mail address validation has already been done in _validate.
+ $recipients[$key] = trim($recipient);
+ }
+ $form_values['recipients'] = implode(',', $recipients);
+ if (arg(3) == 'add') {
+ db_query("INSERT INTO {contact} (category, recipients, reply, weight, selected) VALUES ('%s', '%s', '%s', %d, %d)", $form_values['category'], $form_values['recipients'], $form_values['reply'], $form_values['weight'], $form_values['selected']);
+ drupal_set_message(t('Category %category has been added.', array('%category' => theme('placeholder', $form_values['category']))));
+ watchdog('mail', t('Contact form: category %category added.', array('%category' => theme('placeholder', $form_values['category']))), WATCHDOG_NOTICE, l(t('view'), 'admin/contact'));
+
+ }
+ else {
+ db_query("UPDATE {contact} SET category = '%s', recipients = '%s', reply = '%s', weight = %d, selected = %d WHERE cid = %d", $form_values['category'], $form_values['recipients'], $form_values['reply'], $form_values['weight'], $form_values['selected'], $form_values['cid']);
+ drupal_set_message(t('Category %category has been updated.', array('%category' => theme('placeholder', $form_values['category']))));
+ watchdog('mail', t('Contact form: category %category updated.', array('%category' => theme('placeholder', $form_values['category']))), WATCHDOG_NOTICE, l(t('view'), 'admin/contact'));
+ }
+
+ return 'admin/contact';
+}
+
+/**
+ * Category delete page.
+ */
+function contact_admin_delete($cid = NULL) {
+ if ($info = db_fetch_object(db_query("SELECT category FROM {contact} WHERE cid = %d", $cid))) {
+ $form['category'] = array('#type' => 'value',
+ '#value' => $info->category,
+ );
+
+ return confirm_form('contact_admin_delete', $form, t('Are you sure you want to delete %category?', array('%category' => theme('placeholder', $info->category))), 'admin/contact', t('This action cannot be undone.'), t('Delete'), t('Cancel'));
+ }
+ else {
+ drupal_set_message(t('Category not found.'), 'error');
+ drupal_goto('admin/contact');
+ }
+}
+
+/**
+ * Process category delete form submission.
+ */
+function contact_admin_delete_submit($form_id, $form_values) {
+ db_query("DELETE FROM {contact} WHERE cid = %d", arg(4));
+ drupal_set_message(t('Category %category has been deleted.', array('%category' => theme('placeholder', $form_values['category']))));
+ watchdog('mail', t('Contact form: category %category deleted.', array('%category' => theme('placeholder', $form_values['category']))), WATCHDOG_NOTICE);
+
+ return 'admin/contact';
+}
+
+/**
+ * Settings tab. Using a form rather than hook_settings().
+ */
+function contact_admin_settings() {
+ $form['contact_form_information'] = array('#type' => 'textarea',
+ '#title' => t('Additional information'),
+ '#default_value' => variable_get('contact_form_information', t('You can leave a message using the contact form below.')),
+ '#description' => t('Information to show on the contact page. Can be anything from submission guidelines to your postal address or telephone number.', array('%form' => url('contact'))),
+ );
+ $form['contact_hourly_threshold'] = array('#type' => 'select',
+ '#title' => t('Hourly threshold'),
+ '#options' => drupal_map_assoc(array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50)),
+ '#default_value' => variable_get('contact_hourly_threshold', 3),
+ '#description' => t('The maximum number of contact form submissions a user can perform per hour.'),
+ );
+ $form['submit'] = array('#type' => 'submit',
+ '#value' => t('Save configuration'),
+ );
+ $form['reset'] = array('#type' => 'submit',
+ '#value' => t('Reset to defaults'),
+ );
+ // Use system_settings_form for the callback.
+ return drupal_get_form('contact_admin_settings', $form, 'system_settings_form');
+}
+
+/**
+ * Personal contact page.
+ */
+function contact_mail_user() {
+ global $user;
+
+ if ($account = user_load(array('uid' => arg(1)))) {
+ $admin_access = user_access('administer users');
+ if (!$account->status && !$admin_access) {
+ drupal_access_denied();
+ }
+ else if (!$account->contact && !$admin_access) {
+ $output = t('%name is not accepting e-mails.', array('%name' => $account->name));
+ }
+ else if (!$user->uid) {
+ $output = t('Please login or register to send %name a message.', array('%login' => url('user/login'), '%register' => url('user/register'), '%name' => $account->name));
+ }
+ else if (!valid_email_address($user->mail)) {
+ $output = t('You need to provide a valid e-mail address to contact other users. Please update your user information and try again.', array('%url' => url("user/$user->uid/edit")));
+ }
+ else if (!flood_is_allowed('contact', variable_get('contact_hourly_threshold', 3))) {
+ $output = t('You cannot contact more than %number users per hour. Please try again later.', array('%number' => variable_get('contact_hourly_threshold', 3)));
+ }
+ else {
+ drupal_set_title($account->name);
+
+ $form['#token'] = $user->name . $user->mail;
+ $form['from'] = array('#type' => 'item',
+ '#title' => t('From'),
+ '#value' => $user->name .' <'. $user->mail .'>',
+ );
+ $form['to'] = array('#type' => 'item',
+ '#title' => t('To'),
+ '#value' => $account->name,
+ );
+ $form['subject'] = array('#type' => 'textfield',
+ '#title' => t('Subject'),
+ '#maxlength' => 50,
+ '#required' => TRUE,
+ );
+ $form['message'] = array('#type' => 'textarea',
+ '#title' => t('Message'),
+ '#rows' => 15,
+ '#required' => TRUE,
+ );
+ $form['copy'] = array('#type' => 'checkbox',
+ '#title' => t('Send me a copy.'),
+ );
+ $form['submit'] = array('#type' => 'submit',
+ '#value' => t('Send e-mail'),
+ );
+ $output = drupal_get_form('contact_mail_user', $form);
+ }
+
+ return $output;
+ }
+ else {
+ drupal_not_found();
+ }
+}
+
+/**
+ * Process the personal contact page form submission.
+ */
+function contact_mail_user_submit($form_id, $edit) {
+ global $user;
+
+ $account = user_load(array('uid' => arg(1), 'status' => 1));
+ // Compose the body:
+ $message[] = "$account->name,";
+ $message[] = t("%name (%name-url) has sent you a message via your contact form (%form-url) at %site.", array('%name' => $user->name, '%name-url' => url("user/$user->uid", NULL, NULL, TRUE), '%form-url' => url($_GET['q'], NULL, NULL, TRUE), '%site' => variable_get('site_name', 'drupal')));
+ $message[] = t("If you don't want to receive such e-mails, you can change your settings at %url.", array('%url' => url("user/$account->uid", NULL, NULL, TRUE)));
+ $message[] = t('Message:');
+ $message[] = $edit['message'];
+
+ // Tidy up the body:
+ foreach ($message as $key => $value) {
+ $message[$key] = wordwrap($value);
+ }
+
+ // Prepare all fields:
+ $to = $account->mail;
+ $from = $user->mail;
+
+ // Format the subject:
+ $subject = '['. variable_get('site_name', 'drupal') .'] '. $edit['subject'];
+
+ // Prepare the body:
+ $body = implode("\n\n", $message);
+
+ // Send the e-mail:
+ user_mail($to, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
+
+ // Send a copy if requested:
+ if ($edit['copy']) {
+ user_mail($from, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
+ }
+
+ // Log the operation:
+ flood_register_event('contact');
+ watchdog('mail', t('%name-from sent %name-to an e-mail.', array('%name-from' => theme('placeholder', $user->name), '%name-to' => theme('placeholder', $account->name))));
+
+ // Set a status message:
+ drupal_set_message(t('The message has been sent.'));
+
+ // Jump to the user's profile page:
+ return "user/$account->uid";
+}
+
+/**
+ * Site-wide contact page
+ */
+function contact_mail_page() {
+ global $user;
+
+ if (!flood_is_allowed('contact', variable_get('contact_hourly_threshold', 3))) {
+ $output = t("You cannot send more than %number messages per hour. Please try again later.", array('%number' => variable_get('contact_hourly_threshold', 3)));
+ }
+ else {
+ if ($user->uid) {
+ $edit['name'] = $user->name;
+ $edit['mail'] = $user->mail;
+ }
+
+ $result = db_query('SELECT cid, category, selected FROM {contact} ORDER BY weight, category');
+ while ($category = db_fetch_object($result)) {
+ $categories[$category->cid] = $category->category;
+ if ($category->selected) {
+ $default_category = $category->cid;
+ }
+ }
+
+ if (count($categories) > 0) {
+ $form['#token'] = $user->name . $user->mail;
+ $form['contact_information'] = array('#value' => filter_xss_admin(variable_get('contact_form_information', t('You can leave us a message using the contact form below.'))));
+ $form['name'] = array('#type' => 'textfield',
+ '#title' => t('Your name'),
+ '#maxlength' => 255,
+ '#default_value' => $edit['name'],
+ '#required' => TRUE,
+ );
+ $form['mail'] = array('#type' => 'textfield',
+ '#title' => t('Your e-mail address'),
+ '#maxlength' => 255,
+ '#default_value' => $edit['mail'],
+ '#required' => TRUE,
+ );
+ $form['subject'] = array('#type' => 'textfield',
+ '#title' => t('Subject'),
+ '#maxlength' => 255,
+ '#required' => TRUE,
+ );
+ if (count($categories) > 1) {
+ // If there is more than one category available and no default category has been selected,
+ // prepend a default placeholder value.
+ if (!isset($default_category)) {
+ $categories = array(t('--')) + $categories;
+ }
+ $form['cid'] = array('#type' => 'select',
+ '#title' => t('Category'),
+ '#default_value' => $default_category,
+ '#options' => $categories,
+ '#required' => TRUE,
+ );
+ }
+ else {
+ // If there is only one category, store its cid.
+ $category_keys = array_keys($categories);
+ $form['cid'] = array('#type' => 'value',
+ '#value' => array_shift($category_keys),
+ );
+ }
+ $form['message'] = array('#type' => 'textarea',
+ '#title' => t('Message'),
+ '#required' => TRUE,
+ );
+ $form['copy'] = array('#type' => 'checkbox',
+ '#title' => t('Send me a copy.'),
+ );
+ $form['submit'] = array('#type' => 'submit',
+ '#value' => t('Send e-mail'),
+ );
+ $output = drupal_get_form('contact_mail_page', $form);
+ }
+ else {
+ $output = t('The contact form has not been configured.');
+ }
+ }
+
+ return $output;
+}
+
+/**
+ * Validate the site-wide contact page form submission.
+ */
+function contact_mail_page_validate($form_id, $form_values) {
+ if (!$form_values['cid']) {
+ form_set_error('category', t('You must select a valid category.'));
+ }
+ if (!valid_email_address($form_values['mail'])) {
+ form_set_error('mail', t('You must enter a valid e-mail address.'));
+ }
+}
+
+/**
+ * Process the site-wide contact page form submission.
+ */
+function contact_mail_page_submit($form_id, $edit) {
+
+ // E-mail address of the sender: as the form field is a text field,
+ // all instances of \r and \n have been automatically stripped from it.
+ $from = $edit['mail'];
+
+ // Compose the body:
+ $message[] = t("%name sent a message using the contact form at %form.", array('%name' => $edit['name'], '%form' => url($_GET['q'], NULL, NULL, TRUE)));
+ $message[] = $edit['message'];
+
+ // Tidy up the body:
+ foreach ($message as $key => $value) {
+ $message[$key] = wordwrap($value);
+ }
+
+ // Load the category information:
+ $contact = db_fetch_object(db_query("SELECT * FROM {contact} WHERE cid = %d", $edit['cid']));
+
+ // Format the category:
+ $subject = t('[%category] %subject', array('%category' => $contact->category, '%subject' => $edit['subject']));
+
+ // Prepare the body:
+ $body = implode("\n\n", $message);
+
+ // Send the e-mail to the recipients:
+ user_mail($contact->recipients, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
+
+ // If the user requests it, send a copy.
+ if ($edit['copy']) {
+ user_mail($from, $subject, $body, "From: $from\nReply-to: $from\nX-Mailer: Drupal\nReturn-path: $from\nErrors-to: $from");
+ }
+
+ // Send an auto-reply if necessary:
+ if ($contact->reply) {
+ user_mail($from, $subject, wordwrap($contact->reply), "From: $contact->recipients\nReply-to: $contact->recipients\nX-Mailer: Drupal\nReturn-path: $contact->recipients\nErrors-to: $contact->recipients");
+ }
+
+ // Log the operation:
+ flood_register_event('contact');
+ watchdog('mail', t('%name-from sent an e-mail regarding %category.', array('%name-from' => theme('placeholder', $edit['name'] ." <$from>"), '%category' => theme('placeholder', $contact->category))));
+
+ // Update user:
+ drupal_set_message(t('Your message has been sent.'));
+
+ // Jump to home page rather than back to contact page to avoid contradictory messages if flood control has been activated.
+ return('');
+}
diff --git a/modules/drupal.module b/modules/drupal.module
new file mode 100644
index 0000000..d47d004
--- /dev/null
+++ b/modules/drupal.module
@@ -0,0 +1,364 @@
+'. t('The Drupal module uses the XML-RPC network communication protocol to connect your site with a central server that maintains a directory of client sites.') .'';
+ $output .= t('Enabling the Drupal module will allow you to:
+
+ - register your site with a server, including (optionally) posting information on your installed modules and themes and summary statistics on your number of posts and users, information that can help rank Drupal modules and themes
+ - enable other sites to register with your site
+ - allow members on all sites using the Drupal module to log in to your site without registering using their distributed identification
+ - allow members to log in to any other site that uses the Drupal module, using a login name that looks much like an e-mail address: username@example.com
+
+');
+ $output .= ''. t('The Drupal module administration page allows you to set the xml-rpc server page and other related options.') .'
';
+ $output .= t('You can
+
+', array('%file-cron' => 'cron.php', '%file-xmlrpc' => 'xmlrpc.php', '%admin-settings-drupal' => url('admin/settings/drupal')));
+ $output .= ''. t('If you maintain a directory of sites, you can list them on a page using the drupal_client_page()
function. Sample instructions:
+
') . '';
+
+ $output .= ''. t('For more information please read the configuration and customization handbook Drupal page.', array('%drupal' => 'http://drupal.org/handbook/modules/drupal/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Lets you register your site with a central server and improve ranking of Drupal projects by posting information on your installed modules and themes; also enables users to log in using a Drupal ID.');
+ case 'admin/settings/drupal':
+ return t('Using this your site can "call home" to another Drupal server. By calling home to drupal.org and sending a list of your installed modules and themes, you help rank projects on drupal.org and so assist all Drupal administrators to find the best components for meeting their needs. If you want to register with a different server, you can change the Drupal XML-RPC server setting -- but the server has to be able to handle Drupal XML. Some XML-RPC servers may present directories of all registered sites. To get all your site information listed, go to the settings page and set the site name, the e-mail address, the slogan, and the mission statement.
', array('%site-settings' => url('admin/settings')));
+ case 'user/help#drupal':
+ return variable_get('drupal_authentication_service', 0) ? t("Drupal is the name of the software that powers %this-site. There are Drupal web sites all over the world, and many of them share their registration databases so that users may freely log in to any Drupal site using a single Drupal ID.
+So please feel free to log in to your account here at %this-site with a username from another Drupal site. The format of a Drupal ID is similar to an e-mail address: username@server. An example of a valid Drupal ID is mwlily@drupal.org.
", array('%Drupal' => 'http://drupal.org', '%this-site' => ''. variable_get('site_name', 'this web site') .'')) : '';
+ }
+}
+
+/**
+ * Implementation of hook_settings().
+ */
+function drupal_settings() {
+ // Check if all required fields are present
+ if ((variable_get('site_name', 'drupal') == 'drupal') || (variable_get('site_name', 'drupal') == '')) {
+ form_set_error('drupal_directory', t('You must set the name of your site on the administer » settings page.', array('%url' => url('admin/settings'))));
+ }
+ else if (variable_get('site_mail', ini_get('sendmail_from')) == '') {
+ form_set_error('drupal_directory', t('You must set an e-mail address for your site on the administer » settings page.', array('%url' => url('admin/settings'))));
+ }
+ else if (variable_get('site_slogan', '') == '') {
+ form_set_error('drupal_directory', t('You must set your site slogan on the administer » settings page.', array('%url' => url('admin/settings'))));
+ }
+ else if (variable_get('site_mission', '') == '') {
+ form_set_error('drupal_directory', t('You must set your site mission on the administer » settings page.' , array('%url' => url('admin/settings'))));
+ }
+ $options = array('1' => t('Enabled'), '0' => t('Disabled'));
+
+ $form['drupal'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Post data to another site'),
+ '#tree' => FALSE
+ );
+
+ $form['drupal']['drupal_register'] = array(
+ '#type' => 'radios',
+ '#title' => t('Register with a Drupal server'),
+ '#default_value' => variable_get('drupal_register', 0),
+ '#options' => $options,
+ '#description' => t("If enabled, your Drupal site will register itself with the specified Drupal XML-RPC server. For this to work properly, you must set your site's name, e-mail address, slogan and mission statement. When the \"Drupal XML-RPC server\" field is set to \"%drupal-xml-rpc\", your web site will register itself with drupal.org. Requires the cron feature to be enabled.", array("%drupal-xml-rpc" => "http://drupal.org/xmlrpc.php", "%drupal-sites" => "http://drupal.org/drupal-sites/"))
+ );
+
+ $form['drupal']['drupal_server'] = array(
+ '#type' => 'textfield',
+ '#title' => t('Drupal XML-RPC server'),
+ '#default_value' => variable_get('drupal_server', 'http://drupal.org/xmlrpc.php'),
+ '#description' => t('The URL of the Drupal XML-RPC server you wish to register with.')
+ );
+
+ $form['drupal']['drupal_system'] = array(
+ '#type' => 'radios',
+ '#title' => t('Send system information'),
+ '#default_value' => variable_get('drupal_system', 0),
+ '#options' => $options,
+ '#description' => t("If enabled, your site will send information on its installed components (modules, themes, and theme engines). This information can help in compiling statistics on usage of Drupal projects.")
+ );
+
+ $form['drupal']['drupal_statistics'] = array(
+ '#type' => 'radios',
+ '#title' => t('Send statistics'),
+ '#default_value' => variable_get('drupal_statistics', 0),
+ '#options' => $options,
+ '#description' => t("If enabled, your site will send summary statistics on the number of registered users and the total number of posts. No private information will be sent. These data help to improve the ranking statistics of Drupal projects.")
+ );
+
+ $form['services'] = array(
+ '#type' => 'fieldset',
+ '#title' => t('Receive data from other sites'),
+ '#tree' => FALSE
+ );
+
+ $form['services']['drupal_client_service'] = array(
+ '#type' => 'radios',
+ '#title' => t('Allow other Drupal sites to register'),
+ '#default_value' => variable_get('drupal_client_service', 0),
+ '#options' => $options,
+ '#description' => t('If enabled, your Drupal site will allow other sites to register with your site and send information to this site. This functionality can be used to maintain a list of related sites.')
+ );
+
+ $form['services']['drupal_authentication_service'] = array(
+ '#type' => 'radios',
+ '#title' => t('Authentication service'),
+ '#default_value' => variable_get('drupal_authentication_service', 0),
+ '#options' => $options,
+ '#description' => t('If enabled, your Drupal site will accept logins with the user names of other Drupal sites, and likewise provide authentication for users logging into other Drupal sites, based on their user accounts here.')
+ );
+
+ return $form;
+}
+
+/**
+ * Implementation of hook_cron(); handles pings to and from the site.
+ */
+function drupal_cron() {
+ if (time() - variable_get('cron_last', 0) > 21600) {
+
+ // If this site acts as a Drupal XML-RPC server, delete the sites that
+ // stopped sending "ping" messages.
+ if (variable_get('drupal_client_service', 0)) {
+ $result = db_query("SELECT cid FROM {client} WHERE changed < %d", time() - 259200);
+ while ($client = db_fetch_object($result)) {
+ db_query("DELETE FROM {client_system} WHERE cid = %d", $client->cid);
+ db_query("DELETE FROM {client} WHERE cid = %d", $client->cid);
+ }
+ }
+
+ // If this site acts as a Drupal XML-RPC client, send a message to the
+ // Drupal XML-RPC server.
+ if (variable_get('drupal_register', 0) && variable_get('drupal_server', 0)) {
+ drupal_notify(variable_get('drupal_server', ''));
+ }
+ }
+}
+
+/**
+ * Callback function from drupal_xmlrpc() called when another site pings this one.
+ */
+function drupal_client_ping($client, $system) {
+ /*
+ ** Parse our parameters:
+ */
+
+ foreach (array('link', 'name', 'mail', 'slogan', 'mission') as $key) {
+ $client[$key] = strip_tags($client[$key]);
+ }
+
+ /*
+ ** Update the data in our database and send back a reply:
+ */
+
+ if ($client['link'] && $client['name'] && $client['mail'] && $client['slogan'] && $client['mission']) {
+ $result = db_query(db_rewrite_sql("SELECT cid FROM {client} WHERE link = '%s'"), $client['link']);
+ if (db_num_rows($result)) {
+ $record = db_fetch_object($result);
+ $client['cid'] = $record->cid;
+ // We have an existing record.
+ db_query("UPDATE {client} SET link = '%s', name = '%s', mail = '%s', slogan = '%s', mission = '%s', users = %d, nodes = %d, version = '%s', changed = '%s' WHERE cid = %d", $client['uid'], $client['link'], $client['name'], $client['mail'], $client['slogan'], $client['mission'], $client['users'], $client['nodes'], $client['version'], time(), $client['cid']);
+ }
+ else {
+ $client['cid'] = db_next_id('{client}_cid');
+ db_query("INSERT INTO {client} (cid, link, name, mail, slogan, mission, users, nodes, version, created, changed) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", $client['cid'], $client['link'], $client['name'], $client['mail'], $client['slogan'], $client['mission'], $client['users'], $client['nodes'], $client['version'], time(), time());
+ }
+ if (is_array($system)) {
+ db_query("DELETE FROM {client_system} WHERE cid = %d", $client['cid']);
+ foreach ($system as $item) {
+ db_query("INSERT INTO {client_system} (cid, name, type) VALUES (%d, '%s', '%s')", $client['cid'], $item['name'], $item['type']);
+ }
+ }
+ watchdog('client ping', t('Ping from %name (%link).', array('%name' => theme('placeholder', $client['name']), '%link' => theme('placeholder', $client['link']))), WATCHDOG_NOTICE, 'view');
+
+ return TRUE;
+ }
+ else {
+ return 0;
+ }
+
+}
+
+/**
+ * Formats a list of all clients.
+ *
+ * This function may be called from a custom page on sites that are
+ * Drupal directory servers.
+ */
+function drupal_client_page($sort = 'name') {
+ $result = db_query('SELECT * FROM {client} ORDER BY %s', $sort);
+
+ $clients = array();
+ while ($client = db_fetch_object($result)) {
+ $clients[] = $client;
+ }
+
+ return theme('client_list', $clients);
+}
+
+/**
+ * Theme a client list.
+ */
+function theme_client_list($clients) {
+ // Note: All fields except the mission are treated as plain-text.
+ // The mission is stripped of any HTML tags to keep the output simple and consistent.
+ $output = "\n\n";
+ foreach ($clients as $client) {
+ $output .= ' - ' . check_plain($client->name) . ' - ' . check_plain($client->slogan) . "
\n";
+ $output .= ' - ' . strip_tags($client->mission) . "
\n";
+ }
+ $output .= "
\n";
+ return $output;
+}
+
+/**
+ * Implementation of hook_xmlrpc().
+ */
+function drupal_xmlrpc() {
+ $xmlrpc = array();
+ if (variable_get('drupal_client_service', 0)) {
+ $xmlrpc[] = array(
+ 'drupal.client.ping',
+ 'drupal_client_ping',
+ array('array', 'array', 'array'),
+ t('Handling ping request')
+ );
+ }
+ if (variable_get('drupal_authentication_service', 0)) {
+ $xmlrpc[] = array(
+ 'drupal.login',
+ 'drupal_login',
+ array('int', 'string', 'string'),
+ t('Logging into a Drupal site')
+ );
+ }
+ return $xmlrpc;
+}
+
+/**
+ * Sends a ping to the Drupal directory server.
+ */
+function drupal_notify($server) {
+ global $base_url;
+ $client = array(
+ 'link' => $base_url,
+ 'name' => variable_get('site_name', ''),
+ 'mail' => variable_get('site_mail', ''),
+ 'slogan' => variable_get('site_slogan', ''),
+ 'mission' => variable_get('site_mission', ''),
+ 'version' => VERSION
+ );
+ if (variable_get('drupal_system', 0)) {
+ $system = array();
+ $result = db_query("SELECT name, type FROM {system} WHERE status = 1");
+ while ($item = db_fetch_array($result)) {
+ $system[] = $item;
+ }
+ }
+ if (variable_get('drupal_statistics', 0)) {
+ $users = db_fetch_object(db_query("SELECT COUNT(uid) AS count FROM {users}"));
+ $client['users'] = $users->count;
+ $nodes = db_fetch_object(db_query("SELECT COUNT(nid) AS count FROM {node}"));
+ $client['nodes'] = $nodes->count;
+ }
+ $result = xmlrpc($server, 'drupal.client.ping', $client, $system);
+
+ if ($result === FALSE) {
+ watchdog('server ping', t('Failed to notify %server; error code: %errno; error message: %error_msg.', array('%server' => theme('placeholder', $server), '%errno' => theme('placeholder', xmlrpc_errno()), '%error_msg' => theme('placeholder', xmlrpc_error_msg()))), WATCHDOG_WARNING);
+ }
+}
+
+/**
+ * Implementation of hook_info().
+ */
+function drupal_info($field = 0) {
+ $info['name'] = 'Drupal';
+ $info['protocol'] = 'XML-RPC';
+
+ if ($field) {
+ return $info[$field];
+ }
+ else {
+ return $info;
+ }
+}
+
+/**
+ * Implementation of hook_auth().
+ */
+function drupal_auth($username, $password, $server) {
+ if (variable_get('drupal_authentication_service', 0)) {
+ $result = xmlrpc("http://$server/xmlrpc.php", 'drupal.login', $username, $password);
+ if ($result === FALSE) {
+ drupal_set_message(t('Error %code : %message', array('%code' => theme('placeholder', xmlrpc_errno()), '%message' => theme('placeholder', xmlrpc_error_msg()))), 'error');
+ }
+ else {
+ return $result;
+ }
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function drupal_menu($may_cache) {
+ $items = array();
+ if ($may_cache) {
+ if (variable_get('drupal_authentication_service', 0)) {
+ $items[] = array('path' => 'drupal', 'title' => t('Drupal'),
+ 'callback' => 'drupal_page_help', 'access' => TRUE,
+ 'type' => MENU_SUGGESTED_ITEM
+ );
+ }
+ }
+ return $items;
+}
+
+/**
+ * Menu callback; print Drupal-authentication-specific information from user/help.
+ */
+function drupal_page_help() {
+ return drupal_help('user/help#drupal');
+}
+
+/**
+ * Callback function from drupal_xmlrpc() for authenticating remote clients.
+ *
+ * Remote clients are usually other Drupal instances.
+ */
+function drupal_login($username, $password) {
+ if (variable_get('drupal_authentication_service', 0)) {
+ if ($user = user_load(array('name' => $username, 'pass' => $password, 'status' => 1))) {
+ return $user->uid;
+ }
+ else {
+ return 0;
+ }
+ }
+}
+
+
diff --git a/modules/filter.module b/modules/filter.module
new file mode 100644
index 0000000..2172d37
--- /dev/null
+++ b/modules/filter.module
@@ -0,0 +1,1372 @@
+'. t('The filter module allows administrators to configure text input formats for the site. For example, an administrator may want a filter to strip out malicious HTML from user\'s comments. Administrators may also want to make URLs linkable even if they are only entered in an unlinked format.') .'';
+ $output .= ''. t('Users can choose between the available input formats when creating or editing content. Administrators can configure which input formats are available to which user roles, as well as choose a default input format. Administrators can also create new input formats. Each input format can be configured to use a selection of filters.') .'
';
+ $output .= t('You can
+
+', array('%admin-filters' => url('admin/filters')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Filter page.', array('%filter' => 'http://drupal.org/handbook/modules/filter/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Handles the filtering of content in preparation for display.');
+
+ case 'admin/filters':
+ return t('
+Input formats define a way of processing user-supplied text in Drupal. Every input format has its own settings of which filters to apply. Possible filters include stripping out malicious HTML and making URLs clickable.
+Users can choose between the available input formats when submitting content.
+Below you can configure which input formats are available to which roles, as well as choose a default input format (used for imported content, for example).
+Note that (1) the default format is always available to all roles, and (2) all filter formats can always be used by roles with the "administer filters" permission even if they are not explicitly listed in the Roles column of this table.
');
+
+ case 'admin/filters/'. arg(2):
+ return t('
+Every filter performs one particular change on the user input, for example stripping out malicious HTML or making URLs clickable. Choose which filters you want to apply to text in this input format.
+If you notice some filters are causing conflicts in the output, you can rearrange them.
', array('%rearrange' => url('admin/filters/'. arg(2) .'/order')));
+
+ case 'admin/filters/'. arg(2) .'/configure':
+ return t('
+If you cannot find the settings for a certain filter, make sure you\'ve enabled it on the view tab first.
', array('%url' => url('admin/filters/'. arg(2))));
+
+ case 'admin/filters/'. arg(2) .'/order':
+ return t('
+Because of the flexible filtering system, you might encounter a situation where one filter prevents another from doing its job. For example: a word in an URL gets converted into a glossary term, before the URL can be converted in a clickable link. When this happens, you will need to rearrange the order in which filters get executed.
+Filters are executed from top-to-bottom. You can use the weight column to rearrange them: heavier filters \'sink\' to the bottom.
');
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function filter_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array('path' => 'admin/filters',
+ 'title' => t('input formats'),
+ 'callback' => 'filter_admin_overview',
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/list',
+ 'title' => t('list'),
+ 'callback' => 'filter_admin_overview',
+ 'type' => MENU_DEFAULT_LOCAL_TASK,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/add',
+ 'title' => t('add input format'),
+ 'callback' => 'filter_admin_format_form',
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 1,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/delete',
+ 'title' => t('delete input format'),
+ 'callback' => 'filter_admin_delete',
+ 'type' => MENU_CALLBACK,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'filter/tips',
+ 'title' => t('compose tips'),
+ 'callback' => 'filter_tips_long',
+ 'access' => TRUE,
+ 'type' => MENU_SUGGESTED_ITEM,
+ );
+ }
+ else {
+ if (arg(0) == 'admin' && arg(1) == 'filters' && is_numeric(arg(2))) {
+ $formats = filter_formats();
+
+ if (isset($formats[arg(2)])) {
+ $items[] = array('path' => 'admin/filters/'. arg(2),
+ 'title' => t("'%format' input format", array('%format' => $formats[arg(2)]->name)),
+ 'callback' => 'filter_admin_format_form',
+ 'callback arguments' => array('format' => $formats[arg(2)]),
+ 'type' => MENU_CALLBACK,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/'. arg(2) .'/list',
+ 'title' => t('view'),
+ 'callback' => 'filter_admin_format_form',
+ 'callback arguments' => array('format' => $formats[arg(2)]),
+ 'type' => MENU_DEFAULT_LOCAL_TASK,
+ 'weight' => 0,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/'. arg(2) .'/configure',
+ 'title' => t('configure'),
+ 'callback' => 'filter_admin_configure',
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 1,
+ 'access' => user_access('administer filters'),
+ );
+ $items[] = array('path' => 'admin/filters/'. arg(2) .'/order',
+ 'title' => t('rearrange'),
+ 'callback' => 'filter_admin_order',
+ 'callback arguments' => array('format' => $formats[arg(2)]),
+ 'type' => MENU_LOCAL_TASK,
+ 'weight' => 2,
+ 'access' => user_access('administer filters'),
+ );
+ }
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function filter_perm() {
+ return array('administer filters');
+}
+
+/**
+ * Implementation of hook_filter_tips().
+ */
+function filter_filter_tips($delta, $format, $long = false) {
+ global $base_url;
+ switch ($delta) {
+ case 0:
+ if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
+ if ($allowed_html = variable_get("allowed_html_$format", ' -
-
- ')) {
+ switch ($long) {
+ case 0:
+ return t('Allowed HTML tags') .': '. check_plain($allowed_html);
+ case 1:
+ $output = '
'. t('Allowed HTML tags') .': '. check_plain($allowed_html) .'
';
+ if (!variable_get("filter_html_help_$format", 1)) {
+ return $output;
+ }
+
+ $output .= t('
+This site allows HTML content. While learning all of HTML may feel intimidating, learning how to use a very small number of the most basic HTML "tags" is very easy. This table provides examples for each tag that is enabled on this site.
+For more information see W3C\'s HTML Specifications or use your favorite search engine to find other sites that explain HTML.
');
+ $tips = array(
+ 'a' => array( t('Anchors are used to make links to other pages.'), ''. variable_get('site_name', 'drupal') .''),
+ 'br' => array( t('By default line break tags are automatically added, so use this tag to add additional ones. Use of this tag is different because it is not used with an open/close pair like all the others. Use the extra " /" inside the tag to maintain XHTML 1.0 compatibility'), t('Text with
line break')),
+ 'p' => array( t('By default paragraph tags are automatically added, so use this tag to add additional ones.'), ''. t('Paragraph one.') .'
'. t('Paragraph two.') .'
'),
+ 'strong' => array( t('Strong'), ''. t('Strong'). ''),
+ 'em' => array( t('Emphasized'), ''. t('Emphasized') .''),
+ 'cite' => array( t('Cited'), ''. t('Cited') .''),
+ 'code' => array( t('Coded text used to show programming source code'), ''. t('Coded') .'
'),
+ 'b' => array( t('Bolded'), ''. t('Bolded') .''),
+ 'u' => array( t('Underlined'), ''. t('Underlined') .''),
+ 'i' => array( t('Italicized'), ''. t('Italicized') .''),
+ 'sup' => array( t('Superscripted'), t('Superscripted')),
+ 'sub' => array( t('Subscripted'), t('Subscripted')),
+ 'pre' => array( t('Preformatted'), ''. t('Preformatted') .'
'),
+ 'abbr' => array( t('Abbreviation'), t('Abbrev.')),
+ 'acronym' => array( t('Acronym'), t('TLA')),
+ 'blockquote' => array( t('Block quoted'), ''. t('Block quoted') .'
'),
+ 'q' => array( t('Quoted inline'), ''. t('Quoted inline') .'
'),
+ // Assumes and describes tr, td, th.
+ 'table' => array( t('Table'), ' '. t('Table header') .' |
'. t('Table cell') .' |
'),
+ 'tr' => NULL, 'td' => NULL, 'th' => NULL,
+ 'del' => array( t('Deleted'), ''. t('Deleted') .''),
+ 'ins' => array( t('Inserted'), ''. t('Inserted') .''),
+ // Assumes and describes li.
+ 'ol' => array( t('Ordered list - use the <li> to begin each list item'), ' - '. t('First item') .'
- '. t('Second item') .'
'),
+ 'ul' => array( t('Unordered list - use the <li> to begin each list item'), ' - '. t('First item') .'
- '. t('Second item') .'
'),
+ 'li' => NULL,
+ // Assumes and describes dt and dd.
+ 'dl' => array( t('Definition lists are similar to other HTML lists. <dl> begins the definition list, <dt> begins the definition term and <dd> begins the definition description.'), ' - '. t('First term') .'
- '. t('First definition') .'
- '. t('Second term') .'
- '. t('Second definition') .'
'),
+ 'dt' => NULL, 'dd' => NULL,
+ 'h1' => array( t('Header'), ''. t('Title') .'
'),
+ 'h2' => array( t('Header'), ''. t('Subtitle') .'
'),
+ 'h3' => array( t('Header'), ''. t('Subtitle three') .'
'),
+ 'h4' => array( t('Header'), ''. t('Subtitle four') .'
'),
+ 'h5' => array( t('Header'), ''. t('Subtitle five') .'
'),
+ 'h6' => array( t('Header'), ''. t('Subtitle six') .'
')
+ );
+ $header = array(t('Tag Description'), t('You Type'), t('You Get'));
+ preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out);
+ foreach ($out[1] as $tag) {
+ if (array_key_exists($tag, $tips)) {
+ if ($tips[$tag]) {
+ $rows[] = array(
+ array('data' => $tips[$tag][0], 'class' => 'description'),
+ array('data' => ''. check_plain($tips[$tag][1]) .'
', 'class' => 'type'),
+ array('data' => $tips[$tag][1], 'class' => 'get')
+ );
+ }
+ }
+ else {
+ $rows[] = array(
+ array('data' => t('No help provided for tag %tag.', array('%tag' => check_plain($tag))), 'class' => 'description', 'colspan' => 3),
+ );
+ }
+ }
+ $output .= theme('table', $header, $rows);
+
+ $output .= t('
+Most unusual characters can be directly entered without any problems.
+If you do encounter problems, try using HTML character entities. A common example looks like & for an ampersand & character. For a full list of entities see HTML\'s entities page. Some of the available characters include:
');
+ $entities = array(
+ array( t('Ampersand'), '&'),
+ array( t('Greater than'), '>'),
+ array( t('Less than'), '<'),
+ array( t('Quotation mark'), '"'),
+ );
+ $header = array(t('Character Description'), t('You Type'), t('You Get'));
+ unset($rows);
+ foreach ($entities as $entity) {
+ $rows[] = array(
+ array('data' => $entity[0], 'class' => 'description'),
+ array('data' => ''. check_plain($entity[1]) .'
', 'class' => 'type'),
+ array('data' => $entity[1], 'class' => 'get')
+ );
+ }
+ $output .= theme('table', $header, $rows);
+ return $output;
+ }
+ }
+ else {
+ return t('No HTML tags allowed');
+ }
+ }
+ break;
+
+ case 1:
+ switch ($long) {
+ case 0:
+ return t('You may post PHP code. You should include <?php ?> tags.');
+ case 1:
+ return t('
+Using custom PHP code
+If you know how to script in PHP, Drupal gives you the power to embed any script you like. It will be executed when the page is viewed and dynamically embedded into the page. This gives you amazing flexibility and power, but of course with that comes danger and insecurity if you don\'t write good code. If you are not familiar with PHP, SQL or with the site engine, avoid experimenting with PHP because you can corrupt your database or render your site insecure or even unusable! If you don\'t plan to do fancy stuff with your content then you\'re probably better off with straight HTML.
+Remember that the code within each PHP item must be valid PHP code - including things like correctly terminating statements with a semicolon. It is highly recommended that you develop your code separately using a simple test script on top of a test database before migrating to your production environment.
+Notes:
- You can use global variables, such as configuration parameters, within the scope of your PHP code but remember that global variables which have been given values in your code will retain these values in the engine afterwards.
- register_globals is now set to off by default. If you need form information you need to get it from the "superglobals" $_POST, $_GET, etc.
- You can either use the
print
or return
statement to output the actual content for your item.
+A basic example:
+You want to have a box with the title "Welcome" that you use to greet your visitors. The content for this box could be created by going:
+
+ print t("Welcome visitor, ... welcome message goes here ...");
+
+If we are however dealing with a registered user, we can customize the message by using:
+
+ global $user;
+ if ($user->uid) {
+ print t("Welcome $user->name, ... welcome message goes here ...");
+ }
+ else {
+ print t("Welcome visitor, ... welcome message goes here ...");
+ }
+
+For more in-depth examples, we recommend that you check the existing Drupal code and use it as a starting point, especially for sidebar boxes.
');
+ }
+
+ case 2:
+ switch ($long) {
+ case 0:
+ return t('Lines and paragraphs break automatically.');
+ case 1:
+ return t('Lines and paragraphs are automatically recognized. The <br /> line break, <p> paragraph and </p> close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.');
+ }
+ }
+}
+
+/**
+ * Displays a list of all input formats and which one is the default
+ */
+function filter_admin_overview() {
+
+ // Overview of all formats.
+ $formats = filter_formats();
+ $error = false;
+
+ $rows = array();
+ foreach ($formats as $id => $format) {
+ $roles = array();
+ foreach (user_roles() as $rid => $name) {
+ // Prepare a roles array with roles that may access the filter
+ if (strstr($format->roles, ",$rid,")) {
+ $roles[] = $name;
+ }
+ }
+ $row = array();
+ $default = ($id == variable_get('filter_default_format', 1));
+ $options[$id] = '';
+ $form[$format->name]['id'] = array('#value' => $id);
+ $form[$format->name]['roles'] = array('#value' => $default ? t('All roles may use default format') : ($roles ? implode(', ',$roles) : t('No roles may use this format')));
+ $form[$format->name]['configure'] = array('#value' => l(t('configure'), 'admin/filters/'. $id));
+ $form[$format->name]['delete'] = array('#value' => $default ? '' : l(t('delete'), 'admin/filters/delete/'. $id));
+ }
+ $form['default'] = array('#type' => 'radios', '#options' => $options, '#default_value' => variable_get('filter_default_format', 1));
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Set default format'));
+ return drupal_get_form('filter_admin_overview', $form);
+}
+
+function filter_admin_overview_submit($form_id, $form_values) {
+ // Process form submission to set the default format
+ if (is_numeric($form_values['default'])) {
+ drupal_set_message(t('Default format updated.'));
+ variable_set('filter_default_format', $form_values['default']);
+ }
+}
+
+function theme_filter_admin_overview($form) {
+ foreach ($form as $name => $element) {
+ if (isset($element['roles']) && is_array($element['roles'])) {
+ $rows[] = array(
+ form_render($form['default'][$element['id']['#value']]),
+ check_plain($name),
+ form_render($element['roles']),
+ form_render($element['configure']),
+ form_render($element['delete'])
+ );
+ unset($form[$name]);
+ }
+ }
+ $header = array(t('Default'), t('Name'), t('Roles'), array('data' => t('Operations'), 'colspan' => 2));
+ $output = theme('table', $header, $rows);
+ $output .= form_render($form);
+
+ return $output;
+}
+
+/**
+ * Menu callback; confirm deletion of a format.
+ */
+function filter_admin_delete() {
+ $format = arg(3);
+ $format = db_fetch_object(db_query('SELECT * FROM {filter_formats} WHERE format = %d', $format));
+
+ if ($format) {
+ if ($format->format != variable_get('filter_default_format', 1)) {
+ $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
+ $form['name'] = array('#type' => 'hidden', '#value' => $format->name);
+
+ return confirm_form('filter_admin_delete', $form, t('Are you sure you want to delete the input format %format?', array('%format' => theme('placeholder', $format->name))), 'admin/filters', t('If you have any content left in this input format, it will be switched to the default input format. This action cannot be undone.'), t('Delete'), t('Cancel'));
+ }
+ else {
+ drupal_set_message(t('The default format cannot be deleted.'));
+ drupal_goto('admin/filters');
+ }
+ }
+ else {
+ drupal_not_found();
+ }
+}
+
+/**
+ * Process filter delete form submission.
+ */
+function filter_admin_delete_submit($form_id, $form_values) {
+ db_query("DELETE FROM {filter_formats} WHERE format = %d", $form_values['format']);
+ db_query("DELETE FROM {filters} WHERE format = %d", $form_values['format']);
+
+ $default = variable_get('filter_default_format', 1);
+ // Replace existing instances of the deleted format with the default format.
+ db_query("UPDATE {node_revisions} SET format = %d WHERE format = %d", $default, $form_values['format']);
+ db_query("UPDATE {comments} SET format = %d WHERE format = %d", $default, $form_values['format']);
+ db_query("UPDATE {boxes} SET format = %d WHERE format = %d", $default, $form_values['format']);
+
+ cache_clear_all('filter:'. $form_values['format'], true);
+ drupal_set_message(t('Deleted input format %format.', array('%format' => theme('placeholder', $form_values['name']))));
+
+ return 'admin/filters';
+}
+
+/**
+ * Generate a filter format form.
+ */
+function filter_admin_format_form($format = NULL) {
+ $default = ($format->format == variable_get('filter_default_format', 1));
+ if ($default) {
+ $help = t('All roles for the default format must be enabled and cannot be changed.');
+ $form['default_format'] = array('#type' => 'hidden', '#value' => 1);
+ }
+
+ $form['name'] = array('#type' => 'textfield',
+ '#title' => 'Name',
+ '#default_value' => $format->name,
+ '#description' => t('Specify a unique name for this filter format.'),
+ '#required' => TRUE,
+ );
+
+ // Add a row of checkboxes for form group.
+ $form['roles'] = array('#type' => 'fieldset',
+ '#title' => t('Roles'),
+ '#description' => $default ? $help : t('Choose which roles may use this filter format. Note that roles with the "administer filters" permission can always use all the filter formats.'),
+ '#tree' => TRUE,
+ );
+
+ foreach (user_roles() as $rid => $name) {
+ $checked = strstr($format->roles, ",$rid,");
+ $form['roles'][$rid] = array('#type' => 'checkbox',
+ '#title' => $name,
+ '#default_value' => ($default || $checked),
+ );
+ if ($default) {
+ $form['roles'][$rid]['#attributes'] = array('disabled' => 'disabled');
+ }
+ }
+ // Table with filters
+ $all = filter_list_all();
+ $enabled = filter_list_format($format->format);
+
+ $form['filters'] = array('#type' => 'fieldset',
+ '#title' => t('Filters'),
+ '#description' => t('Choose the filters that will be used in this filter format.'),
+ '#tree' => TRUE,
+ );
+ foreach ($all as $id => $filter) {
+ $form['filters'][$id] = array('#type' => 'checkbox',
+ '#title' => $filter->name,
+ '#default_value' => isset($enabled[$id]),
+ '#description' => module_invoke($filter->module, 'filter', 'description', $filter->delta),
+ );
+ }
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
+
+ if (isset($format)) {
+ $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
+
+ // Composition tips (guidelines)
+ $tips = _filter_tips($format->format, false);
+ $extra = l(t('More information about formatting options'), 'filter/tips');
+ $tiplist = theme('filter_tips', $tips, false, $extra);
+ if (!$tiplist) {
+ $tiplist = t('No guidelines available.
');
+ }
+ $group = t('These are the guidelines that users will see for posting in this input format. They are automatically generated from the filter settings.
');
+ $group .= $tiplist;
+ $output = ''. t('Formatting guidelines') .'
'. $group;
+ }
+ $output = drupal_get_form('filter_admin_format_form', $form) . $output;
+
+ return $output;
+}
+
+/**
+ * Validate filter format form submissions.
+ */
+function filter_admin_format_form_validate($form_id, $form_values) {
+ if (!isset($form_values['format'])) {
+ $name = trim($form_values['name']);
+ $result = db_fetch_object(db_query("SELECT format FROM {filter_formats} WHERE name='%s'", $name));
+ if ($result) {
+ form_set_error('name', t('Filter format names need to be unique. A format named %name already exists.', array('%name' => theme('placeholder', $name))));
+ }
+ }
+}
+
+/**
+ * Process filter format form submissions.
+ */
+function filter_admin_format_form_submit($form_id, $form_values) {
+ $format = isset($form_values['format']) ? $form_values['format'] : NULL;
+ $current = filter_list_format($format);
+ $name = trim($form_values['name']);
+ $cache = TRUE;
+
+ // Add a new filter format.
+ if (!$format) {
+ $new = TRUE;
+ db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
+ $result = db_fetch_object(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
+ $format = $result->format;
+ drupal_set_message(t('Added input format %format.', array('%format' => theme('placeholder', $name))));
+ }
+ else {
+ drupal_set_message(t('The input format settings have been updated.'));
+ }
+
+ db_query("DELETE FROM {filters} WHERE format = %d", $format);
+ foreach ($form_values['filters'] as $id => $checked) {
+ if ($checked) {
+ list($module, $delta) = explode('/', $id);
+ // Add new filters to the bottom.
+ $weight = isset($current[$id]->weight) ? $current[$id]->weight : 10;
+ db_query("INSERT INTO {filters} (format, module, delta, weight) VALUES (%d, '%s', %d, %d)", $format, $module, $delta, $weight);
+
+ // Check if there are any 'no cache' filters.
+ $cache &= !module_invoke($module, 'filter', 'no cache', $delta);
+ }
+ }
+
+ // We store the roles as a string for ease of use.
+ // We should always set all roles to true when saving a default role.
+ // We use leading and trailing comma's to allow easy substring matching.
+ $roles = array();
+ if (isset($form_values['roles'])) {
+ foreach ($form_values['roles'] as $id => $checked) {
+ if ($checked) {
+ $roles[] = $id;
+ }
+ }
+ }
+ $roles = ','. implode(',', ($form_values['default_format'] ? user_roles() : $roles)) .',';
+
+ db_query("UPDATE {filter_formats} SET cache = %d, name='%s', roles = '%s' WHERE format = %d", $cache, $name, $roles, $format);
+
+ cache_clear_all('filter:'. $format, true);
+
+ // If a new filter was added, return to the main list of filters. Otherwise, stay on edit filter page to show new changes.
+ if ($new) {
+ return 'admin/filters/';
+ }
+ else {
+ return 'admin/filters/'. $format;
+ }
+}
+
+/**
+ * Menu callback; display form for ordering filters for a format.
+ */
+function filter_admin_order($format = NULL) {
+ // Get list (with forced refresh)
+ $filters = filter_list_format($format->format);
+
+ $form['weights'] = array('#tree' => TRUE);
+ foreach ($filters as $id => $filter) {
+ $form['names'][$id] = array('#value' => $filter->name);
+ $form['weights'][$id] = array('#type' => 'weight', '#default_value' => $filter->weight);
+ }
+ $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
+ $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
+
+ return drupal_get_form('filter_admin_order', $form);
+}
+
+/**
+ * Theme filter order configuration form.
+ */
+function theme_filter_admin_order($form) {
+ $header = array(t('Name'), t('Weight'));
+ $rows = array();
+ foreach (element_children($form['names']) as $id) {
+ // Don't take form control structures
+ if (is_array($form['names'][$id])) {
+ $rows[] = array(form_render($form['names'][$id]), form_render($form['weights'][$id]));
+ }
+ }
+
+ $output = theme('table', $header, $rows);
+ $output .= form_render($form);
+
+ return $output;
+}
+
+/**
+ * Process filter order configuration form submission.
+ */
+function filter_admin_order_submit($form_id, $form_values) {
+ foreach ($form_values['weights'] as $id => $weight) {
+ list($module, $delta) = explode('/', $id);
+ db_query("UPDATE {filters} SET weight = %d WHERE format = %d AND module = '%s' AND delta = %d", $weight, $form_values['format'], $module, $delta);
+ }
+ drupal_set_message(t('The filter ordering has been saved.'));
+
+ cache_clear_all('filter:'. $form_values['format'], true);
+}
+
+/**
+ * Menu callback; display settings defined by filters.
+ */
+function filter_admin_configure() {
+ $format = arg(2);
+
+ $list = filter_list_format($format);
+ $form = array();
+ foreach ($list as $filter) {
+ $form_module = module_invoke($filter->module, 'filter', 'settings', $filter->delta, $format);
+ if (isset($form_module) && is_array($form_module)) {
+ $form = array_merge($form, $form_module);
+ }
+ }
+
+ if (!empty($form)) {
+ $output = system_settings_form('filter_admin_configure', $form);
+ }
+ else {
+ $output = t('No settings are available.');
+ }
+
+ return $output;
+}
+
+/**
+ * Retrieve a list of input formats.
+ */
+function filter_formats() {
+ global $user;
+ static $formats;
+
+ // Administrators can always use all input formats.
+ $all = user_access('administer filters');
+
+ if (!isset($formats)) {
+ $formats = array();
+
+ $query = 'SELECT * FROM {filter_formats}';
+
+ // Build query for selecting the format(s) based on the user's roles.
+ if (!$all) {
+ $where = array();
+ foreach ($user->roles as $rid => $role) {
+ $where[] = "roles LIKE '%%,%d,%%'";
+ $args[] = $rid;
+ }
+ $query .= ' WHERE '. implode(' OR ', $where) . ' OR format = %d';
+ $args[] = variable_get('filter_default_format', 1);
+ }
+
+ $result = db_query($query, $args);
+ while ($format = db_fetch_object($result)) {
+ $formats[$format->format] = $format;
+ }
+ }
+ return $formats;
+}
+
+/**
+ * Build a list of all filters.
+ */
+function filter_list_all() {
+ $filters = array();
+
+ foreach (module_list() as $module) {
+ $list = module_invoke($module, 'filter', 'list');
+ if (isset($list) && is_array($list)) {
+ foreach ($list as $delta => $name) {
+ $filters[$module .'/'. $delta] = (object)array('module' => $module, 'delta' => $delta, 'name' => $name);
+ }
+ }
+ }
+
+ uasort($filters, '_filter_list_cmp');
+
+ return $filters;
+}
+
+/**
+ * Helper function for sorting the filter list by filter name.
+ */
+function _filter_list_cmp($a, $b) {
+ return strcmp($a->name, $b->name);
+}
+
+/**
+ * Resolve a format id, including the default format.
+ */
+function filter_resolve_format($format) {
+ return $format == FILTER_FORMAT_DEFAULT ? variable_get('filter_default_format', 1) : $format;
+}
+/**
+ * Check if text in a certain input format is allowed to be cached.
+ */
+function filter_format_allowcache($format) {
+ static $cache = array();
+ $format = filter_resolve_format($format);
+ if (!isset($cache[$format])) {
+ $cache[$format] = db_result(db_query('SELECT cache FROM {filter_formats} WHERE format = %d', $format));
+ }
+ return $cache[$format];
+}
+
+/**
+ * Retrieve a list of filters for a certain format.
+ */
+function filter_list_format($format) {
+ static $filters = array();
+
+ if (!isset($filters[$format])) {
+ $filters[$format] = array();
+ $result = db_query("SELECT * FROM {filters} WHERE format = %d ORDER BY weight ASC", $format);
+ while ($filter = db_fetch_object($result)) {
+ $list = module_invoke($filter->module, 'filter', 'list');
+ if (isset($list) && is_array($list) && isset($list[$filter->delta])) {
+ $filter->name = $list[$filter->delta];
+ $filters[$format][$filter->module .'/'. $filter->delta] = $filter;
+ }
+ }
+ }
+
+ return $filters[$format];
+}
+
+/**
+ * @name Filtering functions
+ * @{
+ * Modules which need to have content filtered can use these functions to
+ * interact with the filter system.
+ *
+ * For more info, see the hook_filter() documentation.
+ *
+ * Note: because filters can inject JavaScript or execute PHP code, security is
+ * vital here. When a user supplies a $format, you should validate it with
+ * filter_access($format) before accepting/using it. This is normally done in
+ * the validation stage of the node system. You should for example never make a
+ * preview of content in a disallowed format.
+ */
+
+/**
+ * Run all the enabled filters on a piece of text.
+ *
+ * @param $text
+ * The text to be filtered.
+ * @param $format
+ * The format of the text to be filtered. Specify FILTER_FORMAT_DEFAULT for
+ * the default format.
+ * @param $check
+ * Whether to check the $format with filter_access() first. Defaults to TRUE.
+ * Note that this will check the permissions of the current user, so you
+ * should specify $check = FALSE when viewing other people's content. When
+ * showing content that is not (yet) stored in the database (eg. upon preview),
+ * set to TRUE so the user's permissions are checked.
+ */
+function check_markup($text, $format = FILTER_FORMAT_DEFAULT, $check = TRUE) {
+ // When $check = true, do an access check on $format.
+ if (isset($text) && (!$check || filter_access($format))) {
+ $format = filter_resolve_format($format);
+
+ // Check for a cached version of this piece of text.
+ $id = 'filter:'. $format .':'. md5($text);
+ if ($cached = cache_get($id)) {
+ return $cached->data;
+ }
+
+ // See if caching is allowed for this format.
+ $cache = filter_format_allowcache($format);
+
+ // Convert all Windows and Mac newlines to a single newline,
+ // so filters only need to deal with one possibility.
+ $text = str_replace(array("\r\n", "\r"), "\n", $text);
+
+ // Get a complete list of filters, ordered properly.
+ $filters = filter_list_format($format);
+
+ // Give filters the chance to escape HTML-like data such as code or formulas.
+ foreach ($filters as $filter) {
+ $text = module_invoke($filter->module, 'filter', 'prepare', $filter->delta, $format, $text);
+ }
+
+ // Perform filtering.
+ foreach ($filters as $filter) {
+ $text = module_invoke($filter->module, 'filter', 'process', $filter->delta, $format, $text);
+ }
+
+ // Store in cache with a minimum expiration time of 1 day.
+ if ($cache) {
+ cache_set($id, $text, time() + (60 * 60 * 24));
+ }
+ }
+ else {
+ $text = message_na();
+ }
+
+ return $text;
+}
+
+/**
+ * Generate a selector for choosing a format in a form.
+ *
+ * @param $value
+ * The ID of the format that is currently selected.
+ * @param $weight
+ * The weight of the input format.
+ * @param $parents
+ * Required when defining multiple input formats on a single node or having a different parent than 'format'.
+ * @return
+ * HTML for the form element.
+ */
+function filter_form($value = FILTER_FORMAT_DEFAULT, $weight = NULL, $parents = array('format')) {
+ $value = filter_resolve_format($value);
+ $formats = filter_formats();
+
+ $extra = l(t('More information about formatting options'), 'filter/tips');
+
+ if (count($formats) > 1) {
+ $form = array(
+ '#type' => 'fieldset',
+ '#title' => t('Input format'),
+ '#collapsible' => TRUE,
+ '#collapsed' => TRUE,
+ '#weight' => $weight,
+ '#validate' => array('filter_form_validate' => array()),
+ );
+ // Multiple formats available: display radio buttons with tips.
+ foreach ($formats as $format) {
+ $form[$format->format] = array(
+ '#type' => 'radio',
+ '#title' => $format->name,
+ '#default_value' => $value,
+ '#return_value' => $format->format,
+ '#parents' => $parents,
+ '#description' => theme('filter_tips', _filter_tips($format->format, false)),
+ );
+ }
+ }
+ else {
+ // Only one format available: use a hidden form item and only show tips.
+ $format = array_shift($formats);
+ $form[$format->format] = array('#type' => 'value', '#value' => $format->format, '#parents' => $parents);
+ $tips = _filter_tips(variable_get('filter_default_format', 1), false);
+ $form['format']['guidelines'] = array(
+ '#title' => t('Formatting guidelines'),
+ '#value' => theme('filter_tips', $tips, false, $extra),
+ );
+ }
+ $form[] = array(
+ '#type' => 'markup',
+ '#value' => $extra,
+ );
+ return $form;
+}
+
+function filter_form_validate($form) {
+ foreach (element_children($form) as $key) {
+ if ($form[$key]['#value'] == $form[$key]['#return_value']) {
+ return;
+ }
+ }
+ form_error($form, t('An illegal choice has been detected. Please contact the site administrator.'));
+ watchdog('form', t('Illegal choice %choice in %name element.', array('%choice' => theme('placeholder', check_plain($v)), '%name' => theme('placeholder', empty($form['#title']) ? $form['#parents'][0] : $form['#title']))), WATCHDOG_ERROR);
+}
+
+/**
+ * Returns true if the user is allowed to access this format.
+ */
+function filter_access($format) {
+ $format = filter_resolve_format($format);
+ if (user_access('administer filters') || ($format == variable_get('filter_default_format', 1))) {
+ return true;
+ }
+ else {
+ $formats = filter_formats();
+ return isset($formats[$format]);
+ }
+}
+/**
+ * @} End of "Filtering functions".
+ */
+
+/**
+ * Menu callback; show a page with long filter tips.
+ */
+function filter_tips_long() {
+ $format = arg(2);
+ if ($format) {
+ $output = theme('filter_tips', _filter_tips($format, true), true);
+ }
+ else {
+ $output = theme('filter_tips', _filter_tips(-1, true), true);
+ }
+ return $output;
+}
+
+/**
+ * Helper function for fetching filter tips.
+ */
+function _filter_tips($format, $long = false) {
+ if ($format == -1) {
+ $formats = filter_formats();
+ }
+ else {
+ $formats = array(db_fetch_object(db_query("SELECT * FROM {filter_formats} WHERE format = %d", $format)));
+ }
+
+ $tips = array();
+
+ foreach ($formats as $format) {
+ $filters = filter_list_format($format->format);
+
+ $tips[$format->name] = array();
+ foreach ($filters as $id => $filter) {
+ if ($tip = module_invoke($filter->module, 'filter_tips', $filter->delta, $format->format, $long)) {
+ $tips[$format->name][] = array('tip' => $tip, 'id' => $id);
+ }
+ }
+ }
+
+ return $tips;
+}
+
+/**
+ * Format a set of filter tips.
+ *
+ * @ingroup themeable
+ */
+function theme_filter_tips($tips, $long = false, $extra = '') {
+ $output = '';
+
+ $multiple = count($tips) > 1;
+ if ($multiple) {
+ $output = t('input formats') .':';
+ }
+
+ if (count($tips)) {
+ if ($multiple) {
+ $output .= '';
+ }
+ foreach ($tips as $name => $tiplist) {
+ if ($multiple) {
+ $output .= '- ';
+ $output .= ''. $name .':
';
+ }
+
+ $tips = '';
+ foreach ($tiplist as $tip) {
+ $tips .= ' - ' : '>') . $tip['tip'] . '
';
+ }
+
+ if ($tips) {
+ $output .= "";
+ }
+
+ if ($multiple) {
+ $output .= '
';
+ }
+ }
+ if ($multiple) {
+ $output .= '
';
+ }
+ }
+
+ return $output;
+}
+
+/**
+ * @name Standard filters
+ * @{
+ * Filters implemented by the filter.module.
+ */
+
+/**
+ * Implementation of hook_filter(). Contains a basic set of essential filters.
+ * - HTML filter:
+ * Validates user-supplied HTML, transforming it as necessary.
+ * - PHP evaluator:
+ * Executes PHP code.
+ * - Line break converter:
+ * Converts newlines into paragraph and break tags.
+ */
+function filter_filter($op, $delta = 0, $format = -1, $text = '') {
+ switch ($op) {
+ case 'list':
+ return array(0 => t('HTML filter'), 1 => t('PHP evaluator'), 2 => t('Line break converter'));
+
+ case 'no cache':
+ return $delta == 1; // No caching for the PHP evaluator.
+
+ case 'description':
+ switch ($delta) {
+ case 0:
+ return t('Allows you to restrict if users can post HTML and which tags to filter out.');
+ case 1:
+ return t('Runs a piece of PHP code. The usage of this filter should be restricted to administrators only!');
+ case 2:
+ return t('Converts line breaks into HTML (i.e. <br> and <p> tags).');
+ default:
+ return;
+ }
+
+ case 'process':
+ switch ($delta) {
+ case 0:
+ return _filter_html($text, $format);
+ case 1:
+ return drupal_eval($text);
+ case 2:
+ return _filter_autop($text);
+ default:
+ return $text;
+ }
+
+ case 'settings':
+ switch ($delta) {
+ case 0:
+ return _filter_html_settings($format);
+ default:
+ return;
+ }
+
+ default:
+ return $text;
+ }
+}
+
+/**
+ * Settings for the HTML filter.
+ */
+function _filter_html_settings($format) {
+ $form['filter_html'] = array('#type' => 'fieldset', '#title' => t('HTML filter'), '#collapsible' => TRUE, '#collapsed' => TRUE);
+ $form['filter_html']["filter_html_$format"] = array('#type' => 'radios', '#title' => t('Filter HTML tags'), '#default_value' => variable_get("filter_html_$format", FILTER_HTML_STRIP), '#options' => array(FILTER_HTML_STRIP => t('Strip disallowed tags'), FILTER_HTML_ESCAPE => t('Escape all tags')), '#description' => t('How to deal with HTML tags in user-contributed content. If set to "Strip disallowed tags", dangerous tags are removed (see below). If set to "Escape tags", all HTML is escaped and presented as it was typed.'));
+ $form['filter_html']["allowed_html_$format"] = array('#type' => 'textfield', '#title' => t('Allowed HTML tags'), '#default_value' => variable_get("allowed_html_$format", ' -
-
- '), '#size' => 64, '#maxlength' => 255, '#description' => t('If "Strip disallowed tags" is selected, optionally specify tags which should not be stripped. JavaScript event attributes are always stripped.'));
+ $form['filter_html']["filter_html_help_$format"] = array('#type' => 'checkbox', '#title' => t('Display HTML help'), '#default_value' => variable_get("filter_html_help_$format", 1), '#description' => t('If enabled, Drupal will display some basic HTML help in the long filter tips.'));
+ $form['filter_html']["filter_html_nofollow_$format"] = array('#type' => 'checkbox', '#title' => t('Spam link deterrent'), '#default_value' => variable_get("filter_html_nofollow_$format", FALSE), '#description' => t('If enabled, Drupal will add rel="nofollow" to all links, as a measure to reduce the effectiveness of spam links. Note: this will also prevent valid links from being followed by search engines, therefore it is likely most effective when enabled for anonymous users.'));
+ return $form;
+}
+
+/**
+ * HTML filter. Provides filtering of input into accepted HTML.
+ */
+function _filter_html($text, $format) {
+ if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
+ $allowed_tags = preg_split('/\s+|<|>/', variable_get("allowed_html_$format", '
-
-
- '), -1, PREG_SPLIT_NO_EMPTY);
+ $text = filter_xss($text, $allowed_tags);
+ }
+
+ if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_ESCAPE) {
+ // Escape HTML
+ $text = check_plain($text);
+ }
+
+ if (variable_get("filter_html_nofollow_$format", FALSE)) {
+ $text = preg_replace('/]+)>/i', '', $text);
+ }
+
+ return trim($text);
+}
+
+/**
+ * Convert line breaks into
and
in an intelligent fashion.
+ * Based on: http://photomatt.net/scripts/autop
+ */
+function _filter_autop($text) {
+ // All block level tags
+ $block = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|p|h[1-6])';
+
+ // Split at
, , tags.
+ // We don't apply any processing to the contents of these tags to avoid messing
+ // up code. We look for matched pairs and allow basic nesting. For example:
+ // "processed ignored ignored
processed"
+ $chunks = preg_split('@(?(?:pre|script|style)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
+ // Note: PHP ensures the array consists of alternating delimiters and literals
+ // and begins and ends with a literal (inserting NULL as required).
+ $ignore = false;
+ $ignoretag = '';
+ $output = '';
+ foreach ($chunks as $i => $chunk) {
+ if ($i % 2) {
+ // Opening or closing tag?
+ $open = ($chunk[1] != '/');
+ list($tag) = split('[ >]', substr($chunk, 2 - $open), 2);
+ if (!$ignore) {
+ if ($open) {
+ $ignore = true;
+ $ignoretag = $tag;
+ }
+ }
+ // Only allow a matching tag to close it.
+ else if (!$open && $ignoretag == $tag) {
+ $ignore = false;
+ $ignoretag = '';
+ }
+ }
+ else if (!$ignore) {
+ $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
+ $chunk = preg_replace('|
\s*
|', "\n\n", $chunk);
+ $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
+ $chunk = preg_replace('!('. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
+ $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
+ $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "$1
\n", $chunk); // make paragraphs, including one at the end
+ $chunk = preg_replace('|\s*?
|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
+ $chunk = preg_replace("|(
|", "$1", $chunk); // problem with nested lists
+ $chunk = preg_replace('|]*)>|i', "", $chunk);
+ $chunk = str_replace('
', '
', $chunk);
+ $chunk = preg_replace('!\s*(?'. $block .'[^>]*>)!', "$1", $chunk);
+ $chunk = preg_replace('!(?'. $block .'[^>]*>)\s*
!', "$1", $chunk);
+ $chunk = preg_replace('|(?)\s*\n|', "
\n", $chunk); // make line breaks
+ $chunk = preg_replace('!(?'. $block .'[^>]*>)\s*
!', "$1", $chunk);
+ $chunk = preg_replace('!
(\s*?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
+ $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&$1', $chunk);
+ }
+ $output .= $chunk;
+ }
+ return $output;
+}
+
+/**
+ * Very permissive XSS/HTML filter for admin-only use.
+ *
+ * Use only for fields where it is impractical to use the
+ * whole filter system, but where some (mainly inline) mark-up
+ * is desired (so check_plain() is not acceptable).
+ *
+ * Allows all tags that can be used inside an HTML body, save
+ * for scripts and styles.
+ */
+function filter_xss_admin($string) {
+ return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'object', 'ol', 'p', 'param', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var'));
+}
+
+/**
+ * Filters XSS. Based on kses by Ulf Harnhammar, see
+ * http://sourceforge.net/projects/kses
+ *
+ * For examples of various XSS attacks, see:
+ * http://ha.ckers.org/xss.html
+ *
+ * This code does four things:
+ * - Removes characters and constructs that can trick browsers
+ * - Makes sure all HTML entities are well-formed
+ * - Makes sure all HTML tags and attributes are well-formed
+ * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)
+ *
+ * @param $string
+ * The string with raw HTML in it. It will be stripped of everything that can cause
+ * an XSS attack.
+ * @param $allowed_tags
+ * An array of allowed tags.
+ * @param $format
+ * The format to use.
+ */
+function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
+ // Store the input format
+ _filter_xss_split($allowed_tags, TRUE);
+ // Remove NUL characters (ignored by some browsers)
+ $string = str_replace(chr(0), '', $string);
+ // Remove Netscape 4 JS entities
+ $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
+
+ // Defuse all HTML entities
+ $string = str_replace('&', '&', $string);
+ // Change back only well-formed entities in our whitelist
+ // Named entities
+ $string = preg_replace('/&([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
+ // Decimal numeric entities
+ $string = preg_replace('/&#([0-9]+;)/', '\1', $string);
+ // Hexadecimal numeric entities
+ $string = preg_replace('/&#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '\1', $string);
+
+ return preg_replace_callback('%
+ (
+ <[^>]*.(>|$) # a string that starts with a <, up until the > or the end of the string
+ | # or
+ > # just a >
+ )%x', '_filter_xss_split', $string);
+}
+
+/**
+ * Processes an HTML tag.
+ *
+ * @param @m
+ * An array with various meaning depending on the value of $store.
+ * If $store is TRUE then the array contains the allowed tags.
+ * If $store is FALSE then the array has one element, the HTML tag to process.
+ * @param $store
+ * Whether to store $m.
+ * @return
+ * If the element isn't allowed, an empty string. Otherwise, the cleaned up
+ * version of the HTML element.
+ */
+function _filter_xss_split($m, $store = FALSE) {
+ static $allowed_html;
+
+ if ($store) {
+ $allowed_html = array_flip($m);
+ return;
+ }
+
+ $string = $m[1];
+
+ if (substr($string, 0, 1) != '<') {
+ // We matched a lone ">" character
+ return '>';
+ }
+
+ if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches)) {
+ // Seriously malformed
+ return '';
+ }
+
+ $slash = trim($matches[1]);
+ $elem = &$matches[2];
+ $attrlist = &$matches[3];
+
+ if (!isset($allowed_html[strtolower($elem)])) {
+ // Disallowed HTML element
+ return '';
+ }
+
+ if ($slash != '') {
+ return "$elem>";
+ }
+
+ // Is there a closing XHTML slash at the end of the attributes?
+ // In PHP 5.1.0+ we could count the changes, currently we need a separate match
+ $xhtml_slash = preg_match('%\s?/\s*$%', $attrlist) ? ' /' : '';
+ $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist);
+
+ // Clean up attributes
+ $attr2 = implode(' ', _filter_xss_attributes($attrlist));
+ $attr2 = preg_replace('/[<>]/', '', $attr2);
+ $attr2 = strlen($attr2) ? ' '. $attr2 : '';
+
+ return "<$elem$attr2$xhtml_slash>";
+}
+
+/**
+ * Processes a string of HTML attributes.
+ *
+ * @return
+ * Cleaned up version of the HTML attributes.
+ */
+function _filter_xss_attributes($attr) {
+ $attrarr = array();
+ $mode = 0;
+ $attrname = '';
+
+ while (strlen($attr) != 0) {
+ // Was the last operation successful?
+ $working = 0;
+
+ switch ($mode) {
+ case 0:
+ // Attribute name, href for instance
+ if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
+ $attrname = strtolower($match[1]);
+ $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
+ $working = $mode = 1;
+ $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
+ }
+
+ break;
+
+ case 1:
+ // Equals sign or valueless ("selected")
+ if (preg_match('/^\s*=\s*/', $attr)) {
+ $working = 1; $mode = 2;
+ $attr = preg_replace('/^\s*=\s*/', '', $attr);
+ break;
+ }
+
+ if (preg_match('/^\s+/', $attr)) {
+ $working = 1; $mode = 0;
+ if (!$skip) {
+ $attrarr[] = $attrname;
+ }
+ $attr = preg_replace('/^\s+/', '', $attr);
+ }
+
+ break;
+
+ case 2:
+ // Attribute value, a URL after href= for instance
+ if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname=\"$thisval\"";
+ }
+ $working = 1;
+ $mode = 0;
+ $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
+ break;
+ }
+
+ if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname='$thisval'";;
+ }
+ $working = 1; $mode = 0;
+ $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
+ break;
+ }
+
+ if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname=\"$thisval\"";
+ }
+ $working = 1; $mode = 0;
+ $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
+ }
+
+ break;
+ }
+
+ if ($working == 0) {
+ // not well formed, remove and try again
+ $attr = preg_replace('/
+ ^
+ (
+ "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
+ | # or
+ \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
+ | # or
+ \S # - a non-whitespace character
+ )* # any number of the above three
+ \s* # any number of whitespaces
+ /x', '', $attr);
+ $mode = 0;
+ }
+ }
+
+ // the attribute list ends with a valueless attribute like "selected"
+ if ($mode == 1) {
+ $attrarr[] = $attrname;
+ }
+ return $attrarr;
+}
+
+/**
+ * Processes an HTML attribute value and ensures it does not contain an URL
+ * with a disallowed protocol (e.g. javascript:)
+ *
+ * @param $string
+ * The string with the attribute value.
+ * @param $decode
+ * Whether to decode entities in the $string. Set to FALSE if the $string
+ * is in plain text, TRUE otherwise. Defaults to TRUE.
+ * @return
+ * Cleaned up and HTML-escaped version of $string.
+ */
+function filter_xss_bad_protocol($string, $decode = TRUE) {
+ static $allowed_protocols;
+ if (!isset($allowed_protocols)) {
+ $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal')));
+ }
+
+ // Get the plain text representation of the attribute value (i.e. its meaning)
+ if ($decode) {
+ $string = decode_entities($string);
+ }
+ // Remove soft hyphen
+ $string = str_replace(chr(194) . chr(173), '', $string);
+ // Strip protocols
+
+ do {
+ $before = $string;
+ $colonpos = strpos($string, ':');
+ if ($colonpos > 0) {
+ $protocol = substr($string, 0, $colonpos);
+ if (!isset($allowed_protocols[$protocol])) {
+ $string = substr($string, $colonpos + 1);
+ }
+ }
+ } while ($before != $string);
+ return check_plain($string);
+}
+
+/**
+ * @} End of "Standard filters".
+ */
+
diff --git a/modules/forum.module b/modules/forum.module
new file mode 100644
index 0000000..6d5fe65
--- /dev/null
+++ b/modules/forum.module
@@ -0,0 +1,1126 @@
+'. t('The forum module lets you create threaded discussion forums for a particular topic on your site. This is similar to a message board system such as phpBB. Forums are very useful because they allow community members to discuss topics with one another, and they are archived for future reference.') .'';
+ $output .= ''. t('Forums can be organized under what are called containers. Containers hold forums and, in turn, forums hold threaded discussions. Both containers and forums can be placed inside other containers and forums. By planning the structure of your containers and forums well, you make it easier for users to find a topic area of interest to them. Forum topics can be moved by selecting a different forum and can be left in the existing forum by selecting leave a shadow copy. Forum topics can also have their own URL.') .'
';
+ $output .= ''. t('Forums module requires Taxonomy and Comments module be enabled.') .'
';
+ $output .= t('You can
+
+', array('%admin-forum' => url('admin/forum'), '%admin-modules' => url('admin/modules'), '%admin-help-comment' => url('admin/help/comment'), '%admin-help-taxonomy' => url('admin/help/taxonomy')));
+ $output .= ''. t('For more information please read the configuration and customization handbook Forum page.', array('%forum' => 'http://drupal.org/handbook/modules/forum/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Enables threaded discussions about general topics.');
+ case 'admin/forum':
+ return t('This is a list of existing containers and forums that you can edit. Containers hold forums and, in turn, forums hold threaded discussions. Both containers and forums can be placed inside other containers and forums. By planning the structure of your containers and forums well, you make it easier for users to find a topic area of interest to them.
');
+ case 'admin/forum/add/container':
+ return t('Containers help you organize your forums. The job of a container is to hold, or contain, other forums that are related. For example, a container named "Food" might hold two forums named "Fruit" and "Vegetables".
');
+ case 'admin/forum/add/forum':
+ return t('A forum holds discussion topics that are related. For example, a forum named "Fruit" might contain topics titled "Apples" and "Bananas".
');
+ case 'admin/forum/configure':
+ return t('This is where you can configure system-wide options for how your forums act and display.');
+ case 'node/add#forum':
+ return t('Create a new topic for discussion in the forums.');
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ */
+function forum_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ $items[] = array('path' => 'node/add/forum',
+ 'title' => t('forum topic'),
+ 'access' => user_access('create forum topics'));
+ $items[] = array('path' => 'forum',
+ 'title' => t('forums'),
+ 'callback' => 'forum_page',
+ 'access' => user_access('access content'),
+ 'type' => MENU_SUGGESTED_ITEM);
+ $items[] = array('path' => 'admin/forum',
+ 'title' => t('forums'),
+ 'callback' => 'forum_overview',
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_NORMAL_ITEM);
+ $items[] = array('path' => 'admin/forum/list',
+ 'title' => t('list'),
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_DEFAULT_LOCAL_TASK,
+ 'weight' => -10);
+ $items[] = array('path' => 'admin/forum/add/container',
+ 'title' => t('add container'),
+ 'callback' => 'forum_form_container',
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_LOCAL_TASK);
+ $items[] = array('path' => 'admin/forum/add/forum',
+ 'title' => t('add forum'),
+ 'callback' => 'forum_form_forum',
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_LOCAL_TASK);
+ $items[] = array('path' => 'admin/forum/configure',
+ 'title' => t('configure'),
+ 'callback' => 'forum_admin_configure',
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_LOCAL_TASK);
+ }
+ elseif (is_numeric(arg(4))) {
+ $term = taxonomy_get_term(arg(4));
+ // Check if this is a valid term.
+ if ($term) {
+ $items[] = array('path' => 'admin/forum/edit/container',
+ 'title' => t('edit container'),
+ 'callback' => 'forum_form_container',
+ 'callback arguments' => array((array)$term),
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_CALLBACK);
+ $items[] = array('path' => 'admin/forum/edit/forum',
+ 'title' => t('edit forum'),
+ 'callback' => 'forum_form_forum',
+ 'callback arguments' => array((array)$term),
+ 'access' => user_access('administer forums'),
+ 'type' => MENU_CALLBACK);
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Implementation of hook_node_info().
+ */
+function forum_node_info() {
+ return array('forum' => array('name' => t('forum topic'), 'base' => 'forum'));
+}
+
+/**
+ * Implementation of hook_access().
+ */
+function forum_access($op, $node) {
+ global $user;
+
+ if ($op == 'create') {
+ return user_access('create forum topics');
+ }
+
+ if ($op == 'update' || $op == 'delete') {
+ if (user_access('edit own forum topics') && ($user->uid == $node->uid)) {
+ return TRUE;
+ }
+ }
+}
+
+/**
+ * Implementation of hook_perm().
+ */
+function forum_perm() {
+ return array('create forum topics', 'edit own forum topics', 'administer forums');
+}
+
+/**
+ * Implementation of hook_nodeapi().
+ */
+function forum_nodeapi(&$node, $op, $teaser, $page) {
+ switch ($op) {
+ case 'delete revision':
+ db_query('DELETE FROM {forum} WHERE vid = %d', $node->vid);
+ break;
+ }
+}
+
+/**
+ * Implementation of hook_taxonomy().
+ */
+function forum_taxonomy($op, $type, $term = NULL) {
+ if ($op == 'delete' && $term['vid'] == _forum_get_vid()) {
+ switch ($type) {
+ case 'term':
+ $results = db_query('SELECT f.nid FROM {forum} f WHERE f.tid = %d', $term['tid']);
+ while ($node = db_fetch_object($results)) {
+ // node_delete will also remove any association with non-forum vocabularies.
+ node_delete($node->nid);
+ }
+
+ // For containers, remove the tid from the forum_containers variable.
+ $containers = variable_get('forum_containers', array());
+ $key = array_search($term['tid'], $containers);
+ if ($key !== FALSE) {
+ unset($containers[$key]);
+ }
+ variable_set('forum_containers', $containers);
+ break;
+ case 'vocabulary':
+ variable_del('forum_nav_vocabulary');
+ }
+ }
+}
+
+/**
+ * Implementation of hook_settings
+ */
+function forum_admin_configure() {
+
+ $form = array();
+ $number = drupal_map_assoc(array(5, 10, 15, 20, 25, 30, 35, 40, 50, 60, 80, 100, 150, 200, 250, 300, 350, 400, 500));
+ $form['forum_hot_topic'] = array('#type' => 'select',
+ '#title' => t('Hot topic threshold'),
+ '#default_value' => variable_get('forum_hot_topic', 15),
+ '#options' => $number,
+ '#description' => t('The number of posts a topic must have to be considered hot.'),
+ );
+ $number = drupal_map_assoc(array(10, 25, 50, 75, 100));
+ $form['forum_per_page'] = array('#type' => 'select',
+ '#title' => t('Topics per page'),
+ '#default_value' => variable_get('forum_per_page', 25),
+ '#options' => $number,
+ '#description' => t('The default number of topics displayed per page; links to browse older messages are automatically being displayed.'),
+ );
+ $forder = array(1 => t('Date - newest first'), 2 => t('Date - oldest first'), 3 => t('Posts - most active first'), 4=> t('Posts - least active first'));
+ $form['forum_order'] = array('#type' => 'radios',
+ '#title' => t('Default order'),
+ '#default_value' => variable_get('forum_order', '1'),
+ '#options' => $forder,
+ '#description' => t('The default display order for topics.'),
+ );
+
+ return system_settings_form('forum_admin_configure', $form);
+}
+
+/**
+ * Implementation of hook_form_alter().
+ */
+function forum_form_alter($form_id, &$form) {
+ // hide critical options from forum vocabulary
+ if ($form_id == 'taxonomy_form_vocabulary') {
+ if ($form['vid']['#value'] == _forum_get_vid()) {
+ $form['help_forum_vocab'] = array(
+ '#value' => t('This is the designated forum vocabulary. Some of the normal vocabulary options have been removed.'),
+ '#weight' => -1,
+ );
+ $form['nodes']['forum'] = array('#type' => 'checkbox', '#value' => 1, '#title' => t('forum topic'), '#attributes' => array('disabled' => '' ), '#description' => t('forum topic is affixed to the forum vocabulary.'));
+ $form['hierarchy'] = array('#type' => 'value', '#value' => 1);
+ unset($form['relations']);
+ unset($form['tags']);
+ unset($form['multiple']);
+ $form['required'] = array('#type' => 'value', '#value' => 1);
+ }
+ else {
+ unset($form['nodes']['forum']);
+ }
+ }
+}
+
+/**
+ * Implementation of hook_load().
+ */
+function forum_load($node) {
+ $forum = db_fetch_object(db_query('SELECT * FROM {forum} WHERE vid = %d', $node->vid));
+
+ return $forum;
+}
+
+/**
+ * Implementation of hook_block().
+ *
+ * Generates a block containing the currently active forum topics and the
+ * most recently added forum topics.
+ */
+function forum_block($op = 'list', $delta = 0, $edit = array()) {
+ switch ($op) {
+ case 'list':
+ $blocks[0]['info'] = t('Active forum topics');
+ $blocks[1]['info'] = t('New forum topics');
+ return $blocks;
+
+ case 'configure':
+ $form['forum_block_num_'. $delta] = array('#type' => 'select', '#title' => t('Number of topics'), '#default_value' => variable_get('forum_block_num_'. $delta, '5'), '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)));
+ return $form;
+
+ case 'save':
+ variable_set('forum_block_num_'. $delta, $edit['forum_block_num_'. $delta]);
+ break;
+
+ case 'view':
+ if (user_access('access content')) {
+ switch ($delta) {
+ case 0:
+ $title = t('Active forum topics');
+ $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.status = 1 AND n.type = 'forum' ORDER BY l.last_comment_timestamp DESC");
+ $result = db_query_range($sql, 0, variable_get('forum_block_num_0', '5'));
+ if (db_num_rows($result)) {
+ $content = node_title_list($result);
+ }
+ break;
+
+ case 1:
+ $title = t('New forum topics');
+ $sql = db_rewrite_sql("SELECT n.nid, n.title, l.comment_count FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid WHERE n.type = 'forum' AND n.status = 1 ORDER BY n.nid DESC");
+ $result = db_query_range($sql, 0, variable_get('forum_block_num_1', '5'));
+ if (db_num_rows($result)) {
+ $content = node_title_list($result);
+ }
+ break;
+ }
+
+ if ($content) {
+ $content .= ''. l(t('more'), 'forum', array('title' => t('Read the latest forum topics.'))) .'
';
+ }
+
+ $block['subject'] = $title;
+ $block['content'] = $content;
+
+ return $block;
+ }
+ }
+}
+
+/**
+ * Implementation of hook_view().
+ */
+function forum_view(&$node, $teaser = FALSE, $page = FALSE) {
+ if ($page) {
+ $vocabulary = taxonomy_get_vocabulary(variable_get('forum_nav_vocabulary', ''));
+ // Breadcrumb navigation
+ $breadcrumb = array();
+ $breadcrumb[] = array('path' => 'forum', 'title' => $vocabulary->name);
+ if ($parents = taxonomy_get_parents_all($node->tid)) {
+ $parents = array_reverse($parents);
+ foreach ($parents as $p) {
+ $breadcrumb[] = array('path' => 'forum/'. $p->tid, 'title' => $p->name);
+ }
+ }
+ $breadcrumb[] = array('path' => 'node/'. $node->nid);
+ menu_set_location($breadcrumb);
+ }
+
+ $node = node_prepare($node, $teaser);
+
+ $node->body .= theme('forum_topic_navigation', $node);
+}
+
+/**
+ * Implementation of hook_submit().
+ *
+ * Check in particular that only a "leaf" term in the associated taxonomy
+ * vocabulary is selected, not a "container" term.
+ */
+function forum_submit(&$node) {
+ // Make sure all fields are set properly:
+ $node->icon = $node->icon ? $node->icon : '';
+
+ if ($node->taxonomy) {
+ // Extract the node's proper topic ID.
+ $vocabulary = variable_get('forum_nav_vocabulary', '');
+ foreach ($node->taxonomy as $term) {
+ if (db_result(db_query('SELECT COUNT(*) FROM {term_data} WHERE tid = %d AND vid = %d', $term, $vocabulary))) {
+ $node->tid = $term;
+ }
+ }
+ if ($node->tid && $node->shadow) {
+ // A shadow copy needs to be created. Retain existing term and add new term.
+ $terms = array_keys(taxonomy_node_get_terms($node->nid));
+ if (!in_array($node->tid, $terms)) {
+ $terms[] = $node->tid;
+ }
+ $node->taxonomy = $terms;
+ }
+ }
+}
+
+/**
+ * Implementation of hook_validate().
+ *
+ * Check in particular that only a "leaf" term in the associated taxonomy
+ * vocabulary is selected, not a "container" term.
+ */
+function forum_validate($node) {
+ if ($node->taxonomy) {
+ // Extract the node's proper topic ID.
+ $vocabulary = variable_get('forum_nav_vocabulary', '');
+ $containers = variable_get('forum_containers', array());
+ foreach ($node->taxonomy as $term) {
+ if (db_result(db_query('SELECT COUNT(*) FROM {term_data} WHERE tid = %d AND vid = %d', $term, $vocabulary))) {
+ if (in_array($term, $containers)) {
+ $term = taxonomy_get_term($term);
+ form_set_error('taxonomy', t('The item %forum is only a container for forums. Please select one of the forums below it.', array('%forum' => theme('placeholder', $term->name))));
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Implementation of hook_update().
+ */
+function forum_update($node) {
+ if ($node->revision) {
+ db_query("INSERT INTO {forum} (nid, vid, tid) VALUES (%d, %d, %d)", $node->nid, $node->vid, $node->tid);
+ }
+ else {
+ db_query('UPDATE {forum} SET tid = %d WHERE vid = %d', $node->tid, $node->vid);
+ }
+}
+
+/**
+ * Implementation of hook_form().
+ */
+function forum_form(&$node) {
+ $form['title'] = array('#type' => 'textfield', '#title' => t('Subject'), '#default_value' => $node->title, '#required' => TRUE, '#weight' => -5);
+
+ if ($node->nid) {
+ $forum_terms = taxonomy_node_get_terms_by_vocabulary(_forum_get_vid(), $node->nid);
+ // if editing, give option to leave shadows
+ $shadow = (count($forum_terms) > 1);
+ $form['shadow'] = array('#type' => 'checkbox', '#title' => t('Leave shadow copy'), '#default_value' => $shadow, '#description' => t('If you move this topic, you can leave a link in the old forum to the new forum.'));
+ }
+
+ $form['body_filter']['body'] = array('#type' => 'textarea', '#title' => t('Body'), '#default_value' => $node->body, '#rows' => 20, '#required' => TRUE);
+ $form['body_filter']['format'] = filter_form($node->format);
+
+ return $form;
+}
+
+/**
+ * Implementation of hook_prepare; assign forum taxonomy when adding a topic from within a forum.
+ */
+function forum_prepare(&$node) {
+ if (!$node->nid) {
+ // new topic
+ $node->taxonomy[arg(3)]->vid = _forum_get_vid();
+ $node->taxonomy[arg(3)]->tid = arg(3);
+ }
+}
+
+/**
+ * Implementation of hook_insert().
+ */
+function forum_insert($node) {
+ db_query('INSERT INTO {forum} (nid, vid, tid) VALUES (%d, %d, %d)', $node->nid, $node->vid, $node->tid);
+}
+
+/**
+ * Implementation of hook_delete().
+ */
+function forum_delete(&$node) {
+ db_query('DELETE FROM {forum} WHERE nid = %d', $node->nid);
+}
+
+/**
+ * Returns a form for adding a container to the forum vocabulary
+ *
+ * @param $edit Associative array containing a container term to be added or edited.
+ */
+function forum_form_container($edit = array()) {
+ // Handle a delete operation.
+ if ($_POST['op'] == t('Delete') || $_POST['edit']['confirm']) {
+ return _forum_confirm_delete($edit['tid']);
+ }
+
+ $form['name'] = array(
+ '#title' => t('Container name'),
+ '#type' => 'textfield',
+ '#default_value' => $edit['name'],
+ '#maxlength' => 64,
+ '#description' => t('The container name is used to identify related forums.'),
+ '#required' => TRUE
+ );
+
+ $form['description'] = array(
+ '#type' => 'textarea',
+ '#title' => t('Description'),
+ '#default_value' => $edit['description'],
+ '#description' => t('The container description can give users more information about the forums it contains.')
+ );
+ $form['parent']['#tree'] = TRUE;
+ $form['parent'][0] = _forum_parent_select($edit['tid'], t('Parent'), 'container');
+ $form['weight'] = array('#type' => 'weight',
+ '#title' => t('Weight'),
+ '#default_value' => $edit['weight'],
+ '#description' => t('When listing containers, those with with light (small) weights get listed before containers with heavier (larger) weights. Containers with equal weights are sorted alphabetically.')
+ );
+
+ $form['vid'] = array('#type' => 'hidden',
+ '#value' => _forum_get_vid());
+ $form['submit'] = array(
+ '#type' => 'submit',
+ '#value' => t('Submit')
+ );
+ if ($edit['tid']) {
+ $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
+ $form['tid'] = array('#type' => 'value', '#value' => $edit['tid']);
+ }
+
+ return drupal_get_form('forum_form_container', $form, 'forum_form');
+}
+
+/**
+ * Returns a form for adding a forum to the forum vocabulary
+ *
+ * @param $edit Associative array containing a forum term to be added or edited.
+ */
+function forum_form_forum($edit = array()) {
+ // Handle a delete operation.
+ if ($_POST['op'] == t('Delete') || $_POST['edit']['confirm']) {
+ return _forum_confirm_delete($edit['tid']);
+ }
+
+ $form['name'] = array('#type' => 'textfield',
+ '#title' => t('Forum name'),
+ '#default_value' => $edit['name'],
+ '#maxlength' => 64,
+ '#description' => t('The forum name is used to identify related discussions.'),
+ '#required' => TRUE,
+ );
+ $form['description'] = array('#type' => 'textarea',
+ '#title' => t('Description'),
+ '#default_value' => $edit['description'],
+ '#description' => t('The forum description can give users more information about the discussion topics it contains.'),
+ );
+ $form['parent']['#tree'] = TRUE;
+ $form['parent'][0] = _forum_parent_select($edit['tid'], t('Parent'), 'forum');
+ $form['weight'] = array('#type' => 'weight',
+ '#title' => t('Weight'),
+ '#default_value' => $edit['weight'],
+ '#description' => t('When listing forums, those with lighter (smaller) weights get listed before containers with heavier (larger) weights. Forums with equal weights are sorted alphabetically.'),
+ );
+
+ $form['vid'] = array('#type' => 'hidden', '#value' => _forum_get_vid());
+ $form['submit' ] = array('#type' => 'submit', '#value' => t('Submit'));
+ if ($edit['tid']) {
+ $form['delete'] = array('#type' => 'submit', '#value' => t('Delete'));
+ $form['tid'] = array('#type' => 'hidden', '#value' => $edit['tid']);
+ }
+
+ return drupal_get_form('forum_form_forum', $form, 'forum_form');
+}
+
+/**
+ * Process forum form and container form submissions.
+ */
+function forum_form_submit($form_id, $form_values) {
+ if ($form_id == 'forum_form_container') {
+ $container = TRUE;
+ $type = t('forum container');
+ }
+ else {
+ $container = false;
+ $type = t('forum');
+ }
+
+ $status = taxonomy_save_term($form_values);
+ switch ($status) {
+ case SAVED_NEW:
+ if ($container) {
+ $containers = variable_get('forum_containers', array());
+ $containers[] = $form_values['tid'];
+ variable_set('forum_containers', $containers);
+ }
+ drupal_set_message(t('Created new %type %term.', array('%term' => theme('placeholder', $form_values['name']), '%type' => $type)));
+ break;
+ case SAVED_UPDATED:
+ drupal_set_message(t('The %type %term has been updated.', array('%term' => theme('placeholder', $form_values['name']), '%type' => $type)));
+ break;
+ }
+ return 'admin/forum';
+}
+
+/**
+ * Returns a confirmation page for deleting a forum taxonomy term.
+ *
+ * @param $tid ID of the term to be deleted
+ */
+function _forum_confirm_delete($tid) {
+ $term = taxonomy_get_term($tid);
+
+ $form['tid'] = array('#type' => 'value', '#value' => $tid);
+ $form['name'] = array('#type' => 'value', '#value' => $term->name);
+
+ return confirm_form('forum_confirm_delete', $form, t('Are you sure you want to delete the forum %name?', array('%name' => theme('placeholder', $term->name))), 'admin/forums', t('Deleting a forum or container will delete all sub-forums and associated posts as well. This action cannot be undone.'), t('Delete'), t('Cancel'));
+}
+
+/**
+ * Implementation of forms api _submit call. Deletes a forum after confirmation.
+ */
+function forum_confirm_delete_submit($form_id, $form_values) {
+ taxonomy_del_term($form_values['tid']);
+ drupal_set_message(t('The forum %term and all sub-forums and associated posts have been deleted.', array('%term' => theme('placeholder', $form_values['name']))));
+ watchdog('content', t('forum: deleted %term and all its sub-forums and associated posts.', array('%term' => theme('placeholder', $form_values['name']))));
+
+ return 'admin/forum';
+}
+
+/**
+ * Returns an overview list of existing forums and containers
+ */
+function forum_overview() {
+ $header = array(t('Name'), t('Operations'));
+
+ $tree = taxonomy_get_tree(_forum_get_vid());
+ if ($tree) {
+ foreach ($tree as $term) {
+ if (in_array($term->tid, variable_get('forum_containers', array()))) {
+ $rows[] = array(_taxonomy_depth($term->depth) .' '. check_plain($term->name), l(t('edit container'), "admin/forum/edit/container/$term->tid"));
+ }
+ else {
+ $rows[] = array(_taxonomy_depth($term->depth) .' '. check_plain($term->name), l(t('edit forum'), "admin/forum/edit/forum/$term->tid"));
+ }
+
+ }
+ }
+ else {
+ $rows[] = array(array('data' => '' . t('There are no existing containers or forums. You may add some on the add container or add forum pages.', array('%container' => url('admin/forum/add/container'), '%forum' => url('admin/forum/add/forum'))) . '', 'colspan' => 2));
+ }
+ return theme('table', $header, $rows);
+}
+
+/**
+ * Returns a select box for available parent terms
+ *
+ * @param $tid ID of the term which is being added or edited
+ * @param $title Title to display the select box with
+ * @param $child_type Whether the child is forum or container
+ */
+function _forum_parent_select($tid, $title, $child_type) {
+
+ $parents = taxonomy_get_parents($tid);
+ if ($parents) {
+ $parent = array_shift($parents);
+ $parent = $parent->tid;
+ }
+ else {
+ $parent = 0;
+ }
+
+ $children = taxonomy_get_tree(_forum_get_vid(), $tid);
+
+ // A term can't be the child of itself, nor of its children.
+ foreach ($children as $child) {
+ $exclude[] = $child->tid;
+ }
+ $exclude[] = $tid;
+
+ $tree = taxonomy_get_tree(_forum_get_vid());
+ $options[0] = '<'. t('root') .'>';
+ if ($tree) {
+ foreach ($tree as $term) {
+ if (!in_array($term->tid, $exclude)) {
+ $options[$term->tid] = _taxonomy_depth($term->depth) . $term->name;
+ }
+ }
+ }
+ if ($child_type == 'container') {
+ $description = t('Containers are usually placed at the top (root) level of your forum but you can also place a container inside a parent container or forum.');
+ }
+ else if ($child_type == 'forum') {
+ $description = t('You may place your forum inside a parent container or forum, or at the top (root) level of your forum.');
+ }
+
+ return array('#type' => 'select', '#title' => $title, '#default_value' => $parent, '#options' => $options, '#description' => $description, '#required' => TRUE);
+}
+
+function forum_term_path($term) {
+ return 'forum/'. $term->tid;
+}
+
+/**
+ * Returns the vocabulary id for forum navigation.
+ */
+function _forum_get_vid() {
+ $vid = variable_get('forum_nav_vocabulary', '');
+ if (empty($vid)) {
+ // Check to see if a forum vocabulary exists
+ $vid = db_result(db_query("SELECT vid FROM {vocabulary} WHERE module = '%s'", 'forum'));
+ if (!$vid) {
+ $edit = array('name' => 'Forums', 'multiple' => 0, 'required' => 1, 'hierarchy' => 1, 'relations' => 0, 'module' => 'forum', 'nodes' => array('forum' => 1));
+ taxonomy_save_vocabulary($edit);
+ $vid = $edit['vid'];
+ }
+ variable_set('forum_nav_vocabulary', $vid);
+ }
+
+ return $vid;
+}
+
+/**
+ * Formats a topic for display
+ *
+ * @TODO Give a better description. Not sure where this function is used yet.
+ */
+function _forum_format($topic) {
+ if ($topic && $topic->timestamp) {
+ return t('%time ago
by %author', array('%time' => format_interval(time() - $topic->timestamp), '%author' => theme('username', $topic)));
+ }
+ else {
+ return message_na();
+ }
+}
+
+/**
+ * Returns a list of all forums for a given taxonomy id
+ *
+ * Forum objects contain the following fields
+ * -num_topics Number of topics in the forum
+ * -num_posts Total number of posts in all topics
+ * -last_post Most recent post for the forum
+ *
+ * @param $tid
+ * Taxonomy ID of the vocabulary that holds the forum list.
+ * @return
+ * Array of object containing the forum information.
+ */
+function forum_get_forums($tid = 0) {
+
+ $forums = array();
+ $_forums = taxonomy_get_tree(variable_get('forum_nav_vocabulary', ''), $tid);
+
+ if (count($_forums)) {
+
+ $counts = array();
+
+ $sql = "SELECT r.tid, COUNT(n.nid) AS topic_count, SUM(l.comment_count) AS comment_count FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid INNER JOIN {term_node} r ON n.nid = r.nid WHERE n.status = 1 AND n.type = 'forum' GROUP BY r.tid";
+ $sql = db_rewrite_sql($sql);
+ $_counts = db_query($sql, $forum->tid);
+ while ($count = db_fetch_object($_counts)) {
+ $counts[$count->tid] = $count;
+ }
+ }
+
+ foreach ($_forums as $forum) {
+ if (in_array($forum->tid, variable_get('forum_containers', array()))) {
+ $forum->container = 1;
+ }
+
+ if ($counts[$forum->tid]) {
+ $forum->num_topics = $counts[$forum->tid]->topic_count;
+ $forum->num_posts = $counts[$forum->tid]->topic_count + $counts[$forum->tid]->comment_count;
+ }
+ else {
+ $forum->num_topics = 0;
+ $forum->num_posts = 0;
+ }
+
+ // This query does not use full ANSI syntax since MySQL 3.x does not support
+ // table1 INNER JOIN table2 INNER JOIN table3 ON table2_criteria ON table3_criteria
+ // used to join node_comment_statistics to users.
+ $sql = "SELECT ncs.last_comment_timestamp, IF (ncs.last_comment_uid != 0, u2.name, ncs.last_comment_name) AS last_comment_name, ncs.last_comment_uid FROM {node} n INNER JOIN {users} u1 ON n.uid = u1.uid INNER JOIN {term_node} tn ON n.nid = tn.nid INNER JOIN {node_comment_statistics} ncs ON n.nid = ncs.nid INNER JOIN {users} u2 ON ncs.last_comment_uid=u2.uid WHERE n.status = 1 AND tn.tid = %d ORDER BY ncs.last_comment_timestamp DESC";
+ $sql = db_rewrite_sql($sql);
+ $topic = db_fetch_object(db_query_range($sql, $forum->tid, 0, 1));
+
+ $last_post = new StdClass();
+ $last_post->timestamp = $topic->last_comment_timestamp;
+ $last_post->name = $topic->last_comment_name;
+ $last_post->uid = $topic->last_comment_uid;
+ $forum->last_post = $last_post;
+
+ $forums[$forum->tid] = $forum;
+ }
+
+ return $forums;
+}
+
+/**
+ * Calculate the number of nodes the user has not yet read and are newer
+ * than NODE_NEW_LIMIT.
+ */
+function _forum_topics_unread($term, $uid) {
+ $sql = "SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} tn ON n.nid = tn.nid AND tn.tid = %d LEFT JOIN {history} h ON n.nid = h.nid AND h.uid = %d WHERE n.status = 1 AND n.type = 'forum' AND n.created > %d AND h.nid IS NULL";
+ $sql = db_rewrite_sql($sql);
+ return db_result(db_query($sql, $term, $uid, NODE_NEW_LIMIT));
+}
+
+function forum_get_topics($tid, $sortby, $forum_per_page) {
+ global $user, $forum_topic_list_header;
+
+ $forum_topic_list_header = array(
+ array('data' => ' '),
+ array('data' => t('Topic'), 'field' => 'n.title'),
+ array('data' => t('Replies'), 'field' => 'l.comment_count'),
+ array('data' => t('Created'), 'field' => 'n.created'),
+ array('data' => t('Last reply'), 'field' => 'l.last_comment_timestamp'),
+ );
+
+ $order = _forum_get_topic_order($sortby);
+ for ($i = 0; $i < count($forum_topic_list_header); $i++) {
+ if ($forum_topic_list_header[$i]['field'] == $order['field']) {
+ $forum_topic_list_header[$i]['sort'] = $order['sort'];
+ }
+ }
+
+ $term = taxonomy_get_term($tid);
+
+ $sql = db_rewrite_sql("SELECT n.nid, f.tid, n.title, n.sticky, u.name, u.uid, n.created AS timestamp, n.comment AS comment_mode, l.last_comment_timestamp, IF(l.last_comment_uid != 0, cu.name, l.last_comment_name) AS last_comment_name, l.last_comment_uid, l.comment_count AS num_comments FROM {node_comment_statistics} l, {users} cu, {term_node} r, {users} u, {forum} f, {node} n WHERE n.status = 1 AND l.last_comment_uid = cu.uid AND n.nid = l.nid AND n.nid = r.nid AND r.tid = %d AND n.uid = u.uid AND n.vid = f.vid");
+ $sql .= tablesort_sql($forum_topic_list_header, 'n.sticky DESC,');
+ $sql .= ', n.created DESC'; // Always add a secondary sort order so that the news forum topics are on top.
+
+ $sql_count = db_rewrite_sql("SELECT COUNT(n.nid) FROM {node} n INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1 AND n.type = 'forum'");
+
+ $result = pager_query($sql, $forum_per_page, 0, $sql_count, $tid);
+
+ while ($topic = db_fetch_object($result)) {
+ if ($user->uid) {
+ // folder is new if topic is new or there are new comments since last visit
+ if ($topic->tid != $tid) {
+ $topic->new = 0;
+ }
+ else {
+ $history = _forum_user_last_visit($topic->nid);
+ $topic->new_replies = comment_num_new($topic->nid, $history);
+ $topic->new = $topic->new_replies || ($topic->timestamp > $history);
+ }
+ }
+ else {
+ // Do not track "new replies" status for topics if the user is anonymous.
+ $topic->new_replies = 0;
+ $topic->new = 0;
+ }
+
+ if ($topic->num_comments > 0) {
+ $last_reply = new StdClass();
+ $last_reply->timestamp = $topic->last_comment_timestamp;
+ $last_reply->name = $topic->last_comment_name;
+ $last_reply->uid = $topic->last_comment_uid;
+ $topic->last_reply = $last_reply;
+ }
+ $topics[] = $topic;
+ }
+
+ return $topics;
+}
+
+/**
+ * Finds the first unread node for a given forum.
+ */
+function _forum_new($tid) {
+ global $user;
+
+ $sql = "SELECT n.nid FROM {node} n LEFT JOIN {history} h ON n.nid = h.nid AND h.uid = %d INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1 AND n.type = 'forum' AND h.nid IS NULL AND n.created > %d ORDER BY created";
+ $sql = db_rewrite_sql($sql);
+ $nid = db_result(db_query_range($sql, $user->uid, $tid, NODE_NEW_LIMIT, 0, 1));
+
+ return $nid ? $nid : 0;
+}
+
+/**
+ * Menu callback; prints a forum listing.
+ */
+function forum_page($tid = 0) {
+ if (module_exist('taxonomy') && module_exist('comment')) {
+ $forum_per_page = variable_get('forum_per_page', 25);
+ $sortby = variable_get('forum_order', 1);
+
+ $forums = forum_get_forums($tid);
+ $parents = taxonomy_get_parents_all($tid);
+ if ($tid && !in_array($tid, variable_get('forum_containers', array()))) {
+ $topics = forum_get_topics($tid, $sortby, $forum_per_page);
+ }
+
+ return theme('forum_display', $forums, $topics, $parents, $tid, $sortby, $forum_per_page);
+ }
+ else {
+ drupal_set_message(t('The forum module requires both the taxonomy module and the comment module to be enabled and configured.'), 'error');
+ return ' ';
+ }
+}
+
+/**
+ * Format the forum body.
+ *
+ * @ingroup themeable
+ */
+function theme_forum_display($forums, $topics, $parents, $tid, $sortby, $forum_per_page) {
+ global $user;
+ // forum list, topics list, topic browser and 'add new topic' link
+
+ $vocabulary = taxonomy_get_vocabulary(variable_get('forum_nav_vocabulary', ''));
+ $title = $vocabulary->name;
+
+ // Breadcrumb navigation:
+ $breadcrumb = array();
+ if ($tid) {
+ $breadcrumb[] = array('path' => 'forum', 'title' => $title);
+ }
+
+ if ($parents) {
+ $parents = array_reverse($parents);
+ foreach ($parents as $p) {
+ if ($p->tid == $tid) {
+ $title = $p->name;
+ }
+ else {
+ $breadcrumb[] = array('path' => 'forum/'. $p->tid, 'title' => $p->name);
+ }
+ }
+ }
+
+ drupal_set_title($title);
+
+ $breadcrumb[] = array('path' => $_GET['q']);
+ menu_set_location($breadcrumb);
+
+ if (count($forums) || count($parents)) {
+ $output = '';
+ $output .= '
';
+
+ if (module_exist('tracker')) {
+ if ($user->uid) {
+ $output .= ' - '. l(t('My discussions.'), "tracker/$user->uid") .'
';
+ }
+
+ $output .= ' - '. l(t('Active discussions.'), 'tracker') .'
';
+ }
+
+ if (user_access('create forum topics')) {
+ $output .= '- '. l(t('Post new forum topic.'), "node/add/forum/$tid") .'
';
+ }
+ else if ($user->uid) {
+ $output .= '- '. t('You are not allowed to post a new forum topic.') .'
';
+ }
+ else {
+ $output .= '- '. t('Login to post a new forum topic.', array('%login' => url('user/login'))) .'
';
+ }
+ $output .= '
';
+
+ $output .= theme('forum_list', $forums, $parents, $tid);
+
+ if ($tid && !in_array($tid, variable_get('forum_containers', array()))) {
+ drupal_add_link(array('rel' => 'alternate',
+ 'type' => 'application/rss+xml',
+ 'title' => 'RSS - '. $title,
+ 'href' => url('taxonomy/term/'. $tid .'/0/feed')));
+
+ $output .= theme('forum_topic_list', $tid, $topics, $sortby, $forum_per_page);
+ $output .= theme('feed_icon', url("taxonomy/term/$tid/0/feed"));
+ }
+ $output .= '
';
+ }
+ else {
+ drupal_set_title(t('No forums defined'));
+ $output = '';
+ }
+
+ return $output;
+}
+
+/**
+ * Format the forum listing.
+ *
+ * @ingroup themeable
+ */
+function theme_forum_list($forums, $parents, $tid) {
+ global $user;
+
+ if ($forums) {
+
+ $header = array(t('Forum'), t('Topics'), t('Posts'), t('Last post'));
+
+ foreach ($forums as $forum) {
+ if ($forum->container) {
+ $description = '\n";
+ $description .= '
'. l($forum->name, "forum/$forum->tid") ."
\n";
+
+ if ($forum->description) {
+ $description .= '
'. filter_xss_admin($forum->description) ."
\n";
+ }
+ $description .= "
\n";
+
+ $rows[] = array(array('data' => $description, 'class' => 'container', 'colspan' => '4'));
+ }
+ else {
+ $new_topics = _forum_topics_unread($forum->tid, $user->uid);
+ $forum->old_topics = $forum->num_topics - $new_topics;
+ if (!$user->uid) {
+ $new_topics = 0;
+ }
+
+ $description = '\n";
+ $description .= '
'. l($forum->name, "forum/$forum->tid") ."
\n";
+
+ if ($forum->description) {
+ $description .= '
'. filter_xss_admin($forum->description) ."
\n";
+ }
+ $description .= "
\n";
+
+ $rows[] = array(
+ array('data' => $description, 'class' => 'forum'),
+ array('data' => $forum->num_topics . ($new_topics ? '
'. l(format_plural($new_topics, '1 new', '%count new'), "forum/$forum->tid", NULL, NULL, 'new') : ''), 'class' => 'topics'),
+ array('data' => $forum->num_posts, 'class' => 'posts'),
+ array('data' => _forum_format($forum->last_post), 'class' => 'last-reply'));
+ }
+ }
+
+ return theme('table', $header, $rows);
+
+ }
+
+}
+
+/**
+ * Format the topic listing.
+ *
+ * @ingroup themeable
+ */
+function theme_forum_topic_list($tid, $topics, $sortby, $forum_per_page) {
+ global $forum_topic_list_header;
+
+ if ($topics) {
+
+ foreach ($topics as $topic) {
+ // folder is new if topic is new or there are new comments since last visit
+ if ($topic->tid != $tid) {
+ $rows[] = array(
+ array('data' => theme('forum_icon', $topic->new, $topic->num_comments, $topic->comment_mode, $topic->sticky), 'class' => 'icon'),
+ array('data' => check_plain($topic->title), 'class' => 'title'),
+ array('data' => l(t('This topic has been moved'), "forum/$topic->tid"), 'colspan' => '3')
+ );
+ }
+ else {
+ $rows[] = array(
+ array('data' => theme('forum_icon', $topic->new, $topic->num_comments, $topic->comment_mode, $topic->sticky), 'class' => 'icon'),
+ array('data' => l($topic->title, "node/$topic->nid"), 'class' => 'topic'),
+ array('data' => $topic->num_comments . ($topic->new_replies ? '
'. l(format_plural($topic->new_replies, '1 new', '%count new'), "node/$topic->nid", NULL, NULL, 'new') : ''), 'class' => 'replies'),
+ array('data' => _forum_format($topic), 'class' => 'created'),
+ array('data' => _forum_format($topic->last_reply), 'class' => 'last-reply')
+ );
+ }
+ }
+ }
+
+ $output .= theme('table', $forum_topic_list_header, $rows);
+ $output .= theme('pager', NULL, $forum_per_page, 0);
+
+ return $output;
+}
+
+/**
+ * Format the icon for each individual topic.
+ *
+ * @ingroup themeable
+ */
+function theme_forum_icon($new_posts, $num_posts = 0, $comment_mode = 0, $sticky = 0) {
+
+ if ($num_posts > variable_get('forum_hot_topic', 15)) {
+ $icon = $new_posts ? 'hot-new' : 'hot';
+ }
+ else {
+ $icon = $new_posts ? 'new' : 'default';
+ }
+
+ if ($comment_mode == COMMENT_NODE_READ_ONLY || $comment_mode == COMMENT_NODE_DISABLED) {
+ $icon = 'closed';
+ }
+
+ if ($sticky == 1) {
+ $icon = 'sticky';
+ }
+
+ $output = theme('image', "misc/forum-$icon.png");
+
+ if ($new_posts) {
+ $output = "$output";
+ }
+
+ return $output;
+}
+
+/**
+ * Format the next/previous forum topic navigation links.
+ *
+ * @ingroup themeable
+ */
+function theme_forum_topic_navigation($node) {
+ $output = '';
+
+ // get previous and next topic
+ $sql = "SELECT n.nid, n.title, n.sticky, l.comment_count, l.last_comment_timestamp FROM {node} n INNER JOIN {node_comment_statistics} l ON n.nid = l.nid INNER JOIN {term_node} r ON n.nid = r.nid AND r.tid = %d WHERE n.status = 1 AND n.type = 'forum' ORDER BY n.sticky DESC, ". _forum_get_topic_order_sql(variable_get('forum_order', 1));
+ $result = db_query(db_rewrite_sql($sql), $node->tid);
+
+ while ($topic = db_fetch_object($result)) {
+ if ($stop == 1) {
+ $next = new StdClass();
+ $next->nid = $topic->nid;
+ $next->title = $topic->title;
+ break;
+ }
+ if ($topic->nid == $node->nid) {
+ $stop = 1;
+ }
+ else {
+ $prev = new StdClass();
+ $prev->nid = $topic->nid;
+ $prev->title = $topic->title;
+ }
+ }
+
+ if ($prev || $next) {
+ $output .= '';
+
+ if ($prev) {
+ $output .= l(t('â¹ ') . $prev->title, 'node/'. $prev->nid, array('class' => 'topic-previous', 'title' => t('Go to previous forum topic')));
+ }
+ if ($prev && $next) {
+ // Word break (a is an inline element)
+ $output .= ' ';
+ }
+ if ($next) {
+ $output .= l($next->title . t(' âº'), 'node/'. $next->nid, array('class' => 'topic-next', 'title' => t('Go to next forum topic')));
+ }
+
+ $output .= '
';
+ }
+
+ return $output;
+}
+
+function _forum_user_last_visit($nid) {
+ global $user;
+ static $history = array();
+
+ if (empty($history)) {
+ $result = db_query('SELECT nid, timestamp FROM {history} WHERE uid = %d', $user->uid);
+ while ($t = db_fetch_object($result)) {
+ $history[$t->nid] = $t->timestamp > NODE_NEW_LIMIT ? $t->timestamp : NODE_NEW_LIMIT;
+ }
+ }
+ return $history[$nid] ? $history[$nid] : NODE_NEW_LIMIT;
+}
+
+function _forum_get_topic_order($sortby) {
+ switch ($sortby) {
+ case 1:
+ return array('field' => 'l.last_comment_timestamp', 'sort' => 'desc');
+ break;
+ case 2:
+ return array('field' => 'l.last_comment_timestamp', 'sort' => 'asc');
+ break;
+ case 3:
+ return array('field' => 'l.comment_count', 'sort' => 'desc');
+ break;
+ case 4:
+ return array('field' => 'l.comment_count', 'sort' => 'asc');
+ break;
+ }
+}
+
+function _forum_get_topic_order_sql($sortby) {
+ $order = _forum_get_topic_order($sortby);
+ return $order['field'] .' '. $order['sort'];
+}
+
+
diff --git a/modules/help.module b/modules/help.module
new file mode 100644
index 0000000..5a8f789
--- /dev/null
+++ b/modules/help.module
@@ -0,0 +1,135 @@
+ 'admin/help', 'title' => t('help'),
+ 'callback' => 'help_main',
+ 'access' => $admin_access,
+ 'weight' => 9);
+
+ foreach (module_implements('help', TRUE) as $module) {
+ $items[] = array('path' => 'admin/help/' . $module,
+ 'title' => t($module),
+ 'callback' => 'help_page',
+ 'type' => MENU_CALLBACK,
+ 'access' => $admin_access);
+ }
+ }
+
+ return $items;
+}
+
+/**
+ * Menu callback; prints a page listing a glossary of Drupal terminology.
+ */
+function help_main() {
+ $output = t("
+ Help topics
+ Help is available on the following items:
+ %help_pages
+ Glossary of Drupal terminology
+
+ - Block
- A small box containing information or content placed in the left-hand or right-hand sidebar of a web page.
+ - Comment
- A note attached to a node. Usually intended to clarify, explain, criticize, or express an opinion on the original material.
+ - Moderation
+ - The activity of making sure a post to a Drupal site fits in with what is expected for that Drupal site.
+
+ - Approved
- A moderated post which has been accepted by the moderators for publication. (See published).
+ - Waiting
- A moderated post which is still being voted on to be accepted for publication. (See published.)
+
+
+ - Node
- The basic data unit in Drupal. Everything is a node or an extension of a node.
+ - Public
- See published.
+ - Published
- A node that is viewable by everyone. (See unpublished.)
+ - Role
- A classification users are placed into for the purpose of setting users' permissions.
+ - Taxonomy
- A division of a collection of things into ordered, classified groups. (See taxonomy help.)
+ - Unpublished
- A node that is only viewable by administrators and moderators.
+ - User
- A person who has an account at your Drupal site, and is logged in with that account.
+ - Visitor
- A person who does not have an account at your Drupal site or a person who has an account at your Drupal site but is not logged in with that account. Also termed \"anonymous user\".
+
", array('%help_pages' => help_links_as_list(), '%taxonomy' => url('admin/help/taxonomy')));
+
+ return $output;
+}
+
+function help_links_as_list() {
+ $modules = array();
+ foreach (module_implements('help', TRUE) as $module) {
+ if (module_invoke($module, 'help', "admin/help#$module")) {
+ $modules[] = $module;
+ }
+ }
+ sort($modules);
+
+ // Output pretty four-column list
+ $break = ceil(count($modules) / 4);
+ $output = '';
+ foreach ($modules as $i => $module) {
+ $output .= '- '. l(t($module), 'admin/help/'. $module) .'
';
+ if (($i + 1) % $break == 0) {
+ $output .= '
';
+ }
+ }
+ $output .= '
';
+
+ return $output;
+}
+
+/**
+ * Implementation of hook_help().
+ */
+function help_help($section) {
+ switch ($section) {
+ case 'admin/help':
+ $output = t('This guide explains what the various modules in Drupal do and how to configure them.
+It is not a substitute for the Drupal handbook available online and should be used in conjunction with it. The online reference handbook might be more up-to-date and has helpful user-contributed comments. It is your definitive reference point for all Drupal documentation.
+', array('%Drupal' => 'http://drupal.org', '%handbook' => 'http://drupal.org/handbook'));
+ return $output;
+ case 'admin/help#help':
+ $output = ''. t('The help module displays context sensitive help information. Users can learn how to use modules and accomplish tasks quicker with less errors by clicking on links in provided by the help module.') .'
';
+ $output .= t('Modules can make documentation available to other modules with this module. All user help should be presented using this module. Some examples of help:
+
+- The name of a module (unused, but there).
+- The description found on the admin/system/modules page.
+- The module\'s help text, displayed on the admin/help page and through the module\'s individual help link.
+- The help for a distributed authorization module (if applicable).
+- The description of a post type (if applicable).
+
+');
+ $output .= ''. t('You can not administer the help system.') .'
';
+ $output .= ''. t('For more information please read the configuration and customization handbook Help page.', array('%help' => 'http://drupal.org/handbook/modules/help/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Manages the display of online help.');
+ }
+}
+
+/**
+ * Menu callback; prints a page listing general help for all modules.
+ */
+function help_page() {
+ $name = arg(2);
+ $output = '';
+ if (module_hook($name, 'help')) {
+ $temp = module_invoke($name, 'help', "admin/help#$name");
+ if (empty($temp)) {
+ $output .= t("No help is available for module %module.", array('%module' => $name));
+ }
+ else {
+ $output .= $temp;
+ }
+ }
+ return $output;
+}
diff --git a/modules/legacy.module b/modules/legacy.module
new file mode 100644
index 0000000..91a51db
--- /dev/null
+++ b/modules/legacy.module
@@ -0,0 +1,202 @@
+'. t('The legacy module provides legacy handlers for upgrades from older installations. These handlers help automatically redirect references to pages from old installations and prevent page not found errors for your site.') .'';
+ $output .= ''. t('The legacy module handles legacy style taxonomy page, taxonomy feed, and blog feed paths. It also handles URL upgrades from Drupal 4.1. It rewrites old-style URLs to new-style URLs (clean URLs). ') .'
';
+ $output .= t('Example Mappings:
+
+- taxonomy/page/or/52,97 to taxonomy/term/52+97.
+- taxonomy/feed/or/52,97 to taxonomy/term/52+97/0/feed.
+- blog/feed/52 to blog/52/feed.
+- node/view/52 to node/52.
+- book/view/52 to node/52.
+- user/view/52 to user/52.
+
+');
+ $output .= ''. t('Legacy module has no configurable options.') .'
';
+ $output .= ''. t('For more information please read the configuration and customization handbook Legacy page.', array('%legacy' => 'http://drupal.org/handbook/modules/legacy/')) .'
';
+ return $output;
+ case 'admin/modules#description':
+ return t('Provides legacy handlers for upgrades from older Drupal installations.');
+ }
+}
+
+/**
+ * Implementation of hook_menu().
+ *
+ * Registers menu paths used in earlier Drupal versions.
+ */
+function legacy_menu($may_cache) {
+ $items = array();
+
+ if ($may_cache) {
+ // Map "taxonomy/page/or/52,97" to "taxonomy/term/52+97".
+ $items[] = array('path' => 'taxonomy/page', 'title' => t('taxonomy'),
+ 'callback' => 'legacy_taxonomy_page',
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+
+ // Map "taxonomy/feed/or/52,97" to "taxonomy/term/52+97/0/feed".
+ $items[] = array('path' => 'taxonomy/feed', 'title' => t('taxonomy'),
+ 'callback' => 'legacy_taxonomy_feed',
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+
+ // Map "blog/feed/52" to "blog/52/feed".
+ $items[] = array('path' => 'blog/feed', 'title' => t('blog'),
+ 'callback' => 'legacy_blog_feed',
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+ }
+ else {
+ // Map "node/view/52" to "node/52".
+ $items[] = array('path' => 'node/view', 'title' => t('view'),
+ 'callback' => 'drupal_goto',
+ 'callback arguments' => array('node/'. arg(2), NULL, NULL),
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+
+ // Map "book/view/52" to "node/52".
+ $items[] = array('path' => 'book/view', 'title' => t('view'),
+ 'callback' => 'drupal_goto',
+ 'callback arguments' => array('node/'. arg(2), NULL, NULL),
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+
+ // Map "user/view/52" to "user/52".
+ $items[] = array('path' => 'user/view', 'title' => t('view'),
+ 'callback' => 'drupal_goto',
+ 'callback arguments' => array('user/'. arg(2), NULL, NULL),
+ 'access' => TRUE, 'type' => MENU_CALLBACK);
+ }
+
+ return $items;
+}
+
+/**
+ * Menu callback; redirects users to new taxonomy page paths.
+ */
+function legacy_taxonomy_page($operation = 'or', $str_tids = '') {
+ if ($operation == 'or') {
+ $str_tids = str_replace(',', '+', $str_tids);
+ }
+ drupal_goto('taxonomy/term/'. $str_tids);
+}
+
+/**
+ * Menu callback; redirects users to new taxonomy feed paths.
+ */
+function legacy_taxonomy_feed($operation = 'or', $str_tids = '') {
+ if ($operation == 'or') {
+ $str_tids = str_replace(',', '+', $str_tids);
+ }
+ drupal_goto('taxonomy/term/'. $str_tids .'/0/feed');
+}
+
+/**
+ * Menu callback; redirects users to new blog feed paths.
+ */
+function legacy_blog_feed($str_uid = '') {
+ // if URL is of form blog/feed/52 redirect
+ // if URL is of form blog/feed we have to call blog_feed_last().
+ if (is_numeric($str_uid)) {
+ drupal_goto('blog/'. $str_uid .'/feed');
+ }
+ else {
+ module_invoke('blog', 'feed_last');
+ }
+}
+
+/**
+ * Implementation of hook_filter(). Handles URL upgrades from Drupal 4.1.
+ */
+function legacy_filter($op, $delta = 0, $format = -1, $text = '') {
+ switch ($op) {
+ case 'list':
+ return array(t('Legacy filter'));
+
+ case 'description':
+ return t('Replaces URLs from Drupal 4.1 (and lower) with updated equivalents.');
+
+ case 'process':
+ return _legacy_filter_old_urls($text);
+
+ case 'settings':
+ return;
+
+ default:
+ return $text;
+ }
+}
+
+/**
+ * Rewrite legacy URLs.
+ *
+ * This is a *temporary* filter to rewrite old-style URLs to new-style
+ * URLs (clean URLs). Currently, URLs are being rewritten dynamically
+ * (ie. "on output"), however when these rewrite rules have been tested
+ * enough, we will use them to permanently rewrite the links in node
+ * and comment bodies.
+ */
+function _legacy_filter_old_urls($text) {
+ if (!variable_get('rewrite_old_urls', 0)) {
+ return $text;
+ }
+
+ global $base_url;
+
+ $end = substr($base_url, 12);
+
+ if (variable_get('clean_url', '0') == '0') {
+ // Relative URLs:
+
+ // rewrite 'node.php?id=[&cid=]' style URLs:
+ $text = eregi_replace("\"(node)\.php\?id=([[:digit:]]+)(&cid=)?([[:digit:]]*)", "\"?q=\\1/view/\\2/\\4", $text);
+
+ // rewrite 'module.php?mod={&=}' style URLs:
+ $text = ereg_replace("\"module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))", "\"?q=\\2/\\4/\\6" , $text);
+ $text = ereg_replace("\"module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))", "\"?q=\\2/\\4", $text);
+ $text = ereg_replace("\"module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))", "\"?q=\\2", $text);
+
+ // Absolute URLs:
+
+ // rewrite 'node.php?id=[&cid=]' style URLs:
+ $text = eregi_replace("$end/(node)\.php\?id=([[:digit:]]+)(&cid=)?([[:digit:]]*)", "$end/?q=\\1/view/\\2/\\4", $text);
+
+ // rewrite 'module.php?mod={&=}' style URLs:
+ $text = ereg_replace("$end/module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))", "$end/?q=\\2/\\4/\\6" , $text);
+ $text = ereg_replace("$end/module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))(&?[[:alpha:]]+=([[:alnum:]]+))", "$end/?q=\\2/\\4", $text);
+ $text = ereg_replace("$end/module\.php\?(&?[[:alpha:]]+=([[:alnum:]]+))", "\"$end/?q=\\2", $text);
+ }
+ else {
+ // Relative URLs:
+
+ // Rewrite 'node.php?id=[&cid=]' style URLs:
+ $text = eregi_replace("\"(node)\.php\?id=([[:digit:]]+)(&cid=)?([[:digit:]]*)", "\"\\1/view/\\2/\\4", $text);
+
+ // Rewrite 'module.php?mod={&=