Jump to content

Handling JSON file - tracking certain URL parameters


Recommended Posts

I had some primitive code with JavaScript (ugly enough to scare small children) and I decided to make a proper module. I've touched it, of course, and now it's organized chaos.

I have issues (yea, me like a person, and the code):

  1. It wont create json file. It wont write to json file even I manually created one.
  2. It loads data from the backend pages even I am trying to avoid that. And it is working when you DO NOT reload.
<?php namespace ProcessWire;

class UrlTracker extends WireData implements Module {

    private $logFilePath;

    public static function getModuleInfo() {
        return array(
            'title' => 'URL Tracker',
            'version' => 1,
            'summary' => 'Tracks specified tracking parameters and logs to monthly JSON files.',
            'href' => 'https://vujosevic.com',
            'author' => 'Leftfield',
            'requires' => array('ProcessWire>=3.0.0'),
            'icon' => 'link',
            'autoload' => true,
            'permissions' => array(),
            'installs' => array(),
        );
    }

    public function init() {
        // Ensure the tracking directory exists
        $trackingDir = $this->config->paths->assets . 'tracking/';
        if (!is_dir($trackingDir)) {
            if (mkdir($trackingDir, 0777, true)) {
                $this->wire('log')->save('url-tracker', "Created tracking directory: $trackingDir");
            } else {
                $this->wire('log')->save('url-tracker', "Failed to create tracking directory: $trackingDir");
            }
        }

        $this->logFilePath = $trackingDir . 'url_tracker_log_' . date('Ym') . '.json';
        $this->addHookAfter('ProcessPageView::execute', $this, 'trackVisitedURL');
        $this->wire('log')->save('url-tracker', 'URLTracker module initialized.');
    }

    public function ___install() {
        $this->wire('log')->save('url-tracker', 'URLTracker module installed.');
    }

    public function ___uninstall() {
        $this->wire('log')->save('url-tracker', 'URLTracker module uninstalled.');
    }

    public function trackVisitedURL($event) {
        $pageID = $event->arguments(0);

        // Fetch the Page object from the page ID
        $page = $this->pages->get((int)$pageID);

        // Check if $page is indeed a Page object
        if (!$page instanceof Page || !$page->id) {
            $this->wire('log')->save('url-tracker', "No valid Page object provided. Argument: " . print_r($pageID, true));
            return;
        }

        // Check if the current page is not an admin page
        if ($this->wire('page')->template->name === 'admin' || $page->parent()->id == $this->wire('config')->adminRootPageID) {
            $this->wire('log')->save('url-tracker', "Page is part of admin: {$page->title}");
            return;
        }

        $input = $this->wire('input');
        $url = $input->url;

        // Log the URL
        $this->wire('log')->save('url-tracker', "trackVisitedURL called for URL: $url");

        // Check if the page is not hidden
        if (!$page->isHidden()) {
            $this->wire('log')->save('url-tracker', "Page is visible and published: {$page->title}");

            // Check if the URL contains any of the specified tracking parameters
            if (strpos($url, 'track=email') !== false
                || strpos($url, 'track=x') !== false
                || strpos($url, 'track=facebook') !== false
                || strpos($url, 'track=linkedin') !== false) {

                $this->wire('log')->save('url-tracker', "URL contains tracking parameter: $url");

                // Log to JSON file
                $this->logToJSON($url);
            } else {
                $this->wire('log')->save('url-tracker', "URL does not contain tracking parameter: $url");
            }
        } else {
            $this->wire('log')->save('url-tracker', "Page is hidden: {$page->title}");
        }
    }

    private function logToJSON($url) {
        $logFilePath = $this->getLogFilePath();

        $logEntry = array(
            'url' => $url,
            'timestamp' => array(
                'year' => date('Y'),
                'month' => date('m'),
                'day' => date('d'),
                'hours' => date('H'),
                'minutes' => date('i'),
                'seconds' => date('s'),
            ),
        );

        // Read the log
        $logData = [];
        if (file_exists($logFilePath)) {
            $logData = json_decode(file_get_contents($logFilePath), true);
        }

        // Add new entry
        $logData[] = $logEntry;

        // Write log data
        if (file_put_contents($logFilePath, json_encode($logData, JSON_PRETTY_PRINT))) {
            $this->wire('log')->save('url-tracker', "Logged URL to JSON: $url");
        } else {
            $this->wire('log')->save('url-tracker', "Failed to log URL to JSON: $url");
        }
    }

    private function getLogFilePath() {
        $currentMonth = date('Ym');
        $logFilePath = $this->config->paths->assets . 'tracking/url_tracker_log_' . $currentMonth . '.json';
        return $logFilePath;
    }
}

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...