1<?php
2// (c) Copyright by authors of the Tiki Wiki CMS Groupware Project
3//
4// All Rights Reserved. See copyright.txt for details and a complete list of authors.
5// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
6// $Id$
7
8if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
9	header("location: index.php");
10	exit;
11}
12
13/*
14This patch will TRUNCATE the tiki_objects.itemId and name values so they don't exceed the maximum allowed page name length
15The current maximum allowed page name length = 158 characters.
16However, previously pages could be the full 160 characters. Because there was no bounds checking.
17For pages that don't use tiki_objects, the save would work.
18
19So, this script should truncate to 160 characters (max pageName attribute length), instead of the new 158 char max.
20
21Errors in long names in tiki_objects for wiki page names, is caused by the difference in varchar length.
22tiki_pages.pageName 	varchar(160)
23tiki_objects.itemId		varchar(255)
24tiki_objects.name		varchar(200)
25Previously there was no check on the page name length, causing the maximum possible number of characters to be stored.
26This again caused pagename comparisons to fail and an incorrect href for tiki_objects.
27Pages linked to categories are affected.
28
29New pagenames are now truncated to 158 characters in the code, thus new pages will behave correctly.
30
31This script fixes existing records by
321) Shortening the max page name (ItemId / name) length
332) Rebuilding the href value
34*/
35function upgrade_20130809_limit_name_lengths_in_objects_tiki($installer)
36{
37	$max_pagename_length = 160;
38
39	// Fix tiki_objects
40	///////////////////////////
41
42	// Find all records with long pagenames
43	$query = 'SELECT objectId, itemId, name, href FROM tiki_objects where type = "wiki page" and  length(itemId) > ?';
44	$results = $installer->query($query, [$max_pagename_length]);
45	if ($results) {
46		$newValues = [];
47		while ($row = $results->fetchRow()) {
48			// Update the page name
49			$itemId = substr($row['itemId'], 0, $max_pagename_length);
50			$name = substr($row['name'], 0, $max_pagename_length);
51			// Update the URL
52			$href = "tiki-index.php?page=" . urlencode($itemId);
53			$objectId = (int)$row['objectId'];
54
55			// Build the query parameters
56			$newValues[] = [$itemId, $name, $href, $objectId];
57		}
58
59		// Update the database record
60		$query = "update tiki_objects set itemId = ?, name=?, href=? where objectId = ?";
61		foreach ($newValues as $newVal) {
62			$installer->query($query, $newVal);
63		}
64	}
65}
66