build array in auto_loader constructor (#7158)

* Build an array in the auto_loader constructor

* Update auto_loader.php

* Update auto_loader.php

* minor adjustment to name and comment and remove trailing closing tag

* use best practices for the loader method
Allowing the loader method:
- Should Never Be Called Manually
- Prevents External Modification
- Hides Implementation Details

* cache array in the temp folder and load if available

* re-organize functions within the class

* add cache recreation for auto_loader in upgrade_menu

* add cache recreation for auto_loader in upgrade_menu

* Update app_languages.php
This commit is contained in:
frytimo 2025-02-13 17:48:40 -04:00 committed by GitHub
parent 9b0eead911
commit 0931197137
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 265 additions and 69 deletions

View File

@ -1701,4 +1701,110 @@ $text['button-preview']['zh-cn'] = "预览";
$text['button-preview']['ja-jp'] = "プレビュー";
$text['button-preview']['ko-kr'] = "시사";
?>
$text['label-update_auto_loader']['en-us'] = 'Update Auto Loader Cache';
$text['label-update_auto_loader']['en-gb'] = 'Update Auto Loader Cache';
$text['label-update_auto_loader']['ar-eg'] = 'تحديث ذاكرة التخزين المؤقتة للتحميل التلقائي';
$text['label-update_auto_loader']['de-at'] = 'AutoLoader-Cache aktualisieren';
$text['label-update_auto_loader']['de-ch'] = 'AutoLoader-Cache aktualisieren';
$text['label-update_auto_loader']['de-de'] = 'AutoLoader-Cache aktualisieren';
$text['label-update_auto_loader']['el-gr'] = 'Ενημερώστε την προσωρινή μνήμη Auto Loader';
$text['label-update_auto_loader']['es-cl'] = 'Actualizar la caché del cargador automático';
$text['label-update_auto_loader']['es-mx'] = 'Actualizar la caché del cargador automático';
$text['label-update_auto_loader']['fr-ca'] = 'Mettre à jour le cache du chargeur automatique';
$text['label-update_auto_loader']['fr-fr'] = 'Mettre à jour le cache du chargeur automatique';
$text['label-update_auto_loader']['he-il'] = 'עדכן את מטמון הטעינה האוטומטית';
$text['label-update_auto_loader']['it-it'] = 'Aggiorna la cache del caricatore automatico';
$text['label-update_auto_loader']['ka-ge'] = 'Auto Loader Cache-ის განახლება';
$text['label-update_auto_loader']['nl-nl'] = 'Auto Loader-cache bijwerken';
$text['label-update_auto_loader']['pl-pl'] = 'Aktualizuj pamięć podręczną Auto Loader';
$text['label-update_auto_loader']['pt-br'] = 'Atualizar cache do carregador automático';
$text['label-update_auto_loader']['pt-pt'] = 'Atualizar cache do carregador automático';
$text['label-update_auto_loader']['ro-ro'] = 'Actualizați memoria cache a încărcării automate';
$text['label-update_auto_loader']['ru-ru'] = 'Обновить кэш автозагрузчика';
$text['label-update_auto_loader']['sv-se'] = 'Uppdatera Auto Loader Cache';
$text['label-update_auto_loader']['uk-ua'] = 'Оновити кеш автозавантажувача';
$text['label-update_auto_loader']['tr-tr'] = 'Otomatik Yükleyici Önbelleğini Güncelle';
$text['label-update_auto_loader']['zh-cn'] = '更新自动加载器缓存';
$text['label-update_auto_loader']['ja-jp'] = 'オートローダーキャッシュの更新';
$text['label-update_auto_loader']['ko-kr'] = '자동 로더 캐시 업데이트';
$text['description-update_auto_loader']['en-us'] = 'Updates the auto_loader cache file to include any new classes added to the project';
$text['description-update_auto_loader']['en-gb'] = 'Updates the auto_loader cache file to include any new classes added to the project';
$text['description-update_auto_loader']['ar-eg'] = 'يقوم بتحديث ملف ذاكرة التخزين المؤقت لـ auto_loader ليشمل أي فئات جديدة تمت إضافتها إلى المشروع';
$text['description-update_auto_loader']['de-at'] = 'Aktualisiert die Auto_Loader-Cachedatei, um alle neuen Klassen einzuschließen, die dem Projekt hinzugefügt werden';
$text['description-update_auto_loader']['de-ch'] = 'Aktualisiert die Auto_Loader-Cachedatei, um alle neuen Klassen einzuschließen, die dem Projekt hinzugefügt werden';
$text['description-update_auto_loader']['de-de'] = 'Aktualisiert die Auto_Loader-Cachedatei, um alle neuen Klassen einzuschließen, die dem Projekt hinzugefügt werden';
$text['description-update_auto_loader']['el-gr'] = 'Ενημερώνει το αρχείο προσωρινής μνήμης auto_loader για να συμπεριλάβει τυχόν νέες κλάσεις που προστέθηκαν στο έργο';
$text['description-update_auto_loader']['es-cl'] = 'Actualiza el archivo de caché auto_loader para incluir cualquier clase nueva agregada al proyecto';
$text['description-update_auto_loader']['es-mx'] = 'Actualiza el archivo de caché auto_loader para incluir cualquier clase nueva agregada al proyecto';
$text['description-update_auto_loader']['fr-ca'] = 'Met à jour le fichier cache du chargeur automatique pour inclure toutes les nouvelles classes ajoutées au projet';
$text['description-update_auto_loader']['fr-fr'] = 'Met à jour le fichier cache du chargeur automatique pour inclure toutes les nouvelles classes ajoutées au projet';
$text['description-update_auto_loader']['he-il'] = 'מעדכן את קובץ המטמון auto_loader כך שיכלול כל מחלקות חדשות שנוספו לפרויקט';
$text['description-update_auto_loader']['it-it'] = 'Aggiorna il file di cache auto_loader per includere tutte le nuove classi aggiunte al progetto';
$text['description-update_auto_loader']['ka-ge'] = 'აახლებს auto_loader ქეში ფაილს, რათა შეიცავდეს პროექტში დამატებულ ნებისმიერ ახალ კლასს';
$text['description-update_auto_loader']['nl-nl'] = 'Werkt het auto_loader-cachebestand bij om alle nieuwe klassen op te nemen die aan het project zijn toegevoegd';
$text['description-update_auto_loader']['pl-pl'] = 'Aktualizuje plik pamięci podręcznej auto_loader, aby uwzględnić wszystkie nowe klasy dodane do projektu';
$text['description-update_auto_loader']['pt-br'] = 'Atualiza o arquivo de cache do auto_loader para incluir quaisquer novas classes adicionadas ao projeto';
$text['description-update_auto_loader']['pt-pt'] = 'Atualiza o arquivo de cache do auto_loader para incluir quaisquer novas classes adicionadas ao projeto';
$text['description-update_auto_loader']['ro-ro'] = 'Actualizează fișierul cache auto_loader pentru a include orice clase noi adăugate la proiect';
$text['description-update_auto_loader']['ru-ru'] = 'Обновляет файл кэша auto_loader, включая в него все новые классы, добавленные в проект.';
$text['description-update_auto_loader']['sv-se'] = 'Uppdaterar cachefilen för auto_loader för att inkludera alla nya klasser som lagts till i projektet';
$text['description-update_auto_loader']['uk-ua'] = 'Оновлює файл кешу auto_loader, щоб включити всі нові класи, додані до проекту';
$text['description-update_auto_loader']['tr-tr'] = 'Projeye eklenen tüm yeni sınıfları içerecek şekilde auto_loader önbellek dosyasını günceller';
$text['description-update_auto_loader']['zh-cn'] = '更新 auto_loader 缓存文件以包含添加到项目中的任何新类';
$text['description-update_auto_loader']['ja-jp'] = 'プロジェクトに追加された新しいクラスを含めるために auto_loader キャッシュ ファイルを更新します。';
$text['description-update_auto_loader']['ko-kr'] = '프로젝트에 추가된 모든 새 클래스를 포함하도록 auto_loader 캐시 파일을 업데이트합니다.';
$text['label-reloaded_classes']['en-us'] = 'Reloaded classes';
$text['label-reloaded_classes']['en-gb'] = 'Reloaded classes';
$text['label-reloaded_classes']['ar-eg'] = 'الفصول المعاد تحميلها';
$text['label-reloaded_classes']['de-at'] = 'Neu geladene Klassen';
$text['label-reloaded_classes']['de-ch'] = 'Neu geladene Klassen';
$text['label-reloaded_classes']['de-de'] = 'Neu geladene Klassen';
$text['label-reloaded_classes']['el-gr'] = 'Επαναφόρτωση τάξεων';
$text['label-reloaded_classes']['es-cl'] = 'Clases recargadas';
$text['label-reloaded_classes']['es-mx'] = 'Clases recargadas';
$text['label-reloaded_classes']['fr-ca'] = 'Classes rechargées';
$text['label-reloaded_classes']['fr-fr'] = 'Classes rechargées';
$text['label-reloaded_classes']['he-il'] = 'שיעורים שנטענו מחדש';
$text['label-reloaded_classes']['it-it'] = 'Classi ricaricate';
$text['label-reloaded_classes']['ka-ge'] = 'გადატვირთული კლასები';
$text['label-reloaded_classes']['nl-nl'] = 'Herladen klassen';
$text['label-reloaded_classes']['pl-pl'] = 'Klasy przeładowane';
$text['label-reloaded_classes']['pt-br'] = 'Classes recarregadas';
$text['label-reloaded_classes']['pt-pt'] = 'Classes recarregadas';
$text['label-reloaded_classes']['ro-ro'] = 'Cursuri reîncărcate';
$text['label-reloaded_classes']['ru-ru'] = 'Перезагруженные классы';
$text['label-reloaded_classes']['sv-se'] = 'Omladdade klasser';
$text['label-reloaded_classes']['uk-ua'] = 'Перезавантажені класи';
$text['label-reloaded_classes']['tr-tr'] = 'Yeniden yüklenen sınıflar';
$text['label-reloaded_classes']['zh-cn'] = '重新加载的类';
$text['label-reloaded_classes']['ja-jp'] = 'リロードされたクラス';
$text['label-reloaded_classes']['ko-kr'] = '다시 로드된 클래스';
$text['label-updated_cache']['en-us'] = 'Updated cache';
$text['label-updated_cache']['en-gb'] = 'Updated cache';
$text['label-updated_cache']['ar-eg'] = 'تم تحديث ذاكرة التخزين المؤقت';
$text['label-updated_cache']['de-at'] = 'Cache aktualisiert';
$text['label-updated_cache']['de-ch'] = 'Cache aktualisiert';
$text['label-updated_cache']['de-de'] = 'Cache aktualisiert';
$text['label-updated_cache']['el-gr'] = 'Ενημερώθηκε η προσωρινή μνήμη';
$text['label-updated_cache']['es-cl'] = 'Caché actualizado';
$text['label-updated_cache']['es-mx'] = 'Caché actualizado';
$text['label-updated_cache']['fr-ca'] = 'Cache mis à jour';
$text['label-updated_cache']['fr-fr'] = 'Cache mis à jour';
$text['label-updated_cache']['he-il'] = 'מטמון מעודכן';
$text['label-updated_cache']['it-it'] = 'Cache aggiornata';
$text['label-updated_cache']['ka-ge'] = 'განახლებულია ქეში';
$text['label-updated_cache']['nl-nl'] = 'Bijgewerkte cache';
$text['label-updated_cache']['pl-pl'] = 'Zaktualizowano pamięć podręczną';
$text['label-updated_cache']['pt-br'] = 'Cache atualizado';
$text['label-updated_cache']['pt-pt'] = 'Cache atualizado';
$text['label-updated_cache']['ro-ro'] = 'Cache actualizat';
$text['label-updated_cache']['ru-ru'] = 'Обновлен кэш';
$text['label-updated_cache']['sv-se'] = 'Uppdaterad cache';
$text['label-updated_cache']['uk-ua'] = 'Оновлений кеш';
$text['label-updated_cache']['tr-tr'] = 'Güncellenen önbellek';
$text['label-updated_cache']['zh-cn'] = '更新缓存';
$text['label-updated_cache']['ja-jp'] = 'キャッシュを更新しました';
$text['label-updated_cache']['ko-kr'] = '캐시 업데이트됨';

View File

@ -58,6 +58,11 @@ $display_type = 'text';
//run
show_upgrade_menu();
/**
* Show upgrade menu
* @global type $text
* @global type $software_name
*/
function show_upgrade_menu() {
global $text, $software_name, $settings;
//error_reporting(E_ALL);
@ -72,13 +77,14 @@ function show_upgrade_menu() {
echo "1) {$text['label-upgrade_source']} - {$text['description-update_all_source_files']}\n";
echo " 1a) " . $software_name . " - Update Main Software Only \n";
echo " 1b) {$text['label-update_external_repositories']} - {$text['description-repositories']}\n";
echo "2) {$text['label-schema']} - {$text['description-upgrade_schema']}\n";
echo " 2b) {$text['label-upgrade_data_types']} - {$text['description-upgrade_data_types']}\n";
echo "3) {$text['label-upgrade_apps']} - {$text['description-upgrade_apps']}\n";
echo "4) {$text['label-upgrade_menu']} - {$text['description-upgrade_menu']}\n";
echo "5) {$text['label-upgrade_permissions']} - {$text['description-upgrade_permissions']}\n";
echo "6) {$text['label-update_filesystem_permissions']} - {$text['description-update_filesystem_permissions']}\n";
echo "7) {$text['label-all_of_the_above']} - {$text['description-all_of_the_above']}\n";
echo "2) {$text['label-update_auto_loader']} - {$text['description-update_auto_loader']}\n";
echo "3) {$text['label-schema']} - {$text['description-upgrade_schema']}\n";
echo " 3b) {$text['label-upgrade_data_types']} - {$text['description-upgrade_data_types']}\n";
echo "4) {$text['label-upgrade_apps']} - {$text['description-upgrade_apps']}\n";
echo "5) {$text['label-upgrade_menu']} - {$text['description-upgrade_menu']}\n";
echo "6) {$text['label-upgrade_permissions']} - {$text['description-upgrade_permissions']}\n";
echo "7) {$text['label-update_filesystem_permissions']} - {$text['description-update_filesystem_permissions']}\n";
echo "8) {$text['label-all_of_the_above']} - {$text['description-all_of_the_above']}\n";
echo "0) Exit\n";
echo "\n";
echo "Choice: ";
@ -95,32 +101,36 @@ function show_upgrade_menu() {
do_upgrade_code_submodules();
break;
case 2:
do_upgrade_schema();
break;
case '2b':
do_upgrade_schema(true);
do_upgrade_auto_loader();
break;
case 3:
do_upgrade_domains();
do_upgrade_schema();
break;
case '3b':
do_upgrade_schema(true);
break;
case 4:
do_upgrade_menu();
do_upgrade_domains();
break;
case 5:
do_upgrade_permissions();
do_upgrade_menu();
break;
case 6:
do_filesystem_permissions($text, $settings);
do_upgrade_permissions();
break;
case 7:
do_upgrade_code();
do_upgrade_schema();
do_upgrade_domains();
do_upgrade_menu();
do_upgrade_permissions();
do_filesystem_permissions($text, $settings);
break;
case 8:
do_upgrade_code();
do_upgrade_auto_loader();
do_upgrade_schema();
do_upgrade_domains();
do_upgrade_menu();
do_upgrade_permissions();
do_filesystem_permissions($text, $settings);
break;
case 9:
break;
case 0:
exit();
@ -128,6 +138,23 @@ function show_upgrade_menu() {
}
}
/**
* Rebuild the cache file
* @global type $text
*/
function do_upgrade_auto_loader() {
global $text;
$loader = new auto_loader();
$loader->reload_classes();
echo "{$text['label-reloaded_classes']}\n";
if ($loader->update_cache()) {
echo "{$text['label-updated_cache']}\n";
}
}
/**
* Show the software version
*/
function do_filesystem_permissions($text, settings $settings) {
echo ($text['label-header1'] ?? "Root account or sudo account must be used for this option") . "\n";
@ -185,6 +212,10 @@ function show_software_version() {
echo software::version() . "\n";
}
/**
* Upgrade the source folder
* @return type
*/
function do_upgrade_code() {
//assume failed
$result = ['result' => false, 'message' => 'Failed'];
@ -199,6 +230,10 @@ function do_upgrade_code() {
return;
}
/**
* Upgrade any of the git submodules
* @global type $text
*/
function do_upgrade_code_submodules() {
global $text;
$updateable_repos = git_find_repos(dirname(__DIR__, 2)."/app");
@ -223,7 +258,9 @@ function do_upgrade_code_submodules() {
}
}
//run all app_defaults.php files
/**
* Execute all app_defaults.php files
*/
function do_upgrade_domains() {
require_once dirname(__DIR__, 2) . "/resources/classes/config.php";
require_once dirname(__DIR__, 2) . "/resources/classes/domains.php";
@ -232,7 +269,9 @@ function do_upgrade_domains() {
$domain->upgrade();
}
//upgrade schema and/or data_types
/**
* Upgrade schema and/or data_types
*/
function do_upgrade_schema(bool $data_types = false) {
//get the database schema put it into an array then compare and update the database as needed.
require_once dirname(__DIR__, 2) . "/resources/classes/schema.php";
@ -241,7 +280,9 @@ function do_upgrade_schema(bool $data_types = false) {
echo $obj->schema('text');
}
//restore the default menu
/**
* Restore the default menu
*/
function do_upgrade_menu() {
global $included, $sel_menu, $menu_uuid, $menu_language;
//get the menu uuid and language
@ -273,7 +314,9 @@ function do_upgrade_menu() {
}
}
//restore the default permissions
/**
* Restore the default permissions
*/
function do_upgrade_permissions() {
global $included;
//default the permissions
@ -285,7 +328,9 @@ function do_upgrade_permissions() {
echo $text['message-upgrade_permissions'] . "\n";
}
//default upgrade schema and app defaults
/**
* Default upgrade schema and app defaults
*/
function do_upgrade_defaults() {
//add multi-lingual support
$language = new text;
@ -309,6 +354,10 @@ function do_upgrade_defaults() {
echo "\n";
}
/**
* Load the old config.php file
* @return type
*/
function load_config_php() {
//if the config file doesn't exist and the config.php does exist use it to write a new config file
//include the config.php

View File

@ -26,27 +26,85 @@
class auto_loader {
public function __construct() {
const FILE = 'autoloader_cache.php';
private $classes;
public function __construct($project_path = '') {
//classes must be loaded before this object is registered
if (!$this->load_cache()) {
$this->reload_classes($project_path);
}
//register this object to load any unknown classes
spl_autoload_register(array($this, 'loader'));
}
public static function autoload_search($array) : string {
if (!is_array($array) && count($path) != 0) {
return '';
public function update_cache(string $file = ''): bool {
//ensure we have somewhere to put the file
if (empty($file)) {
$file = sys_get_temp_dir() . '/' . self::FILE;
}
foreach($array as $path) {
if (is_array($path) && count($path) != 0) {
foreach($path as $sub_path) {
if (!empty($sub_path) && file_exists($sub_path)) {
return $sub_path;
}
}
//guard against writing an empty file
if (!empty($this->classes)) {
//export the classes array using PHP engine
$data = var_export($this->classes, true);
//put the array in a form that it can be loaded directly to an array
$result = file_put_contents($file, "<?php\n return " . $data . ";\n");
if ($result !== false) {
return true;
}
elseif (!empty($path) && file_exists($path)) {
return $path;
$error_array = error_get_last();
//send to syslog when debugging
if (!empty($_REQUEST['debug']) && $_REQUEST['debug'] == 'true') {
openlog("PHP", LOG_PID | LOG_PERROR, LOG_LOCAL0);
syslog(LOG_WARNING, "[php][auto_loader] " . $error_array['message']);
closelog();
}
}
return '';
return false;
}
public function load_cache(string $file = ''): bool {
$this->classes = [];
//use a standard file
if (empty($file)) {
$file = sys_get_temp_dir() . '/'. self::FILE;
}
//use PHP engine to parse it
if (file_exists($file)) {
$this->classes = include $file;
}
//assign to an array
if (!empty($this->classes)) {
return true;
}
return false;
}
public function reload_classes($project_path = '') {
//set project path using magic dir constant
if (empty($project_path)) {
$project_path = dirname(__DIR__, 2);
}
//build the array of all classes
$search_path = [];
$search_path = array_merge($search_path, glob($project_path . '/resources/classes/*.php'));
$search_path = array_merge($search_path, glob($project_path . '/resources/interfaces/*.php'));
$search_path = array_merge($search_path, glob($project_path . '/resources/traits/*.php'));
$search_path = array_merge($search_path, glob($project_path . '/*/*/resources/classes/*.php'));
$search_path = array_merge($search_path, glob($project_path . '/*/*/resources/interfaces/*.php'));
$search_path = array_merge($search_path, glob($project_path . '/*/*/resources/traits/*.php'));
//reset the current array
$this->classes = [];
//store the class name (key) and the path (value)
foreach ($search_path as $path) {
$this->classes[basename($path, '.php')] = $path;
}
}
private function loader($class_name) : bool {
@ -54,40 +112,23 @@ class auto_loader {
//sanitize the class name
$class_name = preg_replace('[^a-zA-Z0-9_]', '', $class_name);
//use glob for a more extensive search for the classes (note: GLOB_BRACE doesn't work on some systems)
if (!class_exists($class_name)) {
//set project path using magic dir constant
$project_path = dirname(__DIR__, 2);
//find the path using the class_name as the key in the classes array
if (isset($this->classes[$class_name])) {
//include the class or interface
include_once $this->classes[$class_name];
//build the search path array
$search_path[] = glob($project_path . "/resources/classes/".$class_name.".php");
$search_path[] = glob($project_path . "/resources/interfaces/".$class_name.".php");
$search_path[] = glob($project_path . "/resources/traits/".$class_name.".php");
$search_path[] = glob($project_path . "/*/*/resources/classes/".$class_name.".php");
$search_path[] = glob($project_path . "/*/*/resources/interfaces/".$class_name.".php");
$search_path[] = glob($project_path . "/*/*/resources/traits/".$class_name.".php");
//return boolean
return true;
}
//find the path
$path = self::autoload_search($search_path);
if (!empty($path)) {
//send to syslog
if (!empty($_REQUEST['debug']) && $_REQUEST['debug'] == 'true') {
openlog("PHP", LOG_PID | LOG_PERROR, LOG_LOCAL0);
syslog(LOG_WARNING, "[php][autoloader] name: ".$class_name.", path: ".$path.", line: ".__line__);
closelog();
}
//include the class or interface
include $path;
//return boolean
return true;
}
//send to syslog when debugging
if (!empty($_REQUEST['debug']) && $_REQUEST['debug'] == 'true') {
openlog("PHP", LOG_PID | LOG_PERROR, LOG_LOCAL0);
syslog(LOG_WARNING, "[php][auto_loader] class not found name: ".$class_name);
closelog();
}
//return boolean
return false;
}
}
?>