View · Index

Weblog Page

Filtered by category Cookbook, 11 - 20 of 37 Postings (all, summary)

Server-sent events

Created by Gustaf Neumann, last modified by Gustaf Neumann 14 Jan 2022, at 09:29 PM

Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via an HTTP connection, and describes how servers can initiate data transmission towards clients once an initial client connection has been established.

A simple approach for implementing SSE on OpenACS with discussed in a forum thread.

The example below shows, how to use SSE to associate a background job with the client. This can be used e.g. when executing longer a running job in the background and to keep the client up incrementally to date what is currently happening. This can be seen as an alternative to streaming HTML.

Page with associated background activity

ad_page_contract {

    Sample page for emulating streaming HTML via SSE (server side
    events) for a background job. In this example, the same page is
    used as the event sink (where the events are displayed) and as an
    event source (when called with a session_id).

    @author Gustaf Neumann
} {
    {session_id:integer ""}
}

set title "Sample HTML streaming job page (SSE)"
set context $title

if {$session_id ne ""} {
    #
    # We are called by the event handler from JavaScript. This block
    # could be a different, generic script, but we keep it here
    # together for reducing number of files.
    #

    #
    # Set up SSE: return headers and register reporting channel for
    # the session_id.
    #
    set channel [ns_connchan detach]
    ns_connchan write $channel [append _ \
                                    "HTTP/1.1 200 OK\r\n" \
                                    "Cache-Control: no-cache\r\n" \
                                    "X-Accel-Buffering': no\r\n" \
                                    "Content-type: text/event-stream\r\n" \
                                    "\r\n"]
    sse::channel $session_id $channel
    ad_script_abort
} else {
    #
    # We are called as an ADP page.
    #
    set session_id [ns_conn id]

    #
    # Register the SSE event handler in JavaScript.
    #
    template::head::add_script -script [subst {
        if(typeof(EventSource) !== "undefined") {
            var sse = new EventSource("[ns_conn url]?session_id=$session_id");
            sse.onmessage = function(event) {
                if ('__CLOSE_SSE__' == event.data) {
                    sse.close(); // stop retry
                } else {
                    document.getElementById("result").innerHTML += event.data;
                }
            };
        } else {
            document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
        }
    }]

    #
    # Run some job in the background and report updates via SSE to the
    # current page. The session_id is used to associate the background
    # job with the client.
    #
    sse::job $session_id {
        foreach i {1 2 3 4} {
            set HTML "<li>finish $i: ...([person::name -person_id [ad_conn user_id]])</li>"
            sse::message -localize $session_id $HTML
            ns_sleep 1s
        }
        sse::close $session_id
    }

    ad_return_template
}

Corresponding ADP page:

@title;literal@
@context;literal@
<h1>Getting updates from job associated with session_id @session_id@</h1> 
<ul> </ul>

Library support

Save this under e.g. acs-tcl/tcl/sse-procs.tcl

#############################################################################
# Simple API for SSE messages via a SESSION_ID, e.g. via a job running
# in the background.
#
# Gustaf Neumann fecit
#############################################################################
namespace eval sse {

  #
  # sse::job
  #
  ad_proc ::sse::job { {-lang} session_id script} {
    
    Execute some (long running) script in the background.  The
    background script is associated via the session_id with the client
    and can send messages to it via sse::message. When done, the job
    should issue sse::close.
    
    @param lang language used for internationalization. If not set,
           taken from the calling environment
    @param session_id associated session_id, used for reporting back
    @param script script to be executed in the background
    
  } {
    if {![info exists lang]} {
      set lang [uplevel {ad_conn locale}]
    }
    nsv_set sse_dict $session_id \
        [list \
             lang $lang \
             ad_conn [list array set ::ad_conn [array get ::ad_conn]] \
             xo::cc [expr {[info commands ::xo::cc] ne "" ? [::xo::cc serialize] : ""} ] \
            ]
    ns_job queue -detached sse-jobs \
        [list ::apply [list session_id "sse::init_job $session_id\n$script"] $session_id]
  }

  #
  # sse::message
  #
  ad_proc ::sse::message { {-localize:boolean} session_id msg} {

    Send a message to the client. In case the channel
    was not jet registered, buffer the message in an nsv dict.
    
    @param localize Perform localization of the provided text
    @param session_id associated session_id, used for associating output session
    @param msg The message to be sent back
  } {
    if {$localize_p} {
      set msg [lang::util::localize $msg [nsv_dict get sse_dict $session_id lang]]
    }
    
    if {[nsv_dict get -varname channel sse_dict $session_id channel]} {
      #
      # The channel is already set up.
      #
      if {[nsv_dict get -varname messages sse_dict $session_id messages]} {
        #
        # The "nsv_dict unset" poses a potential race condition,
        # ... but not for the job application scenario.
        #
        nsv_dict unset sse_dict $session_id messages
        #ns_log notice "--- sse $session_id get buffered messages '$messages'"
      } else {
        set messages ""
      }
      
      lappend messages $msg
      foreach message $messages {
        ns_log notice "--- sse $session_id message '$message'"
        #
        # SSE needs handling of new-lines in the data field; here we
        # send two messages in this case. In other cases, maybe coding
        # newline as literally \n and decoding it on the client might
        # be appropriate.
        #
        ns_connchan write $channel \
            [string cat "data:" [join [split $message \n] "\ndata:"] "\n\n"]
        
        if {$message eq "__CLOSE_SSE__"} {
          ns_connchan close $channel
          nsv_unset sse_dict $session_id 
        }
      }
    } else {
      #
      # Buffer the message.
      #
      #ns_log notice "--- sse $session_id must buffer message '$msg'"
      nsv_dict lappend sse_dict $session_id messages $msg
    }
  }
  
  #
  # sse::channel: register a channel for the session id. This is
  # typically called by the event handler, which is called from
  # JavaScript.
  #
  proc ::sse::channel {session_id channel} {
    nsv_dict set sse_dict $session_id channel $channel
  }

  #
  # sse::init_job: setup a context quite similar to a connection thread
  #  
  proc ::sse::init_job {session_id} {
    set sse_dict [nsv_get sse_dict $session_id]
    eval [dict get $sse_dict ad_conn]
    eval [dict get $sse_dict xo::cc]    
  }
  
  #
  # sse::close: provide an API for closing the session
  #
  proc ::sse::close {session_id} {
    ::sse::message $session_id __CLOSE_SSE__
  }
  
  if {"sse-jobs" ni [ns_job queues]} {
    ns_job create sse-jobs 4
    nsv_set sse_dict "" ""    
    #ns_job configure -jobsperthread 10000
  }
}
#
# Local variables:
#    mode: tcl
#    tcl-indent-level: 2
#    indent-tabs-mode: nil
# End:

Im case you are running NGINX and you are experiencing problems with SSE, check out this entry on stackoverflow.

 

Streaming HTML

Created by Gustaf Neumann, last modified by Gustaf Neumann 11 Sep 2021, at 09:58 AM

Streaming HTML can be used to output HTML content to a user incrementally. This is in particular useful for pages for pages with longer response time, to inform during processing about the progress of the tasks.

Newer OpenACS versions come with templates for the standard themes for streaming pages. The template for streaming pages can be retrieved for the current theme via the API call "template::streaming_template". An application developer should structure streaming HTML pages as follows:

Output top of page:

set context ...
set title ...
ad_return_top_of_page [ad_parse_template \
    -params [list context title] \
    [template::streaming_template]]

Output HTML incrementally:

# Assume, we are collecting HTML in the Tcl variable HTML.
# Send this HTML chunk incrementally to the user
ns_write [lang::util::localize $HTML]

Flush Output from body scripts:
(e.g. template::add_body_script, template::add_event_listener, template::add_body_handler, template::add_script)

ns_write [template::collect_body_scripts]

End of Page:

# Optionally
ns_write [lang::util::localize [template::get_footer_html]]
ns_write [template::collect_body_scripts]

Full sample script:
Putting everything together

set title "Sample HTML streaming page"
set context [list $title]
ad_return_top_of_page [ad_parse_template \
                           -params [list context title] \
                           [template::streaming_template]]
ns_write "<ul>\n"
foreach i {1 2 3 4} {
    set HTML "<li>finish $i: ...</li>\n"
    ns_write [lang::util::localize $HTML]
    ns_write [template::collect_body_scripts]
    ns_sleep 1s
}
ns_write "</ul>\n"
ns_write "<p>Done.</p>"

ns_write [lang::util::localize [template::get_footer_html]]
ns_write [template::collect_body_scripts]

See this sample script in action: https://openacs.org/streaming

Caveat: Windows PCs having the current (Sept 2020) version of Bitdefender (antivirus software ) installed with HTTP traffic scanning activated don't show the incremental rendering of the page, but just the full page after it has finished. This might be seen as a problem of Bitdefender and affects streaming HTML from all sites.

When to use URLencode

Created by Gustaf Neumann, last modified by Gustaf Neumann 09 Aug 2021, at 12:31 PM

In general, HTTP requires that URLs are properly encoded. This is not a big issue, when just plain ASCII characters without special characters are used in URL paths and query variables. However, when the framework allows the end-user to define also URLs (such as in xowiki and derivatives), one has to be careful when extending the framework. The section below refers to the behavior in OpenACS 5.10, earlier version might differ in some details.

URLs in HTML

When URLs are embedded in HTML (href, src, ...) the URL must be both first urlencoded and then HTML quoted to be on the safe side from the
point of view of HTML.  Although most characters problematic for HTML are encoded by ns_urlencode, but the single quote is not (this is not a bug but according to the specs, RFC 3986).

ns_urlencode {<a> 'b' "c" &}
# returns:  %3ca%3e+'b'+%22c%22+%26

Only, when it can be guaranteed the the URL contains no "funny characters" the URLencoding can be omitted. Note that double encoding with ns_urlencode leads to over-quoting in the same way as double encoding with ns_quotehtml.


Return_urls

In general, return_urls have to be proper URL encoded according to the HTTP specs. Setting these URLs is more complex, since one has to be aware whether or not an URL as encoded before or not before passing it as a return URL.

Here is a short guideline:

1) Query functions return URLs always URLdecoded

  • ns_conn url
  • ad_conn url
  • xo::cc url

2) Output functions return URLs per default URLencoded

  • export_vars (input parameter "-base" has to be unencoded)
  • ad_return_url
  • :pretty_link

3) Redirect operations have to receive encoded input

  • ad_returnredirect
  • ns_returnredirect
  • :returnredirect

4) Query-variables

When setting query variables with URLs, these should be already URL encoded

   #
   # Setting a query variable
   # 
   set return_url [ad_returnurl]
   set url [export_vars -base . {return_url}]

   #
   # Using query-variable as default value in xo* package
   #
   ad_returnredirect [:query_parameter return_url:localurl [ad_return_url]]

   #
   # Usage in classical OpenACS
   #
   ...
   # get return_url e.g. via page_contract
   ...
   if {[info exists return_url] && $return_url ne ""} {
        ad_returnredirect $return_url
    }

 

Cookbook

Created by Dave Bauer, last modified by Gustaf Neumann 26 May 2021, at 12:10 PM

The OpenACS Cookbook. This is the place to link OpenACS tips and tricks, code fragments, etc.

Accessing LTI services from OpenACS

Created by Gustaf Neumann, last modified by Gustaf Neumann 02 May 2021, at 12:35 PM

The package xooauth supports the use of OpenACS as “Tool Consumer” via LTI. This integration is in regular use at WU for integrating BigBlueButton, Zoom and Jupyter inside the learning platform of the university.

The package implements Basic LTI which is a common denominator for most LTI „Tool Providers“. This package can be used to launch requests from a community (learning) environment (e.g. OpenACS, DotLRN) to some external service (Tool provider) via plain HTTP calls. The service is typically used via an iframe or via window (LTI property “presentation_document_target”).

The LTI interface requires in a first step to register the external tool by providing the following information

  • launch_url: URL to which the LTI Launch request is to be sent
  • oauth_consumer_key: identifies which application is making the request
  • shared_secret: key used for singing the request

In general, this information can be provided via the OpenACS configuration file, or it can be be programmatically hardwired in a web-page via calls to the provided API. The relevant section in the configuration OpenACS configuration file might look like the following:

    ns_section ns/server/$server/lti {
        #
        # Common information for the tool consumer instance
        #
        ns_param tool_consumer_info_product_family_code "LEARN"
        ns_param tool_consumer_instance_guid  "learn.wu.ac.at"
        ns_param tool_consumer_instance_name  "WU Wien"
    }

    ns_section ns/server/$server/lti/bbb {
        ns_param launch_url         "https://demo.bigbluebutton.org/lti/rooms/messages/blti"
        ns_param oauth_consumer_key "bbb"
        ns_param shared_secret      "..."
    }


Once this is configured, one can create a launch button e.g. in an xowiki page via the includelet "launch-bigbluebutton" like in the following example

    Join Online Session via BigBlueButton: {{launch-bigbluebutton}}

When the interface should be used outside the xowiki environment, one can use the API like in the following example:

#
# Create LTI object
#
set lti [::xo::lti::LTI new \
        -launch_url         https://demo.bigbluebutton.org/lti/rooms/messages/blti \
        -oauth_consumer_key "bbb" \
        -shared_secret      "..." ]
set d [$lti form_render]
$lti destroy
#
# Render the form button
#
set HTML [subst {
      <button class="btn btn-primary" title="Click to join"
       type="submit" form="[dict get $d form_name]">Join Meeting</button>
       [dict get $d HTML]
}]

First an LTI object is created, based on the three essential parameters described above, A call to "form_render" returns a dict containing the HTML form and form names. The last command provides the markup for a launch button with a bootstrap styling.

The xooauth package provided pre-configured subclasses of ::xo::lti::LTI for big blue button (::xo::lti::BBB), Zoom (::xo::lti::Zoom) and Jupyter (::xo::lti::Jupyter). These subclasses will pick up the configured parameters from the configuration file and provide means for application specific configurations.

 

How to tune cache sizes

Created by Gustaf Neumann, last modified by Gustaf Neumann 03 Feb 2021, at 10:22 AM

OpenACS maintains many caches, which can be adjusted by different means depending on the version of OpenACS. Most important is the setting of the sizes via configuration files or package parameters (see e.g. [[https://github.com/openacs/openacs-core/blob/master/packages/acs-tcl/tcl/community-core-init.tcl#L1|acs-tcl/tcl/community-core-init.tcl]).

But what are good sizes? For managing the caches, using the NaviServer module nsstats is recommended. This module consists of a single file and is therefore easy installable,  but note that the newest features of the newest versions require often recent versions of NaviServer as well. To be on the safe side, use the nsstats version contained in the modules tar file for every release version of NaviServer (see e.g. NaviServer releases). The install script naviserver-openacs installs nsstats automatically under /admin.

The nsstats module provides among many other things an overview of the used caches with various usage statistics.

Cache overview

If one clicks on a single cache, a detail view is provided. The newest version of the detail view of a cache in nsstats contains now as well estimates for a good cache size. Useful cache entries are entries which were reused at least once. So, when a cache with 1MB size has e.g. a utilization of 50%, and only half of the used entries are reused, then effectively, the calculation suggests that 250KB + 10% are sufficient.

The only memory waste are actually the entries in the cache without any reuse, since the cache size is a max-size, the space which is not used does not cost memory.

The graphic shows, that only 5% of the size of the cache at openacs.org are actually useful, less than 2% has a reuse of 5 or better. Certainly, the reading are only useful after running the server for a while.

Detail view

Another dimension for cache tuning is cache partitioning as supported in OpenACS 5.10, which is important for highly busy sites in case the cache lock times go up. More about this later.

 

 

How to manage/upgrade CKEditor versions

Created by Gustaf Neumann, last modified by Gustaf Neumann 27 Aug 2020, at 07:46 PM

As of this writing (oacs-5-10), OpenACS supports CKEditor 4, which is kept as a separate package.

Per default, the CKEditor is used via CDN. If you prefer to install CKEditor locally, then go to /acs-admin/, click on the "Richtext CKeditor4" package on the link under site-wide admin. The pages show, how CKEditor is currently used, and offer a link for downloading and installing (gzipped, brotli if available).

Since upgrading to a newer version of CKEditor means often a different user experience.So, many site are reluctant to upgrade automatically to different versions. In these cases, one can configure the version of CKEditor in the NaviServer configuration file.

    ns_section ns/server/${server}/acs/richtext-ckeditor
           ns_param CKEditorVersion   4.14.1
           ns_param CKEditorPackage   standard
           ns_param CKFinderURL       /acs-content-repository/ckfinder
           ns_param StandardPlugins   uploadimage

A version specified in the configuration file override version numbers in the richtext package. When there is no such entry, then the version from the package is used.

 

SQL: How to log (slow) queries in the system log

Created by Gustaf Neumann, last modified by Gustaf Neumann 27 Aug 2020, at 11:47 AM

SQL logging is usually controlled via the configuration file of NaviServer. However, it can be as well activated at runtime via ds/shell by using the following commands:

  • make sure to turn sql-debugging level on
  • make sure, the logminduration is small enough (NaviServer allows to log only entries a threshold)
ns_logctl severity "Debug(sql)" on
foreach pool [ns_db pools] {ns_db logminduration $pool 0}

If you are interested e.g. in queries taking longer than 0.5 seconds, you can use

foreach pool [ns_db pools] {ns_db logminduration $pool 0.5}

Creating adp box tags for consistent html/css

Created by openacs community, last modified by Gustaf Neumann 26 Aug 2020, at 02:01 PM

Box tag code:

# The box tag is intended to make the markup around a "box"
# standard sitewide so that you can use the same css everywhere to   
# style the site.

  

template_tag box { chunk params } {
    set class [ns_set iget $params class]
    if {[template::util::is_nil class]} {
        set class box
    }
    set id [ns_set iget $params id]
    if {![template::util::is_nil id]} {
        set id " id=\\\"$id\\\""
    }

    template::adp_append_code "append __adp_output \"<div class=\\\"$class\\\"$id><div class=\\\"boxTop\\\"></div><div class=\\\"boxContent\\\">\""
    template::adp_compile_chunk $chunk
    template::adp_append_code "append __adp_output {</div><div class=\"boxBottom\"></div></div>}"
} 

E-Mail: Incoming E-Mail

Created by Malte Sussdorff, last modified by Gustaf Neumann 24 Aug 2020, at 01:43 PM

Incoming E-Mail in OpenACS works with the latest version of acs-mail-lite in a general fashion using callbacks.

The original version of this documentation is found via archive.org at: http://www.cognovis.de/developer/en/incoming_email

We will take a look on what needs to be done to get incoming e-mail working and then continue on to see how packages can benefit.

Project notes:  ACS Mail Lite sends via SMTP which permits the use of an external server to handle email. For scalability, consider expanding the incoming E-mail paradigm to likewise use Tcllib's imap4 or NaviServer's nsimap so that most all email can be handled on separate servers. 

Install incoming E-Mail

First, one must have an understanding of postfix basics. See http://www.postfix.org/BASIC_CONFIGURATION_README.html.

These instructions use the following example values:

  • hostname: www.yourserver.com
  • oacs user: service0
  • OS: Linux
  • email user: service0
  • email's home dir: /home/service0
  • email user's mail dir: /home/service0/mail

Important: The email user service0 does not have a ".forward" file. This user is only used for running the OpenACS website. Follow careful use of email rules by following strict guidelines to avoid email looping back unchecked.

For postfix, the email user and oacs user do not have to be the same. Furthermore, postfix makes distinctions between virtual users and user aliases.  Future versions of this documentation should use examples with different names to help distinguish between standard configuration examples and the requirements of ACS Mail Lite package.

Postfix configuration parameters:

myhostname=www.yourserver.com

myorigin=$myhostname

inet_interfaces=$myhostname, localhost

mynetworks_style=host

virtual_alias_domains = www.yourserver.com

virtual_maps=regexp:/etc/postfix/virtual

home_mailbox=mail/

Here is the sequence to follow if installing email service on system for first time. If your system already has email service, adapt these steps accordingly:

  1. Install postfix
  2. Install smtp (for postfix)
  3. Install metamail (for acs-mail-lite)
  4. Edit /etc/postfix/main.cf
  5. Edit /etc/postfix/virtual  Add a regular expression to filter relevant incoming emails for processing by OpenACS. 
    @www.yourserver.com service0
  6. Edit /etc/postfix/master.cf - uncomment this line so postfix listens to emails from internet
    smtp inet n - n - - smtpd
  7. Create a mail directory as service0
    mkdir /home/service0/mail
  8. Configure ACS Mail Lite parameters
    BounceDomain: www.yourserver.com
    BounceMailDir: /home/service0/mail
    EnvelopePrefix: bounce

    The EnvelopePrefix is for bounce e-mails only.

    NOTE: Parameters should be renamed: 
    BounceDomain to IncomingDomain
    BounceMailDir to IncomingMaildir
    EnvelopePrefix to BouncePrefix
    ..to reflect that acs-mail-lite is capable of dealing with other types of incoming e-mail.

    Furthermore, setting IncomingMaildir parameter clarifies that incoming email handling is setup. This is useful for other packages to determine if they can rely on incoming e-mail working (e.g. to set the reply-to email to an  e-mail address which actually works through a callback if the IncomingMaildir parameter is enabled).
  9. Configure Notifications parameters
    EmailReplyAddressPrefix: notification
    EmailQmailQueueScanP: 0

    We want acs-mail-lite incoming handle the Email Scanning, not each package separately.
    Configure other packages likewise
     
  10. Invoke postmap in OS shell to recompile virtual db:
    postmap /etc/postfix/virtual
  11. Restart Postfix. 
    /etc/init.d/postfix restart
  12. Restart OpenACS

 

Processing incoming e-mail

 

A sweeper procedure like acs_mail_lite::load_mails should:

  1. scan the e-mails which are in the IncomingMaildir directory on a regular basis.
  2. check if any email came from an auto mailer.
  3. Parse new ones, and
  4. process them by firing off callbacks.

Vinod has made a check for auto mailers by using procmail as follows. Maybe we could get this dragged into Tcl code (using regexp or a Procmail recipe parser) instead, thereby removing the need for setting up procmail in the first place.

Revised procmail filters:

:0 w * ^subject:.*Out of Office AutoReply /dev/null 
:0 w * ^subject:.*Out of Office /dev/null :0 w * ^subject:.*out of the office /dev/null 
:0 w * ^subject:.*NDN /dev/null :0 w * ^subject:.*[QuickML] Error: /dev/null 
:0 w * ^subject:.*autoreply /dev/null :0 w * ^from.*mailer.*daemon /dev/null

To make things granular a separate parsing procedure should deal with loading the e-mail into the Tcl interpreter and setting variables in an array for further processing.

ad_proc parse_email { 
    -file:required
    -array:required
} { 
   ...
}

An email is split into several parts: headers, bodies and files.

The headers consists of a list with header names as keys and their corresponding values. All keys are lower case.

The bodies consists of a list with two elements: content-type and content.

The files consists of a list with three elements: content-type, filename and content.

An array with all the above data is upvarred to the caller environment.

Processing an email should result in an array like this:

HEADERS

  • message_id
  • subject
  • from
  • to
  • date
  • received
  • references
  • in-reply-to
  • return-path
  • .....

X-Headers:

  • X-Mozilla-Status
  • X-Virus Scanned
  • .....

We do not know which headers are going to be available in the e-mail. We set all headers found in the array. The callback implementation then checks if a certain header is present or not.

        #get all available headers
        set keys [mime::getheader $mime -names]
 
        set headers [list]

        # create both the headers array and all headers directly for the email array
        foreach header $keys {
            set value [mime::getheader $mime $header]
            set email([string tolower $header]) $value
            lappend headers [list $header $value]
        }
        set email(headers) $headers

Bodies 

An e-mail usually consists of one or more bodies. With the advent of complex_send, OpenACS supports sending of multi-part e-mails which are needed if you want to send out and e-mail in text/html and text/plain (for old mail readers).

switch [mime::getproperty $part content] {
     "text/plain" {
          lappend bodies [list "text/plain" [mime::getbody $part]]
     }
     "text/html" {
          lappend bodies [list "text/html" [mime::getbody $part]]
     }
}

Files

OpenACS supports tcllib mime functions. Getting incoming files to work is a matter of looking for a part where there exists a "Content-disposition" part. All these parts are file parts. Together with scanning for email bodies, code looks something like this:

        set bodies [list]
        set files [list]
 
        #now extract all parts (bodies/files) and fill the email array
        foreach part $all_parts {

            # Attachments have a "Content-disposition" part
            # Therefore we filter out if it is an attachment here
            if {[catch {mime::getheader $part Content-disposition}]} {
                switch [mime::getproperty $part content] {
                    "text/plain" {
                        lappend bodies [list "text/plain" [mime::getbody $part]]
                    }
                    "text/html" {
                        lappend bodies [list "text/html" [mime::getbody $part]]
                    }
                }
            } else {
                set encoding [mime::getproperty $part encoding]
                set body [mime::getbody $part -decode]
                set content  $body
                set params [mime::getproperty $part params]
                if {[lindex $params 0] == "name"} {
                    set filename [lindex $params 1]
                } else {
                    set filename ""
                }

                # Determine the content_type
                set content_type [mime::getproperty $part content]
                if {$content_type eq "application/octet-stream"} {
                    set content_type [ns_guesstype $filename]
                }

                lappend files [list $content_type $encoding $filename $content]
            }
        }
        set email(bodies) $bodies
        set email(files) $files

Note that the files ie attachments are actually stored in the /tmp directory from where they can be processed further. It is up to the callback to decide if to import the file into OpenACS or not. Once all callbacks have been fired files in /tmp will have to be deleted again though.

Firing off callbacks 

Now that we have the e-mail parsed and have an array with all the information, we can fire off the callbacks. The firing should happen in two stages.

The first stage is where we support a syntax like "object_id@yoursite.com".

Second, incoming e-mail could look up the object_type, and then call the callback implementation specific to this object_type. If object_type = 'content_item', use content_type instead. 

ad_proc -public -callback acs_mail_lite::incoming_object_email { -array:required -object_id:required } { }

callback acs_mail_lite::incoming_object_email -impl $object_type -array email -object_id $object_id

 

ad_proc -public -callback acs_mail_lite::incoming_object_email -impl user {

    -array:required

    -object_id:required

} {

    Implementation of mail through support for incoming emails

} {

    # get a reference to the email array

    upvar $array email

 # make the bodies an array

        template::util::list_of_lists_to_array $email(bodies) email_body

        if {[exists_and_not_null email_body(text/html)]} {

            set body $email_body(text/html)

        } else {

            set body $email_body(text/plain)

        }

        set reply_to_addr "[party::get_by_email $email(from)]@[ad_url]"

        acs_mail_lite::complex_send \

            -from_addr $from_addr \

            -reply_to $reply_to_addr \

            -to_addr $to_addr \

            -subject $email(subject) \

            -body $body \

            -single_email \

            -send_immediately

}

Object id based implementations are useful for automatically generating "reply-to" addresses. With ProjectManager and Contacts object_id is also handy, because Project / TaskID is prominently placed on the website. If you are working on a task and you get an e-mail by your client that is related to the task, just forward the email to "$task_id@server.com" and it will be stored along with the task. Highly useful :).

Obviously you could have implementations for:

  • forums_forum_id: Start a new topic

  • forums_message_id: Reply to an existing topic

  • group_id: Send an e-mail to all group members

  • pm_project_id: add a comment to a project

  • pm_task_id: add a comment to a task and store the files in the projects folder (done)

 

Once the e-mail is dealt with in an object oriented approach we are either done with the message (an object_id was found in the to address) or we need to process it further.

ad_proc -public -callback acs_mail_lite::incoming_email {
    -array:required
    -package_id
} {
}
array set email {}
            
parse_email -file $msg -array email
set email(to) [parse_email_address -email $email(to)]
set email(from) [parse_email_address -email $email(from)]

# We execute all callbacks now
callback acs_mail_lite::incoming_email -array email

For this a general callback should exist which can deal with every leftover e-mail and each implementation will check if it wants to deal with this e-mail. How is this check going to happen? As an example, a package could have a prefix, as is the case with bounce e-mails as handled in acs_mail_lite::parse_bounce_address (see below):

ad_proc -public -callback acs_mail_lite::incoming_email -impl acs-mail-lite {
    -array:required
    -package_id:required
} {
    @param array        An array with all headers, files and bodies. To access the array you need to use upvar.
    @param package_id   The package instance that registered the prefix
    @return             nothing
    @error
} {
    upvar $array email

    set to [acs_mail_lite::parse_email_address -email $email(to)]
    ns_log Debug "acs_mail_lite::incoming_email -impl acs-mail-lite called. Recepient $to"

    util_unlist [acs_mail_lite::parse_bounce_address -bounce_address $to] user_id package_id signature
    
    # If no user_id found or signature invalid, ignore message
    # Here we decide not to deal with the message anymore



    if {[empty_string_p $user_id]} {
        if {[empty_string_p $user_id]} {
            ns_log Debug "acs_mail_lite::incoming_email impl acs-mail-lite: No equivalent user found for $to"
        } else {
            ns_log Debug "acs_mail_lite::incoming_email impl acs-mail-lite: Invalid mail signature $signature"
        }
    } else {
        ns_log Debug "acs_mail_lite::incoming_email impl acs-mail-lite: Bounce checking $to, $user_id"
        
        if { ![acs_mail_lite::bouncing_user_p -user_id $user_id] } {
            ns_log Debug "acs_mail_lite::incoming_email impl acs-mail-lite: Bouncing email from user $user_id"
            # record the bounce in the database
            db_dml record_bounce {}
            
            if {![db_resultrows]} {
                db_dml insert_bounce {}
            }
        }
    }
}
 

Alternatively we could just check the whole to address for other things, e.g. if the to address belongs to a group (party)

ad_proc -public -callback acs_mail_lite::incoming_email -impl contacts_group_mail {
    -array:required
    {-package_id ""}
} {
    Implementation of group support for incoming emails
    
    If the to address matches an address stored with a group then send out the email to all group members

     @author Malte Sussdorff (malte.sussdorff@cognovis.de)
     @creation-date 2005-12-18

     @param array        An array with all headers, files and bodies. To access the array you need to use upvar.
     @return             nothing
     @error
} {

    # get a reference to the email array
    upvar $array email

    # Now run the simplest mailing list of all
    set to_party_id [party::get_by_email -email $email(to)]
    
    if {[db_string group_p "select 1 from groups where group_id = :to_party_id" -default 0]} {
        # make the bodies an array
        template::util::list_of_lists_to_array $email(bodies) email_body
        
        if {[exists_and_not_null email_body(text/html)]} {
            set body $email_body(text/html)
        } else {
            set body $email_body(text/plain)
        }
        
        acs_mail_lite::complex_send \
            -from_addr [lindex $email(from) 0] \
            -to_party_ids [group::get_members -group_id $to_party_id] \
            -subject $email(subject) \
            -body $body \
            -single_email \
            -send_immediately

    }
} 

Or check if the to address follows a certain format.

ad_proc -public -callback acs_mail_lite::incoming_email -impl contacts_mail_through {
    -array:required
    {-package_id ""}
} {
    Implementation of mail through support for incoming emails
 
    You can send an e-amil through the system by sending it to user#target.com@yoursite.com
    The email will be send from your system and if mail tracking is installed the e-mail will be tracked.

    This allows you to go in direct communication with a customer using you standard e-mail program instead of having to go to the website.

    @author Malte Sussdorff (malte.sussdorff@cognovis.de)
    @creation-date 2005-12-18
 
    @param array        An array with all headers, files and bodies. To access the array you need to use upvar.
    @return             nothing
    @error
} {
    # get a reference to the email array
    upvar $array email

    # Take a look if the email contains an email with a "#"
    set pot_email [lindex [split $email(to) "@"] 0]
    if {[string last "#" $pot_email] > -1} {
       ....
   }
}

 Alternatives to this are:

  • ${component_name}-bugs@openacs.org (where component_name could be openacs or dotlrn or contacts or whatever), to store a new bug in bug-tracker
  • username@openacs.org (to do mail-through using the user name, which allows you to hide the actual e-mail of the user whom you are contacting).

Cleanup

Once all callbacks have been fired off,  e-mails need to be deleted from the Maildir directory and files which have been extracted need to be deleted as well from the /tmp directory. 

Next Page
previous November 2024
Sun Mon Tue Wed Thu Fri Sat
27 28 29 30 31 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

Popular tags

17 , 5.10 , 5.10.0 , 5.10.1 , 5.9.0 , 5.9.1 , ad_form , ADP , ajax , aolserver , asynchronous , bgdelivery , bootstrap , bugtracker , CentOS , COMET , compatibility , CSP , CSRF , cvs , debian , docker , docker-compose , emacs , engineering-standards , exec , fedora , FreeBSD , guidelines , host-node-map
No registered users in community xowiki
in last 30 minutes
Contributors

OpenACS.org