<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2018

 See text/EN/licence.txt for full licensing information.

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    core
 */

// Fixup SCRIPT_FILENAME potentially being missing
$_SERVER['SCRIPT_FILENAME'] = __FILE__;

// Find Composr base directory, and chdir into it
global $FILE_BASE, $RELATIVE_PATH;
$FILE_BASE = (strpos(__FILE__, './') === false) ? __FILE__ : realpath(__FILE__);
$FILE_BASE = dirname($FILE_BASE);
if (!is_file($FILE_BASE . '/sources/global.php')) {
    $RELATIVE_PATH = basename($FILE_BASE);
    $FILE_BASE = dirname($FILE_BASE);
} else {
    $RELATIVE_PATH = '';
}
if (!is_file($FILE_BASE . '/sources/global.php')) {
    $FILE_BASE = $_SERVER['SCRIPT_FILENAME']; // this is with symlinks-unresolved (__FILE__ has them resolved); we need as we may want to allow zones to be symlinked into the base directory without getting path-resolved
    $FILE_BASE = dirname($FILE_BASE);
    if (!is_file($FILE_BASE . '/sources/global.php')) {
        $RELATIVE_PATH = basename($FILE_BASE);
        $FILE_BASE = dirname($FILE_BASE);
    } else {
        $RELATIVE_PATH = '';
    }
}
@chdir($FILE_BASE);

global $FORCE_INVISIBLE_GUEST;
$FORCE_INVISIBLE_GUEST = false;
global $EXTERNAL_CALL;
$EXTERNAL_CALL = false;
if (!is_file($FILE_BASE . '/sources/global.php')) {
    exit('<!DOCTYPE html>' . "\n" . '<html lang="EN"><head><title>Critical startup error</title></head><body><h1>Composr startup error</h1><p>The second most basic Composr startup file, sources/global.php, could not be located. This is almost always due to an incomplete upload of the Composr system, so please check all files are uploaded correctly.</p><p>Once all Composr files are in place, Composr must actually be installed by running the installer. You must be seeing this message either because your system has become corrupt since installation, or because you have uploaded some but not all files from our manual installer package: the quick installer is easier, so you might consider using that instead.</p><p>ocProducts maintains full documentation for all procedures and tools, especially those for installation. These may be found on the <a href="http://compo.sr">Composr website</a>. If you are unable to easily solve this problem, we may be contacted from our website and can help resolve it for you.</p><hr /><p style="font-size: 0.8em">Composr is a website engine created by ocProducts.</p></body></html>');
}
require($FILE_BASE . '/sources/global.php');

// Put code that you temporarily want executed into the function. DELETE THE CODE WHEN YOU'RE DONE.
// This is useful when performing quick and dirty upgrades (e.g. adding tables to avoid a reinstall)

if (function_exists('require_all_core_cms_code')) {
    require_all_core_cms_code();
} else {
}
require_code('config2');
require_code('menus2');
execute_temp();

/**
 * Execute some temporary code put into this function.
 *
 * @return mixed Arbitrary result to output, if no text has already gone out
 */
function execute_temp()
{
    header('Content-type: text/plain');

    $GLOBALS['NO_QUERY_LIMIT'] = '1';

    $make_changes = (get_param_integer('make_changes', 0) == 1);

    $max = 500;

    // Find rows that need to be deprecated
    $start = 0;
    do {
        $rows = $GLOBALS['SITE_DB']->query_select('url_id_monikers', array('*'), array('m_deprecated' => 0), 'ORDER BY id', $max, $start);

        foreach ($rows as $row) {
            switch ($row['m_resource_page'] . ':' . $row['m_resource_type']) {
                case 'iotds:view':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('iotd', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'quiz:do':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('quizzes', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'polls:view':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('poll', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'news:view':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('news', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'news:browse':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('news_categories', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'galleries:video':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('videos', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'galleries:image':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('images', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'galleries:browse':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('galleries', 'name', array('name' => $row['m_resource_id']), '', true) !== null);
                    break;
                case 'downloads:view':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('download_downloads', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'downloads:browse':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('download_categories', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'topicview:g:browse':
                    $exists = ($GLOBALS['FORUM_DB']->query_select_value_if_there('f_topics', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'groups:view':
                    $exists = ($GLOBALS['FORUM_DB']->query_select_value_if_there('f_groups', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'forumview:browse':
                    $exists = ($GLOBALS['FORUM_DB']->query_select_value_if_there('f_forums', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'chat:room':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('chat_rooms', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'catalogues:entry':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('catalogue_entries', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'catalogues:category':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('catalogue_categories', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
                case 'calendar:view':
                    $exists = ($GLOBALS['SITE_DB']->query_select_value_if_there('calendar_events', 'id', array('id' => intval($row['m_resource_id'])), '', true) !== null);
                    break;
            }

            if (!$exists) {
                $conflict_map = array('m_resource_page' => $row['m_resource_page'], 'm_resource_type' => $row['m_resource_type'], 'm_moniker' => $row['m_moniker']);
                $is_duplicated = ($GLOBALS['SITE_DB']->query_select_value('url_id_monikers', 'COUNT(*)', $conflict_map) > 1);

                if ($is_duplicated) {
                    echo 'Broken URL moniker reference that is on a duplicated moniker: ' . serialize($row);
                } else {
                    echo 'Broken URL moniker reference that should be marked deprecated: ' . serialize($row);
                }

                if ($make_changes) {
                    if ($is_duplicated) {
                        $GLOBALS['SITE_DB']->query_delete('url_id_monikers', array('id' => $row['id']), '', 1);
                    } else {
                        $GLOBALS['SITE_DB']->query_update('url_id_monikers', array('m_deprecated' => 1), array('id' => $row['id']), '', 1);
                    }

                    echo ' - FIXED';
                }

                echo "\n";
            }
        }

        $start += $max;
    }
    while (count($rows) > 0);

    // Find any duplication
    $start = 0;
    do {
        $rows = $GLOBALS['SITE_DB']->query_select('url_id_monikers', array('*'), array('m_deprecated' => 0), 'ORDER BY id', $max, $start);

        foreach ($rows as $row) {
            $conflict_map = array('m_resource_page' => $row['m_resource_page'], 'm_resource_type' => $row['m_resource_type'], 'm_moniker' => $row['m_moniker']);
            $is_duplicated = ($GLOBALS['SITE_DB']->query_select_value('url_id_monikers', 'COUNT(*)', $conflict_map) > 1);
            if ($is_duplicated) {
                echo 'Duplicated URL moniker reference: ' . serialize($row);

                if ($make_changes) {
                    $GLOBALS['SITE_DB']->query_delete('url_id_monikers', array('id' => $row['id']), '', 1);

                    echo ' - FIXED';
                }

                echo "\n";
            }
        }

        $start += $max;
    }
    while (count($rows) > 0);
}
