MagratheaPHP2

Migrating from 2.3.5 to 2.4.0

From: 2.3.5 · To: 2.4.0

This file is self-contained: it's written to be handed to a person or an AI agent upgrading a project, without the rest of the docs. Go through the sections in order. Each one says how to tell whether it applies to your project (Applies if), what changed, and what to do.

Summary

#ChangeBreaking?Action needed?
1Bootstrap setup wizard is locked unless bootstrap_unlocked = trueYes, for projects using the wizardAdd the flag to [dev]
2Admin first-run setup only with zero users; DB errors show an error pageNoNone
3Failed API authorization no longer runs the action in raw modeOnly for raw-mode callers relying on the bugAuthenticate in tests that call protected endpoints
4DEV/ANALYSIS error stacktrace frames no longer include argsNoNone, unless a tool parses args
5Admin File Editor is no longer loaded by defaultYes, for admins that use itOpt in with $this->LoadFileEditor()
6Query::Clean() escapes backslashes (it was injection-unsafe); deprecatedRarelyPrefer Database::Instance()->Escape()
7Admin Cache feature only touches files inside the cache folder; "clear cache" is POST only; cached content is escapedNoNone, unless custom code calls its actions
8Admin Tests page only runs/reads test files inside registered test folders; shell arguments are escapedNoNone, unless code calls TestsManager with paths outside AddTest() folders
9Admin ?magrathea_page=/?magrathea_subpage= only accept names of the admin's own page/action files; anything else is 404NoNone, unless links use names that aren't files in views/pages/ or views/actions/
10New Database::Transaction(callable $fn)NoNone (optional: use it)
11QueryTransaction() rolls back on failure; success returns trueNoNone
12Cache files are written atomically (temp file + rename)NoNone, unless the cache dir isn't writable
13Cache() logs "adding cache for …" only in DEVNoNone, unless something reads those log lines
14Raw-mode API calls bypass the response cacheOnly for raw callers relying on cached dataNone in practice
15CacheClear() no longer changes the key set by Cache()NoNone
16API errors are sent with real 4xx/5xx HTTP statuses (were 200)Yes, for clients that read success: false in the success handlerMove error handling to the HTTP client's error path before upgrading
17MagratheaApiException::SetStatus() is honored (it was ignored)Only where it's calledCheck SetStatus() calls; a missing token is now HTTP 401 (was 400)
18PHP \Errors in actions become a logged JSON 500 (were a fatal error page)NoNone
19Codes that map outside 400-599 give HTTP 500Only for code 2001-style statusesNone in practice
20BaseAuthorization() takes a MagratheaApiAuth (was typed MagratheaApiControl)No (a plain control never worked)Auth classes extend MagratheaApiAuth
21DEV/DEBUG API responses carry debug items in _debug instead of printed HTML; DB query errors reach the Debugger once (LOG wrote them twice)No (DEV/DEBUG/LOG only)None
22created_at/updated_at handling is unchanged, only documented (DB default on insert, PHP now() on update)NoNone
23Update() on a loaded object writes only the fields that changed, plain assignments includedYes, silently: input loaded with LoadObjectFromTableRow() isn't saved; display-only assignments are; other processes' changes aren't overwrittenUse Assign() for input; check assignments before Save()
24A model object assigned to a field is saved as its id (it wrote 1 or the object's text)No (it never worked)None
25Update() writes SQL NULL for a nulled int/boolean on a loaded object, and for "" alwaysYes, where code nulls an int it didn't mean to clear, or sends "" to a NOT NULL intCheck int assignments and forms posting empty ints
26composer.json requires PHP 8.1+No: the framework already needed 8.1 (it uses an enum)None, unless Composer runs on PHP 8.0
27Failed writes (PrepareAndExecute(), model Insert()/Update()/Delete()) throw with mysqli reporting off (they printed got error! and returned null); QueryMulti($q, false)/ImportFile($f, false) keep going after a failed statement with PHP 8.1+'s default reportingOnly with reporting off, or code checking if (!$obj->Insert())Catch MagratheaDBException instead of checking the return value
28DB errors are always MagratheaDBException (code = MySQL errno, mysqli's exception as getPrevious()), answered by the API with HTTP 500, carrying the statement's valuesYes, for code catching mysqli_sql_exceptionCatch MagratheaDBException
29Model writes bind int/boolean fields (and int PKs in Update()/Delete()) as integers; they were stringsOnly for int PKs above PHP_INT_MAXDeclare those fields as "string"
30One shared connection per request instead of one per queryYes, for long-running CLI workersCall Database::Instance()->Disconnect() at the start of each job
31QueryMulti() returns SELECT rows (they were always empty)NoNone
32db_port from the config is now used (it was ignored)Only if db_port is wrongCheck db_port or remove it
33The timezone key is timezone; time_zone (old samples) was always ignored, and still isNo, until you rename itRename time_zone → timezone: that turns on item 34 too
34With timezone set, MySQL's session time_zone is synced to PHP's (db_sync_timezone, default on)Yes, if MySQL runs in another zone: TIMESTAMP values read back shifted, NOW() changesRun the timezone checks; db_sync_timezone = false to opt out
35Autoloader: with two files of the same name in the code folders, the one whose namespace matches is loaded (was the first one); DEV warnsOnly with duplicate class names, and then it loads different codeCheck duplicates; rename them
36A missing class no longer throws MagratheaException from the autoloader; PHP's Error: Class not found insteadOnly for code catching MagratheaException around new X() / class_exists()Catch \Error, or check class_exists() first
37MagratheaModelControl::ShowAll() works with namespaced models (it failed with Class not found) and escapes values; deprecated (removed in 3.0)NoNone (stop calling it)
38MagratheaPHP::LoadVendor() is deprecated (removed in 3.0); it also finds the autoloader in a standalone checkout; TestsManager no longer calls itNoNone (stop calling it)
39New decimal field type for SQL DECIMAL (exact, kept as a string); the generator detects DECIMAL → decimal, DOUBLE → floatNo, until a field is re-typedRe-type float fields on DECIMAL columns, checking API consumers on strict models
40The admin's object form has a "Strict types" select; new objects generate with $strictTypes = trueNo (objects created before 2.4.0 are unchanged)None
41Code generator's mvc structure: CRUD admin, API and Base GetControl() fixed; SetObject() takes an optional controlNo (they never worked under mvc)Regenerate mvc Base models; fix hand-made mvc CRUD admins
42Admin features run Initialize() before the default featureId is set; AdminCrudObject subclasses run it once (it ran twice)Rarely: a feature reading an unset featureId in Initialize()Set featureId before reading it
43The admin's Query Tester ("Magrathea Query", it ran posted code with eval()) is removedOnly for links to it or a custom menu with GetItem("mag-query")Remove them; use the Queries page
44Admin backups: plain .sql names only, no overwriting, mysqldump without a shell or the password on the command line; AdminDatabase::GetCommand() removedOnly for code calling GetCommand()/DoBackup() or names with other charactersCheck proc_open() is enabled; stop calling GetCommand()
45file-view only shows files chosen by the admin's own views; logs are read by name through log-view; the tail is escapedOnly for custom code posting to file-viewUse your own action, or log-view for logs
46The admin escapes values in Table() and the form elements; callable columns stay raw HTMLYes, for custom admin pages passing HTML as values (it shows as text) or pre-escaping them (entities show)Move HTML into callable columns; stop pre-escaping
47Admin actions escape their query-string parameters; onclose must be a plain JS function nameNoNone, unless custom links pass code as onclose
48Admin feature URLs only call the feature's own actions; CRUD Save/Delete and App Config Import are POST onlyOnly for custom features with actions named like AdminFeature methods or needing arguments, and GET callers of those writesRename/adapt those actions; POST the writes; make your own writing actions refuse GET

Composer constraint

2.4.0's composer.json requires PHP 8.1+ (item 26). The framework already needed it, so this only matters if Composer runs on an older PHP.

Current constraint in composer.jsonWhat happens
~2.3.5, 2.3.*, or an exact 2.3.xStays on 2.3.x. Change it to ^2.4 to receive 2.4.0.
^2.3 (or ^2.0, ^2.1, …)Receives 2.4.0 on the next composer update, with no edit: read this file before running it.
grep -n "platypustechnology/magratheaphp2" composer.json
composer require "platypustechnology/magratheaphp2:^2.4"

New projects require ^2.4.

Changes with no impact

Nothing to check or do for these:


1. Bootstrap setup wizard is locked by default

Applies if: the project has an entry file that opens the setup wizard:

grep -rn "Bootstrap\\\\Start" --include='*.php' . | grep -v vendor/

What changed: Magrathea2\Bootstrap\Start::Load() now only renders the wizard when the active environment's config section has bootstrap_unlocked = true. Otherwise it answers 403 with a "Bootstrap is locked" page. The flag in [general] or in another environment's section is ignored. Also, ?action= only accepts the wizard's own actions; any other value gets a 404 instead of a PHP include.

What to do:

``ini [dev] ; ...existing keys... bootstrap_unlocked = true ``


2. Admin first-run setup can't be reached on an installed system

Applies if: the project uses the admin panel:

grep -rn "AdminManager::Instance()->Start" --include='*.php' . | grep -v vendor/

What changed: the setup form (which creates a super admin) now appears only when there are zero admin users. A database error shows a 500 error page instead of the setup form, with the exception message only in DEV. If users exist but the admin_install_date config row is missing, the row is written and the login page is shown.

What to do: nothing. If the admin used to greet you with the setup form on an install that has users, you'll see the login page now.


3. A failed API authorization stops the request in raw mode too

Applies if: the project calls the API in raw mode, usually from tests or CLI tools:

grep -rn "Run(true)\|SetRaw()\|ExecuteUrl(" --include='*.php' . | grep -v vendor/

What changed: when a protected endpoint's auth method returns false, ExecuteUrl() now returns the 401 error array and never calls the action. In 2.3.5 it built the error and then ran the action anyway; over HTTP this was hidden because the error response ends the script. HTTP behavior doesn't change.

What to do:

``php ["success" => false, "data" => ["code" => 401, "message" => "Authorization Failed! (<method> = false)", "error" => <authenticationErrorData>, ...]] ``


4. API error stack traces no longer include call arguments

Applies if: something reads the stacktrace from API error responses in DEV or ANALYSIS mode and uses each frame's args:

grep -rn "stacktrace" --include='*.js' --include='*.ts' --include='*.php' . | grep -v vendor/ | grep -v node_modules/

What changed: MagratheaApi::ReturnError() and ReturnApiException() build stacktrace with debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS). Frames keep file, line, function, class and type and lose args, which used to leak config arrays, DB credentials, passwords and JWT keys into the JSON response. Production modes never had a stacktrace.

What to do: nothing, unless a tool depends on args. If so, it has to get that data some other way (logs, a debugger); it won't come back in the response.


5. The admin File Editor is opt-in

Applies if: the project uses the admin panel with the default feature set, i.e. its Admin subclass calls parent::SetFeatures() or doesn't override SetFeatures() at all, or it uses AdminManager::Instance()->StartDefault():

grep -rnE 'parent::SetFeatures\(\)|StartDefault\(|Admin\\Admin\b' --include='*.php' . | grep -v vendor/

What changed: Admin::SetFeatures() no longer loads AdminFeatureFileEditor. Any logged-in admin user could use it to edit files on the server, so a leaked admin password became code execution. The "Tools → File Editor" menu entry and the code generator's "View File" link only appear when the feature is loaded. A bookmarked ?magrathea_feature=AdminFeatureFileEditor URL shows "Feature not available".

What to do:

``php public function SetFeatures() { parent::SetFeatures(); $this->LoadFileEditor(); } ``

StartDefault() users have no subclass, so they need to create one to get the editor back.


6. Query::Clean() is safe now, and deprecated

Applies if: the project calls Query::Clean():

grep -rn "Query::Clean\|::Clean(" --include='*.php' . | grep -v vendor/

What changed: Clean() escaped quotes but not backslashes, so a value like \' could close the SQL string: it didn't prevent SQL injection. It now calls Database::Instance()->Escape() (mysqli::real_escape_string), so:

What to do:


7. The admin Cache feature stays inside the cache folder

Applies if: custom code or scripts call the Cache feature's actions directly (magrathea_feature=AdminFeatureCache), e.g. to purge the cache after a deploy:

grep -rn "AdminFeatureCache" --include='*.php' --include='*.js' --include='*.sh' . | grep -v vendor/

What changed: View, Edit, Save and Remove took the posted file as a path relative to the cache folder without checking it, so any logged-in admin could read, overwrite or delete any file the web server can reach (file=../...), including writing a PHP file. They now accept only the name of an existing file directly inside the cache folder; anything else throws "invalid file". ClearCache answers 405 unless it's a POST (with the admin CSRF token). Cache contents and file names are HTML-escaped when shown.

What to do: nothing, unless a script purges the cache with a GET to ?magrathea_feature=AdminFeatureCache&magrathea_feature_action=ClearCache: purge it in code with MagratheaCache::Instance()->RemoveAllCache() instead.


8. The admin Tests page stays inside the registered test folders

Applies if: code calls TestsManager's run or listing methods itself, or registers test folders:

grep -rnE "TestsManager|RunFolder\(|RunFile\(|RunFunction\(|GetTestsFromFolder\(|GetMethodsFromTest\(" --include='*.php' . | grep -v vendor/

What changed: the Tests page posted a folder or file path (and a function name) that Tests\TestsManager put into a shell command unescaped, so any logged-in admin could run shell commands (folder=x; any command) or have PHPUnit run any PHP file on the server. Now RunFolder()/RunFile()/ RunFunction() and the listing methods GetTestsFromFolder()/GetMethodsFromTest() only accept paths inside a folder registered with AddTest() (or the framework's own, AddMagrathaTests()); files must be *Test.php; function names must be letters, digits and _. Anything else throws MagratheaException, which the Tests page shows as an error. Every shell argument is escaped. Also, RunAllTests() now runs every registered folder (it was an empty method), and AddTest() without a name uses the first folder's name.

What to do: nothing for the admin page. Code calling these methods directly with a path outside the registered folders: register the folder first with TestsManager::Instance()->AddTest([...], "name"). Don't register / or the project root: everything under a registered folder can be run.


9. Admin pages and actions can't include other files

Applies if: the project links to admin URLs with magrathea_page= or magrathea_subpage= built by hand, or added its own files to the framework's views/pages/ or views/actions/:

grep -rnE "magrathea_page=|magrathea_subpage=|GetPageUrl\(" --include='*.php' --include='*.js' . | grep -v vendor/

What changed: the admin included "pages/".$_GET["magrathea_page"].".php" and "actions/".$_GET["magrathea_subpage"].".php" as given, so a logged-in admin (or a link a logged-in admin was tricked into opening: GET requests have no CSRF check) could include any .php file the web server can read with ../, including the Bootstrap wizard's actions past item 1's lock. Now only a plain name of a file that exists in src/Admin/views/pages/ or src/Admin/views/actions/ is accepted. A bad action answers 404 "action not found"; a bad page answers 404 with a "Page not found" alert in the admin layout.

What to do: nothing, unless a link uses a page or action name that isn't one of those files: it already showed an empty page with a PHP warning, and now shows the 404. Custom admin pages belong in an admin feature (?magrathea_feature=).


10. New Database::Transaction(callable $fn)

Applies if: never required. Worth adopting where the project wraps several writes that must succeed or fail together (look for QueryTransaction( or sequences of Save()/Insert() that should be atomic).

What changed: new method. Everything the callback runs on the connection (model writes, controls, raw queries, SELECT … FOR UPDATE) commits when it returns and rolls back when it throws; the exception is rethrown unchanged. Nested calls run inline. QueryTransaction() throws if it's called inside Transaction() (no 2.3.5 code can do that, since Transaction() didn't exist).

What to do: nothing. If you adopt it: don't catch-and-continue DB exceptions inside the callback, and keep DDL out of it (MySQL commits DDL implicitly).


11. QueryTransaction() rolls back on failure

Applies if: the project calls QueryTransaction():

grep -rn "QueryTransaction" --include='*.php' . | grep -v vendor/

What changed:

What to do: nothing. Only code that compared the result with null (=== null) notices the new true; if (QueryTransaction(...)) is now true on success, and !== false checks don't change.


12. Cache files are written atomically

Applies if: the project uses the response cache, or calls SaveFile() directly:

grep -rn "Cache(\|SaveFile(\|cache_path" --include='*.php' --include='*.conf' . | grep -v vendor/

What changed: MagratheaCache::SaveFile() writes to a *.tmp file in the cache directory and renames it over the cache file. 2.3.5 truncated the cache file and then wrote it, so a concurrent request could serve an empty or partial JSON response. If the file can't be written, SaveFile() now returns false; 2.3.5 raised a warning and then a TypeError.

What to do: nothing, as long as the web server can write to the cache directory (a rename needs directory write permission; 2.3.5 could get by with a writable file in a read-only directory). Stray *.tmp files in the cache dir come from processes killed mid-write; "clear all cache" in the admin (RemoveAllCache()) removes them.


13. Cache() logs only in DEV

Applies if: something (a script, a log alert, a person) reads "adding cache for" lines from the Logger's files:

grep -rn "adding cache for" --include='*.php' --include='*.sh' . | grep -v vendor/

What changed: MagratheaApiControl::Cache() logged adding cache for [name/data] from (...) on every call in every environment, cache hits included, which flooded the logs on polled routes. It now logs only when MagratheaPHP::Instance()->IsDev() is true (Dev(); Debug() doesn't count).

What to do: nothing. To see the lines again, run the environment with ->Dev().


14. Raw-mode API calls bypass the response cache

Applies if: the project calls the API in raw mode (usually tests or CLI tools) on actions that call $this->Cache(...):

grep -rn "Run(true)\|SetRaw()\|ExecuteUrl(" --include='*.php' . | grep -v vendor/
grep -rn -- "->Cache(" --include='*.php' . | grep -v vendor/

What changed: ExecuteUrl() now calls MagratheaCache::Instance()->Bypass($returnRaw). In raw mode a cached action always runs and returns its data, and nothing is saved. In 2.3.5, a cache hit or a cache save in raw mode printed the JSON and ended the script with die, so the caller never got its return value (in PHPUnit, the run stopped silently with exit code 0).

What to do: nothing. Raw callers that worked around it (no_cache = true in the test environment, clearing the cache before each call) can drop the workaround. Warming the cache through raw calls isn't possible; make real HTTP requests for that.


15. CacheClear() doesn't change the current cache key

Applies if: an action calls Cache() and then CacheClear():

grep -rn "CacheClear(" --include='*.php' . | grep -v vendor/

What changed: MagratheaCache::Clear() (behind CacheClear()) used to set the current cache key to the one it cleared, so the action's response was saved under the cleared key instead of its own. It now leaves the key alone.

What to do: nothing. If such an action exists, its cache file now gets its intended name; stray files saved under the wrong name can be cleared from the admin's Cache feature.


16. API errors are sent with real HTTP statuses

This is the most visible change in 2.4.0. There is no switch to keep the old behavior.

Applies if: the project has API clients (front end, mobile app, other services) built on a client that rejects 4xx/5xx responses (axios, jQuery $.ajax/$.get/$.post, Angular HttpClient, Guzzle with http_errors) and checks success in its success handler:

grep -rnE "\.success\b|success\s*[!=]==?\s*false" --include='*.js' --include='*.ts' --include='*.jsx' --include='*.tsx' --include='*.vue' . | grep -v node_modules/ | grep -v vendor/

and, on the PHP side, if it calls ReturnError() or ReturnFail() itself:

grep -rn "ReturnError(\|ReturnFail(" --include='*.php' . | grep -v vendor/

What changed: in 2.3.5 most error responses were HTTP 200 with {"success": false, ...}: unknown routes (404), exceptions that aren't MagratheaApiException, and ReturnError() without a $status. Only MagratheaApiException and a failed authorization used real statuses. Now every error response has a 4xx/5xx status, derived from the error code (404 → 404, 4031 → 403, 40312 → 403, anything else → 500):

Case2.3.52.4.0
unknown route200404
exception with code 0 (new \Exception("x"))200, data: {}500, data: {"message": "x"}
exception with a code (new \Exception("x", 4091))200409
ReturnError($code, ...) without $status200from $code
ReturnError(..., $status)$status$status (unchanged)
ReturnFail($exception)200from the code (500 for 0)
ReturnFail($array)200200 (unchanged)
MagratheaApiExceptionfrom the codefrom the code (unchanged, except item 19)

Response bodies are the same, except that an exception with code 0 now carries its message (it was encoded as {}).

What to do:

```js // axios, before const rs = (await axios.get("/api/products/1")).data; if (!rs.success) return showError(rs.data.message);

// axios, after (works on both versions) try { const rs = (await axios.get("/api/products/1")).data; if (!rs.success) return showError(rs.data.message); // 2.3.5 only } catch (err) { const body = err.response && err.response.data; // {"success": false, "data": {...}} return showError(body && body.data ? body.data.message : err.message); } ```

```js // jQuery, before $.get("/api/products/1", rs => { if (!rs.success) return showError(rs.data.message); render(rs.data); });

// jQuery, after (works on both versions) $.get("/api/products/1", rs => { if (!rs.success) return showError(rs.data.message); // 2.3.5 only render(rs.data); }).fail(jqXHR => { const body = jqXHR.responseJSON; // {"success": false, "data": {...}} showError(body && body.data ? body.data.message : jqXHR.statusText); }); ```


17. MagratheaApiException::SetStatus() is honored

Applies if:

grep -rn "SetStatus(\|->status\b" --include='*.php' . | grep -v vendor/

What changed: SetStatus() stored a status that nothing read; the HTTP status always came from the code. Now a SetStatus() value between 400 and 599 is the response's status (others are ignored). $status defaults to null (it was 500, or 200 for $kill = false), and $kill no longer affects any status. The framework's own GetAuthorizationToken() uses it: a request without a token gets HTTP 401 (code 400 in the body), where 2.3.5 sent HTTP 400.

What to do: check each SetStatus() call: the status it sets is what clients get now. Code that read $ex->status expecting 500/200 gets null unless SetStatus() was called.


18. PHP \Errors in API actions become a JSON 500

Applies if: always (no action needed).

What changed: a TypeError or other PHP \Error thrown by an API action or auth method (in MagratheaApi and the admin's AdminApi) used to escape as a PHP fatal error, with an HTML body. Now it is logged with Logger::LogError() (class, message, file:line; PHP's error_log() if the Logger can't write) and answered as {"success": false, "data": {"message": "Internal Server Error"}} with HTTP 500. In DEV the response has the real message, the class and file:line. Logger::LogError() also accepts PHP \Errors and non-exceptions now (they used to be logged without a message).

What to do: nothing. These errors now land in the Magrathea log (logs_path) instead of PHP's error log, so check there.


19. Codes outside the status scheme give HTTP 500

Applies if: the project throws exceptions or calls ReturnError() with codes that don't map to a 4xx/5xx status (e.g. 2001, 3000, 7000, or 3-digit codes below 400):

grep -rnE "MagratheaApiException\([^,]+,\s*[0-9]+|ReturnError\(\s*[0-9]+" --include='*.php' . | grep -v vendor/

What changed: the code → status mapping (3 digits as is, 4 digits / 10, 5 digits / 100) is kept, but a result outside 400-599 now gives 500. In 2.3.5 MySQL's 1062 gave HTTP 106, 2001 gave HTTP 200 on an error, 7000 gave 700. Codes 400-599, 4000-5999 and 40000-59999 are unchanged.

What to do: nothing, unless a code was chosen to produce a non-error status; use SetStatus() or an explicit ReturnError() $status instead.


20. BaseAuthorization() takes a MagratheaApiAuth

Applies if: the project calls BaseAuthorization():

grep -rn "BaseAuthorization(" --include='*.php' . | grep -v vendor/

Then check what the class it receives extends:

grep -rnE "class \w+ extends \\\\?(Magrathea2\\\\)?MagratheaApi(Auth|Control)\b" --include='*.php' . | grep -v vendor/

What changed: the parameter was typed MagratheaApiControl, but the value is stored in a ?MagratheaApiAuth property, so passing a plain MagratheaApiControl already threw a TypeError ("Cannot assign … to property … $authClass"). The parameter is now typed MagratheaApiAuth, so the TypeError names the call instead. The framework's own docs and skills.MD showed AuthControl extends MagratheaApiControl passed to BaseAuthorization(): code copied from them never worked.

What to do:

```php // before class AuthControl extends MagratheaApiControl { ... }

// after class AuthControl extends MagratheaApiAuth { ... } ```


21. DEV and DEBUG API responses carry debug items in _debug

Applies if: the project runs its API with ->Dev() or ->Debug() (or Debugger::DEV/Debugger::DEBUG) anywhere: local machines, staging. Production (->Prod()) is unaffected.

grep -rn -- "->Dev()\|->Debug()\|SetDev()\|SetDebug()\|Debugger::DEV\|Debugger::DEBUG" --include='*.php' . | grep -v vendor/

What changed: in DEV every debug item, including every MagratheaException when it's created (even one that's caught), was printed as <pre>…</pre>. In DEBUG they were all printed as an HTML box at the end of the request. In an API call that HTML landed before (DEV) or after (DEBUG) the JSON, so clients failed to parse the response. Now, while MagratheaApi::ExecuteUrl() (and so Run()) runs, DEV and DEBUG collect those items and the response gets them as an extra _debug key. In DEBUG it also carries the items stored before the call, and the end-of-request box is no longer printed after a JSON response:

{"success": true, "data": {...}, "_debug": [
  {"type": "Magrathea2\\Exceptions\\MagratheaException", "message": "...", "code": 42, "file": "/path/X.php:40", "data": {...}},
  "a string passed to Debugger::Add()"
]}

What to do: nothing.


23. Update() writes the fields that changed

Applies if: the project updates models with Save()/Update(). It needs action only where LoadObjectFromTableRow() is fed something that isn't a DB row:

grep -rn "LoadObjectFromTableRow" --include='*.php' . | grep -v vendor/
grep -rnE -- "->(Save|Update)\(\)" --include='*.php' . | grep -v vendor/

What changed: an object is now loaded after new Model($id), GetById(), any Control query, LoadObjectFromTableRow(), or its own Insert()/InsertWithPk()/Update(). A loaded object's Update() writes the fields whose value changed since then (plain assignments like $obj->name = … and Set()/Assign() alike), plus updated_at. In 2.3.5, one Set() made Update() write only the Set() fields and silently drop the plain assignments; without any Set() it rewrote every column.

What to do:

``php $obj = new Article($id); $obj->Assign($this->GetPut()); $obj->Save(); ``


24. A model object in a field is saved as its id

Applies if: code assigns a model object to a field ($article->author_id = $author;) and saves. There's no reliable grep; look at FK assignments near Save()/Insert()/Update().

What changed: Insert()/Update() meant to save a related model's id, inserting the model first if it had none, but the check never matched (is_a() with an unqualified class name). The object itself was bound: an int field got 1 (with a PHP warning), a string field the object's __toString() text. Now the id is written, and a related model without an id is inserted first.

What to do: nothing. If a row was saved this way in 2.3.5, its FK holds 1: fix the data.


25. Update() can set int and boolean columns to NULL

Applies if: code sets an int/boolean field to null on a loaded object and saves, or saves form/API input where an int field can be empty (""), e.g. the admin CRUD (int fields are text inputs):

grep -rnE -- "->[a-z_]+ *= *null;|Set\([^,]+, *null\)" --include='*.php' . | grep -v vendor/
grep -rnE -- "->Assign\(" --include='*.php' . | grep -v vendor/

What changed: Update() skipped every null int/boolean field, so a nullable FK could never be cleared; "" was bound as is (MySQL strict mode: Incorrect integer value error; otherwise 0). Now, for int/boolean fields:

What to do:


26. composer.json requires PHP 8.1+

Applies if: Composer runs on PHP 8.0 or older (php -v, on the machine that runs composer).

What changed: composer.json now has "php": ">=8.1". The framework already needed PHP 8.1: 2.3.x declares an enum (Magrathea2\DB\QueryType), which is a fatal error on PHP 8.0 as soon as the query builder loads. The constraint only makes Composer say so up front.

What to do: nothing if the project runs today. If Composer itself runs on an older PHP than the server (a CI image, a deploy box), upgrade it there, or Composer won't install 2.4.0.


27. Failed writes always throw

Applies if: the project turns mysqli error reporting off, or code checks the return value of a write instead of catching:

grep -rn "mysqli_report" --include='*.php' . | grep -v vendor/
grep -rnE "if *\( *!.*->(Insert|InsertWithPk|Update|Save|Delete|PrepareAndExecute)\(|(Insert|Update|Save|Delete|PrepareAndExecute)\(.*\) *[!=]==? *(null|false)" --include='*.php' . | grep -v vendor/

What changed:

What to do:


28. DB errors are always MagratheaDBException, with MySQL's errno as code

Applies if: code catches mysqli_sql_exception, or reads a DB exception's code:

grep -rn "mysqli_sql_exception" --include='*.php' . | grep -v vendor/
grep -rn "catch *(.*MagratheaDBException" --include='*.php' . | grep -v vendor/

What changed:

What to do:


29. Model writes bind int fields as integers

Applies if: the project has a BIGINT UNSIGNED int field (usually a PK) with values above 9223372036854775807 (PHP_INT_MAX). Every other project: nothing to do.

What changed: Insert(), Update() and Delete() bound every value as a string ("s"), and MySQL converted it: PrepareAndExecute() didn't recognize "integer", the type the model passes for int and boolean fields. They're bound as integers ("i") now. Update() also binds the WHERE PK by the PK field's type (it was always a string), as Delete() already did. float fields stay strings, so DECIMAL values don't go through a PHP float. Direct PrepareAndExecute() calls with "int", "boolean" or "float" are unchanged; "integer" is now bound as an integer too.

What to do: nothing. With a BIGINT UNSIGNED value above PHP_INT_MAX, the WHERE PK of Update() and Delete() is now clamped to PHP_INT_MAX (bound as a string, it worked), so they hit the wrong row or none. Insert()/Update()'s values were already clamped by intval(). Declare such a field as "string", or write those rows with the query builder.


30. One database connection per request

Applies if: always, but it needs action only in long-running CLI scripts (workers, daemons, queue consumers) and in code that relied on CloseConnectionThanks() actually closing:

grep -rnE "while *\(true\)|for *\(;;\)" --include='*.php' . | grep -v vendor/
grep -rn "CloseConnectionThanks\|pcntl_fork" --include='*.php' . | grep -v vendor/

What changed: each Database instance now opens one connection on its first query and reuses it until the end of the request (a shutdown function closes it). 2.3.5 opened and closed a connection for every query, including every escaped value in the query builder.

What to do:

``php while (true) { \Magrathea2\DB\Database::Instance()->Disconnect(); // ... take and process one job ... } ``

Catching MagratheaDBConnectionLostException and retrying is only safe for idempotent work: code 2006 means the statement probably didn't run, 4031 that it didn't, 2013 that it may have.


31. QueryMulti() returns SELECT rows

Applies if: the project calls QueryMulti()/ImportFile(), or Query() with more than one statement:

grep -rn "QueryMulti\|ImportFile" --include='*.php' . | grep -v vendor/

What changed: each SELECT's result used to be an empty array; it now holds the rows (assoc arrays).

What to do: nothing, unless code relied on result being empty for SELECTs.


32. db_port is no longer ignored

Applies if: the config has db_port:

grep -rn "db_port" configs/

What changed: MagratheaPHP::Connect() never read db_port, and Database::SetConnection() threw away any port it was given (an inverted if). Every connection used mysqli's default port. Now Connect() passes db_port, and SetConnection() uses it. Without db_port (or with it empty), mysqli's default port is used, as before. With db_host = "localhost", mysqli connects through the Unix socket and ignores the port either way.

What to do: make sure db_port is the server's real port, or remove it. A wrong value that 2.3.5 silently ignored now makes the connection fail.


33. The timezone key is timezone

Applies if: the config has time_zone (the old sample's spelling), or no timezone key at all:

grep -n "time_zone\|timezone" configs/magrathea.conf

What changed: only timezone, in the environment section, was ever read by MagratheaPHP::Load(). The sample config and the docs wrote time_zone (in [general] and [dev]), which was silently ignored: those projects ran on php.ini's default timezone (often UTC). Nothing changes on upgrade: time_zone is still ignored. The sample now uses timezone only, and the admin's Server page and the Bootstrap wizard's config step show a timezone check that flags time_zone.

What to do:


34. MySQL's session timezone is synced to PHP's

Applies if: the config has timezone (after item 33's rename, or already) and the MySQL server runs in a different zone. Check it on the server, before upgrading:

SELECT @@global.time_zone, @@system_time_zone, NOW();

and compare with PHP (php -r 'date_default_timezone_set("America/Sao_Paulo"); echo date_default_timezone_get(), " ", date("Y-m-d H:i:s"), "\n";', with your timezone). Same time: nothing to do. Different: read on.

What changed: each new connection runs SET time_zone = '<PHP's timezone>', so NOW(), CURRENT_TIMESTAMP, column defaults, ON UPDATE CURRENT_TIMESTAMP and triggers use PHP's zone. It's on by default when timezone is set; db_sync_timezone = false (or 0, off, no, quoted or not) in the same section turns it off. If MySQL's timezone tables aren't loaded (error 1298), the current offset (e.g. -03:00) is used, which doesn't follow DST. MySQL scheduled events and other clients (mysql CLI, BI tools) aren't affected.

When the zones differ, after the upgrade:

``sql SELECT table_name, column_name FROM information_schema.columns WHERE table_schema = DATABASE() AND data_type = 'timestamp'; ``

What to do:

``ini [production] timezone = "America/Sao_Paulo" db_sync_timezone = false ``


35. Autoloader picks the file whose namespace matches

Applies if: two code folders have a file with the same name. List the candidates (run from the project root):

find . -path ./vendor -prune -o -name '*.php' -printf '%f\n' | sort | uniq -d

No output: nothing to do. A name listed there matters only if both files are in registered code folders (AddCodeFolder(), AddFeature()).

What changed: the autoloader looks for <ClassName>.php (basename only) in every code folder. 2.3.5 loaded the first file found, in folder order, even when it declared another namespace (then the class wasn't defined, or the wrong class with the same name was used). 2.4.0 loads the file whose namespace declaration matches the requested class; if none matches, the first one, as before. In DEV, each duplicate lookup adds a debug item (<pre> on pages, _debug in API responses) listing the files. A folder registered twice (AddFeature("X") plus AddRootCodeFolder("features/X")) isn't a duplicate.

What to do: for each duplicate, check that the class now loaded is the one the code meant (2.3.5 may have run the other one without anybody noticing). Then rename one of the classes, so each basename is unique: that removes the DEV warning and the extra file reads.


36. A missing class isn't a MagratheaException anymore

Applies if: the project calls ->AppNamespace(...) (otherwise the autoloader never threw) and catches MagratheaException around code that may use a missing class:

grep -rn "AppNamespace(" --include='*.php' . | grep -v vendor/
grep -rn "catch.*MagratheaException" --include='*.php' . | grep -v vendor/

What changed: for a class in the app namespace that isn't in any code folder, the autoloader threw MagratheaException("Could not find class [...]. Are the code folders correct?", 500). It returns silently now: class_exists("App\X") returns false (it threw), autoloaders registered after Magrathea's run (they never did), and new X() fails with PHP's Error: Class "App\X" not found. In DEV, the "Could not find class" hint is still added as a debug item, with the code folders.

What to do: nothing, unless a catch (MagratheaException ...) was meant to handle a missing class: catch \Error there, or test with class_exists() first. A catch-all catch (\Exception ...) doesn't catch \Error either.


39. New decimal field type

Applies if: a model declares "float" for a column that is DECIMAL in the database. List the float fields, then the database's DECIMAL columns, and compare:

grep -rn '"float"' --include='*.php' . | grep -v vendor/
SELECT table_name, column_name FROM information_schema.columns
WHERE table_schema = DATABASE() AND data_type = 'decimal';

What changed: 2.3.5 had no type for DECIMAL, so money columns were declared "float" (the docs said so). With protected $strictTypes = true;, a float field is cast with (float) on load, so a large DECIMAL (e.g. 12345678901234567.89) loads rounded, and a later Update() writes the rounded value back. 2.4.0 adds "decimal": always the exact string the driver returns, strict or not (strict mode only checks it's numeric and throws MagratheaModelException if not), and bound as a string on writes. The admin's object generator now detects DECIMAL columns as decimal and DOUBLE as float (both were "unknown"). Existing float fields behave exactly as before.

What to do:


40. The code generator makes new objects strict

Applies if: you create or regenerate objects in the admin ("Objects" → object form → generate code).

What changed: the object form has a "Strict types" select, saved as strict_types in the object's section of magrathea_objects.conf. When it's true, the generated Base class gets protected $strictTypes = true; (typed values on load: JSON numbers and booleans instead of strings). It defaults to true for a new object. Objects created before 2.4.0 have no strict_types key: they generate exactly as before, and the form shows false for them, so re-saving one doesn't change it.

What to do: nothing for existing objects. For a new object you want to keep string-typed (e.g. it must match the JSON of older endpoints), pick false before generating.


41. The code generator's mvc structure works

Applies if: the admin's "Generate Code" page is set to "Model-View-Control" (code_structure = mvc in the admin's app config), or a CRUD admin class's model and control live in different namespaces.

What changed:

What to do: on an mvc project, regenerate each object's Base model (the CRUD form calls GetControl() for relation fields). A hand-written CRUD admin whose control isn't <model class>Control can now pass it: $this->SetObject(new Article(), new \App\Controls\ArticleControl());. Nothing for feature projects.


42. Admin features: Initialize() runs first, and once

Applies if: an admin CRUD class's Initialize() does more than SetObject(), or any admin feature's Initialize() reads $this->featureId (directly, or through GetSubpageUrl() and other URL helpers):

grep -rln "extends .*AdminCrudObject" --include='*.php' . | grep -v vendor/ | xargs -r grep -n -A8 "function Initialize"
grep -rlE "extends .*(AdminFeature|AdminCrudObject)\b" --include='*.php' . | grep -v vendor/ | xargs -r grep -n "featureId"

What changed:

What to do:


43. The admin's Query Tester is gone

Applies if: the project links to the Query Tester or adds its menu item:

grep -rnE "query-creator|mag-query" --include='*.php' --include='*.js' . | grep -v vendor/

What changed: the "Magrathea Query Tester [WIP]" page (Database → "Magrathea Query", ?magrathea_page=query-creator) appended the posted text to PHP code and ran it with eval(), so any logged-in admin, or any script running in an admin's browser (see 46), ran PHP on the server. The page, its action and its script are removed, and so is the mag-query menu item. AdminMenu::GetItem("mag-query") returns null, and AdminMenu::Add() now ignores null (alone or inside an array of items).

What to do: nothing for the default menu. A link to ?magrathea_page=query-creator now gets "Page not found": remove it. A custom BuildMenu() that adds GetItem("mag-query") shows nothing there: remove the call. To run SQL from the admin, use the Queries page (Database → Queries).


44. Admin backups: validated names, no shell, no password on the command line

Applies if: code calls AdminDatabase's backup methods, or backups are made with names other than letters, digits, ., _ and -:

grep -rnE "GetCommand\(|DoBackup\(|CreateBackupFile" --include='*.php' --include='*.js' . | grep -v vendor/
php -r 'var_dump(function_exists("proc_open"));'   # on the server, with the web server's PHP config

What changed:

What to do:


45. file-view and the logs page only read their own files

Applies if: custom admin code posts to the file-view action, or includes it:

grep -rn "file-view" --include='*.php' --include='*.js' . | grep -v vendor/

What changed: file-view read the file whose path was posted in file when the including view hadn't set one, and the logs page posted absolute paths to it, so any logged-in admin read any file the web server can read. Now file-view only renders the $viewFile set by the view that includes it (and the optional $viewLines for a tail); called directly (?magrathea_subpage=file-view) it answers 404 "action not found". The logs page uses the new log-view action, which takes a file name inside the logs folder (not a path) and lines clamped to 1–10000. The tail is HTML-escaped (log lines carry request data, so viewing a log could run script in the admin), and the view can be included more than once in a request (it declared a global function, and it ended the request with die, which also cut short the pages that include it).

What to do: nothing, unless custom admin code posts to file-view: write your own action that sets $viewFile to a fixed path and includes file-view.php, or post a log file name to log-view.


46. The admin escapes table and form values

Applies if: the project's own admin code (custom features, custom pages, overridden Columns()/ GetEditColumn()/Fields() in CRUD features) calls Table() or the form elements:

grep -rn "Table(\|->Input(\|->Textarea(\|->Select(" --include='*.php' . | grep -v vendor/

then, in those calls, look for HTML passed as a value (a link, a button, a badge, <b>), and for values escaped before being passed (htmlspecialchars(, htmlentities().

What changed: AdminElements::Table() printed every value as HTML, and so did the form elements' values (Input(), Textarea(), Select(), Checkbox(), and so AdminForm and every CRUD list and form). Any text an app user can store (a name, a title, a comment) ran as script in the admin of whoever looked at it, with the admin's session and CSRF token: one admin click away from running SQL through the Queries page, and PHP through the Query Tester (43). Now:

What to do:

``php // before: "action" => "<a href='".$url."'>Edit</a>" in each row $elements->Table($rows, [ "name" => "Name", ["title" => "Edit", "key" => function($row) use ($url) { return "<a href='".$url."'>".htmlspecialchars($row["name"])."</a>"; }], ]); // or, per row: "action" => fn() => "<a href='".$url."'>Edit</a>" ``


47. Admin actions escape their query-string parameters

Applies if: the project links to the admin's object or code-generation actions with its own onclose callback:

grep -rn "onclose=" --include='*.php' --include='*.js' . | grep -v vendor/

What changed: several admin actions printed query-string parameters as HTML or into onclick handlers: object, table and onclose in object-detail, object-create, object-edit (and its relation views), code-create and code-gen-view; id in a CRUD feature's page and its "can't find" error; env on the Config page; the feature name in "Feature not available". GET requests have no CSRF check, so a link sent to a logged-in admin (…&onclose=alert(document.cookie)//) ran script in the admin. Now those values are escaped, onclose is used only when it's a plain JS function name (AdminElements::JsCallback()), object-detail answers "object not found" for an unknown object, and the table name is backtick-quoted in SHOW COLUMNS.

What to do: nothing, unless a link passes something other than a function name as onclose (e.g. onclose=myFn('x')): pass the function name only; it's called with the card element, or with the object name for code-create.


48. Admin feature URLs only call the feature's own actions

Applies if: the project has its own admin features (classes extending AdminFeature or AdminCrudObject), or calls a CRUD feature's Save/Delete or App Config's Import without a POST:

grep -rlE "extends .*(AdminFeature|AdminCrudObject)\b" --include='*.php' . | grep -v vendor/
grep -rnE "magrathea_feature_(subpage|action)=|callFeature\(" --include='*.php' --include='*.js' . | grep -v vendor/

What changed:

What to do:


Verify after upgrading