<?php /* =======================================================
|                                                              |
|   LinkOfficer v.1.3                                          |
|       Author: MiMiMi Community                               |
|           > www.mimimi.software                              |
|       Licensed under CC BY 4                                 |
|           > www.creativecommons.org/licenses/by/4.0          |
|                                                              |
|   --------------------------------------------------------   |
|                                                              |
|   This file is used to provide access to some specific       |
|   actions of the LinkOfficer component from the server       |
|   side of your website.                                      |
|                                                              |
|   --------------------------------------------------------   |
|                                                              |
|   For example, let's ask the officer to do some action:      |
|                                                              |
|       $app = mimimiCreate('application');                    |
|       $app->link_officer->doSomething();                     |
|                                                              |
|   --------------------------------------------------------   |
|                                                              |
|   Note: This file is part of the LinkOfficer component       |
|         that consists these files:                           |
|             themes/YOUR-THEME-NAME/blocks/link-officer.php   |
|             themes/YOUR-THEME-NAME/css/link-officer.css      |
|             themes/YOUR-THEME-NAME/js/link-officer.js        |
|             themes/YOUR-THEME-NAME/api/link-officer.php      |
|             YOUR-FRAMEWORK/LinkOfficer/LinkOfficer.php       |
|                                                              |
============================================================= */

    /* =========================================================
    |                                                          |
    |   Load the basis for system DB modules from CORE folder  |
    |                                                          |
    ========================================================= */

    mimimiInclude('ModuleWithTable.php');

    /* =========================================================
    |                                                          |
    |   Declare the LINKOFFICER module's class                 |
    |                                                          |
    ========================================================= */

    class MimimiLinkOfficer extends MimimiModuleWithTable {

        /* -------------------------------------
        |                                      |
        |   The module's table details         |
        |                                      |
        ------------------------------------- */

        protected $table        = 'link_officer';
        protected $tableFields  = array(
                      '`id`       BIGINT                 NOT NULL  AUTO_INCREMENT  COMMENT "record identifier"',
                      '`enabled`  TINYINT(1)             NOT NULL  DEFAULT 1       COMMENT "0 if this is a disabled record"',
                      '`link`     VARCHAR(100)           NOT NULL  DEFAULT ""      COMMENT "unique identifier of the link"',
                      '`uri`      VARCHAR(2000)          NOT NULL  DEFAULT ""      COMMENT "final link URI"',
                      '`clicks`   INT          UNSIGNED  NOT NULL  DEFAULT 0       COMMENT "how many times the link was clicked"',
                      '`remark`   VARCHAR(4000)          NOT NULL  DEFAULT ""      COMMENT "some administrative notes about this record"'
                  );
        protected $tableKeys    = array(
                      'PRIMARY KEY   (`id`)',
                      'KEY `enabled` (`enabled`)',
                      'KEY `link`    (`link`)',
                      'KEY `uri`     (`uri`)',
                      'KEY `clicks`  (`clicks`)'
                  );

        /* -------------------------------------
        |                                      |
        |   Demo rows for an empty database    |
        |                                      |
        ------------------------------------- */

        protected $demoRows = [
            [
                'link' => 'mimimi-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-5.2.zip'
            ], [
                'link' => 'license-cc-bb-4',
                'uri'  => 'https://www.creativecommons.org/licenses/by/4.0'
            ], [
                'link' => 'mimimi-1-0-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-1.0.zip'
            ], [
                'link' => 'mimimi-2-0-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-2.0.zip'
            ], [
                'link' => 'mimimi-3-0-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-3.0.zip'
            ], [
                'link' => 'mimimi-3-1-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-3.1.zip'
            ], [
                'link' => 'mimimi-4-0-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-4.0.zip'
            ], [
                'link' => 'mimimi-5-0-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-5.0.zip'
            ], [
                'link' => 'mimimi-5-1-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-5.1.zip'
            ], [
                'link' => 'mimimi-5-2-download',
                'uri'  => 'https://mimimi.software/media/mimimi-framework-5.2.zip'
            ], [
                'link' => 'mimimi-credits',
                'uri'  => 'https://mimimi.software/'
            ]
        ];

        /* =====================================================
        |                                                      |
        |   Perform some actions required to resolve the       |
        |   link identifier                                    |
        |                                                      |
        |   ------------------------------------------------   |
        |                                                      |
        |   Input parameters:                                  |
        |       $params = STRING = requested link identifier   |
        |                                                      |
        |   ------------------------------------------------   |
        |                                                      |
        |   Output parameters:                                 |
        |       STRING = resolved URI                          |
        |                                                      |
        ===================================================== */

        public function run ( $params = '' ) {
            $uri = NULL;
            $field = 'moduleLinkOfficer-linkId-' . $params;

            /* ---------------------------------
            |                                  |
            |   Maybe resolved URI exists in   |
            |   the visitor's session?         |
            |                                  |
            --------------------------------- */

            if ($this->app->has->session) {
                $uri = $this->app->session->get(
                    $field,
                    NULL
                );
            }

            /* ---------------------------------
            |                                  |
            |   Otherwise prepare a query      |
            |                                  |
            |   ----------------------------   |
            |                                  |
            |   The QUESTION simbols are       |
            |   placeholders to replace with   |
            |   a related parameter.           |
            |                                  |
            --------------------------------- */

            if (is_null($uri)) {
                if ($this->app->has->db) {
                    $query = 'SELECT *  ' .
                             'FROM   `__' . $this->table . '`  ' .
                             'WHERE  `enabled` = 1  AND  ' .
                                   ' `link` != ""   AND  `link` = ?  ' .
                             'LIMIT 1';

                    /* -------------------------
                    |                          |
                    |   Execute it             |
                    |                          |
                    |   --------------------   |
                    |                          |
                    |   The second argument    |
                    |   is an array of the     |
                    |   related parameters for |
                    |   the QUESTION symbols.  |
                    |                          |
                    ------------------------- */

                    $result = $this->app->db->query(
                        $query,
                        array(
                            $params
                        )
                    );

                    /* -------------------------
                    |                          |
                    |   Extract a record       |
                    |                          |
                    |   --------------------   |
                    |                          |
                    |   We are fetching it as  |
                    |   associative array.     |
                    |   And closing DB line.   |
                    |                          |
                    ------------------------- */

                    if ($result) {
                        $row = $result->fetch(
                                   PDO::FETCH_ASSOC
                               );
                        $result->closeCursor();

                        /* ---------------------
                        |                      |
                        |   Increment the      |
                        |   clicks counter     |
                        |                      |
                        --------------------- */

                        if (isset($row['uri'])) {
                            $this->updateRecord(
                                $row['id'],
                                array(
                                    'clicks' => $row['clicks'] + 1
                                )
                            );

                            /* -----------------
                            |                  |
                            |   Save the final |
                            |   link URI to    |
                            |   the visitor's  |
                            |   session        |
                            |                  |
                            ----------------- */

                            if ($this->app->has->session) {
                                $this->app->session->set(
                                    $field,
                                    $row['uri'],
                                    24 * 60 * 60
                                );
                            }

                            /* -----------------
                            |                  |
                            |   Return the URI |
                            |                  |
                            ----------------- */

                            $uri = $row['uri'];
                        }
                    }
                }
            }
            return is_string($uri)
                   ? $uri
                   : '';
        }
    };

    /* =========================================================
    |                                                          |
    |   Block trailing injections                              |
    |                                                          |
    ========================================================= */

    return;