<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  Christopher Graham
 * @package    core_cns
 */

/**
 * Hook class.
 */
class Hook_task_cns_members_dedup
{
    /**
     * Run the task hook.
     *
     * @return ?array A tuple of at least 2: Return mime-type, content (either Tempcode, or a string, or a filename and file-path pair to a temporary file), map of HTTP headers if transferring immediately, map of ini_set commands if transferring immediately (null: show standard success message)
     */
    public function run() : ?array
    {
        push_query_limiting(false);

        set_mass_import_mode(true); // Usually this task is run from the importer

        cms_extend_time_limit(TIME_LIMIT_EXTEND__SLUGGISH);

        require_code('cns_members2');

        $current_row = null;

        // For matching on e-mail, we grant priority to the account which was most recently used; all others will be merged into it
        $duplicate_members = $GLOBALS['FORUM_DB']->query_parameterised('SELECT id,m_email_address,m_last_visit_time FROM {prefix}f_members WHERE m_email_address!=\'\' AND m_email_address IN (SELECT m_email_address FROM {prefix}f_members GROUP BY m_email_address HAVING COUNT(m_email_address) > 1) ORDER BY m_email_address, m_last_visit_time DESC', []);

        foreach ($duplicate_members as $member) {
            if ($member['m_email_address'] == '') { // Ignore accounts with no set e-mail address
                continue;
            }

            // Change in address, so note which member we are on now and continue
            if (($current_row === null) || ($current_row['m_email_address'] != $member['m_email_address'])) {
                $current_row = $member;
                continue;
            }

            // This address matches the previous, so merge it in
            cns_merge_members($member['id'], $current_row['id'], false);
        }

        pop_query_limiting();

        set_mass_import_mode(false);

        return null;
    }
}
