<?php
function tokenTruncate($string, $your_desired_width) {
    $parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);
    $parts_count = count($parts);

    $length = 0;
    $last_part = 0;
    for (; $last_part < $parts_count; ++$last_part) {
        $length += strlen($parts[$last_part]);
        if ($length > $your_desired_width) { break; }
    }

    return implode(array_slice($parts, 0, $last_part));
}

$events_config_key = 'events_ext_config';
$events_config = $pfcache->get($events_config_key);

if($events_config == null) {

    // Get Categories
    $categories = array();
    $q = "SELECT category_group_id, category_group_title, category_id, category_title FROM events WHERE crawled='1' AND active='1' GROUP BY category_group_id, category_id ORDER BY category_group_title ASC, category_title ASC";
    $r = @mysql_query($q);
    if($r && mysql_num_rows($r) > 0) {
        while($row = mysql_fetch_assoc($r)) {
            $category_group_id = intval($row['category_group_id']);
            $category_group_title = trim(stripslashes($row['category_group_title']));
            $category_id = intval($row['category_id']);
            $category_title = stripslashes(trim($row['category_title']));

            if(!isset($categories[$category_group_id])) {
                $categories[$category_group_id] = array(
                    'title' => $category_group_title != '' ? $category_group_title : 'Other',
                    'subs' => array()
                );
            }

            $categories[$category_group_id]['subs'][$category_id] = $category_title != '' ? $category_title : $category_group_title;
        }
    }
    $events_config['categories'] = $categories;

    // Get Locations
    $locations = array();
    $q = "SELECT dcode, region, city FROM events WHERE crawled='1' AND active='1' GROUP BY dcode, city ORDER BY region ASC, city ASC";
    $r = @mysql_query($q);
    if($r && mysql_num_rows($r) > 0) {
        while($row = mysql_fetch_assoc($r)) {
            $dcode = $row['dcode'];
            $region = trim(stripslashes($row['region']));
            $city = trim(stripslashes($row['city']));

            if(!isset($locations[$dcode])) {
                $locations[$dcode] = array(
                    'title' => $region != '' ? $region : 'All Cyprus',
                    'subs' => array()
                );
            }

            $locations[$dcode]['subs'] = $city != '' ? $city : 'N/A';
        }
    }
    $events_config['locations'] = $locations;


    $pfcache->set($events_config_key, $events_config, $pfcache_ttl);

    //echo '<pre>$categories = ', var_export($categories, true), '</pre>';
}
else {
    //echo '<pre>$events_config = ', var_export($events_config, true), '</pre>';
}