<?php
/**
 * Dashboard module - saving indicators selection for further export
 * 
 * 
 * @package linea21\modules\dashboard
 * @author $Author$ - linea21 <info@linea21.com>
 * @version $Id$ 
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 */

$noplugin = true; // flag for ../config/define.php file
include_once('../config/define.php');
include_once("../dashboard/".SQL.".inc.php");
include_once("../dashboard/common.php");
include_once('../class/class.sdi.php');
include_once('../languages/' . U_L . '/lang_sdi.' . CHARSET . '.php');
include_once('../languages/' . U_L . '/lang_dashboard.' . CHARSET . '.php');

securityCheck();

// necessary for cron / CLI call
chdir (__DIR__);

// if called from command-line (cron)
// Crontab syntax
// * * * * * /usr/bin/php -q /var/www/linea21/admin/send.php token=mySecretToken
// * * * * * /usr/bin/php /home/simon/www/linea21_dev/admin/cron.php token=6255533e95978ff87c168b71e413frd4
// OR
// * * * * * curl -s http://yourinstall.com/admin/cron.php
// * * * * * /usr/bin/curl http://localhost/linea21_dev/admin/cron.php?token=6255533e95978ff87c168b71e413frd4
if (PHP_SAPI === 'cli') {
    
    // we get the given token
    parse_str($argv[1], $_GET);
    $source = 'cron_call';
    
} else {
    $source = $_SERVER["REQUEST_URI"];
}
if(!defined('API_RETRIEVE') || API_RETRIEVE == 0) {
    logfile(LOG_MAINFILE, array('[API call]', 'API_RETRIEVE is disabled, we exit the script', $source));
    exit;
}


// we check if the given token is correct
// else we quit
if(!isset($_GET['token']) || $_GET['token'] != SECRET_KEY) die('Invalid token!');


// we discover data structure
// return an array with available attributes
if(isset($_GET['apiURL'])) {
    $r = api_discover($_GET['apiURL']);
    if(is_array($r)) $a = array("status"=> 1,"keys"=> array_keys($r));
    else $a = array("status"=> 0,"keys"=> [], "msg" => $r);
    echo json_encode($a);
    exit;
}

// if an id is given (from /dashboard/det.php for example) we get unique sdi
if(isset($_GET['id'])) {
    $sdi = $sql_object -> DBSelect(SQL_getInfoSdi($_GET['id']));
    $r = api_update_indicators($sdi, true); // we act as an initial import
}else {
    $sdi = $sql_object -> DBSelect(SQL_get_indicators_to_update_by_api()); //  $sdi = $sql_object -> DBSelect(SQL_getListSdi("R", 0));
    $r = api_update_indicators($sdi);
}

if(isset($_GET['mode']) && $_GET['mode'] == 'ajax') {
    if($r == 1) $a = array("status"=> 1,"msg"=> _t('msg', 'update_successful'));
    elseif($r == 2) $a = array("status"=> 1,"msg"=> _t('msg', 'update_successful_partial'));
    else $a = array("status"=> 0,"msg"=>  _t('msg', 'action_failed'));
    echo json_encode($a);
} else {
    // @todo - check if still needed
    if(isset($_GET['id'])) header("Location: ".'../admin/confirm.php?rub=dashboard&todo=det&id='.$_GET['id']);
    exit;
}
?>