36 ini_set(
"short_open_tag", 1);
38 register_shutdown_function(array(
'Fakoli',
'shutdownHandler'));
40 require_once realpath(dirname(__FILE__).
"/../framework/data_item.inc");
41 require_once realpath(dirname(__FILE__).
"/../framework/cache.inc");
42 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component.inc");
45 $fontawesome =
"https://use.fontawesome.com/releases/v5.1.1/css/all.css";
116 static function using()
120 $num = func_num_args();
121 for($i = 0; $i < $num; ++$i)
129 $includes = Cache::get(
"fakoli_includes_$component");
132 if (
$config[
'strict_includes'])
134 foreach ($includes as $include)
136 require_once $include;
141 foreach ($includes as $include)
143 include_once $include;
153 trace(
"Attempt to reference unknown or disabled component '$component'", 2);
161 $dm =
$c->component_path . DIRECTORY_SEPARATOR .
"datamodel";
164 $handle = opendir($dm);
165 while(
false !== (
$file = readdir($handle)))
167 if (endsWith(
$file,
".inc"))
169 $f = $dm . DIRECTORY_SEPARATOR .
$file;
179 trace(
$c->component_path, 4);
181 $handle = opendir(
$c->component_path);
183 if (!$handle)
continue;
185 while(
false !== (
$file = readdir($handle)))
187 if (endsWith(
$file,
".inc"))
189 $f =
$c->component_path . DIRECTORY_SEPARATOR .
$file;
198 Cache::put(
"fakoli_includes_$component", $includes);
259 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component.inc");
260 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component_page.inc");
261 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/admin_page.inc");
262 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component_update_log.inc");
263 require_once realpath(dirname(__FILE__).
"/components/component/serialization_manager.inc");
264 require_once realpath(dirname(__FILE__).
"/components/component/component_manager.inc");
265 require_once realpath(dirname(__FILE__).
"/components/component/upgrade_manager.inc");
266 require_once realpath(dirname(__FILE__).
"/components/component/component_upgrade_manager.inc");
278 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component.inc");
279 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component_page.inc");
280 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/admin_page.inc");
281 require_once realpath(dirname(__FILE__).
"/components/component/datamodel/component_update_log.inc");
282 require_once realpath(dirname(__FILE__).
"/components/component/serialization_manager.inc");
283 require_once realpath(dirname(__FILE__).
"/components/component/component_manager.inc");
284 require_once realpath(dirname(__FILE__).
"/components/component/upgrade_manager.inc");
285 require_once realpath(dirname(__FILE__).
"/components/component/component_upgrade_manager.inc");
311 $mgr->storeRedirectPage();
352 if (method_exists(
$mgr,
"isActive"))
return $mgr->isActive(
$user);
353 if (
$user->hasField(
"active"))
return $user->active;
363 return ($ip) ? $ip : $_SERVER[
"SERVER_ADDR"];
371 $num = func_num_args();
373 for($i = 0; $i < $num; ++$i)
375 $file = func_get_arg($i);
377 $f = realpath(dirname(__FILE__).
"/../$file");
390 $num = func_num_args();
392 for($i = 0; $i < $num; ++$i)
394 $file = func_get_arg($i);
396 $f = realpath(dirname(__FILE__).
"/../framework/{$file}.inc");
407 $menu = Cache::get(
"fakoli_admin_menu");
410 $menu = array(
"Site Content" => array(),
411 "Site Configuration" => array(),
412 "Collaboration" => array(),
413 "Classification" => array(),
414 "Email Management" => array(),
415 "User Management" => array());
423 $componentMenuItems = $manifest->getAdminMenu();
424 if ($componentMenuItems)
426 foreach($componentMenuItems as $category =>
$items)
428 if (!
$menu[$category])
446 Cache::put(
"fakoli_admin_menu",
$menu);
458 $icons = Cache::get(
"fakoli_admin_icons");
459 if ($icons)
return $icons;
461 $icons = array(
"Site Content" =>
"file-alt",
462 "Site Configuration" =>
"cogs",
463 "Collaboration" =>
"comments",
464 "Classification" =>
"tags",
465 "Email Management" =>
"envelope",
466 "User Management" =>
"users",
468 "Public Site" =>
"home"
473 Cache::put(
"fakoli_admin_icons", $icons);
477 private static function getAdminPageRoles()
479 $pageRoles = Cache::get(
"fakoli_admin_page_roles");
480 if ($pageRoles)
return $pageRoles;
482 $pageRoles = array();
488 if (method_exists($manifest,
"getAdminPageRoles"))
490 $pageRoles = array_merge($pageRoles, $manifest->getAdminPageRoles());
494 Cache::put(
"fakoli_admin_page_roles", $pageRoles);
515 $uri =
"/admin/$identifier";
523 if ($item[
"page"] ==
$uri)
527 $role = $item[
"role"];
534 trace(
"###Role: $role", 3);
536 $pageRoles = Fakoli::getAdminPageRoles();
537 trace(print_r($pageRoles,
true), 3);
539 if ($pageRoles[
$uri])
544 trace(
"###ADMIN PAGE ROLE: $identifier $role", 3);
548 private static $includedScripts = array();
556 $scripts = Cache::get(
"fakoli_scripts");
557 if ($scripts)
return $scripts;
560 foreach($scriptArray as $s)
562 Fakoli::$includedScripts[$s] =
true;
568 foreach($scriptArray as $s)
570 $scripts .=
" <script type='text/javascript' src='$s'></script>\n";
573 Cache::put(
"fakoli_scripts", $scripts);
583 $scriptArray = array();
592 $scriptArray = array_merge($scriptArray, array_diff($manifest->getScripts(), $scriptArray));
605 $styles = Cache::get(
"fakoli_styles");
612 foreach($styleArray as $s)
614 $styles .=
" <link href='$s' rel='stylesheet' type='text/css' media='all'/>\n";
617 Cache::put(
"fakoli_styles",
$styles);
627 $styleArray = array();
636 $styleArray = array_merge($styleArray, array_diff($manifest->getStyles(), $styleArray));
661 global $menu_identifier;
667 $codePath = explode(
",", $filePath);
668 if (count($codePath) == 2)
670 $name = $codePath[0];
671 $php_code_file = $codePath[1];
677 trace(
"Evaluating $path", 3);
688 if (preg_match(
'/^\/components\/(.*?)\//', $filePath, $matches))
691 $path = str_replace(
"/components/{$c}",
"", $filePath);
701 include
$config[
'homedir'].
"/{$filePath}";
718 if (!array_key_exists(
$src, Fakoli::$includedScripts))
720 $script .=
"<script type='text/javascript' src='$src'></script>\n";
721 Fakoli::$includedScripts[
$src] =
true;
733 $styles .=
"<link href='$src' rel='stylesheet' type='text/css' media='$media'/>\n";
744 return $item1[
"weight"] - $item2[
"weight"];
754 return str_replace(
" ",
"", prettify(
$name));
784 $mimeType = DocumentHandler::getMIMEType($resource);
786 if(array_key_exists(
"HTTP_IF_MODIFIED_SINCE",$_SERVER))
789 $if_modified_since=strtotime($_SERVER[
"HTTP_IF_MODIFIED_SINCE"]);
794 header(
"HTTP/1.0 304 Not Modified");
799 header(
"Content-Type: $mimeType");
801 header(
"Cache-Control: max-age=300, must-revalidate");
802 header(
"Pragma: private");
803 header(
"Expires: " . date(DATE_RFC822,strtotime(
" 2 day")));
809 header(
"X-SendFile: $resource");
814 $f = fopen($resource,
"r");
816 $size = filesize($resource);
817 header(
"Content-Length: $size");
836 if (function_exists(
"apache_get_modules"))
838 $support = in_array(
'mod_xsendfile', apache_get_modules());
854 if (strpos(
"../", $resource) !== FALSE)
859 if (endsWith($resource,
".inc") || endsWith($resource,
".php"))
861 header(
"HTTP/1.0 403 Forbidden");
865 $resource = sanitizePath($resource);
867 $dir = dirname($resource);
870 if (
$dir ==
"datamodel" ||
$dir ==
"updates" ||
$dir ==
"admin")
return null;
878 throw new FakoliException(
"Attempt to reference unknown or disabled component '$component'");
883 $file =
$c->component_path . DIRECTORY_SEPARATOR . $resource;
888 $file = Cache::get(
"resource:$resource");
891 $path =
$config[
'homedir'] . PATH_SEPARATOR . ini_get(
"include_path");
894 $roots = explode(PATH_SEPARATOR,
$path);
896 foreach($roots as
$root)
898 $file = sanitizePath(
$root . DIRECTORY_SEPARATOR . $resource);
899 if (file_exists(
$file))
901 Cache::put(
"resource:$resource",
$file);
905 $file = sanitizePath(
$root . DIRECTORY_SEPARATOR .
"cms" . DIRECTORY_SEPARATOR . $resource);
906 if (file_exists(
$file))
908 Cache::put(
"resource:$resource",
$file);
915 $file = sanitizePath(
$c->component_path . DIRECTORY_SEPARATOR . $resource);
916 if (file_exists(
$file))
918 Cache::put(
"resource:$resource",
$file);
923 trace(
"Cannot resolve $file", 2);
952 return $target->format($template);
961 $https = $_SERVER[
'HTTPS'];
962 if ($https ==
"off") $https =
false;
963 if (isset($_SERVER[
'HTTP_X_FORWARDED_PROTO']) && $_SERVER[
'HTTP_X_FORWARDED_PROTO'] ===
'https')
980 trace(
"Send Page: '$sectionIdentifier', '$identifier', '$page_id'", 2);
984 if (!$sectionIdentifier) $sectionIdentifier =
"/";
986 if ($sectionIdentifier ==
"/" &&
$identifier ==
"admin")
988 redirect(
"/admin/index");
1007 throw new FakoliException(
"The section you were attempting to access could not be found.");
1015 redirect(
$url.$contentManager->getDefaultPage(
$section));
1028 throw new FakoliException(
"The page you were attempting to access could not be found.");
1034 trace(
"Checking Permissions: [{$permissions}]", 4);
1045 trace(
"\$_SERVER['HTTPS'] = {$_SERVER['HTTPS']}", 3);
1046 trace(
"\$_SERVER['REQUEST_URI'] = {$_SERVER['REQUEST_URI']}", 3);
1052 if ($useSSL && !$https )
1054 redirect(
"https://".
$config[
'http_host'].$_SERVER[
'REQUEST_URI']);
1056 else if (!$useSSL && $https &&
$identifier !=
"login" && !isset($_REQUEST[
"login"]))
1058 redirect(
"http://".
$config[
'http_host'].$_SERVER[
'REQUEST_URI']);
1067 echo $exit->getMessage();
1087 $sessions = scandir(ini_get(
"session.save_path"));
1088 trace(
"SESSIONS: ".print_r($session,
true), 1);
1089 $number_of_users = count(
$sessions) - 2;
1090 return $number_of_users;
1111 if (
$config[
'admin_SSL'] && !$https )
1113 redirect(
"https://".
$config[
'http_host'].$_SERVER[
'REQUEST_URI']);
1125 $reflector =
new ReflectionClass(
$class);
1126 $file = $reflector->getFileName();
1127 trace(
"File for $class: $file", 3);
1131 $file = str_replace(DIRECTORY_SEPARATOR,
"/",
$file);
1134 if (preg_match(
"/components\\/(.*?)\\//",
$file, $matches))
1136 trace(
"Component for $class is {$matches[1]}", 3);
1141 throw new FakoliException(
"Failed to determine component for $class");
1160 static function JSONreturn($object, $sendType =
true, $wrap =
true)
1162 if ($sendType) header(
"Content-Type: application/json");
1163 if (method_exists($object,
"toJSON"))
1165 $out = ($wrap) ?
'{"result": '.$object->toJSON().
'}' : $object->toJSON();
1169 $out = ($wrap) ?
'{"result": '.json_encode($object).
'}' : json_encode($object);
1182 if ($sendType) header(
"Content-Type: application/json");
1184 $errorObject = (object)array(
'error' =>
$error);
1204 $options =
", {blocking: true, buttonText: '$button', onClick: $onClick}";
1209 <script type=
'text/javascript'>
1210 window.addEvent(
'load',
function()
1226 $_SESSION[
"notification_pending_blocking"] = $blocking;
1228 $_SESSION[
"notification_pending_onclick"] = $onClick;
1242 $_SESSION[
"notification_pending_blocking"],
1243 $_SESSION[
"notification_pending_button"],
1244 $_SESSION[
"notification_pending_onclick"]);
1245 unset(
$_SESSION[
"notification_pending"]);
1246 unset(
$_SESSION[
"notification_pending_blocking"]);
1247 unset(
$_SESSION[
"notification_pending_button"]);
1248 unset(
$_SESSION[
"notification_pending_onclick"]);
1264 <script type=
'text/javascript'>
1265 window.addEvent(
'domready',
function()
1267 window.scrollToElement(
'{$element}',
$offset);
1281 $_SESSION[
"scrollto_pending"] = $element;
1332 $config[
"trace_level"] = $level;
1371 if ($errLevel==E_WARNING && (substr_count($errMsg,
"DOMDocument::loadXML()")>0))
1373 throw new DOMException($errMsg);
1376 if ($errLevel & (E_NOTICE | E_WARNING | E_USER_WARNING | E_STRICT | E_DEPRECATED))
return;
1378 throw new ErrorException($errMsg, $errLevel, $errLevel, $errFile, $errLine);
1394 $errMsg = $exception->getMessage();
1395 $errLevel = $exception->getCode();
1396 $errFile = $exception->getFile();
1397 $errLine = $exception->getLine();
1399 if ($errLevel & (E_NOTICE | E_WARNING | E_USER_WARNING | E_STRICT | E_DEPRECATED))
return;
1401 trace(
"ZIP: Winding back output buffers from ".ob_get_level(), 3);
1411 $msg = $exception->getMessage();
1412 if (
$config[
"bootstrap_error_stack_trace"])
1414 $msg .=
"<br/><b>Stack trace:</b><br/>".$exception->getTraceAsString();
1424 $template = file_get_contents(
$err);
1425 $out = str_replace(
"{message}",
$msg, $template);
1431 catch (Exception $ex)
1433 echo $ex->getMessage();
1448 list ($s,
$qs) = explode(
"?", $_SERVER[
'REQUEST_URI']);
1457 return (strtolower(substr(PHP_OS, 0, 3)) ==
"win");
1475 if (class_exists(
"COM"))
1477 $wmi =
new COM(
"Winmgmts:{impersonationlevel=impersonate}!\\Root\\Cimv2");
1478 $cpus = $wmi->InstancesOf(
"Win32_Processor");
1480 foreach ($cpus as $cpu)
1482 $out .= $cpu->LoadPercentage.
"% ";
1487 $out .=
"Not Available";
1492 $sys_load = sys_getloadavg();
1493 $load0 = number_format($sys_load[0], 2);
1494 $load1 = number_format($sys_load[1], 2);
1495 $load2 = number_format($sys_load[2], 2);
1496 $out =
"$load0 $load1 $load2";
1510 if (isset(
$config[
'filesystems']))
1512 $fs = explode(
",",
$config[
'filesystems']);
1523 $out =
"<table class='list'><thead><tr><th>File System</th><th>Size</th><th>Available</th><th>% Free</th></tr></thead><tbody>";
1526 $free = disk_free_space(
$f);
1527 $total = disk_total_space(
$f);
1528 $percent = number_format($free * 100 / $total, 1);
1529 $style = ($percent < 10) ?
" style='background-color: #f00;color: #fff'" : (($percent < 25) ?
" style='background-color: #ff0'" :
"");
1530 $out .=
"<tr$style><td>$f</td><td style='text-align: right'>" . getScaledSize($total) .
1531 "</td><td style='text-align: right'>" . getScaledSize($free) .
1532 "</td><td style='text-align: right'>" . $percent .
"%</td></tr>";
1535 $out .=
"</tbody></table>";
1545 $error = error_get_last();
1547 trace(
"## Shutdown", 4);
1555 case E_COMPILE_ERROR:
1579 if (
$config[
"default_content_type"])
1581 header(
"Content-Type: {$config['default_content_type']}");
1584 $isAction = (basename($_SERVER[
"SCRIPT_FILENAME"]) ==
"action.php" || php_sapi_name() ==
"cli");
1585 $isResource = basename($_SERVER[
"SCRIPT_FILENAME"]) ==
"resource.php";
1589 registerURLRewriteParameters(
"component",
"identifier");
1593 registerURLRewriteParameters(
"component",
"path");
1597 registerURLRewriteParameters(
"identifier");
1601 registerURLRewriteParameters(
"section",
"identifier");
1606 set_error_handler(array(
"Fakoli",
"errorHandler"));
1607 set_exception_handler(array(
"Fakoli",
"exceptionHandler"));
1615 Fakoli::usingFeature(
"auto_form",
"auto_form_layout",
"data_view",
"grouped_data_view",
"join",
"search_form",
"tab_bar",
"paged_list",
"expanding_list",
"date_utils");
1620 Fakoli::usingFeature(
"data_item",
"auto_form",
"field_renderers",
"cache",
"data_view",
"grouped_data_view",
"filter_form",
"search_form",
1621 "paged_list",
"grouped_list",
"facet_manager",
"join",
"tab_bar",
"tree");
1650 $mgr->validateLogin();
if(! $class||! $itemID) $adminAccess
ComponentManager provides the core functionality for building the component map describing the applic...
static fireEvent($event, $parameter=null, $mustBeConsumed=false)
Fire an event to all subscribers as detailed in their manifests.
FakoliEarlyExit is an internal exception class used to provide for controlled early exits during page...
FakoliEventNotConsumed is thrown when no subscriber has handled an event that was fired with $mustBeC...
FakoliException is the base exception class for all Fakoli errors.
This class provides the Fakoli CMS core.
static scriptName()
Returns the name of the currently executing script.
static compareByWeight($item1, $item2)
Sorting callback function that sorts two admin menu items by their specified weights.
static getStyles()
Returns the HTML link tags for CSS files specified by the registered components in their manifest fil...
static componentExists($name)
Test whether the specified component has been registered.
static coreTraceLevel()
Change to the configured trace level for Fakoli core code.
static applyTemplate($target, $templateFile, $component="")
Format the target DataItem or JoinResult using the specified template file.
static $requestStartTime
Start of request in DateTime format.
static sendAdminPage($identifier)
Send the admin page for the given identifier.
static shutdownHandler()
Custom shutdown handler.
scrollTo($element, $offset=0)
Automatically scroll the page to the specified element (by DOM ID) when the page loads.
static errorHandler($errLevel, $errMsg, $errFile, $errLine)
Custom Error Handler.
static resolveResource($resource, $component="")
Resolves the path to a web resource based on the PHP include path.
static usingFeature()
Uses the specified framework feature(s).
static $timestamp
Microsecond Timestamp for start of request.
static getScripts()
Returns the HTML scripts tags for Javascript files specified by the registered components in their ma...
static exceptionHandler($exception)
Custom Exception Handler.
static setTraceLevel($level)
Set the trace log level.
static getServerLoad()
Retrieves information about the Server CPU load.
static detectWindowsOS()
Returns true if running on Windows, false otherwise.
static $bodyClass
Override for the body class of the page currently being served.
static detectXSendFileSupport()
Determines whether the mod_xsendfile extension is present, when running under Apache.
static sendPage($sectionIdentifier, $identifier, $page_id=null)
Serves the page with the specified section and identifier.
static $outputBufferLevel
Records the level at which gzip output buffering began.
static checkRole($role, $msg=null)
Check that the user has one of the specified roles.
getAdminPageRole($identifier)
Get the applicable access roles for a given admin page, based on information supplied by components i...
static getLocalIP()
Returns the local IP address for the server.
static getComponent($name)
Return the component record by name.
static JSONerror($error, $sendType=true)
Return an error code to the client in JSON format, as an object with the single property 'error'.
static checkSSL()
Checks if SSL is enabled on the current request.
static loadStyles()
Load the list of CSS files from the manifests of all registered, active components.
static writePendingScripts()
Outputs any pending scripts submitted by Fakoli::scriptOnNextPage()
static $rollbackBuffers
Specifies whether to rollback output buffers when there is an unhandled exception.
static isUserActive($user)
Checks if the given user is active.
static $requestURI
The initial request URI.
static sendFile($resource)
Sends the contents of the specified file to the client.
static loadScripts()
Load the list of JS scripts from the manifests of all registered, active components.
static notifyOnNextPage($message, $blocking=false, $button="OK", $onClick="null")
Schedules a notification message to be displayed to the user at the next full page load.
static getComponents()
Retrieve an array of all the currently enabled components, indexed by component name.
static loadResource($resource, $component="")
Load the specified resource into memory.
static scheduledTaskTraceLevel()
Changed to the configured trace level for scheduled task worker code.
static getAdminIcons()
Builds the admin icon map.
static getComponentForClass($class)
Find the component containing the specified class.
static applicationTraceLevel()
Change to the configured trace level for application code.
static getAdminMenu()
Builds the administration menu, combining menu items supplied by the registered components in their m...
static getAdminAccessRoles()
Returns the user roles that have access to the admin section.
static includeStylesheet($src, $media="all")
Utility function to pull in a specific CSS Stylesheet for the current page.
scriptOnNextPage($s)
Schedules the provided script fragment to be output when the next page is loaded.
scrollToOnNextPage($element, $offset=0)
Schedules a scrollTo event when the next page is loaded.
static getFileSystemInfo()
Returns formatted summary information regarding usage of the server's filesystem.
static using()
Import the datamodels, views and manifest for the specified component(s).
static put($key, $obj)
Stores a value or object at the given key.
static getComponentClassRoot($name)
Retrieves the capitalized camlCase name for the specified component.
static includeScript($src)
Utility function to pull in a specific Javascript file for the current page.
static $storage
General storage (volatile). See Fakoli::put and Fakoli::get.
static end($message="")
Use this method to terminate execution of a script instead of using the php keywords exit() or die().
static countActiveSessions()
Returns the number of active user sessions.
static usingFile()
Uses the specified framework file(s) from the framework directory.
static showPendingNotification()
Display any previously scheduled notification message.
static initialComponentScan()
Performs a complete component scan if the component table is found to be empty.
static sendResource($uri, $component="")
Sends the resource at the specified URI to the client.
static JSONreturn($object, $sendType=true, $wrap=true)
Return a DataItem to the client in JSON format.
static notify($message, $blocking=false, $button="OK", $onClick="null")
Utility method to display a notification message to the user when the page has finished loading.
static showPendingScrollTo()
Display any previously scheduled scrollto event.
static bootstrap()
Bootstraps the creation of the database schema if the component table does not exist.
static evaluateFile($filePath)
Evaluates a PHP include file and returns the generated content.
static $scanning
Semaphore indicating that a component scan is in progress.
static $componentsUsed
Array of the components that have been referenced in this page request.
static assertRole($role, $redirect="", $message="")
Assert that the user has one of the specified roles.
LoginManager provides the authentication workflow for logging users into the system.
static redirectToLogin()
Redirect the user to the login page.
static createFromIdentifier($identifier)
static checkPermissions($permissions, $account=null)
Check all the permissions specified in the given string.
static getValue($component, $name)
Retrieve the value of the specified Setting.
static getSite()
Returns the Site object that describes the currently active site (i.e.
Provides the interface to the user model for the application.
$method
Pull out a simple reference to the request method.
if($config["default_content_type"]) $isAction
if(!checkRole("admin")) $c
while(ob_get_level()) $last_modified
if(array_key_exists("HTTP_IF_MODIFIED_SINCE", $_SERVER)) $content