$_LW Functions

The $_LW object is a useful tool that you can use in your custom PHP modules to execute certain operations. You’ll notice most core and example module functions begin with global $_LW;.

Getting the current page

Back-end (private.application.my_module.php)
if ($_LW->page == 'events_edit') {

Front-end (public.application.my_module.php)
if ($_LW->page=='/admission/index.php') {

Checking User Status and Permissions

$_LW->isLiveWhaleUser()
Returns true if a LiveWhale user is logged in

$_LW->isSSOAuthOnlyUser()
Returns true if user successfully logged in via SSO, but is not a LiveWhale editor

$_LW->userSetting($id)
Returns true if the currently logged-in user has a certain setting (e.g. core_admin means they’re an administrator, core_publish means they can save changes as Live)

Error and Debug Logging

$_LW->logDebug('This is a debug message.');

Debug messages are the most common (and useful) function when you are developing a module and want to check if a certain block of code is running, or test the value of a variable. Debug messages can be checked by visiting /livewhale/?lw_debug=4. You can also log errors and notices:

$_LW->logError('This is an error.');
$_LW->logError('This is an error saved with a custom URL.', $url);
$_LW->logError('This is a notice.', false, true);

Errors are shown to logged-in users who check /livewhale/?lw_debug=2, notices are at /livewhale/?lw_debug=3.

Getting the URL of Dynamic Content

$_LW->getPermalinkUrl($type, $id, $title, $gid=false, $is_remote, $link_url, $item_url);

Input Description
$type The module to load (e.g. ‘events’, ‘news’)
$id The ID of the dynamic content
$title The title for the dynamic content, as you want it encoded into the URL
$gid ID of the content group; required for LWC if you want to link to the event within its group calendar (default: false)
$is_remote Make the URL remote by prefixing the full http(s) URL (default: true)
$link_url Override the LW-generated URL and use this instead (default: false)
$item_url The URL of a custom details template (default: false)
echo '<a href="'.$_LW->
getPermalinkUrl('events', $res2['id'], $res2['title']).'">'.
($_LW->setFormatClean($res2['title']).'</a>

Sending Email

Sometimes you may want to send email notifications from a custom module. You can leverage the existing “messages” module to do so using this code:

`$_LW->d_messages->sendMail($to, $subject, $message, $additional_headers=false, $additional_parameters=false, $message_vars=[])`

Input Description
$to Recipient email address (or multiple, separated by commas)
$subject Subject line
$message HTML message body
$additional_headers Array of additional headers (key=>value).
Most common is 'From'=>'my_email@myschool.edu' to set a From address. (The provided email address gets used as From Name and Reply-To in LW, since we can’t actually set From to an arbitrary address.)
$additional_parameters Array of additional parameters to send to PHPMailer (can be ignored in custom implementations)
$message_vars Internal LW functions for messages with template variables (can be ignored in custom implementations)
// Basic email implementation
$email='recipient@myschool.edu';
$subject='My Email';
$body='This is my email body.';
$_LW->d_messages->sendMail($recipient_email, $subject, $body);

Note: If your script sends multiple emails, we recommend including sleep(1); between each loop as some basic email throttling. If you send a lot of emails, your SMTP server might throttle you separately which can lead to buggy-seeming behavior. In general, when sending multiple emails from a single script, test and proceed carefully.

Saving and Loading Variables

You can leverage the LiveWhale variable system to cache useful bits of data.

$_LW->setVariable($key, $val, $ttl=0);
$_LW->getVariable($name);

For example,

public function getMyResult($criteria) {
        global $_LW;

        /* Complex code to get or calculate $result from $criteria... */
        return $result;
}

can be replaced with

public function getMyResult($criteria) { 
        global $_LW;

        $result=$_LW->getVariable('my_result_'.$criteria);
        if (empty($result)) {
                /* Complex code to get or calculate $result from $criteria... */
                $_LW->setVariable('my_result_'.$criteria, $result, 86400);
        };
        return $result;
}

In the above example, $criteria could be replaced by md5(serialize($criteria) in lines 2 and 5 if $criteria is not a string.

Additional features that might be useful for managing variables:

  • $_LW->hasVariable($key) – returns true if variable exists
  • $_LW->getVariableMTime($key) – returns the time a variable was last cached
  • $_LW->removeVariable($key) – removes a variable
  • When logged-in, you can preview a LiveWhale variable’s value in your browser by visiting the URL /live/variable/my_variable_name

In cases where your code might not always succeed—for instance, querying an external API with a rate limit—you may want to save the original variable indefinitely and decide, based on its last-cached-time, if you want to attempt to get a new value. See the example below.

public function getMyResult($criteria) { 
        global $_LW;
        $last_refreshed=(int)$_LW->getVariableMTime('my_result_'.$criteria);
        if ($last_refreshed<$_SERVER['REQUEST_TIME']-300) { // if variable is more than 300 seconds old
                /* Complex code to get or calculate new $result from $criteria... */
                if ($result) {
                        /* If new query was successful, cache the $result indefinitely */
                        $_LW->setVariable('my_result_'.$criteria, $result);
                        return $result;
                }
        }
        /* In all other cases, fall back to the cached variable */
        $result=$_LW->getVariable('my_result_'.$criteria);
        /* Re-cache that result to reset the 300 second clock, so as not to run failing code over and over again */
        $_LW->setVariable('my_result_'.$criteria, $result); 
        return $result;
}

Variables across multiple web nodes

Note: For performance purposes, variables saved with setVariable are stored in server memory and in the /livewhale/data filesystem, both of which are unique to each web node of your LiveWhale installation. This means you might have variables on web1 and web2 that expire at different times, or—depending on your code—have different values.

Since LiveWhale 2.6.0, there is an optional fourth value $all_nodes (defaults to false) you can set to true if you want setVariable to bypass this behavior and save your variable once for all nodes:

$_LW->setVariable($key, $val, $ttl=0, $all_nodes=false);

// In LiveWhale 2.6.0+, this variable will be saved to all web nodes for one hour
$_LW->setVariable('my_variable', $value, 3600, true);

And since LiveWhale 2.8.0, this ability has also been extended to the removeVariable function:

$_LW->removeVariable($key, $all_nodes=false);

// In LiveWhale 2.8.0+, this variable will be removed from all web nodes
$_LW->removeVariable('my_variable', true);

Accessing External APIs with getURL

$_LW->getUrl($arr, $response=true, $post=false, $curl_opts=false, $always_return=false);

Input Description
$arr URL or array of URLs
$response Should function return the response from the URL (default: true)
$post Array of POST values to send with the request (default: false)
$curl_opts Array of curl options for the request (default: false)
$always_return Always return response, even if request was unsuccessful (default: false)

Simple GetURL

public function getMyResult() {
        global $_LW;


        if ($json=$_LW->getUrl('https://api.something.net/something.json')) {
                if ($json=@json_decode($json, true)) {
                        /* do something with the returned $json... */
                        /* cache your results with SetVariable to limit API hits! */
                };
        };

        return $result;
}

Advanced GetURL

public function getMyResult($criteria) {
        global $_LW;

        $my_settings=[

                'username'=>$criteria['username'],

                'token'=>$criteria['password']
        ];
  
        if ($json=$_LW->getUrl('https://api.something.net/endpoint', true, $my_settings)) {
                if ($json=@json_decode($json, true)) {
                        /* do something with the returned $json... */
                        /* cache your results with SetVariable to limit API hits! */
                };
        };

        return $result;
}

Getting custom field data

Custom field data in LiveWhale is stored in a separate database table. Most of the time, the data will already be made available to you in an easy custom_variable_name format (learn more) but sometimes you may need to access that data from your own module.

$_LW->getCustomFields($data_type, $id, $include_non_public=true)
Gets the custom fields for a particular item, returns an array

$_LW->getContentForCustomFieldValue($data_type, $name, $value)
Gets content for the specifieid type which possesses the specified name/value pair

For example:

// Get the room numbers for a particular event
$custom_fields = $_LW->getCustomFields('events', $id);
$room_number = $custom_fields['room_number'];

// Get all events in Room 100, using a custom room_number field
$events = $_LW->getContentForCustomFieldValue('events', 'room_number', 'Room 100');

Custom field input markup

Sometimes in a custom application, you may want to grab the HTML markup for an input (text, checkbox, textarea, etc.) that corresponds to one of the custom fields you have already defined. In LiveWhale 2.4.0 the function $_LW->displayCustomFieldFormInput($name) was added—this returns the HTML markup of your custom field’s form input, provided you pass through a $name matching your custom field configuration.

Formatting Functions

LiveWhale includes a number of helper functions for formatting strings and dates:

$_LW->setFormatFilename($input, $show_extension=true)
Formats a title for use in filenames and permalink URLs

$_LW->setFormatClean($var, $preserve_newlines=false)
Format data for display within form field values (quotes encoded)

$_LW->setFormatAmps($var)
Encodes ampersands (outside of JS/XPHP scripts)

$_LW->setFormatAltText($var)
Formats text for use within an ALT tag, removing invalid characters

$_LW->setFormatSanitize($var)
Attempts to sanitize string (removing HTML/quotes)

$_LW->toDate($format, $ts=false, $tz=false)
Returns a date in the specified PHP format (returns based on the current timestamp and timezone, unless specified with $ts and $tz)

$_LW->toTS($date, $tz=false, $tz_for_mod=false)
Converts the specified date into a timestamp (returns based on the current system timezone, unless specified with $tz. $tz_for_mod can be used to override the current $tz on a one-off-basis, when calculating timezone differences.)

$_LW->setFormatSummarize($str, $limit_words=false, $limit_chars=false)
Summarize text (ending with ellipses) up to the specified number of words or characters, preserving XHTML

Miscellaneous Functions

$_LW->appendBodyClass($class)
Adds the specified string as a CSS body class in page output

$_LW->appendMetaTag($tags)
Adds the specified array of tags (formatted as $key => $val pairs) to the meta tags in page output

$_LW->getWeather($weather_id)
Returns the weather for a specified weather_id (zip code or another supported format in 1.7+, WOEID in 1.6.2 and before)

$_LW->hasSSL()
Returns true if SSL is enabled for this server. This is commonly used for generating absolute URLS like $url = 'http' . ($this->hasSSL() ? 's' : '') . '//www.myschool.edu';

On this page