%myvars; ]> Advanced Topics by Joel Aufrecht This tutorial covers topics which are not essential to creating a minimal working package. Each section can be used independently of all of the others; all sections assume that you've completed the basic tutorial. Write the Requirements and Design Specs Before you get started you should make yourself familiar with the tags that are used to write your documentation. For tips on editing SGML files in emacs, see . It's time to document. For the tutorial we'll use pre-written documentation. When creating a package from scratch, start by copying the documentation template from /var/lib/aolserver/openacs-dev/packages/acs-core-docs/xml/docs/xml/package-documentation-template.xml to myfirstpackage/www/docs/xml/index.xml. You then edit that file with emacs to write the requirements and design sections, generate the html, and start coding. Store any supporting files, like page maps or schema diagrams, in the www/doc/xml directory, and store png or jpg versions of supporting files in the www/doc directory. For this tutorial, you should instead install the pre-written documentation files for the tutorial app. Log in as $OPENACS_SERVICE_NAME, create the standard directories, and copy the prepared documentation: [$OPENACS_SERVICE_NAME $OPENACS_SERVICE_NAME]$ cd /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/ [$OPENACS_SERVICE_NAME myfirstpackage]$ mkdir -p www/doc/xml [$OPENACS_SERVICE_NAME myfirstpackage]$ cd www/doc/xml [$OPENACS_SERVICE_NAME xml]$ cp /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/acs-core-docs/www/files/myfirstpackage/* . [$OPENACS_SERVICE_NAME xml]$ OpenACS uses DocBook for documentation. DocBook is an XML standard for semantic markup of documentation. That means that the tags you use indicate meaning, not intended appearance. The style sheet will determine appearance. You will edit the text in an XML file, and then process the file into html for reading. Open the file index.xml in emacs. Examine the file. Find the version history (look for the tag <revhistory>). Add a new record to the document version history. Look for the <authorgroup> tag and add yourself as a second author. Save and exit. Process the XML file to create HTML documentation. The HTML documentation, including supporting files such as pictures, is stored in the www/docs/ directory. A Makefile is provided to generate html from the xml, and copy all of the supporting files. If Docbook is set up correctly, all you need to do is: [$OPENACS_SERVICE_NAME xml]$ make cd .. ; /usr/bin/xsltproc ../../../acs-core-docs/www/xml/openacs.xsl xml/index.xml Writing requirements-introduction.html for chapter(requirements-introduction) Writing requirements-overview.html for chapter(requirements-overview) Writing requirements-cases.html for chapter(requirements-cases) Writing sample-data.html for chapter(sample-data) Writing requirements.html for chapter(requirements) Writing design-data-model.html for chapter(design-data-model) Writing design-ui.html for chapter(design-ui) Writing design-config.html for chapter(design-config) Writing design-future.html for chapter(design-future) Writing filename.html for chapter(filename) Writing user-guide.html for chapter(user-guide) Writing admin-guide.html for chapter(admin-guide) Writing bi01.html for bibliography Writing index.html for book [$OPENACS_SERVICE_NAME xml]$ Verify that the documentation was generated and reflects your changes by browsing to http://yoursite:8000/myfirstpackage/doc Add the new package to CVS Before you do any more work, make sure that your work is protected by putting it all into cvs. The cvs add command is not recursive, so you'll have to traverse the directory tree manually and add as you go. (More on CVS) [$OPENACS_SERVICE_NAME xml]$ cd .. [$OPENACS_SERVICE_NAME doc]$ cd .. [$OPENACS_SERVICE_NAME www]$ cd .. [$OPENACS_SERVICE_NAME myfirstpackage]$ cd .. [$OPENACS_SERVICE_NAME packages]$ cvs add myfirstpackage/ Directory /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage added to the repository [$OPENACS_SERVICE_NAME packages]$ cd myfirstpackage/ [$OPENACS_SERVICE_NAME myfirstpackage]$ cvs add www Directory /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www added to the repository [$OPENACS_SERVICE_NAME myfirstpackage]$ cd www [$OPENACS_SERVICE_NAME www]$ cvs add doc Directory /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/doc added to the repository [$OPENACS_SERVICE_NAME www]$ cd doc [$OPENACS_SERVICE_NAME doc]$ cvs add * cvs add: cannot add special file `CVS'; skipping cvs add: scheduling file `admin-guide.html' for addition cvs add: scheduling file `bi01.html' for addition cvs add: scheduling file `data-model.dia' for addition cvs add: scheduling file `data-model.png' for addition cvs add: scheduling file `design-config.html' for addition cvs add: scheduling file `design-data-model.html' for addition cvs add: scheduling file `design-future.html' for addition cvs add: scheduling file `design-ui.html' for addition cvs add: scheduling file `filename.html' for addition cvs add: scheduling file `index.html' for addition cvs add: scheduling file `page-map.dia' for addition cvs add: scheduling file `page-map.png' for addition cvs add: scheduling file `requirements-cases.html' for addition cvs add: scheduling file `requirements-introduction.html' for addition cvs add: scheduling file `requirements-overview.html' for addition cvs add: scheduling file `requirements.html' for addition cvs add: scheduling file `sample-data.html' for addition cvs add: scheduling file `sample.png' for addition cvs add: scheduling file `user-guide.html' for addition cvs add: scheduling file `user-interface.dia' for addition cvs add: scheduling file `user-interface.png' for addition Directory /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/doc/xml added to the repository cvs add: use 'cvs commit' to add these files permanently [$OPENACS_SERVICE_NAME doc]$ cd xml [$OPENACS_SERVICE_NAME xml]$ cvs add Makefile index.xml cvs add: scheduling file `Makefile' for addition cvs add: scheduling file `index.xml' for addition cvs add: use 'cvs commit' to add these files permanently [$OPENACS_SERVICE_NAME xml]$ cd ../../.. [$OPENACS_SERVICE_NAME myfirstpackage]$ cvs commit -m "new package" cvs commit: Examining . cvs commit: Examining www cvs commit: Examining www/doc cvs commit: Examining www/doc/xml RCS file: /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/doc/admin-guide.html,v done Checking in www/doc/admin-guide.html; /cvsroot/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/doc/admin-guide.html,v <-- admin-guide.html initial revision: 1.1 done (many lines omitted) [$OPENACS_SERVICE_NAME myfirstpackage]$
Upgrading a local CVS repository
OpenACS Edit This Page Templates by Nick Carroll Goals Learn about the OpenACS templating system. Learn about subsites and site-map administration. Introduction The OpenACS templating system allows you to give your site a consistent look and feel. It also promotes code maintainability in the presentation layer, by allowing presentation components to be reused across multiple pages. If you need to change the layout for some reason, then you only need to make that change in one location, instead of across many files. In this problem set you will familiarise yourself with the templating system in openacs. This will be achieved through customising an existing edit-this-page application template. Before proceeding, it is strongly advised to read the templating documentation on your OpenACS installation (http://localhost:8000/doc/acs-templating). The documentation lists the special tags available for ADP files. Exercise 1: Create a Subsite Create a subsite called pset3. A subsite is simply a directory or subdirectory mounted at the end of your domain name. This can be done in one of two places: http://localhost:8000/admin/site-map or the subsite admin form on the main site, which is available when you login to your OpenACS installation. Exercise 2: Checkout and Install edit-this-page (ETP) Checkout ETP from CVS: cd ~/openacs/packages cvs -d:pserver:anonymous@openacs.org:/cvsroot login cvs -d:pserver:anonymous@openacs.org:/cvsroot co edit-this-page Go to the package manager at http://yoursite/acs-admin/apm. And install the new package: edit-this-page. Or use the "Add Application" form available on the Main site. Change ETP Application Work out how to change the ETP application. Investigate each of the available ETP templates: Default News FAQ Exercise 4: Create a New ETP Template Browse the files for each of the above ETP templates at: cd ~/openacs/packages/edit-this-page/templates Use the article template as the basis of our new col2 template. cp article-content.adp col2-content.adp cp article-content.tcl col2-content.tcl cp article-index.adp col2-index.adp cp article-index.tcl col2-index.tcl The template should provide us with the following ETP layout: table showing ETP layout Header Sidebar Main Content Pane
The "Main Content" pane should contain the editable content that ETP provides. The "Header" should display the title of the page that you set in ETP. The "Sidebar" should display the extlinks that you add as a content item in ETP.
Exercise 5: Register the col2 Template with ETP Need to register your template with ETP so that it appears in the drop-down menu that you would have seen in Exercise 3. cd ~/openacs/packages/edit-this-page/tcl emacs etp-custom-init.tcl Use the function etp::define_application to register your template with ETP Uncomment the "asc" definition Set allow_extlinks to true, the rest should be false. Restart your server for the changes to take effect. Exercise 6: Configure ETP to use the col2 Template Configure your ETP instance at /lab4/index to use the col2 template. Create external links to link to other mounted ETP instances. Check that your external links show up in the sidebar when you view your ETP application using the col2 template. Who Wrote This and When This problem set was originally written by Nick Carroll in August 2004 for the University of Sydney Course EBUS5002. This material is copyright 2004 by Nick Carroll. It may be copied, reused, and modified, provided credit is given to the original author. ($Id: tutorial-advanced.xml,v 1.60.2.6 2019/11/29 14:28:48 antoniop Exp $)
Adding Comments You can track comments for any ACS Object. Here we'll track comments for notes. On the note-edit.tcl/adp pair, which is used to display individual notes, we want to put a link to add comments at the bottom of the screen. If there are any comments, we want to show them. First, we need to generate a URL for adding comments. In note-edit.tcl: set comment_add_url [export_vars -base [general_comments_package_url]comment-add { { object_id $note_id } { object_name $title } { return_url "[ad_conn url]?[ad_conn query]"} }] This calls a global, public Tcl function that the general_comments package registered, to get its url. You then embed in that url the id of the note and its title, and set the return_url to the current url so that the user can return after adding a comment. We need to create html that shows any existing comments. We do this with another general_comments function: set comments_html [general_comments_get_comments -print_content_p 1 $note_id] First, we pass in an optional parameter that says to actually show the contents of the comments, instead of just the fact that there are comments. Then you pass the note id, which is also the acs_object id. We put our two new variables in the note-edit.adp page. <a href="@comment_add_url@">Add a comment</a> @comments_html@ Admin Pages There are at least two flavors of admin user interface: Admins use same pages as all other users, except that they are offered admin links and buttons where appropriate. For example, if admins have privilege to bulk-delete items you could provide checkboxes next to every item seen on a list and the Delete Selected button on the bottom of the list. Dedicated admin pages. If you want admins to have access to data that users aren't interested in or aren't allowed to see you will need dedicated admin pages. The conventional place to put those dedicated admin pages is in the /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/admin directory. [$OPENACS_SERVICE_NAME www]$ mkdir admin [$OPENACS_SERVICE_NAME www]$ cd admin Even if your application doesn't need any admin pages of its own you will usually need at least one simple page with a bunch of links to existing administration UI such as Category Management or standard Parameters UI. Adding the link to Category Management is described in the section on categories. The listing below adds a link to the Parameters UI of our package. [$OPENACS_SERVICE_NAME admin]$ vi index.adp <master> <property name="title">@title;noquote@</property> <property name="context">@context;noquote@</property> <ul class="action-links"> <li><a href="@parameters_url@" title="Set parameters" class="action_link">Set parameters</a></li> </ul> [$OPENACS_SERVICE_NAME admin]$ vi index.tcl ad_page_contract {} { } -properties { context_bar } set package_id [ad_conn package_id] permission::require_permission \ -object_id $package_id \ -privilege admin] set context [list] set title "Administration" set parameters_url [export_vars -base "/shared/parameters" { package_id { return_url [ad_return_url] } }] Now that you have the first admin page it would be nice to have a link to it somewhere in the system so that admins don't have to type in the /admin every time they need to reach it. You could put a static link to the toplevel index.adp but that might be distracting for people who are not admins. Besides, some people consider it impolite to first offer a link and then display a nasty "You don't have permission to access this page" message. In order to display the link to the admin page only to users that have admin privileges add the following code near the top of /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/admin/index.tcl: set package_id [ad_conn package_id] set admin_p [permission::permission_p -object_id $package_id \ -privilege admin -party_id [ad_conn untrusted_user_id]] if { $admin_p } { set admin_url "admin" set admin_title Administration } In /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/admin/index.adp put: <if @admin_p@ ne nil> <a href="@admin_url@">@admin_title@</a> </if> Categories extended by Nima Mazloumi You can associate any ACS Object with one or more categories. In this tutorial we'll show how to equip your application with user interface to take advantage of the Categories service. We'll start by installing the Categories service. Go to /acs/admin and install it. This step won't be necessary for the users of your applications because you'll create a dependency with the Package Manager which will take care that the Categories service always gets installed when your application gets installed. Now that we have installed the Categories service we can proceed to modifying our application so that it can take advantage of it. We'll do it in three steps: The Categories service provides a mechanism to associate one or more category trees that are relevant to your application. One example of such tree is a tree of geographical locations. Continents are on the top of such tree, each continent containing countries etc. Another tree might contain market segments etc. Before users of your application can take advantage of the Categories service there needs to be a way for administrators of your application to choose which category trees are applicable for the application. The way to achieve this is to provide a link to the Category Management pages. Add the following snippet to your /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/admin/index.tcl file: set category_map_url [export_vars -base "[site_node::get_package_url -package_key categories]cadmin/one-object" { { object_id $package_id } }] and the following snippet to your /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www/admin/index.adp file: <a href="@category_map_url@">#­categories.Site_wide_Categories#</a> The link created by the above code (category_map_url) will take the admin to the generic admin UI where he can pick category trees that make sense for this application. The same UI also includes facilities to build and edit category trees. Notice that the only parameter in this example is package_id so that category trees will be associated with the object identified by this package_id. The categorization service is actually more general than that: instead of package_id you could use an ID of some other object that serves as a "container" in your application. For example, if your discussion forums application supports multiple forums you would use forum_id to associate category trees with just that one forum rather than the entire application instance. Once the category trees have been selected users need a way to categorize items. The easiest way to do this is by adding the category widget type of the form builder to note-edit.tcl. To achieve this we'll need to use the -extend switch to the ad_form command. Here's the "meat" of the note-edit.tcl page: # extend the form to support categories set package_id [ad_conn package_id] category::ad_form::add_widgets -form_name note -container_object_id $package_id -categorized_object_id [expr {[info exists item_id] ? $item_id : ""}] ad_form -extend -name note -on_submit { set category_ids [category::ad_form::get_categories -container_object_id $package_id] } -new_data { .... category::map_object -remove_old -object_id $item_id $category_ids db_dml insert_asc_named_object "insert into acs_named_objects (object_id, object_name, package_id) values ( :item_id, :title, :package_id)" } -edit_data { .... db_dml update_asc_named_object "update acs_named_objects set object_name = :title, package_id = :package_id where object_id = :item_id" category::map_object -remove_old -object_id $item_id $category_ids } -after_submit { ad_returnredirect "." ad_script_abort } While the category::ad_form::add_widgets proc is taking care to extend your form with associated categories you need to ensure that your items are mapped to the corresponding category object yourself. Also since the categories package knows nothing from your objects you have to keep the acs_named_objects table updated with any changes taking place. We use the items title so that they are listed in the categories browser by title.Make sure that you also delete these entries if your item is delete. Add this to your corresponding delete page: db_dml delete_named_object "delete from acs_named_objects where object_id = :item_id" note-edit.tcl requires a note_id to determine which record should be deleted. It also looks for a confirmation variable, which should initially be absert. If it is absent, we create a form to allow the user to confirm the deletion. Note that in entry-edit.tcl we used ad_form to access the Form Template commands; here, we call them directly because we don't need the extra features of ad_form. The form calls itself, but with hidden variables carrying both note_id and confirm_p. If confirm_p is present, we delete the record, set redirection back to the index, and abort script execution. The database commands: [$OPENACS_SERVICE_NAME@yourserver www]$ emacs note-delete.xql <?xml version="1.0"?> <queryset> <fullquery name="do_delete"> <querytext> select samplenote__delete(:note_id) </querytext> </fullquery> <fullquery name="get_name"> <querytext> select samplenote__name(:note_id) </querytext> </fullquery> </queryset> And the adp page: [$OPENACS_SERVICE_NAME@yourserver www]$ emacs note-delete.adp <master> <property name="title">@title@</property> <property name="context">{@title@}</property> <h2>@title@</h2> <formtemplate id="note-del-confirm"></formtemplate> </form> The ADP is very simple. The formtemplate tag outputs the HTML form generated by the ad_form command with the matching name. Test it by adding the new files in the APM and then deleting a few samplenotes. We will now make categories optional on package instance level and also add a configuration page to allow the package admin to enable/disable categories for his package. Go to the APM and create a number parameter with the name "EnableCategoriesP" and the default value "0". Add the following lines to your index.tcl: set return_url [ns_conn url] set use_categories_p [parameter::get -parameter "EnableCategoriesP"] Change your to this: <a href=configure?<%=[export_vars -url {return_url}]%>>Configure</a> <if @use_categories_p@> <a href="@category_map_url@">#­categories.Site_wide_Categories#</a> </if> Now create a configure page ad_page_contract { This page allows an admin to change the categories usage mode. } { {return_url ""} } set title "Configure category mode" set context [list $title] set use_categories_p [parameter::get -parameter "EnableCategoriesP"] ad_form -name categories_mode -form { {enabled_p:text(radio) {label "Enable Categories"} {options {{Yes 1} {No 0}}} {value $use_categories_p} } {return_url:text(hidden) {value $return_url}} {submit:text(submit) {label "Set Mode"}} } -on_submit { parameter::set_value -parameter "EnableCategoriesP" -value $enabled_p if {$return_url ne ""} { ns_returnredirect $return_url } } and add this to its corresponding ADP page <master> <property name="title">@title@</property> <property name="context">@context@</property> <formtemplate id="categories_mode"></formtemplate> Reference this page from your admin page #TCL: set return_url [ad_conn url] #ADP: <a href=configure?<%=[export_vars -url {return_url}]%>>Configure</a> Change the note-edit.tcl: # Use Categories? set use_categories_p [parameter::get -parameter "EnableCategoriesP" -default 0] if { $use_categories_p == 1 } { # YOUR NEW FORM DEFINITION } else { # YOUR OLD FORM DEFINITION } You can filter your notes using categories. The below example does not support multiple filters and displays a category in a flat format.The first step is to define the optional parameter category_id for index.tcl: ad_page_contract { YOUR TEXT } { YOURPARAMS {category_id:integer,optional {}} } Now you have to check whether categories are enabled or not. If this is the case and a category id is passed you need to extend your sql select query to support filtering. One way would be to extend the mfp::note::get proc to support two more swiches -where_clause and -from_clause. set use_categories_p [parameter::get -parameter "EnableCategoriesP" -default 0] if { $use_categories_p == 1 && $category_id ne "" } { set from_clause "category_object_map com, acs_named_objects ano" set_where_clause "com.object_id = qa.entry_id and ano.package_id = :package_id and com.object_id = ano.object_id and com.category_id = :category_id" ... mfp::note::get \ -item_id $item_id \ -array note_array \ -where_clause $where_clause \ -from_clause $from_clause ... } else { # OLD STUFF } Also you need to make sure that the user can see the corresponding categories. Add the following snippet to the end of your index page: # Site-Wide Categories if { $use_categories_p == 1} { set package_url [ad_conn package_url] if { $category_id ne "" } { set category_name [category::get_name $category_id] if { $category_name eq "" } { ad_return_exception_page 404 "No such category" "Site-wide \ Category with ID $category_id doesn't exist" return } # Show Category in context bar append context_base_url /cat/$category_id lappend context [list $context_base_url $category_name] set type "all" } # Cut the URL off the last item in the context bar if { [llength $context] > 0 } { set context [lreplace $context end end [lindex $context end end]] } db_multirow -unclobber -extend { category_name tree_name } categories categories { select c.category_id as category_id, c.tree_id from categories c, category_tree_map ctm where ctm.tree_id = c.tree_id and ctm.object_id = :package_id } { set category_name [category::get_name $category_id] set tree_name [category_tree::get_name $tree_id] } } and to the corresponding index ADP page: <if @use_categories_p@> <multiple name="categories"> <h2>@categories.tree_name@ <group column="tree_id"> <a href="@package_url@cat/@categories.category_id@?@YOURPARAMS@&category_id=@categories.category_id@">@categories.category_name@ </group> </multiple> <a href="@package_url@view?@YOURPARAMS@">All Items</if> Finally you need a an index.vuh in your www folder to rewrite the URLs correctly, : set url /[ad_conn extra_url] if {[regexp {^/+cat/+([^/]+)/*} $url ignore_whole category_id]} { rp_form_put category_id $category_id } rp_internal_redirect "/packages/YOURPACKAGE/www/index" Now when ever the user select a category only notes that belong to this category are displayed. Profile your code by Jade Rubick There are several facilities for profiling your code in OpenACS. The first thing to do is to install the developer-support package and play around with it. But there is also support in the API for profiling your code: profiling your code using ds_profile Prepare the package for distribution. Browse to the package manager. Click on tutorialapp. Click on Generate a distribution file for this package from the filesystem. Click on the file size (37.1KB) after the label Distribution File: and save the file to /var/tmp. The publish point for new packages should be fixed. Package development guidelines Distributing upgrades of your package by Jade Rubick The OpenACS Package Repository builds a list of packages that can be installed on OpenACS installations, and can be used by administrators to update their packages. If you are a package developer, there are a couple of steps you need to take in order to release a new version of your package. For the sake of this example, let's assume you are the package owner of the notes package. It is currently at version 1.5, and you are planning on releasing version 1.6. It is also located in OpenACS's CVS. To release your package: cd /path/to/notes cvs commit -m "Update package to version 1.6." cvs tag notes-1-6-final cvs tag -F openacs-5-1-compat Of course, make sure you write upgrade scripts () Notifications by David Bell and Simon Carstensen The notifications package allows you to send notifications through any defined communications medium (e.g. email, sms) upon some event occurring within the system. This tutorial steps through the process of integrating the notifications package with your package. First step is to create the notification types. To do this a script similar to the one below needs to be loaded into Postgresql. I create this script in a package-name/sql/postgresql/package-name-notifications-init.sql file. I then load this file from my create SQL file. The following code snippet is taken from Weblogger. It creates a lars_blogger_notif notification type (which was created above). create function inline_0() returns integer as $$ declare impl_id integer; v_foo integer; begin -- the notification type impl impl_id := acs_sc_impl__new ( 'NotificationType', 'lars_blogger_notif_type', 'lars-blogger' ); v_foo := acs_sc_impl_alias__new ( 'NotificationType', 'lars_blogger_notif_type', 'GetURL', 'lars_blogger::notification::get_url', 'TCL' ); v_foo := acs_sc_impl_alias__new ( 'NotificationType', 'lars_blogger_notif_type', 'ProcessReply', 'lars_blogger::notification::process_reply', 'TCL' ); PERFORM acs_sc_binding__new ( 'NotificationType', 'lars_blogger_notif_type' ); v_foo:= notification_type__new ( NULL, impl_id, 'lars_blogger_notif', 'Blog Notification', 'Notifications for Blog', now(), NULL, NULL, NULL ); -- enable the various intervals and delivery methods insert into notification_types_intervals (type_id, interval_id) select v_foo, interval_id from notification_intervals where name in ('instant','hourly','daily'); insert into notification_types_del_methods (type_id, delivery_method_id) select v_foo, delivery_method_id from notification_delivery_methods where short_name in ('email'); return (0); end; $$ language plpgsql; select inline_0(); drop function inline_0(); You also need a drop script. This is untested for compatibility with the above script. -- @author gwong@orchardlabs.com,ben@openforce.biz -- @creation-date 2002-05-16 -- -- This code is newly concocted by Ben, but with significant concepts and code -- lifted from Gilbert's UBB forums. Thanks Orchard Labs. -- Lars and Jade in turn lifted this from gwong and ben. create function inline_0 () returns integer as $$ declare row record; begin for row in select nt.type_id from notification_types nt where nt.short_name in ('lars_blogger_notif_type','lars_blogger_notif') loop perform notification_type__delete(row.type_id); end loop; return null; end; $$ language plpgsql; select inline_0(); drop function inline_0 (); -- -- Service contract drop stuff was missing - Roberto Mello -- create function inline_0() returns integer as $$ declare impl_id integer; v_foo integer; begin -- the notification type impl impl_id := acs_sc_impl__get_id ( 'NotificationType', -- impl_contract_name 'lars_blogger_notif_type' -- impl_name ); PERFORM acs_sc_binding__delete ( 'NotificationType', 'lars_blogger_notif_type' ); v_foo := acs_sc_impl_alias__delete ( 'NotificationType', -- impl_contract_name 'lars_blogger_notif_type', -- impl_name 'GetURL' -- impl_operation_name ); v_foo := acs_sc_impl_alias__delete ( 'NotificationType', -- impl_contract_name 'lars_blogger_notif_type', -- impl_name 'ProcessReply' -- impl_operation_name ); select into v_foo type_id from notification_types where sc_impl_id = impl_id and short_name = 'lars_blogger_notif'; perform notification_type__delete (v_foo); delete from notification_types_intervals where type_id = v_foo and interval_id in ( select interval_id from notification_intervals where name in ('instant','hourly','daily') ); delete from notification_types_del_methods where type_id = v_foo and delivery_method_id in ( select delivery_method_id from notification_delivery_methods where short_name in ('email') ); return (0); end; $$ language plpgsql; select inline_0(); drop function inline_0(); The next step is to setup our notification creation. A new notification must be added to the notification table for each blog entry added. We do this using the notification::new procedure notification::new \ -type_id [notification::type::get_type_id \ -short_name lars_blogger_notif] \ -object_id $blog(package_id) \ -response_id $blog(entry_id) \ -notif_subject $blog(title) \ -notif_text $new_content This code is placed in the Tcl procedure that creates blog entries, right after the entry gets created in the code. The $blog(package_id) is the OpenACS object_id of the Weblogger instance to which the entry has been posted to and the $new_content is the content of the entry. This example uses the package_id for the object_id, which results in setting up notifications for all changes for blogger entries in this package. However, if you instead used the blog_entry_id or something like that, you could set up per-item notifications. The forums packages does this -- you can look at it for an example. The final step is to setup the notification subscription process. In this example we want to let a user find out when a new entry has been posted to the blog. To do this we put a link on the blog that allows them to subscribe to notifications of new entries. The notifications/requests-new page is very handy in this situation. Such a link can be created using the notification::display::request_widget proc: set notification_chunk [notification::display::request_widget \ -type lars_blogger_notif \ -object_id $package_id \ -pretty_name [lars_blog_name] \ -url [lars_blog_public_package_url] \ ] which will return something like You may <a href="/notifications/request-new?...">request notification</a> for Weblogger. which can be readily put on the blog index page. The pretty_name parameter is what appears at the end of the text returned (i.e. "... request notification</a> for pretty_name"), The url parameter should be set to the address we want the user to be redirected to after they have finished the subscription process. This should be all you need to implement a notification system. For more examples look at the forums package. Hierarchical data by Jade Rubick with help from many people in the OpenACS community One of the nice things about using the OpenACS object system is that it has a built-in facility for tracking hierarchical data in an efficient way. The algorithm behind this is called tree_sortkey. Any time your tables are subclasses of the acs_objects table, then you automatically get the ability to structure them hierarchically. The way you do this is currently via the context_id column of acs_objects (Note that there is talk of adding in a parent_id column instead, because the use of context_id has been ambiguous in the past). So when you want to build your hierarchy, simply set the context_id values. Then, when you want to make hierarchical queries, you can do them as follows: db_multirow categories blog_categories " SELECT c.*, o.context_id, tree_level(o.tree_sortkey) FROM blog_categories c, acs_objects o WHERE c.category_id = o.object_id ORDER BY o.tree_sortkey" Note the use of the tree_level() function, which gives you the level, starting from 1, 2, 3... Here's an example, pulling all of the children for a given parent: SELECT children.*, tree_level(children.tree_sortkey) - tree_level(parent.tree_sortkey) as level FROM some_table parent, some_table children WHERE children.tree_sortkey between parent.tree_sortkey and tree_right(parent.tree_sortkey) and parent.tree_sortkey <> children.tree_sortkey and parent.key = :the_parent_key; The reason we subtract the parent's tree_level from the child's tree_level is that the tree_levels are global, so if you want the parent's tree_level to start with 0, you'll want the subtraction in there. This is a reason you'll commonly see magic numbers in tree_sortkey SQL queries, like tree_level(children.tree_sortkey) - 4. That is basically an incorrect way to do it, and subtracting the parent's tree_level is the preferred method. This example does not include the parent. To return the entire subtree including the parent, leave out the non-equals clause: SELECT subtree.*, tree_level(subtree.tree_sortkey) - tree_level(parent.tree_sortkey) as level FROM some_table parent, some_table subtree WHERE subtree.tree_sortkey between parent.tree_sortkey and tree_right(parent.tree_sortkey) and parent.key = :the_parent_key; If you are using the Content Repository, you get a similar facility, but the parent_id column is already there. Note you can do joins with tree_sortkey: SELECT p.item_id, repeat(:indent_pattern, (tree_level(p.tree_sortkey) - 5)* :indent_factor) as indent, p.parent_id as folder_id, p.project_name FROM pm_projectsx p, cr_items i WHERE p.project_id = i.live_revision ORDER BY i.tree_sortkey This rather long thread explains How tree_sortkeys work and this paper describes the technique for tree_sortkeys, although the OpenACS implementation has a few differences in the implementation, to make it work for many languages and the LIKE construct in Postgres. Using .vuh files for pretty URLs .Vuh files are special cases of .tcl files, used for rewriting incoming URLs. We can use a vuh file to prettify the uri for our notes. Instead of note-edit?item_id=495, we can use note/495. To do this, we will need a new .vuh file for redirection and we will need to change the referring links in note-list. First, add the vuh: [$OPENACS_SERVICE_NAME $OPENACS_SERVICE_NAME]$ cd /var/lib/aolserver/$OPENACS_SERVICE_NAME/packages/myfirstpackage/www [$OPENACS_SERVICE_NAME www]$ emacs note.vuh Paste this into the file: example missing We parse the incoming request and treat everything after the final / as the item id. Note that this simple redirection will lose any additional query parameters passed in. Many OpenACS objects maintain a pretty-name, which is a unique, human-readable string, usually derived from title, which makes an even better 'pretty url' than a numeric id; this requires that your display page be able to look up an item based on pretty id. We use rp_form_put to store the item id in the internal register that the next page is expecting, and then redirects the request in process internally (ie, without a browser refresh). Next, modify note-list so that its link is of the new form.: [$OPENACS_SERVICE_NAME www]$ emacs ../lib/note-edit.tcl db_multirow \ -extend { edit_url delete_url } notes notes_select { select ci.item_id, n.title from cr_items ci, mfp_notesx n where n.revision_id = ci.live_revision } { set edit_url [export_vars -base "note/$item_id"] set delete_url [export_vars -base "note-delete" {item_id}] } You may also need to change some of the links in your package. Commonly, you would use ad_conn package_url to build the URL. Otherwise, some of your links may be relative to the virtual directory (note/) instead of the actual directory that the note is being served from. Laying out a page with CSS instead of tables .LRN home page with table-based layout A sample of the HTML code (full source) <table border="0" width="100%"> <tr> <td valign="top" width="50%"> <table class="element" border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td colspan="3" class="element-header-text"> <bold>Groups</bold> </td> </tr> <tr> <td colspan="3" class="dark-line" height="0"><img src="/resources/acs-subsite/spacer.gif"></td></tr> <tr> <td class="light-line" width="1"> <img src="/resources/acs-subsite/spacer.gif" width="1"> </td> <td class="element-text" width="100%"> <table cellspacing="0" cellpadding="0" class="element-content" width="100%"> <tr> <td> <table border="0" bgcolor="white" cellpadding="0" cellspacing="0" width="100%"> <tr> <td class=element-text> MBA 101 .LRN Home with CSS-based layout A sample of the HTML code (full source) <div class="left"> <div class="portlet-wrap-shadow"> <div class="portlet-wrap-bl"> <div class="portlet-wrap-tr"> <div class="portlet"> <h2>Groups</h2> <ul> <li> <a href="#">Class MBA 101</a> If the CSS is removed from the file, it looks somewhat different: Sending HTML email from your application by Jade Rubick Sending email is fairly simple using the acs-mail-lite package. Sending HTML email is only slightly more complicated. set subject "my subject" set message "<b>Bold</b> not bold" set from_addr "me@myemail.com" set to_addr "me@myemail.com" # the from to html closes any open tags. set message_html [ad_html_text_convert -from html -to html $message] # some mailers chop off the last few characters. append message_html " " set message_text [ad_html_text_convert -from html -to text $message] set message_data [ad_build_mime_message $message_text $message_html] set extra_headers [ns_set new] ns_set put $extra_headers MIME-Version [ns_set get $message_data MIME-Version] ns_set put $extra_headers Content-ID [ns_set get $message_data Content-ID] ns_set put $extra_headers Content-Type [ns_set get $message_data Content-Type] set message [ns_set get $message_data body] acs_mail_lite::send \ -to_addr $to_addr \ -from_addr $from_addr \ -subject $subject \ -body $message \ -extraheaders $extra_headers Basic Caching Based on a post by Dave Bauer. Caching using the database API is described in the database API tutorial. Caching using util_memoize Implement your proc as my_proc_not_cached Create a version of your proc called my_proc which wraps the non-cached version in the caching mechanism. In this example, my_proc_not_cached takes one argument, -foo, so the wrapper passes that on. The wrapper also uses the list command, to ensure that the arguments get passed correctly and to prevent commands passed in as arguments from being executed. ad_proc my_proc {-foo} { Get a cached version of my_proc. } { return [util_memoize [list my_proc_not_cached -foo $foo]] } In your code, always call my_proc. There will be a separate cache item for each unique call to my_proc_not_cached so that calls with different arguments are cached separately. You can flush the cache for each cache key by calling util_memoize_flush my_proc_not_cached args. The cached material will of course become obsolete over time. There are two ways to handle this. Timed Expiration: pass in max_age to util_memoize. If the content is older than max_age, it will be re-generated. Direct Flushing. In any proc which invalidates the cached content, call util_memoize_flush my_proc_not_cached args. If you are correctly flushing the cached value, then it will need to be reloaded. You may wish to pre-load it, so that the loading delay does not impact users. If you have a sequence of pages, you could call the cached proc in advance, to increase the chances that it's loaded and current when the user reaches it. Or, you can call (and discard) it immediately after flushing it. Scheduled Procedures Put this proc in a file /packages/myfirstpackage/tcl/scheduled-init.tcl. Files in /tcl with the -init.tcl ending are sourced on server startup. This one executes my_proc every 60 seconds: ad_schedule_proc 60 myfirstpackage::my_proc This executes once a day, at midnight: ad_schedule_proc \ -schedule_proc ns_schedule_daily \ [list 0 0] \ myfirstpackage::my_proc See ad_schedule_proc for more information. Enabling WYSIWYG by Nima Mazloumi Most of the forms in OpenACS are created using the form builder, see . For detailed information on the API take a look here. The following section shows how you can modify your form to allow WYSIWYG functionalities. Convert your page to use ad_form (some changes but worth it) Here an examples. From: template::form create my_form template::element create my_form my_form_id -label "The ID" -datatype integer -widget hidden template::element create my_form my_input_field_1 -html { size 30 } -label "Label 1" -datatype text -optional template::element create my_form my_input_field_2 -label "Label 2" -datatype text -help_text "Some Help" -after_html {<a name="#">Anchor</a>} To: ad_form -name my_form -form { my_form_id:key(acs_object_id_seq) {my_input_field_1:text,optional {label "Label 1"} {html {size 30}}} {my_input_field_2:text {label "Label 2"} {help_text "Some Help"} {after_html {<a name="#">Anchor</a>}}} } ... You must not give your form the same name that your page has. Otherwise HTMLArea won't load. Convert your textarea widget to a richtext widget and enable htmlarea. The htmlarea_p-flag can be used to prevent WYSIWYG functionality. Defaults to true if left away. From: {my_input_field_2:text To: {my_input_field_2:richtext(richtext) {htmlarea_p "t"} The richtext widget presents a list with two elements: text and content type. To learn more on existing content types search in Google for "MIME-TYPES" or take a look at the cr_mime_types table. Make sure that both values are passed as a list to your ad_form or you will have problems displaying the content or handling the data manipulation correctly. Depending on the data model of your package you either support a content format or don't. If you don't you can assume "text/html" or "text/richtext" or "text/enhanced". The relevant parts in your ad_form definition are the switches -new_data, -edit_data, -on_request and -on_submit. To allow your data to display correctly you need to add an -on_request block. If you have the format stored in the database pass this as well else use "text/html": set my_input_field_2 [template::util::richtext::create $my_input_field_2 "text/html"] Now make sure that your SQL queries that do the data manipulation retrieve the correct value. If you simply use my_input_field_2 you will store a list. Thus you need to add an -on_submit block: set my_input_field_2 [ template::util::richtext::get_property contents $my_input_field_2] set format [ template::util::richtext::get_property format $my_input_field_2] #This is optional Now the correct values for my_input_field_2 and format are passed to the -new_data and -edit_data blocks which don't need to get touched. To make HTMLArea optional per package instance define a string parameter UseWysiwygP which defaults 0 for your package using the APM. In your edit page make the following changes # Is WYSIWYG enabled? set use_wysiwyg_p [parameter::get -parameter "UseWysiwygP" -default "f"] ... {htmlarea_p $use_wysiwyg_p} The -on_request switch should set this value for your form. set htmlarea_p $use_wysiwyg_p All you need now is a configuration page where the user can change this setting. Create a configure.tcl file: ad_page_contract { This page allows a faq admin to change the UseWysiwygP setting } { {return_url ""} } set title "Should we support WYSIWYG?" set context [list $title] set use_wysiwyg_p ad_form -name categories_mode -form { {enabled_p:text(radio) {label "Enable WYSIWYG"} {options {{Yes t} {No f}}} {value $use_wysiwyg_p} } {return_url:text(hidden) {value $return_url}} {submit:text(submit) {label "Change"}} } -on_submit { parameter::set_value -parameter "UseWysiwygP" -value $enabled_p if {$return_url ne ""} { ns_returnredirect $return_url } } In the corresponding ADP file write <master> <property name="title">@title@</property> <property name="context">@context@</property> <formtemplate id="categories_mode"></formtemplate> And finally reference this page from your admin page #TCL: set return_url [ad_conn url] #ADP: <a href=configure?<%=[export_vars -url {return_url}]%>>Configure</a> Adding in parameters for your package Each instance of a package can have parameters associated with it. These are like preferences, and they can be set by the administrator for each application to change the behavior of your application. To add parameters for your package, go to the Automatic Package Manager (/acs-admin/apm) Click on your package Under the Manage section, click on Parameters It's fairly self-explanatory at this point. Create the parameters you want, and then access them in your code using the parameter::get procedure. Writing upgrade scripts by Jade Rubick If your package changes its data model, you have to write an upgrade script. This is very easy in OpenACS. First, you want to make sure you change the original .sql file so that new installation will have the new data model. Next, check what version your package is currently at. For example, it may be at version 1.0b1. Create a file in yourpackage/sql/postgres/upgrade called packagename-1.0b1-1.0b2.sql and put the SQL code that will update the data model. For example, if you add in a column, you would have an alter table add column statement in this file. Test this out very well, because data model changes are more serious and fundamental changes than the program .tcl files. Now use the APM to create a new package version 1.0b2. Commit all your changes, tag the release (), and both new installations and upgrades will be taken care of. Connect to a second database It is possible to use the OpenACS Tcl database API with other databases. In this example, the OpenACS site uses a PostGre database, and accesses another PostGre database called legacy. Modify config.tcl to accommodate the legacy database, and to ensure that the legacy database is not used for standard OpenACS queries: ns_section ns/db/pools ns_param pool1 "Pool 1" ns_param pool2 "Pool 2" ns_param pool3 "Pool 3" ns_param legacy "Legacy" ns_section ns/db/pool/pool1 #Unchanged from default ns_param maxidle 1000000000 ns_param maxopen 1000000000 ns_param connections 5 ns_param verbose $debug ns_param extendedtableinfo true ns_param logsqlerrors $debug if { $database eq "oracle" } { ns_param driver ora8 ns_param datasource {} ns_param user $db_name ns_param password $db_password } else { ns_param driver postgres ns_param datasource ${db_host}:${db_port}:${db_name} ns_param user $db_user ns_param password "" } ns_section ns/db/pool/pool2 #Unchanged from default, removed for clarity ns_section ns/db/pool/pool3 #Unchanged from default, removed for clarity ns_section ns/db/pool/legacy ns_param maxidle 1000000000 ns_param maxopen 1000000000 ns_param connections 5 ns_param verbose $debug ns_param extendedtableinfo true ns_param logsqlerrors $debug ns_param driver postgres ns_param datasource ${db_host}:${db_port}:legacy_db ns_param user legacy_user ns_param password legacy_password ns_section ns/server/${server}/db ns_param pools * ns_param defaultpool pool1 ns_section ns/server/${server}/acs/database ns_param database_names [list main legacy] ns_param pools_main [list pool1 pool2 pool3] ns_param pools_legacy [list legacy] To use the legacy database, use the -dbn flag for any of the db_ API calls. For example, suppose there is a table called "foo" in the legacy system, with a field "bar". List "bar" for all records with this Tcl file: db_foreach -dbn legacy get_bar_query { select bar from foo limit 10 } { ns_write "<br/>$bar" } Future Topics How to enforce security so that users can't change other users records How to use the content management tables so that ... what? How to change the default stylesheets for Form Builder HTML forms. How to make your package searchable with OpenFTS/Oracle How to prepare pagelets for inclusion in other pages How and when to put procedures in a Tcl procedure library More on ad_form - data validation, other stuff. (plan to draw from Jon Griffin's doc) partialquery in xql How to use the html/text entry widget to get the "does this look right" confirm page APM package dependencies See also the OpenACS Programming FAQ