Copy a track and all it's related data (rounds/fields etc)

@param inte $oldTrackId  The id of the track to copy
@return int              The id of the copied track
345103
public function copyTrack($oldTrackId)
    {
        $trackModel = $this->tracker->getTrackModel();

        $roundModel = $this->getRoundModel(true, 'rounds');
        $fieldModel = $this->getFieldsMaintenanceModel();

        // First load the track
        $trackModel->applyParameters(array('id' => $oldTrackId));
        $track = $trackModel->loadFirst();

        // Create an empty track
        $newTrack = $trackModel->loadNew();
        unset($track['gtr_id_track'], $track['gtr_changed'], $track['gtr_changed_by'], $track['gtr_created'], $track['gtr_created_by']);
        $track['gtr_track_name'] .= $this->_(' - Copy');
        $newTrack = $track + $newTrack;
        // Now save (not done yet)
        $savedValues = $trackModel->save($newTrack);
        $newTrackId = $savedValues['gtr_id_track'];

        // Now copy the fields
        $fieldModel->applyParameters(array('id' => $oldTrackId));
        $fields = $fieldModel->load();

        if ($fields) {
            $oldIds = array();
            $numFields = count($fields);
            $newFields = $fieldModel->loadNew($numFields);
            foreach ($newFields as $idx => $newField) {
                $field = $fields[$idx];
                $oldIds[$idx] = $field['gtf_id_field'];
                unset($field['gtf_id_field'], $field['gtf_changed'], $field['gtf_changed_by'], $field['gtf_created'], $field['gtf_created_by']);
                $field['gtf_id_track'] = $newTrackId;
                $newFields[$idx] = $field + $newFields[$idx];
            }
            // Now save (not done yet)
            $savedValues = $fieldModel->saveAll($newFields);
            foreach($savedValues as $idx => $field) {
                $oldNewFieldMap[$oldIds[$idx]] = $field['gtf_id_field'];
            }
        } else {
            $numFields = 0;
        }

        // Now copy the rounds and map the gro_id_relation to the right field
        $roundModel->applyParameters(array('id' => $oldTrackId));
        $rounds = $roundModel->load();

        if ($rounds) {
            $numRounds = count($rounds);
            $newRounds = $roundModel->loadNew($numRounds);
            foreach ($newRounds as $idx => $newRound) {
                $round = $rounds[$idx];
                unset($round['gro_id_round'], $round['gro_changed'], $round['gro_changed_by'], $round['gro_created'], $round['gro_created_by']);
                $round['gro_id_track'] = $newTrackId;
                if (array_key_exists('gro_id_relationfield', $round) && $round['gro_id_relationfield']>0) {
                    $round['gro_id_relationfield'] = $oldNewFieldMap[$round['gro_id_relationfield']];
                }
                $newRounds[$idx] = $round + $newRounds[$idx];
            }
            // Now save (not done yet)
            $savedValues = $roundModel->saveAll($newRounds);
        } else {
            $numRounds = 0;
        }

        //MUtil_Echo::track($track, $copy);
        //MUtil_Echo::track($rounds, $newRounds);
        //MUtil_Echo::track($fields, $newFields);
        Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger')->addMessage(sprintf($this->_('Copied track, including %s round(s) and %s field(s).'), $numRounds, $numFields));

        return $newTrackId;
    }
1069847
public function addChangeMethod($output, $new, $old)
    {
        $output[] = $this->ind . 'public function change()';
        $output[] = $this->ind . '{';
        $output = $this->getTableMigration($output, $new, $old);
        $output[] = $this->ind . '}';

        return $output;
    }
721891
public function execute($respTrackData = null)
    {
        $batch     = $this->getBatch();
        $tracker   = $this->loader->getTracker();
        $respTrack = $tracker->getRespondentTrack($respTrackData);

        $fieldsChanged = false;
        $tokensChanged = $respTrack->recalculateFields($fieldsChanged);

        $t = $batch->addToCounter('trackFieldsChecked');
        if ($fieldsChanged) {
            $i = $batch->addToCounter('trackFieldsChanged');
        } else {
            $i = $batch->getCounter('trackFieldsChanged');
        }
        if ($tokensChanged) {
            $j = $batch->addToCounter('trackTokensChanged');
        } else {
            $j = $batch->getCounter('trackTokensChanged');
        }

        $batch->setMessage(
                'trackFieldsCheck',
                sprintf($this->_('%d tracks checked, %d fields changed, %d token changed.'), $t, $i, $j));
    }
199946
protected function getCopiedLocationsMap($oldParentId, $newParentId)
    {
        $originalLocations = $this->locationGateway->getSubtreeContent($oldParentId);
        $copiedLocations = $this->locationGateway->getSubtreeContent($newParentId);

        $map = array();
        foreach ($originalLocations as $index => $originalLocation) {
            $map['eznode:' . $originalLocation['node_id']] = 'eznode:' . $copiedLocations[$index]['node_id'];
        }

        return $map;
    }
34626
protected function auditUpdatedAttributes(array &$old, array &$new)
    {
        foreach ($this->getDirty() as $attribute => $value) {
            if ($this->isAttributeAuditable($attribute)) {
                $old[$attribute] = array_get($this->original, $attribute);
                $new[$attribute] = array_get($this->attributes, $attribute);
            }
        }
    }
764177
public static function version2($ktb, $trackNumber = null)
    {
        $data = new EncryptionData();
        $data->version = '02';
        $data->trackNumber = $trackNumber;
        $data->ktb = $ktb;
        return $data;
    }
12826
public function importArticleStatistic($oldId, $newId)
    {
        $article = $this->em->getRepository('VipaJournalBundle:Article')->find($newId);

        if (!$article) {
            $this->consoleOutput->writeln("Couldn't find #" . $newId . " on the new database.");
            return;
        }

        $this->consoleOutput->writeln("Reading view statistics for #" . $oldId . "...");
        $viewStatsSql = "SELECT DATE(view_time) AS date, COUNT(*) as view FROM " .
            "article_view_stats WHERE article_id = :id GROUP BY DATE(view_time)";
        $viewStatsStatement = $this->dbalConnection->prepare($viewStatsSql);
        $viewStatsStatement->bindValue('id', $oldId);
        $viewStatsStatement->execute();

        $this->consoleOutput->writeln("Reading download statistics for #" . $oldId . "...");
        $downloadStatsSql = "SELECT DATE(download_time) AS date, COUNT(*) as download FROM " .
            "article_download_stats WHERE article_id = :id GROUP BY DATE(download_time)";
        $downloadStatsStatement = $this->dbalConnection->prepare($downloadStatsSql);
        $downloadStatsStatement->bindValue('id', $oldId);
        $downloadStatsStatement->execute();
        
        $pkpViewStats = $viewStatsStatement->fetchAll();
        $pkpDownloadStats = $downloadStatsStatement->fetchAll();
        foreach ($pkpViewStats as $stat) {
            $articleFileStatistic = new ArticleStatistic();
            $articleFileStatistic->setArticle($article);
            $articleFileStatistic->setDate(DateTime::createFromFormat('Y-m-d', $stat['date']));
            $articleFileStatistic->setView($stat['view']);
            $this->em->persist($articleFileStatistic);
        }

        if (!$article->getArticleFiles()->isEmpty()) {
            foreach ($pkpDownloadStats as $stat) {
                $articleFileStatistic = new ArticleFileStatistic();
                $articleFileStatistic->setArticleFile($article->getArticleFiles()->first());
                $articleFileStatistic->setDate(DateTime::createFromFormat('Y-m-d', $stat['date']));
                $articleFileStatistic->setDownload($stat['download']);
                $this->em->persist($articleFileStatistic);
            }
        }

        $this->em->flush();
    }
1136145
public function getTrackDateFields($trackId)
    {
        $dateFields = $this->db->fetchPairs("SELECT gtf_id_field, gtf_field_name FROM gems__track_fields WHERE gtf_id_track = ? AND gtf_field_type = 'date' ORDER BY gtf_id_order", $trackId);

        if (! $dateFields) {
            $dateFields = array();
        }

        return $dateFields;
    }
601871
protected function doSumActionsMetrics($newRowToAdd, &$oldRowToUpdate)
    {
        // Pre 1.2 format: string indexed rows are returned from the DB
        // Left here for Backward compatibility with plugins doing custom SQL queries using these metrics as string
        if (!isset($newRowToAdd[Metrics::INDEX_NB_VISITS])) {
            $oldRowToUpdate[Metrics::INDEX_NB_VISITS] += $newRowToAdd['nb_visits'];
            $oldRowToUpdate[Metrics::INDEX_NB_ACTIONS] += $newRowToAdd['nb_actions'];
            $oldRowToUpdate[Metrics::INDEX_NB_UNIQ_VISITORS] += $newRowToAdd['nb_uniq_visitors'];
            return;
        }

        // Edge case fail safe
        if (!isset($oldRowToUpdate[Metrics::INDEX_NB_VISITS])) {
            return;
        }

        $oldRowToUpdate[Metrics::INDEX_NB_VISITS] += $newRowToAdd[Metrics::INDEX_NB_VISITS];
        if (array_key_exists(Metrics::INDEX_NB_ACTIONS, $newRowToAdd)) {
            $oldRowToUpdate[Metrics::INDEX_NB_ACTIONS] += $newRowToAdd[Metrics::INDEX_NB_ACTIONS];
        }
        if (array_key_exists(Metrics::INDEX_PAGE_NB_HITS, $newRowToAdd)) {
            if (!array_key_exists(Metrics::INDEX_PAGE_NB_HITS, $oldRowToUpdate)) {
                $oldRowToUpdate[Metrics::INDEX_PAGE_NB_HITS] = 0;
            }
            $oldRowToUpdate[Metrics::INDEX_PAGE_NB_HITS] += $newRowToAdd[Metrics::INDEX_PAGE_NB_HITS];
        }
        $oldRowToUpdate[Metrics::INDEX_NB_UNIQ_VISITORS] += $newRowToAdd[Metrics::INDEX_NB_UNIQ_VISITORS];
    }
571619
public function getTrackingId()
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $trackingId = '';
        for ($i = 0; $i < 10; $i++) {
            $trackingId .= $characters[rand(0, $charactersLength - 1)];
        }
        return $trackingId;
    }
1159245
public function getUpdatedAt() : ?int 
    {
        if ( ! $this->hasUpdatedAt()) {
            $this->setUpdatedAt($this->getDefaultUpdatedAt());
        }
        return $this->updatedAt;
    }
1137347
public function saveFields(array $fieldData)
    {
        $trackEngine = $this->getTrackEngine();

        if (! $trackEngine) {
            return 0;
        }

        //\MUtil_Echo::track($fieldData);
        $this->_fieldData = $this->_mergeFieldValues($fieldData, $this->getFieldData(), $trackEngine);

        $changed = $trackEngine->getFieldsDefinition()->saveFields($this->_respTrackId, $this->_fieldData);

        if ($changed) {
            $this->_ensureFieldData(true);
        }

        $this->handleFieldUpdate();

        return $changed;
    }
500122
private function get_new_scale_definition($oldscaleid) {

        $data = array(
            'userid'            => 0,   // restore will remap to the current user
            'courseid'          => 0,   // global scale
            'description'       => '',
            'descriptionformat' => FORMAT_HTML,
        );

        switch ($oldscaleid) {
        case 0:
            $data['name']  = get_string('scalename0', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('no'), get_string('yes')));
            break;
        case 1:
            $data['name']  = get_string('scalename1', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('absent', 'workshopform_accumulative'),
                                                get_string('present', 'workshopform_accumulative')));
            break;
        case 2:
            $data['name']  = get_string('scalename2', 'workshopform_accumulative');
            $data['scale'] = implode(',', array(get_string('incorrect', 'workshopform_accumulative'),
                                                get_string('correct', 'workshopform_accumulative')));
            break;
        case 3:
            $data['name']  = get_string('scalename3', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('poor', 'workshopform_accumulative'),
                                                '**',
                                                '*** ' . get_string('good', 'workshopform_accumulative')));
            break;
        case 4:
            $data['name']  = get_string('scalename4', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '**** ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        case 5:
            $data['name']  = get_string('scalename5', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '****',
                                                '***** ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        case 6:
            $data['name']  = get_string('scalename6', 'workshopform_accumulative');
            $data['scale'] = implode(',', array('* ' . get_string('verypoor', 'workshopform_accumulative'),
                                                '**',
                                                '***',
                                                '****',
                                                '*****',
                                                '******',
                                                '******* ' . get_string('excellent', 'workshopform_accumulative')));
            break;
        }

        return $data;
    }
1003013
public function deleteTracks(string $typeName, ?int $typeId = null, ?int $expiryTime = 0, int $trackableType = Tracker::TRACKER_LIVE) : int
    {
        $query = $this->getModel()
            ->newQuery()
            ->where('type', $this->getAlias($typeName));

        if ($typeId !== -1) {
            $query->where('type_id', $typeId);
        }

        if ($expiryTime !== null && $expiryTime > 0) {
            $query->whereRaw('(TIMESTAMPDIFF(MINUTE, created_at, NOW()) >= ?)', $expiryTime);
        }

        $query->where($this->typeClosure($trackableType));

        return $query->delete();
    }
1119696
public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
        global $DB;
        if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
            $merge = false;
        } else {
            $merge = array(
                'courseid'   => $data->courseid,
                'enrol'      => $this->get_name(),
                'status'     => $data->status,
                'roleid'     => $data->roleid,
            );
        }
        if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
            $instance = reset($instances);
            $instanceid = $instance->id;
        } else {
            if (!empty($data->customint5)) {
                if ($step->get_task()->is_samesite()) {
                    // Keep cohort restriction unchanged - we are on the same site.
                } else {
                    // Use some id that can not exist in order to prevent self enrolment,
                    // because we do not know what cohort it is in this site.
                    $data->customint5 = -1;
                }
            }
            $instanceid = $this->add_instance($course, (array)$data);
        }
        $step->set_mapping('enrol', $oldid, $instanceid);
    }
362735
public function setFieldData($newFieldData)
    {
        $trackEngine = $this->getTrackEngine();

        if (! $trackEngine) {
            return $newFieldData;
        }

        $this->_fieldData = $this->processFieldsBeforeSave($newFieldData);
        $changes          = $this->saveFields(array());

        if ($changes) {
            $info = $trackEngine->getFieldsDefinition()->calculateFieldsInfo($this->_fieldData);

            if ($info != $this->_respTrackData['gr2t_track_info']) {
                $this->_updateTrack(array('gr2t_track_info' => $info), $this->currentUser->getUserId());
            }
        }

        return $this->_fieldData;
    }
495859
public function execute($roundId = null, $roundDescription = null)
    {
        $batch  = $this->getBatch();

        if ($batch->hasVariable('trackEngine')) {
            $trackEngine = $batch->getVariable('trackEngine');
            if ($trackEngine instanceof \Gems_Tracker_Engine_TrackEngineInterface) {

                $model = $trackEngine->getRoundModel(true, 'delete');

                $roundData['gro_id_round'] = $roundId;
                $roundData['gro_active']   = 0;
                $roundData = $model->save($roundData);

                $batch->addMessage(sprintf(
                        $this->_('Deactivated round %s.'),
                        ($roundDescription ? $roundDescription : $roundId)
                        ));
            }
        }
    }