Beispiel #1
0
 protected function initializeForPage()
 {
     $this->assign('deviceName', Kurogo::getOptionalSiteVar($this->platform, null, 'deviceNames'));
     $this->assign('introduction', $this->getOptionalModuleVar('introduction', null, $this->platform, 'apps'));
     $this->assign('instructions', $this->getOptionalModuleVar('instructions', null, $this->platform, 'apps'));
     $this->assign('downloadUrl', $this->getOptionalModuleVar('url', null, $this->platform, 'apps'));
 }
Beispiel #2
0
function getMinifyGroupsConfig()
{
    $minifyConfig = array();
    $key = $_GET['g'];
    //
    // Check for specific file request
    //
    if (strpos($key, MIN_FILE_PREFIX) === 0) {
        // file path relative to either templates or the theme (check theme first)
        $path = substr($key, strlen(MIN_FILE_PREFIX));
        $config = array('include' => 'all', 'files' => array(THEME_DIR . $path, SITE_APP_DIR . $path, SHARED_APP_DIR . $path, APP_DIR . $path));
        return array($key => buildFileList($config));
    }
    //
    // Page request
    //
    $pageOnly = isset($_GET['pageOnly']) && $_GET['pageOnly'];
    // if this is a copied module also pull in files from that module
    $configModule = isset($_GET['config']) ? $_GET['config'] : '';
    list($ext, $module, $page, $pagetype, $platform, $browser, $pathHash) = explode('-', $key);
    $cache = new DiskCache(CACHE_DIR . '/minify', Kurogo::getOptionalSiteVar('MINIFY_CACHE_TIMEOUT', 30), true);
    $cacheName = "group_{$key}";
    if ($configModule) {
        $cacheName .= "-{$configModule}";
    }
    if ($pageOnly) {
        $cacheName .= "-pageOnly";
    }
    if ($cache->isFresh($cacheName)) {
        $minifyConfig = $cache->read($cacheName);
    } else {
        $dirs = array(APP_DIR, SHARED_APP_DIR, SITE_APP_DIR, THEME_DIR);
        if ($pageOnly || ($pagetype == 'tablet' || $platform == 'computer') && in_array($module, array('info', 'admin'))) {
            // Info module does not inherit from common files
            $subDirs = array('/modules/' . $module);
        } else {
            $subDirs = array('/common', '/modules/' . $module);
        }
        if ($configModule) {
            $subDirs[] = '/modules/' . $configModule;
        }
        $checkFiles = array('css' => getFileConfigForDirs('css', 'css', $page, $pagetype, $platform, $browser, $dirs, $subDirs, $pageOnly), 'js' => getFileConfigForDirs('js', 'javascript', $page, $pagetype, $platform, $browser, $dirs, $subDirs, $pageOnly));
        //error_log(print_r($checkFiles, true));
        $minifyConfig[$key] = buildFileList($checkFiles[$ext]);
        //error_log(__FUNCTION__."($pagetype-$platform-$browser) scanned filesystem for $key");
        $cache->write($minifyConfig, $cacheName);
    }
    // Add minify source object for the theme config.ini
    if ($ext == 'css') {
        $themeVarsFile = realpath_exists(THEME_DIR . '/config.ini');
        if ($themeVarsFile) {
            $minifyConfig[$key][] = new Minify_Source(array('id' => 'themeConfigModTimeChecker', 'getContentFunc' => 'minifyThemeConfigModTimeCheckerContent', 'minifier' => '', 'contentType' => Minify::TYPE_CSS, 'lastModified' => filemtime($themeVarsFile)));
        }
    }
    //error_log(__FUNCTION__."($pagetype-$platform-$browser) returning: ".print_r($minifyConfig, true));
    return $minifyConfig;
}
 protected function init($page = '', $args = array())
 {
     if (!Kurogo::getSiteVar('PRODUCTION_ERROR_HANDLER_ENABLED')) {
         set_exception_handler("exceptionHandlerForError");
     }
     $this->pagetype = Kurogo::deviceClassifier()->getPagetype();
     $this->platform = Kurogo::deviceClassifier()->getPlatform();
     $this->page = 'index';
     $this->setTemplatePage($this->page, $this->id);
     $this->args = $args;
     $this->logView = Kurogo::getOptionalSiteVar('STATS_ENABLED', true) ? true : false;
     try {
         $this->moduleName = $this->getOptionalModuleVar('title', 'Error', 'module');
     } catch (KurogoConfigurationException $e) {
     }
     return;
 }
 public function migrateData($updateSummaryOnly = false)
 {
     $this->out("Beginning Migration");
     if ($table = Kurogo::getOptionalSiteVar("KUROGO_STATS_TABLE", "")) {
         $this->out("Using table {$table}");
         $this->out("Analyzing data.", false);
         $day = KurogoStats::getStartDate($table);
         $this->out(".", false);
         $endDay = KurogoStats::getLastDate($table);
         $this->out(".", false);
         $totalRows = KurogoStats::getTotalRows($table);
         $totalNumberOfDays = floor((strtotime($endDay) - strtotime($day)) / (60 * 60 * 24));
         $this->out(".", false);
         $this->out("Done.");
         $this->out("Migrating data from {$day} to {$endDay}");
         $this->out("Total Number of Days: {$totalNumberOfDays}");
         $this->out("Total Number of Rows: " . number_format($totalRows));
         $this->out("");
         $startTime = microtime(true);
         $totalRowsProcessed = 0;
         $dayCount = 0;
         while (strtotime($day) <= strtotime($endDay)) {
             $this->out("Migrating data for {$day}....", false);
             $rowsProcessed = KurogoStats::migrateData($table, $day, 50000, $updateSummaryOnly);
             $totalRowsProcessed += $rowsProcessed;
             $dayCount++;
             $this->out("rows found: {$rowsProcessed}", false);
             $timeTaken = microtime(true) - $startTime;
             $clockTimeTaken = $this->secondsToTime($timeTaken);
             $rowsRemaining = $totalRows - $totalRowsProcessed;
             $daysRemaining = $totalNumberOfDays - $dayCount;
             $pctDone = floor($totalRowsProcessed * 100 / $totalRows);
             $this->out("\t Elapsed: {$clockTimeTaken} \t {$daysRemaining} days remaining. " . number_format($rowsRemaining) . " rows remaining. {$pctDone}% complete.");
             $dayTimestamp = strtotime($day);
             $nextDayTimestamp = strtotime("+1 day", $dayTimestamp);
             $day = date("Y-m-d", $nextDayTimestamp);
         }
         $this->out('All data has been migrated successfully.');
     } else {
         $this->out('The stats table is not configured.');
     }
 }
 public function init($args)
 {
     $args['TITLE'] = '';
     // set BASE_URL first so parent doesn't complain
     $this->isPlaces = Kurogo::getOptionalSiteVar('USE_GOOGLE_PLACES', false, 'maps');
     if ($this->isPlaces) {
         $args['BASE_URL'] = self::PLACES_BASE_URL;
         $this->apiKey = Kurogo::getSiteVar('GOOGLE_PLACES_API_KEY', 'maps');
     } else {
         $args['BASE_URL'] = self::GEOCODE_BASE_URL;
         // the Google Maps license requires that geocode results
         // be displayed with a Google Map
         $this->staticMapClass = 'GoogleStaticMap';
         $this->dynamicMapClass = 'GoogleJSMap';
     }
     $this->defaultCenter = Kurogo::getSiteVar('DEFAULT_CENTER', 'maps');
     // TODO: grab the following from config
     //   default lat/lon, radius
     parent::init($args);
 }
  function __construct($device = null) {
  
    $this->version = intval(Kurogo::getSiteVar('MOBI_SERVICE_VERSION'));
    $this->userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    
    if ($device && strlen($device)) {
      $this->setDevice($device); // user override of device detection
      
    } elseif (isset($_COOKIE[self::COOKIE_KEY])) {
      $this->setDevice($_COOKIE[self::COOKIE_KEY]);
      
    } elseif (isset($_SERVER['HTTP_USER_AGENT'])) {
      
      if ($data = Kurogo::getSiteVar('MOBI_SERVICE_USE_EXTERNAL') ? 
        $this->detectDeviceExternal($this->userAgent) : $this->detectDeviceInternal($this->userAgent) ) {
        

        if ($data['pagetype']=='tablet' && !Kurogo::getOptionalSiteVar('TABLET_ENABLED', 1)) {
            
            //@TODO make this less hard coded
            switch ($data['platform'])
            {
                case 'android':
                    $data['pagetype'] = 'compliant';  
                    break;
                case 'ipad':
                    $data['pagetype'] = 'compliant';  
                    $data['platform'] = 'iphone';
                    break;
            }
        }        
        
        $this->pagetype = $data['pagetype'];
        $this->platform = $data['platform'];
        $this->certs = $data['supports_certificate'];
        $this->setDeviceCookie();
      }
    }
  }
 protected function init($page = '', $args = array())
 {
     if ($page == 'error') {
         if (!Kurogo::getSiteVar('PRODUCTION_ERROR_HANDLER_ENABLED')) {
             set_exception_handler("exceptionHandlerForError");
         }
         $this->pagetype = Kurogo::deviceClassifier()->getPagetype();
         $this->platform = Kurogo::deviceClassifier()->getPlatform();
         $this->browser = Kurogo::deviceClassifier()->getBrowser();
         $this->page = 'error';
         $this->setTemplatePage($this->page, $this->id);
         $this->setArgs($args);
         $this->ajaxContentLoad = $this->getArg(self::AJAX_PARAMETER) ? true : false;
         $this->logView = Kurogo::getOptionalSiteVar('STATS_ENABLED', true) ? true : false;
         try {
             $this->moduleName = $this->getOptionalModuleVar('title', 'Error', 'module');
         } catch (KurogoConfigurationException $e) {
         }
     } else {
         $this->redirectToModule($this->getHomeModuleID(), 'index');
     }
     return;
 }
 public function init($args)
 {
     // alter args for initializing retriever
     if (isset($args['title'])) {
         $args['TITLE'] = $args['title'];
     }
     $this->isPlaces = Kurogo::getOptionalSiteVar('USE_GOOGLE_PLACES', false, 'maps');
     if ($this->isPlaces) {
         $args['BASE_URL'] = self::PLACES_BASE_URL;
         $this->apiKey = Kurogo::getSiteVar('GOOGLE_PLACES_API_KEY', 'maps');
     } else {
         $args['BASE_URL'] = self::GEOCODE_BASE_URL;
         // the Google Maps license requires that geocode results
         // be displayed with a Google Map
         $this->staticMapClass = 'GoogleStaticMap';
         $this->dynamicMapClass = 'GoogleJSMap';
     }
     $this->defaultCenter = $args['center'];
     if (isset($args['NEARBY_THRESHOLD'])) {
         $this->defaultRadius = $args['NEARBY_THRESHOLD'];
     }
     parent::init($args);
     $this->retriever->setCacheLifetime(1);
 }
 private function getAdminData($type, $section, $subsection = null)
 {
     if ($type == 'site') {
         $configData = $this->getSiteAdminConfig();
         $module = $this;
     } elseif ($type instanceof Module) {
         $configData = $type->getModuleAdminConfig();
         $module = $type;
     } else {
         throw new KurogoConfigurationException("Invalid type {$type}");
     }
     if (!isset($configData[$section])) {
         throw new KurogoConfigurationException("Invalid section {$section}");
     }
     $sectionData = $configData[$section];
     if ($subsection) {
         if (!isset($configData[$section]['sections'][$subsection])) {
             throw new KurogoConfigurationException("Invalid subsection {$subsection} for section {$section}");
         }
         $sectionData = $configData[$section]['sections'][$subsection];
     }
     $sectionData['section'] = $section;
     if (isset($sectionData['titleKey'])) {
         $sectionData['title'] = $module->getLocalizedString($sectionData['titleKey']);
         unset($sectionData['titleKey']);
     }
     if (isset($sectionData['descriptionKey'])) {
         $sectionData['description'] = $module->getLocalizedString($sectionData['descriptionKey']);
         unset($sectionData['descriptionKey']);
     }
     if (isset($sectionData['fieldgroups'])) {
         foreach ($sectionData['fieldgroups'] as $fieldgroup => &$fieldgroupData) {
             if (isset($fieldgroupData['labelKey'])) {
                 $fieldgroupData['label'] = $module->getLocalizedString($fieldgroupData['labelKey']);
                 unset($fieldgroupData['labelKey']);
             }
             if (isset($fieldgroupData['descriptionKey'])) {
                 $fieldgroupData['description'] = $module->getLocalizedString($fieldgroupData['descriptionKey']);
                 unset($fieldgroupData['descriptionKey']);
             }
         }
     }
     switch ($sectionData['sectiontype']) {
         case 'fields':
             foreach ($sectionData['fields'] as $key => &$field) {
                 if (isset($field['labelKey'])) {
                     $field['label'] = $module->getLocalizedString($field['labelKey']);
                     unset($field['labelKey']);
                 }
                 if (isset($field['descriptionKey'])) {
                     $field['description'] = $module->getLocalizedString($field['descriptionKey']);
                     unset($field['descriptionKey']);
                 }
                 if (isset($field['valueMethod'])) {
                     $field['value'] = call_user_func(array($module, $field['valueMethod']));
                     unset($field['valueMethod']);
                 } elseif (isset($field['valueKey'])) {
                     $field['value'] = $module->getLocalizedString($field['valueKey']);
                     unset($field['valueKey']);
                 } elseif ($type == 'site') {
                     if (isset($field['config'])) {
                         switch ($field['config']) {
                             case 'site':
                                 $field['value'] = Kurogo::getOptionalSiteVar($key, '', $field['section']);
                                 break;
                             case 'strings':
                                 $field['value'] = Kurogo::getOptionalSiteString($key);
                                 break;
                             default:
                                 throw new KurogoConfigurationException("Unknown config " . $field['config']);
                                 break;
                         }
                     }
                 } elseif (isset($field['config'], $field['section'])) {
                     $field['value'] = $module->getOptionalModuleVar($key, isset($field['default']) ? $field['default'] : '', $field['section'], $field['config']);
                 }
                 switch ($field['type']) {
                     case 'paragraph':
                         if (is_array($field['value'])) {
                             $field['value'] = implode("\n\n", $field['value']);
                         }
                         break;
                     case 'select':
                         if (isset($field['optionsMethod'])) {
                             if (is_array($field['optionsMethod'])) {
                                 $field['options'] = call_user_func($field['optionsMethod']);
                             } else {
                                 $field['options'] = $module->{$field}['optionsMethod']();
                             }
                             unset($field['optionsMethod']);
                         }
                         if (isset($field['optionsFirst'])) {
                             $field['options'] = array_merge(array('' => $field['optionsFirst']), $field['options']);
                             unset($field['optionsFirst']);
                         }
                 }
                 if (isset($field['value'])) {
                     $value = $this->getUnconstantedValue($field['value'], $constant);
                     if ($constant) {
                         $field['value'] = $value;
                         $field['constant'] = $constant;
                     }
                 }
             }
             break;
         case 'section':
             if (isset($sectionData['sectionsmethod'])) {
                 if (is_array($sectionData['sectionsmethod'])) {
                     $sectionData['sections'] = call_user_func($sectionData['sectionsmethod']);
                 } else {
                     $sectionData['sections'] = $module->{$sectionData}['sectionsmethod']();
                 }
                 unset($sectionData['sectionsmethod']);
             } elseif ($type == 'site') {
                 throw new KurogoConfigurationException("Getting sections for site is not written yet");
             } else {
                 $configMode = isset($sectionData['configMode']) ? $sectionData['configMode'] : 0;
                 $sectionData['sections'] = $module->getModuleSections($sectionData['config'], Config::NO_EXPAND_VALUE, $configMode);
             }
             if (isset($sectionData['sectionsnoneKey'])) {
                 $sectionData['sectionsnone'] = $module->getLocalizedString($sectionData['sectionsnoneKey']);
                 unset($sectionData['sectionsnoneKey']);
             }
             if (isset($sectionData['sectionaddpromptkey'])) {
                 $sectionData['sectionaddprompt'] = $module->getLocalizedString($sectionData['sectionaddpromptkey']);
                 unset($sectionData['sectionaddpromptkey']);
             }
             foreach ($sectionData['fields'] as $key => &$field) {
                 if (isset($field['labelKey'])) {
                     $field['label'] = $module->getLocalizedString($field['labelKey']);
                     unset($field['labelKey']);
                 }
                 if (isset($field['descriptionKey'])) {
                     $field['description'] = $module->getLocalizedString($field['descriptionKey']);
                     unset($field['descriptionKey']);
                 }
                 if (isset($field['valueKey'])) {
                     $field['value'] = $module->getLocalizedString($field['valueKey']);
                     unset($field['valueKey']);
                 }
                 switch ($field['type']) {
                     case 'select':
                         if (isset($field['optionsMethod'])) {
                             if (is_array($field['optionsMethod'])) {
                                 $field['options'] = call_user_func($field['optionsMethod']);
                             } else {
                                 $field['options'] = $module->{$field}['optionsMethod']();
                             }
                             unset($field['optionsMethod']);
                         }
                         if (isset($field['optionsFirst'])) {
                             $field['options'] = array_merge(array('' => $field['optionsFirst']), $field['options']);
                             unset($field['optionsFirst']);
                         }
                 }
             }
             foreach ($sectionData['sections'] as $section => &$sectionFields) {
                 foreach ($sectionFields as $key => &$value) {
                     if (isset($sectionData['fields'][$key]['type']) && $sectionData['fields'][$key]['type'] == 'paragraph') {
                         $value = implode("\n\n", $value);
                     }
                     $v = $this->getUnconstantedValue($value, $constant);
                     if ($constant) {
                         $value = array($constant, $v, $value);
                     }
                 }
             }
             break;
         case 'sections':
             foreach ($sectionData['sections'] as $subsection => &$_sectionData) {
                 $subsectionData = $this->getAdminData($type, $section, $subsection);
                 if (isset($subsectionData['showIfSiteVar'])) {
                     if (Kurogo::getOptionalSiteVar($subsectionData['showIfSiteVar'][0], '') != $subsectionData['showIfSiteVar'][1]) {
                         unset($sectionData['sections'][$subsection]);
                         continue;
                     }
                 }
                 if (isset($subsectionData['showIfModuleVar'])) {
                     if ($type->getOptionalModuleVar($subsectionData['showIfModuleVar'][0], '') != $subsectionData['showIfModuleVar'][1]) {
                         unset($sectionData['sections'][$subsection]);
                         continue;
                     }
                 }
                 $sectionData['sections'][$subsection] = $subsectionData;
             }
             break;
         default:
             throw new KurogoConfigurationException("Section type " . $sectionData['sectiontype'] . " not understood for section {$section}");
     }
     return $sectionData;
 }
Beispiel #10
0
 protected function getLoginModuleID()
 {
     if (!$this->loginModuleID) {
         $this->loginModuleID = Kurogo::getOptionalSiteVar('LOGIN_MODULE', 'login', 'authentication');
     }
     return $this->loginModuleID;
 }
Beispiel #11
0
 protected function getHomeModuleID()
 {
     if (!$this->homeModuleID) {
         $this->homeModuleID = Kurogo::getOptionalSiteVar('HOME_MODULE', 'home', 'modules');
     }
     return $this->homeModuleID;
 }
 public static function getLastDateFromSummary()
 {
     $summaryTable = Kurogo::getOptionalSiteVar("KUROGO_STATS_SUMMARY_TABLE", "kurogo_stats_module_v1");
     $conn = self::connection();
     $sql = "SELECT date(`date`) AS date FROM `{$summaryTable}` GROUP BY 1 ORDER BY 1 DESC LIMIT 1";
     if (!($data = $conn->query($sql, array(), db::IGNORE_ERRORS))) {
         self::createSummaryTables($summaryTable);
         $data = $conn->query($sql);
     }
     if (!($result = $data->fetch())) {
         return false;
     }
     return $result['date'];
 }
Beispiel #13
0
 public static function retrieveStats(KurogoStatsOption $OptionObject)
 {
     // get data type, group and fields
     $type = $OptionObject->getType();
     $group = $OptionObject->getGroup();
     $fields = $OptionObject->getFields();
     switch ($type) {
         case 'count':
             if (count($fields) == 0) {
                 $fields[] = "COUNT(*) AS count";
             } elseif (count($fields) == 1) {
                 $fields[] = "COUNT(DISTINCT " . current($fields) . ") AS count";
             } else {
                 throw new Exception("Counting can only include 0 or 1 fields");
             }
             break;
         case 'sum':
             if (count($fields) > 1) {
                 throw new Exception("Sum logging type can only contain 1 field");
             }
             $fields = array("SUM(" . current($fields) . ") AS sum");
             break;
         case 'avg':
             if (count($fields) > 1) {
                 throw new Exception("Average logging type can only contain 1 field");
             }
             $fields = array("AVG(" . current($fields) . ") AS avg");
             break;
     }
     // get the group fields
     if ($group) {
         $fields = array_unique(array_merge($fields, self::getGroupFields($group)));
     }
     // build a list of parameters
     $filters = array();
     $params = array();
     foreach ($OptionObject->getFilters() as $filter) {
         $filters[] = $filter->getDBString();
         $params[] = $filter->getValue();
     }
     // build the query
     $table = Kurogo::getOptionalSiteVar("KUROGO_STATS_TABLE", "kurogo_stats_v1");
     $sql = "SELECT " . implode(',', $fields) . " FROM " . $table;
     $sql .= $filters ? " WHERE " . implode(' AND ', $filters) : '';
     $sql .= $group ? " GROUP BY " . implode(', ', $group) : '';
     //what happens where there are more than 1 group?
     if (count($group) > 1) {
         throw new Exception("Multi groups not functioning");
     }
     $groupString = implode(',', $group);
     if ($type == 'count' && $OptionObject->getSortField() == 'count') {
         $dir = $OptionObject->getSortDir() == SORT_ASC ? "ASC" : "DESC";
         $sql .= " ORDER BY count {$dir}, {$groupString}";
         if ($OptionObject->getLimit()) {
             $sql .= " LIMIT " . $OptionObject->getLimit();
         }
     }
     //prime the results as necessary
     $result = self::initStatsResult($OptionObject);
     //query
     $conn = self::connection();
     $data = $conn->query($sql, $params);
     while ($row = $data->fetch()) {
         if ($groupString && isset($row[$groupString])) {
             if ($groupString == 'data') {
                 $result[$row[$groupString]] = array('label' => $row['dataLabel'] ? $row['dataLabel'] : $row[$groupString], $type => $row[$type]);
             } else {
                 $result[$row[$groupString]] = $row[$type];
             }
         } else {
             return $row[$type] ? $row[$type] : 0;
         }
     }
     if ($type == 'count' && $OptionObject->getSortField() == 'count') {
         if ($OptionObject->getSortDir() == SORT_ASC) {
             asort($result);
         } else {
             arsort($result);
         }
         if ($OptionObject->getLimit()) {
             $result = array_slice($result, 0, $OptionObject->getLimit(), true);
         }
     }
     return $result;
 }
 public static function getServerConfig($id, $page, $args)
 {
     $isNative = self::hasNativePlatform();
     $staticConfig = array('module' => $id, 'page' => $page, 'ajaxArgs' => WebModule::AJAX_PARAMETER . "=1", 'timeout' => Kurogo::getOptionalSiteVar('WEB_BRIDGE_AJAX_TIMEOUT', 60), 'events' => $isNative);
     if (self::forceNativePlatform($pagetype, $platform, $browser)) {
         $staticConfig['ajaxArgs'] .= '&' . http_build_query(self::pagetypeAndPlatformToParams($pagetype, $platform, $browser));
     }
     // configMappings are so that keys used by native side are
     // independent of the config keys in the kgoBridge class
     $configMappings = json_encode(array('KGO_WEB_BRIDGE_CONFIG_URL' => 'urlPrefix', 'KGO_WEB_BRIDGE_PAGE_ARGS' => 'pageArgs', 'KGO_WEB_BRIDGE_COOKIES' => 'cookies', 'KGO_WEB_BRIDGE_AJAX_CONTENT' => 'ajaxContent', 'KGO_WEB_BRIDGE_GEOLOCATION' => 'geolocation'));
     // native bridge variables
     $jsInit = '__KGO_WEB_BRIDGE_JAVASCRIPT_INIT__';
     $bridgeConfig = '__KGO_WEB_BRIDGE_CONFIG_JSON__';
     if (!$isNative) {
         // emulate what native bridge would replace variables with
         $jsInit = '';
         $bridgeConfig = json_encode(array('KGO_WEB_BRIDGE_CONFIG_URL' => rtrim(FULL_URL_PREFIX, '/'), 'KGO_WEB_BRIDGE_PAGE_ARGS' => http_build_query($args)));
     }
     return array('jsInit' => $jsInit, 'configMappings' => $configMappings, 'staticConfig' => json_encode($staticConfig), 'bridgeConfig' => $bridgeConfig);
 }
 public function buildNativeWebTemplatesForPlatform($platform)
 {
     $pages = array_keys($this->getModuleSections('pages'));
     if ($pages) {
         $pages = array_diff($pages, array('pane'));
     }
     if (!$pages) {
         throw new KurogoConfigurationException("module does not have any pages defined in pages.ini");
     }
     $additionalAssets = $this->nativeWebTemplateAssets();
     $nativeConfig = $this->getOptionalModuleSection('native_template');
     if ($nativeConfig && $nativeConfig['additional_assets']) {
         $additionalAssets = array_unique(array_merge($additionalAssets, $nativeConfig['additional_assets']));
     }
     // Phone version
     $rewriter = new KurogoWebBridge($this->configModule, KurogoWebBridge::PAGETYPE_PHONE, $platform, KurogoWebBridge::BROWSER);
     $rewriter->saveTemplates($pages, $additionalAssets);
     if (Kurogo::getOptionalSiteVar('NATIVE_TABLET_ENABLED', 1)) {
         // Tablet version
         $rewriter = new KurogoWebBridge($this->configModule, KurogoWebBridge::PAGETYPE_TABLET, $platform, KurogoWebBridge::BROWSER);
         $rewriter->saveTemplates($pages, $additionalAssets);
     }
 }
Beispiel #16
0
    $args = deepStripslashes($args);
}

/* if the path is "empty" route to the default page. Will search the config file in order:
 * DEFAULT-PAGETYPE-PLATFORM
 * DEFAULT-PAGETYPE
 * DEFAULT
 * home is the default
 */
if (!strlen($path) || $path == '/') {
  $platform = strtoupper(Kurogo::deviceClassifier()->getPlatform());
  $pagetype = strtoupper(Kurogo::deviceClassifier()->getPagetype());

  if (!$url = Kurogo::getOptionalSiteVar("DEFAULT-{$pagetype}-{$platform}",'','urls')) {
    if (!$url = Kurogo::getOptionalSiteVar("DEFAULT-{$pagetype}",'', 'urls')) {
        $url = Kurogo::getOptionalSiteVar("DEFAULT",'home','urls');
    }
  } 
  
  if (!preg_match("/^http/", $url)) {
    $url = URL_PREFIX . $url . "/";
  }
  
  header("Location: $url");
  exit;
} 

$parts = explode('/', ltrim($path, '/'), 2);

if ($parts[0]==API_URL_PREFIX) {
    set_exception_handler("exceptionHandlerForAPI");
Beispiel #17
0
 private function setPageVariables()
 {
     $this->loadTemplateEngineIfNeeded();
     $this->loadPageConfig();
     // Set variables common to all modules
     $this->assign('moduleID', $this->id);
     $this->assign('configModule', $this->configModule);
     $this->assign('templateModule', $this->templateModule);
     $this->assign('moduleName', $this->moduleName);
     $this->assign('page', $this->page);
     $this->assign('isModuleHome', $this->page == 'index');
     $this->assign('request_uri', $_SERVER['REQUEST_URI']);
     $this->assign('hideFooterLinks', $this->hideFooterLinks);
     $this->assign('ajaxContentLoad', $this->ajaxContentLoad);
     $this->assign('charset', Kurogo::getCharset());
     // Font size for template
     $this->assign('fontsizes', $this->fontsizes);
     $this->assign('fontsize', $this->fontsize);
     $this->assign('fontsizeCSS', $this->getFontSizeCSS());
     $this->assign('fontSizeURLs', $this->getFontSizeURLs());
     // Minify URLs
     $this->assign('minify', $this->getMinifyUrls());
     // Google Analytics. This probably needs to be moved
     if ($gaID = Kurogo::getOptionalSiteVar('GOOGLE_ANALYTICS_ID')) {
         $this->assign('GOOGLE_ANALYTICS_ID', $gaID);
         $this->assign('GOOGLE_ANALYTICS_DOMAIN', Kurogo::getOptionalSiteVar('GOOGLE_ANALYTICS_DOMAIN'));
         $this->assign('gaImageURL', $this->googleAnalyticsGetImageUrl($gaID));
     }
     // Percent Mobile Analytics
     if ($pmID = Kurogo::getOptionalSiteVar('PERCENT_MOBILE_ID')) {
         $this->assign('PERCENT_MOBILE_ID', $pmID);
         $pmBASEURL = "http://assets.percentmobile.com/percent_mobile.js";
         $this->assign('PERCENT_MOBILE_URL', $pmBASEURL);
         //$this->assign('pmImageURLJS', $this->percentMobileAnalyticsGetImageUrlJS($pmID));
         $this->assign('pmImageURL', $this->percentMobileAnalyticsGetImageUrl($pmID));
     }
     // Breadcrumbs
     $this->loadBreadcrumbs();
     // Tablet module nav list
     if ($this->pagetype == 'tablet' && $this->page != 'pane') {
         $this->addInternalJavascript('/common/javascript/lib/iscroll-4.0.js');
         $this->assign('moduleNavList', $this->getModuleNavlist());
     }
     Kurogo::log(LOG_DEBUG, "Calling initializeForPage for {$this->configModule} - {$this->page}", 'module');
     $this->initializeForPage();
     //subclass behavior
     Kurogo::log(LOG_DEBUG, "Returned from initializeForPage for {$this->configModule} - {$this->page}", 'module');
     // Set variables for each page
     $this->assign('pageTitle', $this->pageTitle);
     // Variables which may have been modified by the module subclass
     $this->assign('inlineCSSBlocks', $this->inlineCSSBlocks);
     $this->assign('cssURLs', $this->cssURLs);
     $this->assign('inlineJavascriptBlocks', $this->inlineJavascriptBlocks);
     $this->assign('onOrientationChangeBlocks', $this->onOrientationChangeBlocks);
     $this->assign('onLoadBlocks', $this->onLoadBlocks);
     $this->assign('inlineJavascriptFooterBlocks', $this->inlineJavascriptFooterBlocks);
     $this->assign('javascriptURLs', $this->javascriptURLs);
     $this->assign('breadcrumbs', $this->breadcrumbs);
     $this->assign('breadcrumbArgs', $this->getBreadcrumbArgs());
     $this->assign('breadcrumbSamePageArgs', $this->getBreadcrumbArgs(false));
     $this->assign('moduleDebugStrings', $this->moduleDebugStrings);
     $moduleStrings = $this->getOptionalModuleSection('strings');
     $this->assign('moduleStrings', $moduleStrings);
     $this->assign('homeLink', $this->buildURLForModule($this->getHomeModuleID(), '', array()));
     $this->assign('homeModuleID', $this->getHomeModuleID());
     $this->assignLocalizedStrings();
     // Module Help
     if ($this->page == 'help') {
         $this->assign('hasHelp', false);
         $template = 'common/templates/' . $this->page;
     } else {
         $this->assign('hasHelp', isset($moduleStrings['help']));
         $this->assign('helpLink', $this->buildBreadcrumbURL('help', array()));
         $this->assign('helpLinkText', $this->getLocalizedString('HELP_TEXT', $this->getModuleName()));
         $template = 'modules/' . $this->templateModule . '/templates/' . $this->templatePage;
     }
     Kurogo::log(LOG_DEBUG, "Template file is {$template}", 'module');
     // Pager support
     if (isset($this->htmlPager)) {
         $this->assign('pager', $this->getPager());
     }
     // Tab support
     if (isset($this->tabbedView)) {
         $this->assign('tabbedView', $this->tabbedView);
     }
     $this->assign('imageExt', $this->imageExt);
     $this->assign($this->getThemeVars());
     // Access Key Start
     $accessKeyStart = count($this->breadcrumbs);
     if ($this->configModule != $this->getHomeModuleID()) {
         $accessKeyStart++;
         // Home link
     }
     $this->assign('accessKeyStart', $accessKeyStart);
     if (Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
         Kurogo::includePackage('Authentication');
         $this->setCacheMaxAge(0);
         $session = $this->getSession();
         $this->assign('session', $session);
         $this->assign('session_isLoggedIn', $this->isLoggedIn());
         $this->assign('showLogin', Kurogo::getSiteVar('AUTHENTICATION_ENABLED') && $this->showLogin());
         if ($this->isLoggedIn()) {
             $user = $session->getUser();
             $authority = $user->getAuthenticationAuthority();
             $this->assign('session_userID', $user->getUserID());
             $this->assign('session_fullName', $user->getFullname());
             if (count($session->getUsers()) == 1) {
                 $this->assign('session_logout_url', $this->buildURLForModule('login', 'logout', array('authority' => $user->getAuthenticationAuthorityIndex())));
                 $this->assign('footerLoginLink', $this->buildURLForModule('login', '', array()));
                 $this->assign('footerLoginText', $this->getLocalizedString('SIGNED_IN_SINGLE', $authority->getAuthorityTitle(), $user->getFullName()));
                 $this->assign('footerLoginClass', $authority->getAuthorityClass());
             } else {
                 $this->assign('footerLoginClass', 'login_multiple');
                 $this->assign('session_logout_url', $this->buildURLForModule('login', 'logout', array()));
                 $this->assign('footerLoginLink', $this->buildURLForModule('login', 'logout', array()));
                 $this->assign('footerLoginText', $this->getLocalizedString('SIGNED_IN_MULTIPLE'));
             }
             if ($session_max_idle = intval(Kurogo::getOptionalSiteVar('AUTHENTICATION_IDLE_TIMEOUT', 0))) {
                 $this->setRefresh($session_max_idle + 2);
             }
         } else {
             $this->assign('footerLoginClass', 'noauth');
             $this->assign('footerLoginLink', $this->buildURLForModule('login', '', array()));
             $this->assign('footerLoginText', $this->getLocalizedString('SIGN_IN_SITE', Kurogo::getSiteString('SITE_NAME')));
         }
     }
     /* set cache age. Modules that present content that rarely changes can set this value
        to something higher */
     header(sprintf("Cache-Control: max-age=%d", $this->cacheMaxAge));
     header("Expires: " . gmdate('D, d M Y H:i:s', time() + $this->cacheMaxAge) . ' GMT');
     return $template;
 }
Beispiel #18
0
    protected function getModuleAdminSections() {
        $configData = $this->getModuleAdminConfig();
        $sections = array();
        foreach ($configData as $section=>$sectionData) {
            if (isset($sectionData['showIfSiteVar'])) {
                if (Kurogo::getOptionalSiteVar($sectionData['showIfSiteVar'][0], '') != $sectionData['showIfSiteVar'][1]) {
                    continue;
                }
            }

            if (isset($sectionData['showIfModuleVar'])) {
                if ($this->getOptionalModuleVar($sectionData['showIfModuleVar'][0], '') != $sectionData['showIfModuleVar'][1]) {
                    continue;
                }
            }
            
            $sections[$section] = array(
                'title'=>$sectionData['title'],
                'type'=>$sectionData['type']
            );
        }
                
        return $sections;
    }
Beispiel #19
0
 public static function tempDirectory()
 {
     return Kurogo::getOptionalSiteVar('TMP_DIR', sys_get_temp_dir());
 }
  private function setPageVariables() {
    $this->loadTemplateEngineIfNeeded();
        
    $this->loadPageConfig();
    
    // Set variables common to all modules
    $this->assign('moduleID',     $this->id);
    $this->assign('configModule',  $this->configModule);
    $this->assign('templateModule', $this->templateModule);
    $this->assign('moduleName',   $this->moduleName);
    $this->assign('page',         $this->page);
    $this->assign('isModuleHome', $this->page == 'index');
    $this->assign('request_uri' , $_SERVER['REQUEST_URI']);
    
    // Font size for template
    $this->assign('fontsizes',    $this->fontsizes);
    $this->assign('fontsize',     $this->fontsize);
    $this->assign('fontsizeCSS',  $this->getFontSizeCSS());
    $this->assign('fontSizeURLs', $this->getFontSizeURLs());

    // Minify URLs
    $this->assign('minify', $this->getMinifyUrls());
    
    // Google Analytics. This probably needs to be moved
    if ($gaID = Kurogo::getOptionalSiteVar('GOOGLE_ANALYTICS_ID')) {
        $this->assign('GOOGLE_ANALYTICS_ID', $gaID);
        $this->assign('gaImageURL', $this->googleAnalyticsGetImageUrl($gaID));
    }
    
    // Breadcrumbs
    $this->loadBreadcrumbs();
    
    // Tablet module nav list
    if ($this->pagetype == 'tablet') {
      $this->addInternalJavascript('/common/javascript/lib/iscroll-4.0.js');
      $this->assign('moduleNavList', $this->getModuleNavlist());
    }
            
    // Set variables for each page
    $this->initializeForPage();

    $this->assign('pageTitle', $this->pageTitle);

    // Variables which may have been modified by the module subclass
    $this->assign('inlineCSSBlocks',              $this->inlineCSSBlocks);
    $this->assign('cssURLs',                      $this->cssURLs);
    $this->assign('inlineJavascriptBlocks',       $this->inlineJavascriptBlocks);
    $this->assign('onOrientationChangeBlocks',    $this->onOrientationChangeBlocks);
    $this->assign('onLoadBlocks',                 $this->onLoadBlocks);
    $this->assign('inlineJavascriptFooterBlocks', $this->inlineJavascriptFooterBlocks);
    $this->assign('javascriptURLs',               $this->javascriptURLs);
    
    $this->assign('breadcrumbs',            $this->breadcrumbs);
    $this->assign('breadcrumbArgs',         $this->getBreadcrumbArgs());
    $this->assign('breadcrumbSamePageArgs', $this->getBreadcrumbArgs(false));

    $this->assign('moduleDebugStrings',     $this->moduleDebugStrings);
    
    $moduleStrings = $this->getOptionalModuleSection('strings');
    $this->assign('moduleStrings', $moduleStrings);

    // Module Help
    if ($this->page == 'help') {
      $this->assign('hasHelp', false);
      $template = 'common/templates/'.$this->page;
    } else {
      $this->assign('hasHelp', isset($moduleStrings['help']));
      $template = 'modules/'.$this->templateModule.'/templates/'.$this->templatePage;
    }
    
    // Pager support
    if (isset($this->htmlPager)) {
      $this->assign('pager', $this->getPager());
    }
    
    // Tab support
    if (isset($this->tabbedView)) {
      $this->assign('tabbedView', $this->tabbedView);
    }
    
    $this->assign('imageExt', $this->imageExt);
    $this->assign($this->getThemeVars());
    
    // Access Key Start
    $accessKeyStart = count($this->breadcrumbs);
    if ($this->configModule != 'home') {
      $accessKeyStart++;  // Home link
    }
    $this->assign('accessKeyStart', $accessKeyStart);

    if (Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
        includePackage('Authentication');
        $this->setCacheMaxAge(0);
        $session = $this->getSession();
        $this->assign('session', $session);
        $this->assign('session_isLoggedIn', $this->isLoggedIn());
        if ($this->isLoggedIn()) {
            $user = $session->getUser();
            $authority = $user->getAuthenticationAuthority();
            $this->assign('session_authority_class', $authority->getAuthorityClass());
            $this->assign('session_authority_title', $authority->getAuthorityTitle());
            $this->assign('session_userID', $user->getUserID());
            $this->assign('session_fullName', $user->getFullname());
            if (count($session->getUsers())==1) {
                $this->assign('session_logout_url', $this->buildURLForModule('login', 'logout', array('authority'=>$user->getAuthenticationAuthorityIndex())));
                $this->assign('session_multiple_logins', false);
            } else {
                $this->assign('session_multiple_logins', true);
                $this->assign('session_logout_url', $this->buildURLForModule('login', 'logout', array()));
            }

            if ($session_max_idle = intval(Kurogo::getOptionalSiteVar('AUTHENTICATION_IDLE_TIMEOUT', 0))) {
                $this->setRefresh($session_max_idle+2);
            }
        }
    }

    /* set cache age. Modules that present content that rarely changes can set this value
    to something higher */
    header(sprintf("Cache-Control: max-age=%d", $this->cacheMaxAge));
    header("Expires: " . gmdate('D, d M Y H:i:s', time() + $this->cacheMaxAge) . ' GMT');
    
    return $template;
  }
 public static function smartyPrefilterHandleIncludeAndExtends($source, $template) {
   $template->smarty->extendsTrackerCheckTemplate($template);
   
   $variables = $template->smarty->getTemplateVars();
   
   // findIncludes
   $search = array();
   $replace = array();
   if (preg_match_all(';file\s*=\s*"findInclude:([^"]+)";', $source, $matches, PREG_PATTERN_ORDER)) {
     foreach ($matches[1] as $i => $name) {
       $path = self::getIncludeFile(self::replaceVariables($name, $variables));
       if ($path) {
         $search[] = $matches[0][$i];
         $replace[] = 'file="file:'.$path.'"';
         if (Kurogo::getOptionalSiteVar('TEMPLATE_DEBUG')) {
           error_log(__FUNCTION__." replacing include $name with $path");
         }
       } else {
         trigger_error(__FUNCTION__." FAILED to find INCLUDE for $name", E_USER_ERROR);
       }
     }
   }
   if (preg_match_all(';file\s*=\s*"findExtends:([^"]+)";', $source, $matches, PREG_PATTERN_ORDER)) {
     foreach ($matches[1] as $i => $name) {
       $path = self::getExtendsFile(self::replaceVariables($name, $variables), $template);
       if ($path) {
         $search[] = $matches[0][$i];
         $replace[] = 'file="file:'.$path.'"';
         if (Kurogo::getOptionalSiteVar('TEMPLATE_DEBUG')) {
           error_log(__FUNCTION__." replacing extends $name with $path");
         }
       } else {
         trigger_error(__FUNCTION__." FAILED to find EXTENDS for $name", E_USER_ERROR);
       }
     }
   }
   
   return $search ? str_replace($search, $replace, $source) : $source;
 }
 protected function detectDeviceExternal($user_agent)
 {
     if (!$user_agent) {
         return;
     }
     // see if the server has cached the results from the the device detection server
     try {
         $cache = new DiskCache($this->cacheFolder(), $this->cacheLifetime(), TRUE);
     } catch (KurogoDataException $e) {
         $cache = null;
     }
     $cacheFilename = md5($user_agent);
     if ($cache && $cache->isFresh($cacheFilename)) {
         $json = $cache->read($cacheFilename);
         Kurogo::log(LOG_INFO, "Using cached data for external device detection", 'deviceDetection');
     } else {
         $query = http_build_query(array('user-agent' => $user_agent, 'version' => $this->version));
         $url = Kurogo::getSiteVar('MOBI_SERVICE_URL') . '?' . $query;
         Kurogo::log(LOG_INFO, "Detecting device using external device detection: {$url}", 'deviceDetection');
         $timeout = Kurogo::getOptionalSiteVar('MOBI_SERVICE_EXTERNAL_TIMEOUT', 5);
         $context = stream_context_create(array('http' => array('timeout' => $timeout, 'user_agent' => Kurogo::KurogoUserAgent())));
         $json = @file_get_contents($url, false, $context);
         if (false === $json) {
             return $this->detectDeviceInternal($user_agent);
         }
         $test = json_decode($json, true);
         // make sure the response is valid
         if ($cache) {
             if ($json && isset($test['pagetype'], $test['platform'])) {
                 $cache->write($json, $cacheFilename);
             } else {
                 Kurogo::log(LOG_WARNING, "Error receiving device detection data from {$url}.  Reading expired cache.", 'deviceDetection');
                 $json = $cache->read($cacheFilename);
             }
         }
     }
     $data = json_decode($json, true);
     // fix values when using old version
     if ($this->version == 1) {
         switch (strtolower($data['pagetype'])) {
             case 'basic':
                 if ($data['platform'] == 'computer' || $data['platform'] == 'spider') {
                     $data['pagetype'] = 'compliant';
                 } else {
                     if ($data['platform'] == 'bbplus') {
                         $data['pagetype'] = 'compliant';
                     } else {
                         $data['pagetype'] = 'basic';
                     }
                 }
                 break;
             case 'touch':
                 if ($data['platform'] == 'blackberry') {
                     $data['pagetype'] = 'compliant';
                     // Storm, Storm 2
                 } else {
                     if ($data['platform'] == 'winphone7') {
                         $data['pagetype'] = 'compliant';
                         // Windows Phone 7
                     } else {
                         $data['pagetype'] = 'touch';
                     }
                 }
                 break;
             case 'compliant':
             case 'webkit':
             default:
                 $data['pagetype'] = 'compliant';
                 break;
         }
     }
     return $data;
 }
Beispiel #23
0
 public function getLocalizedString($key, $opts = null)
 {
     if (!preg_match("/^[a-z0-9_]+\$/i", $key)) {
         throw new KurogoConfigurationException("Invalid string key {$key}");
     }
     Kurogo::log(LOG_DEBUG, "Retrieving localized string for {$key}", 'module');
     // use any number of args past the first as options
     $args = func_get_args();
     array_shift($args);
     if (count($args) == 0 || is_null($args[0])) {
         $args = null;
     }
     $languages = Kurogo::sharedInstance()->getLanguages();
     foreach ($languages as $language) {
         $val = $this->getStringForLanguage($key, $language, $args);
         if ($val !== null) {
             Kurogo::log(LOG_INFO, "Found localized string \"{$val}\" for {$key} in {$language}", 'module');
             return Kurogo::getOptionalSiteVar('LOCALIZATION_DEBUG') ? $key : $val;
         }
     }
     throw new KurogoConfigurationException("Unable to find string {$key} for Module {$this->id}");
 }
Beispiel #24
0
 public static function defaultModule()
 {
     $platform = strtoupper(Kurogo::deviceClassifier()->getPlatform());
     $pagetype = strtoupper(Kurogo::deviceClassifier()->getPagetype());
     $browser = strtoupper(Kurogo::deviceClassifier()->getBrowser());
     if (!($module = Kurogo::getOptionalSiteVar("DEFAULT-{$pagetype}-{$platform}-{$browser}", '', 'urls'))) {
         if (!($module = Kurogo::getOptionalSiteVar("DEFAULT-{$pagetype}-{$platform}", '', 'urls'))) {
             if (!($module = Kurogo::getOptionalSiteVar("DEFAULT-{$pagetype}", '', 'urls'))) {
                 $homeModuleID = Kurogo::getOptionalSiteVar('HOME_MODULE', 'home', 'modules');
                 $module = Kurogo::getOptionalSiteVar("DEFAULT", $homeModuleID, 'urls');
             }
         }
     }
     return $module;
 }
Beispiel #25
0
 protected function initializeForPage()
 {
     $nativeApp = (bool) $this->getArg('nativeApp', false);
     $this->assign('nativeApp', $nativeApp);
     // Default args to pass through forms and urls
     $defaultArgs = array();
     if ($nativeApp) {
         $defaultArgs['nativeApp'] = 1;
     }
     // If this is a native app, use the native app GA id
     if ($nativeApp) {
         $this->assign('GOOGLE_ANALYTICS_ID', Kurogo::getOptionalSiteVar('GOOGLE_ANALYTICS_NATIVE_ID'));
     }
     if (!Kurogo::getSiteVar('AUTHENTICATION_ENABLED')) {
         throw new KurogoConfigurationException($this->getLocalizedString("ERROR_AUTHENTICATION_DISABLED"));
     }
     $session = $this->getSession();
     //return URL
     $urlArray = $this->extractModuleArray($this->args);
     //see if remain logged in is enabled by the administrator, then if the value has been passed (i.e. the user checked the "remember me" box)
     $allowRemainLoggedIn = Kurogo::getOptionalSiteVar('AUTHENTICATION_REMAIN_LOGGED_IN_TIME');
     if ($allowRemainLoggedIn) {
         $remainLoggedIn = $this->getArg('remainLoggedIn', 0);
     } else {
         $remainLoggedIn = 0;
     }
     // initialize
     $authenticationAuthorities = array('total' => 0, 'direct' => array(), 'indirect' => array(), 'auto' => array());
     $invalidAuthorities = array();
     // cycle through the defined authorities in the config
     foreach (AuthenticationAuthority::getDefinedAuthenticationAuthorities() as $authorityIndex => $authorityData) {
         // USER_LOGIN property determines whether the authority is used for logins (or just groups or oauth)
         $USER_LOGIN = $this->argVal($authorityData, 'USER_LOGIN', 'NONE');
         // trap the exception if the authority is invalid (usually due to misconfiguration)
         try {
             $authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex);
             $authorityData['listclass'] = $authority->getAuthorityClass();
             $authorityData['title'] = $authorityData['TITLE'];
             $authorityData['url'] = $this->buildURL('login', array_merge($urlArray, array('authority' => $authorityIndex, 'remainLoggedIn' => $remainLoggedIn, 'startOver' => 1)));
             if ($USER_LOGIN == 'FORM') {
                 $authenticationAuthorities['direct'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             } elseif ($USER_LOGIN == 'LINK') {
                 $authenticationAuthorities['indirect'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             } elseif ($USER_LOGIN == 'AUTO') {
                 $authenticationAuthorities['auto'][$authorityIndex] = $authorityData;
                 $authenticationAuthorities['total']++;
             }
         } catch (KurogoConfigurationException $e) {
             Kurogo::log(LOG_WARNING, "Invalid authority data for %s: %s", $authorityIndex, $e->getMessage(), 'auth');
             $invalidAuthorities[$authorityIndex] = $e->getMessage();
         }
     }
     //see if we have any valid authorities
     if ($authenticationAuthorities['total'] == 0) {
         $message = $this->getLocalizedString("ERROR_NO_AUTHORITIES");
         if (count($invalidAuthorities) > 0) {
             $message .= sprintf(" %s invalid authorit%s found:\n", count($invalidAuthorities), count($invalidAuthorities) > 1 ? 'ies' : 'y');
             foreach ($invalidAuthorities as $authorityIndex => $invalidAuthority) {
                 $message .= sprintf("%s: %s\n", $authorityIndex, $invalidAuthority);
             }
         }
         //we don't
         throw new KurogoConfigurationException($message);
     }
     //assign template variables
     $this->assign('authenticationAuthorities', $authenticationAuthorities);
     $this->assign('allowRemainLoggedIn', $allowRemainLoggedIn);
     if ($forgetPasswordURL = $this->getOptionalModuleVar('FORGET_PASSWORD_URL')) {
         $this->assign('FORGET_PASSWORD_URL', $this->buildBreadcrumbURL('forgotpassword', array()));
         $this->assign('FORGET_PASSWORD_TEXT', $this->getOptionalModuleVar('FORGET_PASSWORD_TEXT', $this->getLocalizedString('FORGET_PASSWORD_TEXT')));
     }
     $multipleAuthorities = count($authenticationAuthorities['direct']) + count($authenticationAuthorities['indirect']) > 1;
     switch ($this->page) {
         case 'logoutConfirm':
             //this page is presented when a specific authority is chosen and the user is presented the option to actually log out.
             $authorityIndex = $this->getArg('authority');
             if (!$this->isLoggedIn($authorityIndex)) {
                 // they aren't logged in
                 $this->redirectTo('index', $defaultArgs);
             } elseif ($user = $this->getUser($authorityIndex)) {
                 $authority = $user->getAuthenticationAuthority();
                 $this->assign('message', $this->getLocalizedString('LOGIN_SIGNED_IN_SINGLE', Kurogo::getSiteString('SITE_NAME'), $authority->getAuthorityTitle(), $user->getFullName()));
                 $this->assign('url', $this->buildURL('logout', array('authority' => $authorityIndex)));
                 $this->assign('linkText', $this->getLocalizedString('SIGN_OUT'));
                 $this->setTemplatePage('message');
             } else {
                 //This honestly should never happen
                 $this->redirectTo('index', $defaultArgs);
             }
             break;
         case 'logout':
             $authorityIndex = $this->getArg('authority');
             //hard logouts attempt to logout of the indirect service provider (must be implemented by the authority)
             $hard = $this->getArg('hard', false);
             if (!$this->isLoggedIn($authorityIndex)) {
                 //not logged in
                 $this->redirectTo('index', $defaultArgs);
             } elseif ($authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex)) {
                 $user = $this->getUser($authority);
                 //log them out
                 $result = $session->logout($authority, $hard);
             } else {
                 //This honestly should never happen
                 $this->redirectTo('index', $defaultArgs);
             }
             if ($result) {
                 $this->setLogData($user, $user->getFullName());
                 $this->logView();
                 //if they are still logged in return to the login page, otherwise go home.
                 if ($this->isLoggedIn()) {
                     $this->redirectTo('index', array_merge(array('logout' => $authorityIndex), $defaultArgs));
                 } else {
                     $this->redirectToModule($this->getHomeModuleID(), '', array('logout' => $authorityIndex));
                 }
             } else {
                 //there was an error logging out
                 $this->setTemplatePage('message');
                 $this->assign('message', $this->getLocalizedString("ERROR_SIGN_OUT"));
             }
             break;
         case 'forgotpassword':
             //redirect to forgot password url
             if ($forgetPasswordURL = $this->getOptionalModuleVar('FORGET_PASSWORD_URL')) {
                 Kurogo::redirectToURL($forgetPasswordURL);
             } else {
                 $this->redirectTo('index', $defaultArgs);
             }
             break;
         case 'login':
             //get arguments
             $login = $this->argVal($_POST, 'loginUser', '');
             $password = $this->argVal($_POST, 'loginPassword', '');
             $options = array_merge($urlArray, array('remainLoggedIn' => $remainLoggedIn), $defaultArgs);
             $session = $this->getSession();
             $session->setRemainLoggedIn($remainLoggedIn);
             $authorityIndex = $this->getArg('authority', '');
             if (!($authorityData = AuthenticationAuthority::getAuthenticationAuthorityData($authorityIndex))) {
                 //invalid authority
                 $this->redirectTo('index', $options);
             }
             if ($this->isLoggedIn($authorityIndex)) {
                 //we're already logged in
                 $this->redirectTo('index', $options);
             }
             $this->assign('authority', $authorityIndex);
             $this->assign('remainLoggedIn', $remainLoggedIn);
             $this->assign('authorityTitle', $authorityData['TITLE']);
             //if they haven't submitted the form and it's a direct login show the form
             if ($authorityData['USER_LOGIN'] == 'FORM' && empty($login)) {
                 if (!($loginMessage = $this->getOptionalModuleVar('LOGIN_DIRECT_MESSAGE'))) {
                     $loginMessage = $this->getLocalizedString('LOGIN_DIRECT_MESSAGE', Kurogo::getSiteString('SITE_NAME'));
                 }
                 $this->assign('LOGIN_DIRECT_MESSAGE', $loginMessage);
                 $this->assign('urlArray', array_merge($urlArray, $defaultArgs));
                 break;
             } elseif ($authority = AuthenticationAuthority::getAuthenticationAuthority($authorityIndex)) {
                 //indirect logins handling the login process themselves. Send a return url so the indirect authority can come back here
                 if ($authorityData['USER_LOGIN'] == 'LINK') {
                     $options['return_url'] = FULL_URL_BASE . $this->configModule . '/login?' . http_build_query(array_merge($options, array('authority' => $authorityIndex)));
                 }
                 $options['startOver'] = $this->getArg('startOver', 0);
                 $result = $authority->login($login, $password, $session, $options);
             } else {
                 $this->redirectTo('index', $options);
             }
             switch ($result) {
                 case AUTH_OK:
                     $user = $this->getUser($authority);
                     $this->setLogData($user, $user->getFullName());
                     $this->logView();
                     if ($urlArray) {
                         self::redirectToArray(array_merge($urlArray, $defaultArgs));
                     } else {
                         $this->redirectToModule($this->getHomeModuleID(), '', array('login' => $authorityIndex));
                     }
                     break;
                 case AUTH_OAUTH_VERIFY:
                     // authorities that require a manual oauth verification key
                     $this->assign('verifierKey', $authority->getVerifierKey());
                     $this->setTemplatePage('oauth_verify.tpl');
                     break 2;
                 default:
                     //there was a problem.
                     if ($authorityData['USER_LOGIN'] == 'FORM') {
                         $this->assign('message', $this->getLocalizedString('ERROR_LOGIN_DIRECT'));
                         break 2;
                     } else {
                         $this->redirectTo('index', array_merge(array('messagekey' => 'ERROR_LOGIN_INDIRECT'), $options, $defaultArgs));
                     }
             }
         case 'index':
             //sometimes messages are passed. This probably has some
             if ($messagekey = $this->getArg('messagekey')) {
                 $this->assign('messagekey', $this->getLocalizedString($messagekey));
                 try {
                     $message = $this->getLocalizedString($messagekey);
                     $this->assign('message', $message);
                 } catch (KurogoException $e) {
                 }
             }
             if ($this->isLoggedIn()) {
                 //if the url is set then redirect
                 if ($urlArray) {
                     self::redirectToArray(array_merge($urlArray, $defaultArgs));
                 }
                 //if there is only 1 authority then redirect to logout confirm
                 if (!$multipleAuthorities) {
                     $user = $this->getUser();
                     $this->redirectTo('logoutConfirm', array_merge(array('authority' => $user->getAuthenticationAuthorityIndex()), $defaultArgs));
                 }
                 //more than 1 authority. There could be 1 or more actual logged in users
                 $sessionUsers = $session->getUsers();
                 $users = array();
                 //cycle through the logged in users to build a list
                 foreach ($sessionUsers as $authorityIndex => $user) {
                     $authority = $user->getAuthenticationAuthority();
                     $users[] = array('class' => $authority->getAuthorityClass(), 'title' => count($sessionUsers) > 1 ? $this->getLocalizedString("SIGN_OUT_AUTHORITY", array($authority->getAuthorityTitle(), $user->getFullName())) : $this->getLocalizedString('SIGN_OUT'), 'subtitle' => count($sessionUsers) > 1 ? $this->getLocalizedString('SIGN_OUT') : '', 'url' => $this->buildBreadcrumbURL('logout', array('authority' => $authorityIndex), false));
                     //remove the authority from the list of available authorities (since they are logged in)
                     if (isset($authenticationAuthorities['direct'][$authorityIndex])) {
                         unset($authenticationAuthorities['direct'][$authorityIndex]);
                     }
                     if (isset($authenticationAuthorities['indirect'][$authorityIndex])) {
                         unset($authenticationAuthorities['indirect'][$authorityIndex]);
                     }
                 }
                 $this->assign('users', $users);
                 // navlist of users
                 $this->assign('authenticationAuthorities', $authenticationAuthorities);
                 //list of authorities not logged in
                 $this->assign('moreAuthorities', count($authenticationAuthorities['direct']) + count($authenticationAuthorities['indirect']));
                 //see if there are any left
                 if (count($sessionUsers) == 1) {
                     //there's only on logged in user
                     $user = current($sessionUsers);
                     $authority = $user->getAuthenticationAuthority();
                     $this->assign('LOGIN_SIGNED_IN_MESSAGE', $this->getLocalizedString('LOGIN_SIGNED_IN_SINGLE', Kurogo::getSiteString('SITE_NAME'), $authority->getAuthorityTitle(), $user->getFullName()));
                 } else {
                     //there are multiple logged in users
                     $this->assign('LOGIN_SIGNED_IN_MESSAGE', $this->getLocalizedString('LOGIN_SIGNED_IN_MULTIPLE', array(Kurogo::getSiteString('SITE_NAME'))));
                 }
                 //use loggedin.tpl
                 $this->setTemplatePage('loggedin');
             } else {
                 // not logged in
                 // if there is only 1 direct authority then redirect to the login page for that authority
                 if (!$multipleAuthorities && count($authenticationAuthorities['direct'])) {
                     $this->redirectTo('login', array_merge($urlArray, array('authority' => key($authenticationAuthorities['direct'])), $defaultArgs));
                 }
                 // if there is only 1 auto authority then redirect to the login page for that authority
                 if (!$multipleAuthorities && count($authenticationAuthorities['auto']) && !$messagekey) {
                     $this->redirectTo('login', array_merge($urlArray, array('authority' => key($authenticationAuthorities['auto'])), $defaultArgs));
                 }
                 // do we have any indirect authorities?
                 if (count($authenticationAuthorities['indirect'])) {
                     if (!($indirectMessage = $this->getOptionalModuleVar('LOGIN_INDIRECT_MESSAGE'))) {
                         $indirectMessage = $this->getLocalizedString('LOGIN_INDIRECT_MESSAGE', Kurogo::getSiteString('SITE_NAME'));
                     }
                     $this->assign('LOGIN_INDIRECT_MESSAGE', $indirectMessage);
                 }
                 // the site can create their own message at the top, or it will use the default message
                 if (!($loginMessage = $this->getOptionalModuleVar('LOGIN_INDEX_MESSAGE'))) {
                     if ($multipleAuthorities) {
                         $loginMessage = $this->getLocalizedString('LOGIN_INDEX_MESSAGE_MULTIPLE', Kurogo::getSiteString('SITE_NAME'));
                     } else {
                         $loginMessage = $this->getLocalizedString('LOGIN_INDEX_MESSAGE_SINGLE', Kurogo::getSiteString('SITE_NAME'));
                     }
                 }
                 $this->assign('LOGIN_INDEX_MESSAGE', $loginMessage);
             }
             break;
     }
 }
Beispiel #26
0
 public function isPlaces()
 {
     return Kurogo::getOptionalSiteVar('USE_GOOGLE_PLACES', false, 'maps');
 }
Beispiel #27
0
 protected function initializeForPage()
 {
     switch ($this->page) {
         case 'help':
             break;
         case 'index':
             $this->setPageTitle($this->getOptionalModuleVar('pageTitle', Kurogo::getSiteString('SITE_NAME'), 'index', 'pages'));
             if ($this->pagetype == 'tablet') {
                 $modulePanes = $this->getTabletModulePanes();
                 $this->assign('modulePanes', $modulePanes);
                 $this->addInlineJavascript('var homePortlets = {};');
                 $this->addOnLoad('loadModulePages(' . json_encode($modulePanes) . ');');
                 $this->addOnOrientationChange('moduleHandleWindowResize();');
             } else {
                 $this->assign('modules', $this->getAllModuleNavigationData(self::EXCLUDE_HIDDEN_MODULES));
                 $this->assign('hideImages', $this->getOptionalModuleVar('HIDE_IMAGES', false));
             }
             if ($this->getOptionalModuleVar('BANNER_ALERT', false, 'notice')) {
                 $noticeData = $this->getOptionalModuleSection('notice');
                 if ($noticeData) {
                     $bannerNotice = null;
                     // notice can either take a module or data model class or retriever class. The section is passed on. It must implement the HomeAlertInterface interface
                     if (isset($noticeData['BANNER_ALERT_MODULE'])) {
                         $moduleID = $noticeData['BANNER_ALERT_MODULE'];
                         $controller = WebModule::factory($moduleID);
                         $string = "Module {$moduleID}";
                     } elseif (isset($noticeData['BANNER_ALERT_MODEL_CLASS'])) {
                         $controller = DataModel::factory($noticeData['BANNER_ALERT_MODEL_CLASS'], $noticeData);
                         $string = $noticeData['BANNER_ALERT_MODEL_CLASS'];
                     } elseif (isset($noticeData['BANNER_ALERT_RETRIEVER_CLASS'])) {
                         $controller = DataRetriever::factory($noticeData['BANNER_ALERT_RETRIEVER_CLASS'], $noticeData);
                         $string = $noticeData['BANNER_ALERT_RETRIEVER_CLASS'];
                     } else {
                         throw new KurogoConfigurationException("Banner alert not properly configured");
                     }
                     if (!$controller instanceof HomeAlertInterface) {
                         throw new KurogoConfigurationException("{$string} does not implement HomeAlertModule interface");
                     }
                     $bannerNotice = $controller->getHomeScreenAlert();
                     if ($bannerNotice) {
                         $this->assign('bannerNotice', $bannerNotice);
                         // is this necessary?
                         $bannerModule = $this->getOptionalModuleVar('BANNER_ALERT_MODULE_LINK', false, 'notice');
                         if ($bannerModule) {
                             $this->assign('bannerURL', $this->buildURLForModule($moduleID, 'index'));
                         }
                     }
                 }
             }
             if ($this->getOptionalModuleVar('SHOW_FEDERATED_SEARCH', true)) {
                 $this->assign('showFederatedSearch', true);
                 $this->assign('placeholder', $this->getLocalizedString("SEARCH_PLACEHOLDER", Kurogo::getSiteString('SITE_NAME')));
             }
             if ($this->getPlatform() == 'iphone' && $this->getOptionalModuleVar('ADD_TO_HOME', false)) {
                 $this->addInternalJavascript('/common/javascript/lib/add2homeConfig.js');
                 $this->addInternalJavascript('/common/javascript/lib/add2home.js');
                 $this->addInternalCSS('/common/css/add2home.css');
             }
             $this->assignUserContexts($this->getOptionalModuleVar('ALLOW_CUSTOMIZE', true));
             $this->assign('SHOW_DOWNLOAD_TEXT', Kurogo::getOptionalSiteVar('downloadText', '', $this->platform, 'apps'));
             $homeModuleID = $this->getHomeModuleID();
             if ($iconSet = $this->getOptionalThemeVar('navigation_icon_set')) {
                 $iconSetSize = $this->getOptionalThemeVar('navigation_icon_size');
                 $downloadImgPrefix = "/common/images/iconsets/{$iconSet}/{$iconSetSize}/download";
             } else {
                 $downloadImgPrefix = "/modules/{$homeModuleID}/images/download";
             }
             $this->assign('downloadImgPrefix', $downloadImgPrefix);
             $this->assign('displayType', $this->getModuleVar('display_type'));
             break;
         case 'search':
             $searchTerms = $this->getArg('filter');
             $useAjax = $this->pagetype != 'basic';
             $searchModules = array();
             if ($this->getOptionalModuleVar('SHOW_FEDERATED_SEARCH', true)) {
                 $this->assign('showFederatedSearch', true);
                 foreach ($this->getAllModuleNavigationData(self::EXCLUDE_HIDDEN_MODULES) as $type => $modules) {
                     foreach ($modules as $id => $info) {
                         if ($id == 'customize') {
                             continue;
                         }
                         $module = self::factory($id);
                         if ($module->getOptionalModuleVar('search', false, 'module')) {
                             $searchModule = array('id' => $id, 'elementId' => 'federatedSearchModule_' . $id, 'title' => $info['title']);
                             if ($useAjax) {
                                 $searchModule['ajaxURL'] = FULL_URL_PREFIX . ltrim($this->buildURL('searchResult', array('id' => $id, 'filter' => $searchTerms)), '/');
                             } else {
                                 $searchModule['results'] = $this->runFederatedSearchForModule($module, $searchTerms);
                             }
                             $searchModules[] = $searchModule;
                         }
                     }
                 }
                 if ($useAjax) {
                     $this->addInternalJavascript('/common/javascript/lib/ellipsizer.js');
                     $this->addInlineJavascript('var federatedSearchModules = ' . json_encode($searchModules) . ";\n");
                     $this->addOnLoad('runFederatedSearch(federatedSearchModules);');
                 }
             }
             $this->assign('federatedSearchModules', $searchModules);
             $this->assign('searchTerms', $searchTerms);
             $this->setLogData($searchTerms);
             break;
         case 'modules':
             $configModule = $this->getArg('configModule', $this->configModule);
             $this->assign('modules', $this->getAllModuleNavigationData(self::EXCLUDE_HIDDEN_MODULES));
             $this->assign('hideImages', $this->getOptionalModuleVar('HIDE_IMAGES', false));
             $this->assign('displayType', $this->getModuleVar('display_type'));
             if ($configModule == $this->configModule && $this->getOptionalModuleVar('SHOW_FEDERATED_SEARCH', true)) {
                 $this->assign('showFederatedSearch', true);
                 $this->assign('placeholder', $this->getLocalizedString("SEARCH_PLACEHOLDER", Kurogo::getSiteString('SITE_NAME')));
             }
             $this->assignUserContexts($this->getOptionalModuleVar('ALLOW_CUSTOMIZE', true));
             break;
         case 'searchResult':
             $moduleID = $this->getArg('id');
             $searchTerms = $this->getArg('filter');
             $this->setLogData($searchTerms);
             $module = self::factory($moduleID);
             $this->assign('federatedSearchResults', $this->runFederatedSearchForModule($module, $searchTerms));
             break;
         case 'pane':
             // This wrapper exists so we can catch module errors and prevent redirection to the error page
             $moduleID = $this->getArg('id');
             try {
                 $module = self::factory($moduleID, 'pane', array(self::AJAX_PARAMETER => 1));
                 $content = $module->fetchPage();
             } catch (Exception $e) {
                 Kurogo::log(LOG_WARNING, $e->getMessage(), "home", $e->getTrace());
                 $content = '<p class="nonfocal">' . $this->getLocalizedString('ERROR_MODULE_PANE') . '</p>';
             }
             $this->assign('content', $content);
             break;
         case 'customize':
             $allowCustomize = $this->getOptionalModuleVar('ALLOW_CUSTOMIZE', true);
             $this->assign('allowCustomize', $allowCustomize);
             if (!$allowCustomize) {
                 break;
             }
             $this->handleCustomizeRequest($this->args);
             $modules = $this->getModuleCustomizeList();
             $moduleIDs = array_keys($modules);
             switch ($this->pagetype) {
                 case 'compliant':
                 case 'tablet':
                     $this->addInlineJavascript('var MODULE_NAV_COOKIE = "' . self::MODULE_NAV_COOKIE . '";' . 'var MODULE_NAV_COOKIE_LIFESPAN = ' . Kurogo::getSiteVar('MODULE_NAV_COOKIE_LIFESPAN') . ';' . 'var COOKIE_PATH = "' . COOKIE_PATH . '";');
                     $this->addInlineJavascriptFooter('init();');
                     break;
                 case 'basic':
                     foreach ($moduleIDs as $index => $id) {
                         $modules[$id]['toggleVisibleURL'] = $this->buildBreadcrumbURL('index', array('action' => $modules[$id]['visible'] ? 'off' : 'on', 'module' => $id), false);
                         if ($index > 0) {
                             $modules[$id]['swapUpURL'] = $this->buildBreadcrumbURL('index', array('action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index - 1]), false);
                         }
                         if ($index < count($moduleIDs) - 1) {
                             $modules[$id]['swapDownURL'] = $this->buildBreadcrumbURL('index', array('action' => 'swap', 'module1' => $id, 'module2' => $moduleIDs[$index + 1]), false);
                         }
                     }
                     break;
                 default:
                     break;
             }
             // show user selectable context switching
             if ($contexts = Kurogo::sharedInstance()->getContexts()) {
                 $userContextList = $this->getUserContextListData('customizemodules', false);
                 $this->assign('customizeUserContextListDescription', $this->getLocalizedString('USER_CONTEXT_LIST_DESCRIPTION'));
                 if ($this->platform == 'iphone') {
                     $this->assign('customizeUserContextListDescriptionFooter', $this->getLocalizedString('USER_CONTEXT_LIST_DESCRIPTION_FOOTER_DRAG'));
                 } else {
                     $this->assign('customizeUserContextListDescriptionFooter', $this->getLocalizedString('USER_CONTEXT_LIST_DESCRIPTION_FOOTER'));
                 }
                 $this->assign('customizeUserContextList', $userContextList);
             } else {
                 $key = 'CUSTOMIZE_INSTRUCTIONS';
                 if ($this->pagetype == 'compliant' || $this->pagetype == 'tablet') {
                     $key = 'CUSTOMIZE_INSTRUCTIONS_' . strtoupper($this->pagetype);
                     if ($this->platform == 'iphone') {
                         $key .= '_DRAG';
                     }
                 }
                 $this->assign('customizeInstructions', $this->getLocalizedString($key));
             }
             $this->assign('modules', $modules);
             break;
         case 'customizemodules':
             $modules = $this->getModuleCustomizeList();
             $this->assign('modules', $modules);
             break;
     }
 }
Beispiel #28
0
 private function getAdminData($type, $section, $subsection = null)
 {
     if (in_array($type, array('site'))) {
         $configData = $this->getSiteAdminConfig($type);
         $module = $this;
         if (is_null($section)) {
             $section = key($configData);
         }
     } elseif ($type instanceof Module) {
         $configData = $type->getModuleAdminConfig();
         $module = $type;
     } else {
         throw new KurogoConfigurationException(__LINE__ . ": Invalid type {$type}");
     }
     if (!isset($configData[$section])) {
         throw new KurogoConfigurationException(__LINE__ . ": Invalid section {$section}");
     }
     $sectionData = $configData[$section];
     if ($subsection) {
         if (!isset($configData[$section]['sections'][$subsection])) {
             throw new KurogoConfigurationException(__LINE__ . ": Invalid subsection {$subsection} for section {$section}");
         }
         $sectionData = $configData[$section]['sections'][$subsection];
     }
     $sectionData['section'] = $section;
     if (isset($sectionData['titleKey'])) {
         $sectionData['title'] = $module->getLocalizedString($sectionData['titleKey']);
         unset($sectionData['titleKey']);
     }
     if (isset($sectionData['descriptionKey'])) {
         $sectionData['description'] = $module->getLocalizedString($sectionData['descriptionKey']);
         unset($sectionData['descriptionKey']);
     }
     if (isset($sectionData['fieldgroups'])) {
         foreach ($sectionData['fieldgroups'] as $fieldgroup => &$fieldgroupData) {
             if (isset($fieldgroupData['labelKey'])) {
                 $fieldgroupData['label'] = $module->getLocalizedString($fieldgroupData['labelKey']);
                 unset($fieldgroupData['labelKey']);
             }
             if (isset($fieldgroupData['descriptionKey'])) {
                 $fieldgroupData['description'] = $module->getLocalizedString($fieldgroupData['descriptionKey']);
                 unset($fieldgroupData['descriptionKey']);
             }
         }
     }
     switch ($sectionData['sectiontype']) {
         case 'fields':
             foreach ($sectionData['fields'] as $key => &$field) {
                 $_key = isset($field['key']) ? $field['key'] : $key;
                 if (isset($field['labelKey'])) {
                     $field['label'] = $module->getLocalizedString($field['labelKey']);
                     unset($field['labelKey']);
                 }
                 if (isset($field['descriptionKey'])) {
                     $field['description'] = $module->getLocalizedString($field['descriptionKey']);
                     unset($field['descriptionKey']);
                 }
                 if (isset($field['value'])) {
                     // value is set. used typically for hidden fields
                 } elseif (isset($field['valueMethod'])) {
                     if (is_array($field['valueMethod'])) {
                         $method = array_shift($field['valueMethod']);
                         $field['value'] = call_user_func_array(array($module, $method), $field['valueMethod']);
                     } else {
                         $field['value'] = call_user_func(array($module, $field['valueMethod']));
                     }
                     if (is_null($field['value']) && isset($field['default'])) {
                         $field['value'] = $field['default'];
                     }
                     unset($field['valueMethod']);
                 } elseif (isset($field['valueKey'])) {
                     $field['value'] = $module->getLocalizedString($field['valueKey']);
                     unset($field['valueKey']);
                 } elseif (in_array($type, array('site'))) {
                     if (isset($field['config'])) {
                         switch ($field['config']) {
                             case 'site':
                             case 'kurogo':
                                 $field['value'] = Kurogo::getOptionalSiteVar($_key, '', $field['section']);
                                 break;
                             case 'strings':
                                 $field['value'] = Kurogo::getOptionalSiteString($_key);
                                 break;
                             default:
                                 throw new KurogoConfigurationException(__LINE__ . ": Unknown config " . $field['config']);
                                 break;
                         }
                     }
                 } elseif (isset($field['config'], $field['section'])) {
                     $field['value'] = $module->getOptionalModuleVar($_key, isset($field['default']) ? $field['default'] : '', $field['section'], $field['config']);
                 }
                 switch ($field['type']) {
                     case 'paragraph':
                         if (is_array($field['value'])) {
                             $field['value'] = implode("\n\n", $field['value']);
                         }
                         break;
                     case 'select':
                         if (isset($field['optionsMethod'])) {
                             if (is_array($field['optionsMethod'])) {
                                 $field['options'] = call_user_func($field['optionsMethod']);
                             } else {
                                 $field['options'] = $module->{$field}['optionsMethod']();
                             }
                             unset($field['optionsMethod']);
                         }
                         if (isset($field['optionsFirst'])) {
                             $field['options'] = array_merge(array('' => $field['optionsFirst']), $field['options']);
                             unset($field['optionsFirst']);
                         }
                 }
                 if (isset($field['value'])) {
                     $useConstant = isset($field['useConstant']) ? $field['useConstant'] : true;
                     if ($useConstant) {
                         $value = $this->getUnconstantedValue($field['value'], $constant);
                         if ($constant) {
                             $field['value'] = $value;
                             $field['constant'] = $constant;
                         }
                     }
                 }
                 if (isset($field['enabledMethod'])) {
                     if (is_array($field['enabledMethod'])) {
                         $field['enabled'] = call_user_func($field['enabledMethod']);
                     } else {
                         $field['enabled'] = $module->{$field}['enabledMethod']();
                     }
                     unset($field['enabledMethod']);
                 }
             }
             break;
         case 'section':
             if (isset($sectionData['sectionsmethod'])) {
                 if (is_array($sectionData['sectionsmethod'])) {
                     $sectionData['sections'] = call_user_func($sectionData['sectionsmethod']);
                 } else {
                     $sectionData['sections'] = $module->{$sectionData}['sectionsmethod']();
                 }
                 $sectionindex = isset($sectionData['sectionindex']) ? $sectionData['sectionindex'] : null;
                 if ($sectionindex == 'numeric') {
                     $sectionData['sections'] = array_values($sectionData['sections']);
                 }
                 unset($sectionData['sectionsmethod']);
             } elseif (in_array($type, array('site'))) {
                 throw new KurogoConfigurationException(__LINE__ . ": Getting sections for {$type} is not written yet");
             } else {
                 $configMode = isset($sectionData['configMode']) ? $sectionData['configMode'] : 0;
                 $sectionData['sections'] = $module->getModuleSections($sectionData['config']);
             }
             if (isset($sectionData['sectionsnoneKey'])) {
                 $sectionData['sectionsnone'] = $module->getLocalizedString($sectionData['sectionsnoneKey']);
                 unset($sectionData['sectionsnoneKey']);
             }
             if (isset($sectionData['sectionaddpromptkey'])) {
                 $sectionData['sectionaddprompt'] = $module->getLocalizedString($sectionData['sectionaddpromptkey']);
                 unset($sectionData['sectionaddpromptkey']);
             }
             foreach ($sectionData['fields'] as $key => &$field) {
                 if (isset($field['labelKey'])) {
                     $field['label'] = $module->getLocalizedString($field['labelKey']);
                     unset($field['labelKey']);
                 }
                 if (isset($field['descriptionKey'])) {
                     $field['description'] = $module->getLocalizedString($field['descriptionKey']);
                     unset($field['descriptionKey']);
                 }
                 if (isset($field['valueKey'])) {
                     $field['value'] = $module->getLocalizedString($field['valueKey']);
                     unset($field['valueKey']);
                 }
                 switch ($field['type']) {
                     case 'select':
                         if (isset($field['optionsMethod'])) {
                             if (is_array($field['optionsMethod'])) {
                                 $field['options'] = call_user_func($field['optionsMethod']);
                             } else {
                                 $field['options'] = $module->{$field}['optionsMethod']();
                             }
                             unset($field['optionsMethod']);
                         }
                         if (isset($field['optionsFirst'])) {
                             $field['options'] = array_merge(array('' => $field['optionsFirst']), $field['options']);
                             unset($field['optionsFirst']);
                         }
                 }
             }
             foreach ($sectionData['sections'] as $section => &$sectionFields) {
                 foreach ($sectionFields as $key => &$value) {
                     if (isset($sectionData['fields'][$key]['type']) && $sectionData['fields'][$key]['type'] == 'paragraph') {
                         $value = implode("\n\n", $value);
                     }
                     $v = $this->getUnconstantedValue($value, $constant);
                     if ($constant) {
                         $value = array($constant, $v, $value);
                     }
                 }
             }
             break;
         case 'sections':
             foreach ($sectionData['sections'] as $subsection => &$_sectionData) {
                 $subsectionData = $this->getAdminData($type, $section, $subsection);
                 if (isset($subsectionData['showIfSiteVar'])) {
                     if (Kurogo::getOptionalSiteVar($subsectionData['showIfSiteVar'][0], '') != $subsectionData['showIfSiteVar'][1]) {
                         unset($sectionData['sections'][$subsection]);
                         continue;
                     }
                 }
                 if (isset($subsectionData['showIfModuleVar'])) {
                     if ($type->getOptionalModuleVar($subsectionData['showIfModuleVar'][0], '') != $subsectionData['showIfModuleVar'][1]) {
                         unset($sectionData['sections'][$subsection]);
                         continue;
                     }
                 }
                 $sectionData['sections'][$subsection] = $subsectionData;
             }
             break;
         default:
             throw new KurogoConfigurationException(__LINE__ . ": Section type " . $sectionData['sectiontype'] . " not understood for section {$section}");
     }
     return $sectionData;
 }
Beispiel #29
0
 protected function initializeForPage()
 {
     if (!Kurogo::getOptionalSiteVar('STATS_ENABLED', true)) {
         throw new KurogoException($this->getLocalizedString('STATS_DISABLED'));
     }
     if ($this->page == 'updateStats') {
         KurogoStats::exportStatsData();
         $this->redirectTo('index');
     }
     if ($this->getOptionalModuleVar('AUTO_UPDATE_STATS')) {
         KurogoStats::exportStatsData();
     }
     $serviceTypes = $this->getServiceTypes();
     $service = $this->getArg('service', 'web');
     if (!array_key_exists($service, $serviceTypes)) {
         $service = 'web';
     }
     $interval_types = $this->getIntervalTypes();
     $interval = $this->getArg('interval', 'day');
     if (!array_key_exists($interval, $interval_types)) {
         $interval = 'day';
     }
     if ($interval == 'custom') {
         $start = $this->getArg('start');
         $startTime = $start ? mktime(0, 0, 0, $start['Month'], $start['Day'], $start['Year']) : mktime(0, 0, 0);
         $end = $this->getArg('end', array());
         $endTime = $end ? mktime(23, 59, 59, $end['Month'], $end['Day'], $end['Year']) : mktime(23, 59, 59);
         if ($endTime < $startTime) {
             $endTime = $startTime;
         }
     } else {
         $times = $this->getTimesForInterval($interval, $interval_types[$interval]['duration']);
         $startTime = $times['start'];
         $endTime = $times['end'];
     }
     $intervalOptions = array();
     $args = $this->args;
     $args['service'] = $service;
     $args['interval'] = $interval;
     foreach ($interval_types as $interval_type => $type) {
         $args['interval'] = $interval_type;
         $intervalOptions[$interval_type] = array('title' => $type['title'], 'selected' => $interval_type == $interval, 'url' => $this->buildbreadcrumbURL($this->page, $args, false));
     }
     $args = $this->args;
     $args['service'] = $service;
     $args['interval'] = $interval;
     foreach ($serviceTypes as $serviceType => $serviceTypeTitle) {
         $args['service'] = $serviceType;
         $serviceOptions[$serviceType] = array('title' => $serviceTypeTitle, 'selected' => $service == $serviceType, 'url' => $this->buildbreadcrumbURL($this->page, $args, false));
     }
     $this->assign('starttime', $startTime);
     $this->assign('endtime', $endTime);
     $this->assign('statsService', $service);
     $this->assign('interval', $interval);
     $this->assign('intervalOptions', $intervalOptions);
     $this->assign('serviceOptions', $serviceOptions);
     $this->assign('intervalTabclass', count($interval_types) == 4 ? 'fourtabs' : 'threetabs');
     $this->assign('serviceTabclass', 'twotabs');
     $commonData = array('service' => $service, 'start' => $startTime, 'end' => $endTime);
     if ($date = KurogoStats::getLastDateFromSummary()) {
         includePackage('DateTime');
         $date = new DateTime($date);
         $this->assign('lastUpdated', DateFormatter::formatDate($date, DateFormatter::LONG_STYLE, DateFormatter::NO_STYLE));
     }
     switch ($this->page) {
         case 'index':
             //get config
             $chartsConfig = $this->getModuleSections('stats-index');
             $charts = array();
             foreach ($chartsConfig as $chartIndex => $chartData) {
                 try {
                     $charts[] = $this->prepareChart(array_merge($chartData, $commonData), $interval);
                 } catch (KurogoStatsConfigurationException $e) {
                     $this->redirectTo('statsconfigerror', array('chart' => $chartData['title']));
                 }
             }
             $this->assign('charts', $charts);
             break;
         case 'detail':
             if (!($group = $this->getArg('group'))) {
                 $this->redirectTo('index');
             }
             if (!(${$group} = $this->getArg($group))) {
                 $this->redirectTo('index');
             }
             if (!($chartsConfig = $this->getChartsConfig($group, ${$group}))) {
                 $this->redirectTo('index');
             }
             $charts = array();
             $commonData[$group] = ${$group};
             foreach ($chartsConfig as $chartIndex => $chartData) {
                 try {
                     $charts[] = $this->prepareChart(array_merge($chartData, $commonData), $interval);
                 } catch (KurogoStatsConfigurationException $e) {
                     $this->redirectTo('statsconfigerror', array('chart' => $chartData['title']));
                 }
             }
             $this->setPageTitle(sprintf("Stats for %s", ${$group}));
             $this->assign('charts', $charts);
             break;
         case 'statsconfigerror':
             $this->assign('chart', $this->getArg('chart'));
             break;
     }
 }
Beispiel #30
0
 protected function detectDeviceInternal($user_agent)
 {
     Kurogo::log(LOG_INFO, "Detecting device using internal device detection", 'deviceDetection');
     if (!$user_agent) {
         return;
     }
     /*
      * Two things here:
      * First off, we now have two files which can be used to classify devices,
      * the master file, usually at LIB_DIR/deviceData.json, and the custom file,
      * usually located at DATA_DIR/deviceData.json.
      *
      * Second, we're still allowing the use of sqlite databases (despite it
      * being slower and more difficult to update).  So, if you specify the
      * format of the custom file as sqlite, it should still work.
      */
     $master_file = LIB_DIR . "/deviceData.json";
     $site_file = Kurogo::getOptionalSiteVar('MOBI_SERVICE_SITE_FILE');
     $site_file_format = Kurogo::getOptionalSiteVar('MOBI_SERVICE_SITE_FORMAT', 'json');
     if (!($site_file && $site_file_format)) {
         // We don't have a site-specific file.  This means we can only
         // detect on the master file.
         $site_file = "";
     }
     if (!empty($site_file) && ($site_file = realpath_exists($site_file))) {
         switch ($site_file_format) {
             case 'json':
                 $site_devices = json_decode(file_get_contents($site_file), true);
                 $site_devices = $site_devices['devices'];
                 if (($error_code = json_last_error()) !== JSON_ERROR_NONE) {
                     throw new KurogoConfigurationException("Problem decoding Custom Device Detection File. Error code returned was " . $error_code);
                 }
                 if (($device = $this->checkDevices($site_devices, $user_agent)) !== false) {
                     return $this->translateDevice($device);
                 }
                 break;
             case 'sqlite':
                 Kurogo::includePackage('db');
                 try {
                     $db = new db(array('DB_TYPE' => 'sqlite', 'DB_FILE' => $site_file));
                     $result = $db->query('SELECT * FROM userAgentPatterns WHERE version<=? ORDER BY patternorder,version DESC', array($this->version));
                 } catch (Exception $e) {
                     Kurogo::log(LOG_ALERT, "Error with internal device detection: " . $e->getMessage(), 'deviceDetection');
                     if (!in_array('sqlite', PDO::getAvailableDrivers())) {
                         die("SQLite PDO drivers not available. You should switch to external device detection by changing MOBI_SERVICE_USE_EXTERNAL to 1 in " . SITE_CONFIG_DIR . "/site.ini");
                     }
                     return false;
                 }
                 while ($row = $result->fetch()) {
                     if (preg_match("#" . $row['pattern'] . "#i", $user_agent)) {
                         return $row;
                     }
                 }
                 break;
             default:
                 throw new KurogoConfigurationException('Unknown format specified for Custom Device Detection File: ' . $site_file_format);
         }
     }
     if (!empty($master_file) && ($master_file = realpath_exists($master_file))) {
         $master_devices = json_decode(file_get_contents($master_file), true);
         $master_devices = $master_devices['devices'];
         if (function_exists('json_last_error') && ($error_code = json_last_error()) !== JSON_ERROR_NONE) {
             Kurogo::log(LOG_ALERT, "Error with JSON internal device detection: " . $error_code, 'deviceDetection');
             die("Problem decoding Device Detection Master File. Error code returned was " . $error_code);
         }
         if (($device = $this->checkDevices($master_devices, $user_agent)) !== false) {
             return $this->translateDevice($device);
         }
     }
     Kurogo::log(LOG_WARNING, "Could not find a match in the internal device detection database for: {$user_agent}", 'deviceDetection');
 }