Last commit for controllers/MainController.php: 1391d4923f22f4e1c08d1389ee23802f4e407fb1

Additional changes to get ad script download working, a=chris

Chris Pollett [2015-09-01 17:Sep:st]
Additional changes to get ad script download working, a=chris
<?php
/**
 *  SeekQuarry/Yioop --
 *  Open Source Pure PHP Search Engine, Crawler, and Indexer
 *
 *  Copyright (C) 2009 - 2014  Chris Pollett chris@pollett.org
 *
 *  LICENSE:
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  END LICENSE
 *
 * @author Chris Pollett chris@pollett.org
 * @package seek_quarry
 * @subpackage controller
 * @license http://www.gnu.org/licenses/ GPL3
 * @link http://www.seekquarry.com/
 * @copyright 2009 - 2015
 * @filesource
 */
namespace seekquarry\yioop\controllers;

use seekquarry\yioop\configs as C;
use seekquarry\yioop\library as L;

/**
 * This is the default controller used by the seek_quarry site. It will
 * set up the main view, which has mainly links to static pages describing the
 * Yioop search engine.
 *
 * @author Chris Pollett
 * @package seek_quarry
 * @subpackage controller
 */
class MainController extends Controller
{
    /**
     * Says which activities (roughly methods invoke from the web)
     * this controller will respond to
     * @var array
     */
    var $activities = array("download", "store");
    /**
     *  This is the main entry point for handling people arriving to the
     * SeekQuarry site.
     */
    function processRequest()
    {
        $data = array();
        $view = "main";
        if(isset($_SESSION['USER_ID'])) {
            $user = $_SESSION['USER_ID'];
        } else {
            $user = $_SERVER['REMOTE_ADDR'];
        }
        if(isset($_REQUEST['a'])) {
            if(in_array($_REQUEST['a'], $this->activities)) {
                $activity = $_REQUEST['a'];
                if($activity == "signout") {
                    unset($_SESSION['USER_ID']);
                    $user = $_SERVER['REMOTE_ADDR'];
                    $activity = "main";
                    $data['SCRIPT'] = "doMessage('<h1 class=\"red\" >".
                        tl('search_controller_logout_successful')."</h1>')";
                }
            } else {
                $activity = "download";
            }
        } else {
            $activity = "download";
        }
        $data['VIEW'] = $view;
        $data = array_merge($data, $this->$activity());
        $data['YIOOP_TOKEN'] = $this->generateCSRFToken($user);
        $this->displayView($data['VIEW'], $data);
    }
    /**
     * This activity handles downloads of Yioop from the seekquarry site.
     * It collects user information and sends an email with the download
     * link.
     *
     * @return array $data has which field variables from drawing download forms
     */
     function store()
     {
        $data['VIEW'] = "store";
        $purchase_model = $this->model("purchase");
        $data['page'] = tl('main_controller_store');
        $data['SCRIPT'] = "";
        $data['FORM_TYPE'] = 'getScript';
        $data['MONTHS'] = [ 0 => tl('advertisement_component_month'),
            "01" => "01", "02" => "02", "03" => "03",
            "04" => "04", "05" => "05", "06" => "06", "07" => "07",
            "08" => "08", "09" => "09", "10" => "10", "11" => "11",
            "12" => "12"
        ];
        $current_year = date('Y');
        $data['YEARS'] = [ 0 => tl('advertisement_component_year')];
        for ( $year = $current_year; $year < $current_year + 20; $year++ ) {
            $data['YEARS'][$year] = $year;
        }
        $arg = isset($_REQUEST['arg']) ? $_REQUEST['arg'] : "";
        switch ($arg) {
            case 'getScript':
                $required_fields = ["e_mail" => 'string',
                    "name_server" => 'web-url'];
                foreach ($required_fields as $field => $type) {
                    if (empty($_REQUEST[$field])) {
                        $data['SCRIPT'] .=
                            "doMessage('<h1 class=\"red\" >".
                            tl('main_controller_missing_field').
                            "</h1>')";
                        break 2;
                    }
                    $data[strtoupper($field)] = $this->clean($_REQUEST[$field],
                        $type);
                }
                if ($purchase_model->checkPurchase( $data['E_MAIL'],
                    $data['NAME_SERVER'])) {
                    $data['FORM_TYPE'] = 'showScript';
                } else {
                    if(C\CreditConfig::isActive()) {
                        $data["INCLUDE_SCRIPTS"][] = 'credit';
                        $get_credit_token_initialize_script =
                            L\crawlHash(C\NAME_SERVER . C\YIOOP_VERSION .
                            "getCreditTokenInitializeScript");
                        $data['SCRIPT'] .=
                        C\CreditConfig::$get_credit_token_initialize_script();
                    }
                    $data['FORM_TYPE'] = 'purchaseScript';
                }
                break;
            case 'purchaseScript':
                $required_fields = ["e_mail" => 'string',
                    "name_server" => 'web-url'];
                foreach ($required_fields as $field => $type) {
                    if (empty($_REQUEST[$field])) {
                        $data['SCRIPT'] .=
                            "doMessage('<h1 class=\"red\" >".
                            tl('main_controller_missing_fields').
                            "</h1>')";
                        break 2;
                    }
                    $data[strtoupper($field)] = $this->clean($_REQUEST[$field],
                        $type);
                }
                if ($purchase_model->checkPurchase($data['E_MAIL'],
                    $data['NAME_SERVER'])) {
                    $_REQUEST['arg'] = 'getScript';
                    return $this->redirectWithMessage(
                        tl('main_controller_already_purchased'),
                        ['arg', 'e_mail', 'name_server']);
                }
                if (C\CreditConfig::isActive() && !C\CreditConfig::charge(
                    C\AD_SCRIPT_COST, $this->clean(
                    $_REQUEST['CREDIT_TOKEN'], "string"), $message)) {
                    return $this->redirectWithMessage(
                        tl('main_controller_processing_error',
                        $message), ['arg', 'e_mail', 'name_server']);
                }
                $reference = $purchase_model->addPurchase($data['E_MAIL'],
                    $data['NAME_SERVER']);
                $_REQUEST['arg'] = 'getScript';
                $headers = C\FROM_EMAIL_HEADER . "\r\n";
                $title = tl('main_controller_purchase_email_title');
                $body = tl('main_controller_purchase_email_body')."\n".
                    $reference;
                mail($data['E_MAIL'], $title, $body, $headers);
                return $this->redirectWithMessage(
                    tl('main_controller_purchase_completed'),
                    ['arg', 'e_mail', 'name_server']);
                break;
        }
        return $data;
     }
    /**
     * This activity handles downloads of Yioop from the seekquarry site.
     * It collects user information and sends an email with the download
     * link.
     *
     * @return array $data has which field variables from drawing download forms
     */
     function download()
     {
        $data['VIEW'] = "download";
        $data['page'] = tl('main_controller_download');
        $data['SCRIPT'] = "";
        $downloads = [C\CURRENT_YIOOP_VERSION, C\PREVIOUS_YIOOP_VERSION];
        $data['version'] = C\CURRENT_YIOOP_VERSION;
        if(isset($_REQUEST['version']) &&
            in_array($_REQUEST['version'], $downloads)) {
            $data['version'] = $_REQUEST['version'];
        }
        if(isset($_REQUEST['arg'])) {
            switch($_REQUEST['arg'])
            {
                case "step1":
                    $require_fields = ["full_name", "e_mail"];
                    foreach($require_fields as $field) {
                        if(!isset($_REQUEST[$field])) {
                            $data['SCRIPT'] .=
                                "doMessage('<h1 class=\"red\" >".
                                tl('main_controller_missing_fields').
                                "</h1>')";
                            break 2;
                        }
                    }
                    $all_fields = ["full_name", "e_mail", "business",
                        "interest"];
                    $hash_name = "";
                    foreach($all_fields as $field) {
                        $request[$field] = (isset($_REQUEST[$field])) ?
                            $this->clean($_REQUEST[$field], "string") : "";
                        $request[$field] = substr($request[$field], 0, 256);
                        $hash_name .= $request[$field];
                    }
                    $request["version"] = $data['version'];
                    $hash_name .= $request["version"];
                    $time = time();
                    $hash_name = md5($hash_name);
                    $email_dir = C\WORK_DIRECTORY."/data/emails";
                    if(!file_exists($email_dir)) {
                        mkdir($email_dir);
                    }
                    $save_data = serialize($request);
                    file_put_contents($email_dir."/$hash_name|$time.txt",
                        $save_data);
                    $pre_name = $email_dir."/$hash_name|".substr($time, 0, 4);
                    $save_time = substr($time, 4, 1);
                    for($i = 0; $i < 10; $i++) {
                        if($save_time != "$i") {
                            @array_map('unlink', glob($pre_name."$i*.txt"));
                        }
                    }
                    $headers = C\FROM_EMAIL_HEADER . "\r\n";
                    $link = C\BASE_URL."?c=main&a=download&name=".
                        "$hash_name|$time&version={$data['version']}&arg=step2";
                    $title = tl('main_controller_yioop_download');
                    $body = tl('main_controller_click_download')."\n".$link;
                    mail($request['e_mail'], $title, $body, $headers);
                    $url = C\BASE_URL."?c=static&p=Download_Sent";
                    header("Location: ".$url);
                    exit();
                break;
                case "step2":
                    $email_dir = C\WORK_DIRECTORY."/data/emails";
                    if(!isset($_REQUEST['name'])) {
                        $data['VIEW'] = "main";
                        $data['page'] = "home";
                        $data['SCRIPT'] .=
                            "doMessage('<h1 class=\"red\" >".
                            tl('main_controller_url_error').
                            "</h1>')";
                        break;
                    }
                    $name = $email_dir."/".
                        $this->clean($_REQUEST['name'], "string").".txt";
                    if(!file_exists($name)) {
                        $data['SCRIPT'] .=
                            "doMessage('<h1 class=\"red\" >".
                            tl('main_controller_expired_url').
                            "</h1>')";
                        $data['VIEW'] = "download";
                        $data['version'] = C\CURRENT_YIOOP_VERSION;
                        break;
                    }
                    $request = array_values(unserialize(
                        file_get_contents($name)));
                    if(isset($_SERVER["REMOTE_ADDR"])) {
                        $request[] = $_SERVER["REMOTE_ADDR"];
                    }
                    $data_string = implode("\n", $request);
                    $time = time();
                    $day = date("d", $time);
                    $emails = [];
                    $email_filename = "$email_dir/$day.txt";
                    if(file_exists($email_filename)) {
                        $emails = unserialize(
                            file_get_contents($email_filename));
                    }
                    $emails[$request[1]] = $data_string;
                    file_put_contents($email_filename, serialize($emails));
                    @unlink($name);
                    $yesterday = date("d", $time - 86400);
                    $old_email_filename = "$email_dir/$yesterday.txt";
                    if(file_exists($old_email_filename)) {
                        $yester_mail = array_values(unserialize(
                            file_get_contents($old_email_filename)));
                        $yester_string = implode("\n======\n\n",
                            $yester_mail);
                        $headers = C\FROM_EMAIL_HEADER . "\r\n";
                        foreach(C\maintainers() as $maintainer) {
                            mail($maintainer, "Leads ".date('Y-M-d', time()),
                                $yester_string, $headers);
                        }
                        $new_email_filename = "$email_dir/old_$yesterday.txt";
                        rename($old_email_filename, $new_email_filename);
                    }
                    if($data['version'] == C\CURRENT_YIOOP_VERSION) {
                        $url = C\CURRENT_VERSION_URL;
                    } else {
                        $url = C\PREVIOUS_VERSION_URL;
                    }
                    header("Location: ".$url);
                    exit();
                break;
            }
        }
        return $data;
     }
}
ViewGit