Exemple #1
0
 public function __construct()
 {
     $this->session = Session::getInstance();
     $this->user = User::getInstance();
     $this->webDBUtils = WebDBUtils::getInstance();
     $this->log = Log::getInstance();
 }
 /**
  * 
  * Enter description here ...
  * @param unknown_type $itemid
  */
 public function read($itemid)
 {
     $db = Database::getInstance();
     $log = Log::getInstance();
     $sql = "SELECT link_type_item type," . "v_descr name,material," . "price_unit,price_paq price_pack,price_box," . "stock_min,link_marca trademark,image " . "FROM " . TBL_ITEM . " WHERE id={$itemid}";
     $res = $db->query($sql);
     if (!$res) {
         $log->addError("No se puedo obtener datos de Producto.");
         return false;
     }
     if ($db->rows($res) != 1) {
         $log->addError("No se encontraron datos de Producto solicitado.");
         $db->dispose($res);
         return false;
     }
     $row = $db->getRow($res);
     $this->id = $itemid;
     $this->name = $row['name'];
     $this->type = $row['type'];
     $this->stockMin = $row['stock_min'];
     $this->trademark = $row['trademark'];
     $this->priceUnit = $row['price_unit'];
     $this->priceBox = $row['price_box'];
     $this->pricePack = $row['price_pack'];
     $this->material = $row['material'];
     return true;
 }
Exemple #3
0
 public function execute($sql, $params = array())
 {
     $startTime = microtime(true);
     $this->affectRowCount = 0;
     $stmt = $this->conn->prepare($sql);
     if ($stmt) {
         if ($params) {
             foreach ($params as $k => &$param) {
                 $stmt->bindParam($k, $param, PDO::PARAM_STR, strlen($param));
             }
         }
     } else {
         return false;
     }
     $res = $stmt->execute();
     $endTime = microtime(true);
     $execTime = round($endTime - $startTime, 3);
     if ($this->longtime && $execTime > $this->longtime) {
         Log::getInstance('LongTime')->write(json_encode(array('sql' => $sql, 'params' => $params, 'runTime' => $execTime)));
     }
     if (!$res) {
         $error = $stmt->errorInfo();
         if (isset($error[2]) && $error[2]) {
             Log::getInstance('DBerror')->write(json_encode(array('sql' => $sql, 'params' => $params, 'error' => $error[2])));
         }
     }
     $this->affectRowCount = $res ? $stmt->rowCount() : 0;
     return $stmt;
 }
Exemple #4
0
 public function __construct()
 {
     $this->session = Session::getInstance();
     $this->log = Log::getInstance();
     $this->loadEmbedSettings();
     $this->procUtils = ProcUtils::getInstance();
 }
 /**
  * 
  * Enter description here ...
  * @param unknown_type $lotid
  */
 public function read($lotid)
 {
     $db = Database::getInstance();
     $log = Log::getInstance();
     $sql = "SELECT itemid,cajas,unidades,stock,active,idalmacen,costo,tran_mar,tran_ter,aduana,trans_bank,otros,price_final,obs FROM " . TBL_LOT . " WHERE id={$lotid}";
     $res = $db->query($sql);
     if (!$res) {
         $log->addError("No se pudo recuperar información de Lote.");
         return false;
     }
     if ($db->rows($res) != 1) {
         $log->addError("Lote solicitado no existe.");
         $db->dispose($res);
         return false;
     }
     $row = $db->getRow($res);
     $this->id = $lotid;
     $this->itemid = $row['itemid'];
     $this->boxes = $row['cajas'];
     $this->units = $row['unidades'];
     $this->active = $row['active'];
     $this->storeid = $row['idalmacen'];
     $this->cost = $row['costo'];
     $this->costMar = $row['tran_mar'];
     $this->costTer = $row['tran_ter'];
     $this->costAdu = $row['aduana'];
     $this->costBank = $row['trans_bank'];
     $this->price = $row['price_final'];
     $this->stock = $row['stock'];
     $this->gloss = $row['obs'];
     $db->dispose($res);
     return true;
 }
function user_edit()
{
    $log = Log::getInstance();
    $user = new User();
    $storeid = isset($_POST['store']) ? $_POST['store'] : 0;
    $user->id = isset($_POST['user']) ? $_POST['user'] : "";
    $user->firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
    $user->lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
    $user->username = isset($_POST['username']) ? $_POST['username'] : "";
    $user->password = isset($_POST['passwd']) ? $_POST['passwd'] : "";
    $user->ci = isset($_POST['ci']) ? $_POST['ci'] : "";
    $user->active = isset($_POST['active']);
    $user->level = isset($_POST['role']) ? $_POST['role'] : 0;
    $user->address = isset($_POST['address']) ? $_POST['address'] : "";
    $user->phone = isset($_POST['phone']) ? $_POST['phone'] : "";
    $user->email = isset($_POST['email']) ? $_POST['email'] : "";
    if ($user->update()) {
        if ($_FILES['upload']['name']) {
            $imagepath = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']) . "img/user/\${$user->id}.jpg";
            if (move_uploaded_file($_FILES['upload']['tmp_name'], $imagepath)) {
                $user->imagepath = $imagepath;
                $user->update();
            } else {
                $log->addError("No fue posible subir imagen");
            }
        }
    } else {
        $log->addError("No fue posible actualizar usuario, verifique que Usuario sea único.");
    }
}
Exemple #7
0
 public function __construct($item)
 {
     if (empty($item)) {
         return $item;
     }
     $dbConf = Conf::getConf('/db/mysql/' . $item);
     $this->log = Log::getInstance('mysql');
     $this->connect($dbConf["hostname"], $dbConf["username"], $dbConf["password"], $dbConf["database"], $dbConf["pconnect"]);
 }
Exemple #8
0
 public function executeDeleteContact()
 {
     $data = array("contacts_id" => $_REQUEST["cid"]);
     if ($this->model->delete($data)) {
         Log::getInstance()->insert(array("action" => "delete", "module" => "contacts", "title" => "Suppression d'un contact", "message" => "Un contact a été supprimé avec succès"));
     } else {
         echo json_encode(array("alert" => "Une erreur est survenue pendant la suppression d'un contact"));
     }
 }
 /**
  * Does nativ query(MySQL)
  * Returns PDO result
  * @param string $query
  * @return queryResult
  */
 public function nativQuery($query)
 {
     //Log::getInstance()->event($query,Log::INFO);
     try {
         return $this->pdo->query($query);
     } catch (PDOException $e) {
         Log::getInstance()->event($e->getMessage(), Log::ERROR);
     }
 }
Exemple #10
0
 public static function fire($event, $args = array())
 {
     if (isset(self::$events[$event])) {
         foreach (self::$events[$event] as $func) {
             call_user_func($func, $args);
         }
     }
     $Log = Log::getInstance();
     $Log->NewLog($event);
 }
Exemple #11
0
 public function getLogger($obj = null)
 {
     if (!self::$logger) {
         self::$logger = Log::getInstance();
     }
     if ($obj instanceof DB_DataObject) {
         return self::returnStatus(self::$logger);
     }
     return self::$logger;
 }
Exemple #12
0
 public function __construct()
 {
     $this->session = Session::getInstance();
     $this->log = Log::getInstance();
     $this->user = User::getInstance();
     $this->storage = Storage::getInstance();
     $this->webDBUtils = WebDBUtils::getInstance();
     $this->dpUtils = DataProviderUtils::getInstance();
     $this->screen = false;
     $this->availableFeatures = false;
 }
Exemple #13
0
 /**
  * constructor
  *
  * @param string $type tipo de datamanager a ser incializado
  *
  * inicializa o objeto de log e de bd
  * inicializa o vetor de dados nulo de acordo com o tipo
  */
 function __construct($type)
 {
     $this->db = MysqliDb::getInstance();
     $this->log = Log::getInstance();
     //tipo de dado valido pra iniciar
     if (array_key_exists($type, $this->_validFields)) {
         $this->type = $type;
         foreach ($this->_validFields[$this->type] as $key => $value) {
             $this->setField($key, null);
         }
     }
 }
 /**
  * 
  * Enter description here ...
  */
 public function update()
 {
     $log = Log::getInstance();
     $db = Database::getInstance();
     $this->setupSafeInput();
     $sql = "UPDATE " . TBL_CUSTOMER . " SET " . "name='{$this->name}'," . "address='{$this->address}'," . "phone='{$this->phone}'," . "cell='{$this->cell}'," . "nit='{$this->nit}'," . "active={$this->active}," . "email='{$this->email}'," . "date_modified=NOW() " . "WHERE id={$this->id}";
     if (!$db->query($sql)) {
         $log->addError("No se pudo actualizar datos de Cliente.");
         return false;
     }
     return true;
 }
 public function add()
 {
     $db = Database::getInstance();
     $log = Log::getInstance();
     $this->setupSafeInput();
     $sql = "INSERT INTO " . TBL_DEPARTMENT . "(name," . "contact_name," . "phone," . "active," . "address," . "fax," . "email," . "description) " . " VALUES " . "('" . $db->escape($this->name) . "'," . "'" . $db->escape($this->contact) . "'," . "'" . $db->escape($this->phone) . "'," . "{$this->active}," . "'" . $db->escape($this->address) . "'," . "'" . $db->escape($this->fax) . "'," . "'" . $db->escape($this->email) . "'," . "'" . $db->escape($this->description) . "')";
     $res = $db->query($sql);
     if (!$res) {
         $log->addError("No se pudo agregar datos.");
     } else {
         $this->id = $db->lastID();
     }
     return $res;
 }
Exemple #16
0
/**
 * Created by PhpStorm.
 * User: André
 * Date: 01/04/2015
 * Time: 13:57
 */
function buildOutput($data, $debug = false)
{
    $log = Log::getInstance();
    $db = MysqliDb::getInstance();
    $output = array();
    if ($log->countErrors() > 0) {
        $errors = $log->getErrors();
    }
    $output = $data;
    if (isset($errors) && sizeof($errors) > 0) {
        $output['_ERROR_'] = $errors;
    }
    if ($debug == 'true') {
        $output['_DEBUG_'] = $log->getLogs();
    }
    echo json_encode($output, JSON_PRETTY_PRINT);
}
Exemple #17
0
 public function query($keyword = '', $start = 0, $limit = 10)
 {
     if (!$this->search || empty($keyword)) {
         return array();
     }
     $this->search->SetLimits($start, $limit, 1000);
     $list = $this->search->query($keyword, 'document_index');
     $log = Log::getInstance('sphinx');
     if ($list === false) {
         $log->warning("Sphinx Search Faild:" . $this->search->GetLastError());
         return array();
     }
     if (!isset($list['matches']) || empty($list['matches'])) {
         return array();
     }
     $cms = new Data_CmsModel();
     $articles = $cms->getArticle(array_keys($list['matches']));
     $titles = array();
     $contents = array();
     $catids = array();
     foreach ($articles as $k => $v) {
         $titles[$k] = strip_tags($v['title']);
         $contents[$k] = preg_replace("/[\\s\t\r\n( )]+/", "", strip_tags($v['introtext']));
         $catids[$v['catid']] = true;
     }
     $catids = array_keys($catids);
     $categorys = $cms->getCategory($catids);
     $catMap = array();
     foreach ($categorys as $k => $v) {
         $catMap[$v['id']] = $v['title'];
     }
     $redclass = array("before_match" => "<span style='color:#FF0000'>", "after_match" => "</span>");
     $titles = $this->search->buildExcerpts($titles, "document_index", $keyword, $redclass);
     $contents = $this->search->buildExcerpts($contents, "document_index", $keyword, $redclass);
     foreach ($articles as $k => $v) {
         $articles[$k]['title'] = $titles[$k];
         $articles[$k]['introtext'] = $contents[$k];
         $articles[$k]['catTitle'] = $catMap[$v['catid']];
     }
     $result = array();
     $result['articles'] = $articles;
     $result['count'] = $list['total'];
     return $result;
 }
 /**
  * 
  * Enter description here ...
  * @param unknown_type $itemid
  * @param unknown_type $storeid
  */
 public static function getLotsFromItem($itemid, $storeid)
 {
     $db = Database::getInstance();
     $result = array();
     $sql = "SELECT l.id," . "s.name store," . "l.stock," . "l.active," . "l.price_final price " . "FROM " . TBL_LOT . " l INNER JOIN " . TBL_DEPARTMENT . " s ON s.id=l.idalmacen " . "WHERE l.itemid={$itemid} AND l.stock>0 " . ($storeid ? "AND s.id={$storeid}" : "");
     $res = $db->query($sql);
     if (!$res) {
         $log = Log::getInstance();
         $log->addError(ERROR_BD_QUERY . " No se pudo obtener datos de Lotes.");
         return $result;
     }
     $row = $db->getRow($res);
     while ($row) {
         $result[] = $row;
         $row = $db->getRow($res);
     }
     $db->dispose($res);
     return $result;
 }
 /**
  * save new achievement via REST.
  * role: player
  */
 public function unlock_achievement()
 {
     if (Authenticate::is_player()) {
         if (isset($_POST['token']) && Authenticate::is_valid_token($_POST['token'])) {
             $this->model_achievement = Achievement::getInstance();
             /*
              * populate type of achievement.
              * invoke method to unlock the achievement.
              * log this event about achievement earning.
              */
             $achievement = $_POST["achievement"];
             $result = $this->model_achievement->unlock_achievement($achievement);
             $log = Log::getInstance();
             $log->logging_game_earn_achievement("Achievement id {$achievement}");
             $binding = array("result_var" => "session_ready", "unlock_status" => $result);
             binding_data($binding);
         } else {
             transport("error404");
         }
     } else {
         $binding = array("result_var" => "no_session");
         binding_data($binding);
     }
 }
Exemple #20
0
/**
 * the main apiController function that outputs json_encoded results
 * @param $path
 * @param $request
 * @param $files
 */
function apiController($path, $request, $files = null)
{
    global $dao;
    list($reqPath, $queryString) = explode('?', $path);
    $pathParts = explode('/', substr($reqPath, 1));
    list($action) = $pathParts;
    if ($action != "addExpeditionPoint" && $action != "getDeviceByAuthKey") {
        $log = Log::getInstance();
        $log->log("{$action}");
        $log->log("{$path}, {$request}");
    }
    $authKey = $request["authKey"];
    if ($action != "registerDevice" && $action != "getPendingDeviceStatus" && !$authKey) {
        $response = array("errorCode" => ERR_AUTHKEY_MISSING, "errorMessage" => "You must provide an authentication key with each request.");
        echo json_encode($response);
        die;
    }
    $device = $dao->getDeviceByAuthKey($authKey);
    if ($action != "registerDevice" && $action != "getPendingDeviceStatus" && !$device) {
        $response = array("errorCode" => ERR_AUTHKEY_INVALID, "errorMessage" => "Invalid authentication key.");
        echo json_encode($response);
        die;
    }
    $deviceUserId = $device["user_id"];
    $deviceIdentifier = $device["imei"];
    switch ($action) {
        case 'getDeltaFindsIds':
            //			echo $dao->getDeltaFindsIds($deviceIdentifier);
            echo $dao->getDeltaFindsIds($deviceIdentifier, $request["projectId"]);
            break;
        case 'recordSync':
            echo $dao->recordSync($deviceIdentifier);
            break;
        case 'registerDevice':
            $imei = $request["imei"];
            $name = null;
            if (strstr($authKey, "sb_")) {
                $result = $dao->addSandboxDevice($authKey, $imei);
            } else {
                $result = $dao->confirmDevice($authKey, $imei, $name);
            }
            echo json_encode($result);
            break;
        case 'addExpedition':
            echo $dao->addExpedition($request["projectId"]);
            break;
        case 'addExpeditionPoint':
            echo $request["expeditionId"] . ",";
            echo $dao->addExpeditionPoint($request["expeditionId"], $request["lat"], $request["lng"], $request["alt"], $request["swath"]);
            break;
        case 'getPendingDeviceStatus':
            $device = $dao->getDeviceByAuthKey($authKey);
            if ($device["status"] == "ok") {
                echo json_encode($device);
            } else {
                echo json_encode(false);
            }
            break;
        case 'listOpenProjects':
            $result = $dao->getProjects(PROJECTS_OPEN);
            echo json_encode($result);
            break;
        case 'listMyProjects':
            $result = $dao->getUserProjects($deviceUserId);
            echo json_encode($result);
            break;
        case 'listFinds':
            echo json_encode($dao->getFinds($request["project_id"]));
            break;
        case 'getFind':
            $result = $dao->getFind($request["guid"]);
            echo json_encode($result);
            break;
        case 'deleteFind':
            echo $dao->deleteFind($request["id"]);
            break;
        case 'deleteProject':
            $dao->deleteProject($request["projectId"]);
            break;
        case 'deleteAllFinds':
            $dao->deleteAllFinds($request["projectId"]);
            break;
        case 'createFind':
            echo $dao->createFind($request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["latitude"], $request["longitude"], $request["revision"]);
            break;
        case 'updateFind':
            echo $dao->updateFind($request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["revision"]);
            break;
        case 'attachPicture':
            $imagedata = base64_decode($request["data_full"]);
            $imagethumbdata = base64_decode($request["data_thumbnail"]);
            $result = $dao->addPictureToFind($request["imei"], $request["guid"], $request["identifier"], $request["project_id"], $request["mime_type"], $request["timestamp"], $imagedata, $imagethumbdata);
            echo json_encode($result);
            break;
        case 'attachVideo':
            $video_data = $files['file']['tmp_name'];
            $video_type = $request["mimeType"];
            $video_name = str_replace(' ', '_', $files["file"]["name"]);
            move_uploaded_file($video_data, "uploads/{$video_name}");
            $result = $dao->addVideoToFind($request['id'], $request["findId"], $video_type, $video_name);
            return $result;
            break;
        case 'attachAudio':
            $audio_data = $files['file']['tmp_name'];
            $audio_type = $request["mimeType"];
            $audio_name = str_replace(' ', '_', $files["file"]["name"]);
            move_uploaded_file($audio_data, "uploads/{$audio_name}");
            $result = $dao->addAudioClipToFind($request['id'], $request["findId"], $audio_type, $audio_name);
            return $result;
            break;
        case 'removePicture':
            $dao->deletePictureFromFind($request["id"]);
            break;
        case 'removeVideo':
            $dao->deleteVideoFromFind($request["id"]);
            break;
        case 'removeAudioClip':
            $dao->deleteAudioClipFromFind($request["id"]);
            break;
        case 'deleteAllPictures':
            $dao->deleteImages($request["findId"]);
            break;
        case 'deleteAllVideos':
            $dao->deleteVideos($request["findId"]);
            break;
        case 'deleteAllAudioClips':
            $dao->deleteAudioClips($request["findId"]);
            break;
        case 'getPicture':
            $picture = $dao->getPicture($request["id"]);
            $imageEncoded = base64_encode($picture["data_full"]);
            $imageThumbEncoded = base64_encode($picture["data_thumb"]);
            $pictureEncoded = $picture;
            if ($imageEncoded != "") {
                $pictureEncoded["data_full"] = $imageEncoded;
            }
            if ($imageThumbEncoded != "") {
                $pictureEncoded["data_thumb"] = $imageThumbEncoded;
            }
            if (count($pictureEncoded) > 0) {
                echo json_encode($pictureEncoded);
            } else {
                echo "false";
            }
            break;
        case 'getPicturesByFind':
            $pictures = $dao->getPicturesByFind($request["guid"]);
            $result = array();
            foreach ($pictures as $pic) {
                $imageEncoded = base64_encode($pic["data_full"]);
                $imageThumbEncoded = base64_encode($pic["data_thumb"]);
                $pictureEncoded = $pic;
                if ($imageEncoded != "") {
                    $pictureEncoded["data_full"] = $imageEncoded;
                }
                if ($imageThumbEncoded != "") {
                    $pictureEncoded["data_thumb"] = $imageThumbEncoded;
                }
                if (count($pictureEncoded) > 0) {
                    $result[] = $pictureEncoded;
                }
            }
            if (count($result) > 0) {
                echo json_encode($result);
            } else {
                echo "false";
            }
            break;
        case 'getVideo':
            $video = $dao->getVideo($request["id"]);
            $video_name = $video["data_path"];
            $video_path = "uploads/{$video_name}";
            $fp_v = fopen($video_path, 'r');
            $video_data = fread($fp_v, filesize($video_path));
            $videoEncoded = base64_encode($video_data);
            $clipEncoded = $video;
            $clipEncoded["data_full"] = $videoEncoded;
            echo json_encode($clipEncoded);
            break;
        case 'getAudio':
            $audio = $dao->getAudioClip($request["id"]);
            $audio_name = $audio["data_path"];
            $audio_path = "uploads/{$audio_name}";
            $fp_v = fopen($audio_path, 'r');
            $audio_data = fread($fp_v, filesize($audio_path));
            $audioEncoded = base64_encode($audio_data);
            $clipEncoded = $audio;
            $clipEncoded["data_full"] = $audioEncoded;
            echo json_encode($clipEncoded);
            break;
        case 'searchFinds':
            $search_value = $request['search_value'];
            $project_id = $request['project_id'];
            $result = $dao->searchFinds($search_value, $project_id);
            echo json_encode($result);
            break;
        case 'execCommand':
            $command = $request['command'];
            echo $dao->execCommand($command);
            break;
        default:
            break;
    }
}
Exemple #21
0
require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'core' . DIRECTORY_SEPARATOR . 'bootstrap.php';
// check if there is query string with book id. If not, redirect.
if (Input::exists('get') === false || Input::found('id') === false) {
    Redirect::to('index.php');
}
if (Token::check(Input::get('token'))) {
    //delete book from database
    $bookManager = new BookManage();
    $bookManager->delete(Input::get('id'));
    /**
     *
     * The following block of code if responsible for deleting book cover
     *
     **/
    $destination = dirname(__DIR__) . DIRECTORY_SEPARATOR . Config::get('upload_book_cover/default_folder');
    // adding trailing slash if there isn't one
    if ($destination[strlen($destination) - 1] != '/') {
        $destination .= '/';
    }
    // find the file by given name no mater what extension it has and delete it
    $pattern = $destination . Input::get('id') . '.*';
    $file = glob($pattern)[0];
    unlink($file);
    $logMessage = 'Книга удалена (' . Input::get('id') . ')';
    Log::getInstance()->message($logMessage, 'book_manage');
    Session::flash('home', 'Товар удален из каталога');
    Redirect::to('manage.php');
} else {
    Session::flash('home', 'Неправильный токен');
    Redirect::to('manage.php');
}
Exemple #22
0
 /**
  * confirm registration 
  * @param unknown_type $authKey
  * @param unknown_type $imei
  * @param unknown_type $name
  */
 function confirmDevice($authKey, $imei, $name)
 {
     Log::getInstance()->log("confirmDevice: {$authKey}, {$imei}, {$name}");
     $stmt = $this->db->prepare("SELECT auth_key FROM device WHERE imei = :imei");
     $stmt->bindValue(":imei", $imei);
     $stmt->execute();
     if ($existingDevice = $stmt->fetch(PDO::FETCH_ASSOC)) {
         $res = mysql_query("select user_id from device where auth_key = '{$authKey}'") or die(mysql_error());
         list($userId) = mysql_fetch_array($res, MYSQL_NUM);
         mysql_query("DELETE FROM device WHERE auth_key = '{$authKey}'");
         mysql_query("UPDATE device SET auth_key = '{$authKey}', status = 'ok', user_id = '{$userId}' WHERE imei = '{$imei}'");
         return true;
         //$stmt->bindValue(":authKey", $authKey);
         //$stmt->bindValue(":imei", $imei);
         //return $stmt->execute();
         /*
         $stmt = $this->db->prepare(
         	"SELECT name FROM device WHERE imei = :imei"
         );
         $stmt->bindValue(":imei", $imei);
         $stmt->execute();
         
         list($name) = $stmt->fetch(PDO::FETCH_ASSOC);
         */
     }
     $stmt = $this->db->prepare("UPDATE device SET\n\t\t\t imei = :imei,\n\t\t\t name = :name,\n\t\t\t status = 'ok'\n\t\t\t WHERE auth_key = :authKey");
     $stmt->bindValue(":imei", $imei);
     $stmt->bindValue(":name", $name);
     $stmt->bindValue(":authKey", $authKey);
     $result = $stmt->execute();
     return $result;
 }
 /**
  * Update information about a find
  * @param unknown_type $guId -- globally unique ID
  * @param unknown_type $name
  * @param unknown_type $description
  * @param unknown_type $revision
  */
 function updateFind($auth_key, $imei, $guId, $projectId, $name, $description, $revision, $data, $latitude, $longitude)
 {
     Log::getInstance()->log("updateFind: {$auth_key}, {$imei}, {$guId}, {$projectId}, {$name}, {$description}, {$revision}, {$data}, {$latitude}, {$longitude}");
     $stmt = $this->db->prepare("update find set name = :name, description = :description, \n\t\t\trevision = :revision, modify_time = NOW(), latitude = :latitude, longitude = :longitude where guid = :guid AND project_id = :projectId");
     $stmt->bindValue(":name", $name);
     $stmt->bindValue(":description", $description);
     $stmt->bindValue(":revision", $revision);
     $stmt->bindValue(":guid", $guId);
     $stmt->bindValue(":projectId", $projectId);
     $stmt->bindValue(":latitude", $latitude);
     $stmt->bindValue(":longitude", $longitude);
     $stmt->execute();
     $this->createLog("I", "updateFind", "Updated Find= {$guId}");
     Log::getInstance()->log("getFind: id = {$id}");
     // Get this Find's id for query to extended data
     $stmt = $this->db->prepare("select id from find where guid = :guid");
     $stmt->bindValue(":guid", $guId);
     $stmt->execute();
     $idResult = $stmt->fetchAll(PDO::FETCH_ASSOC);
     $id = $idResult[0]["id"];
     Log::getInstance()->log("updateFind: id = {$id}");
     // Update the extended data
     $stmt = $this->db->prepare("update find_extension set data = :data where find_id = :find_id");
     $stmt->bindValue(":find_id", $id);
     $stmt->bindValue(":data", $data);
     $stmt->execute();
     Log::getInstance()->log("updateFind: updated extended data for find_id = {$id}");
     // Make an entry in find_history
     $stmt = $this->db->prepare("insert into find_history (find_guid, action, imei, auth_key) VALUES (:find_guid, :action, :imei, :auth_key)");
     $stmt->bindValue(":find_guid", $guId);
     $stmt->bindValue(":action", "update");
     $stmt->bindValue(":imei", $imei);
     $stmt->bindValue(":auth_key", $auth_key);
     $stmt->execute();
     Log::getInstance()->log("Updated find_history, updated Find {$guId} {$imei}");
     return "True Updated {$guId} on server";
 }
<p class="form-title">Nuevo Cliente</p>
<?php 
if (!Forms::checkPermission(FORM_CUSTOMER_NEW)) {
    return;
}
require 'inc/class.customer.php';
require_once 'inc/class.log.php';
$log = Log::getInstance();
$customer = new Customer();
$customer->name = isset($_POST['name']) ? $_POST['name'] : "";
$customer->nit = isset($_POST['nit']) ? $_POST['nit'] : "";
$customer->phone = isset($_POST['phone']) ? $_POST['phone'] : "";
$customer->cell = isset($_POST['cell']) ? $_POST['cell'] : "";
$customer->active = isset($_POST['active']) ? $_POST['active'] : 1;
$customer->address = isset($_POST['address']) ? $_POST['address'] : "";
$customer->email = isset($_POST['email']) ? $_POST['email'] : "";
include 'inc/widget/error.php';
?>
<form action="" method="post">
	<table class="form">
	<tbody>
	<tr>
		<td class="label">Nombre:</td>
		<td><input name="name" type="text" id="name" value="<?php 
echo $customer->name;
?>
" size="60"> <span class="mandatory">*</span></td>
	</tr>
	<tr>
		<td class="label">NIT:</td>
		<td><input name="nit" type="text" id="nit" value="<?php 
/**
 * the main apiController function that outputs json_encoded results
 * @param $path
 * @param $request
 * @param $files
 */
function apiController($path, $request, $files = null)
{
    global $dao, $smarty;
    list($reqPath, $queryString) = explode('?', $path);
    $pathParts = explode('/', substr($reqPath, 1));
    list($action) = $pathParts;
    Log::getInstance()->log("Reached server");
    Log::getInstance()->log("{$path} , {$request}");
    if ($action != "addExpeditionPoint" && $action != "getDeviceByAuthKey") {
        $log = Log::getInstance();
        $log->log("{$action}");
        $log->log("{$path}, {$request}");
    }
    $authKey = $request["authKey"];
    if ($action != "isreachable" && $action != "login" && $action != "registerUser" && $action != "registerDevice" && $action != "getPendingDeviceStatus" && !$authKey) {
        $response = array("errorCode" => ERR_AUTHKEY_MISSING, "errorMessage" => "You must provide an authentication key with each request.");
        echo json_encode($response);
        die;
    }
    if ($action != isreachable && $action != "login" && $action != "registerUser") {
        $device = $dao->getDeviceByAuthKey($authKey);
        if ($action != "registerDevice" && $action != "getPendingDeviceStatus" && !$device) {
            $response = errorResponseCode(ERR_AUTHKEY_INVALID, "Invalid authentication key.");
            echo json_encode($response);
            die;
        }
        $deviceUserId = $device["user_id"];
        $deviceIdentifier = $device["imei"];
    }
    switch ($action) {
        case 'isreachable':
            jsonMessage(AUTHN_OK, "The server is reachable");
            break;
        case 'login':
            extract($request);
            Log::getInstance()->log("Login = {$request} email={$email} imei={$imei}");
            if (!$email) {
                jsonError(ERR_EMAIL_MISSING, "Email Address is required");
            } else {
                if (!validate_email_address($email)) {
                    jsonError(ERR_EMAIL_INVALID, "Email Address is invalid");
                }
            }
            if (!$password) {
                jsonError(ERR_PASSWORD_MISSING, "Password is required");
            }
            // NOTE: Tablets don't have imei.  So this will only work for phones.
            //			if (!$imei){
            //				jsonError(ERR_IMEI_MISSING, "IMEI Code is required");
            //			}
            if ($login = $dao->checkLogin($email, $password)) {
                $authKey = genAuthKey();
                $userId = $login["id"];
                if ($dao->registerDevicePending($userId, $authKey)) {
                    jsonMessage(AUTHN_OK, $authKey);
                } else {
                    jsonError(ERR_SERVER, "Authentication Key cannot be generated");
                }
            } else {
                jsonError(AUTHN_FAILED, "Authentication failed. Please Check email address or password.");
            }
            break;
        case 'registerUser':
            extract($request);
            if (!$email) {
                jsonError(ERR_EMAIL_MISSING, "Email Address is required");
            } else {
                if (!validate_email_address($email)) {
                    jsonError(ERR_EMAIL_INVALID, "Email Address is invalid");
                }
            }
            if (!$firstname) {
                jsonError(ERR_FIRSTNAME_MISSING, "Firstname is required");
            }
            if (!$lastname) {
                jsonError(ERR_LASTNAME_MISSING, "LastName is required");
            }
            if (strlen($password1) < 6) {
                jsonError(ERR_PASSWORD1_INVALID, "Password must be 6 characters or longer");
            }
            if ($password1 != $password2) {
                jsonError(ERR_PASSWORD_UNMATCHED, "Passwords must match");
            }
            $newUser = array($email, $firstname, $lastname, $password1);
            $result = $dao->registerUser($newUser);
            if ($result === REGISTRATION_EMAILEXISTS) {
                jsonError(ERR_EMAIL_INVALID, "Email already exists");
            }
            $smarty->assign('link', SERVER_BASE_URI . "/web/verifyEmail?email={$email}");
            sendEmail($email, "email verification", $smarty->fetch("emails/new_user.tpl"));
            jsonMessage(AUTHN_OK, "Registration Successful");
            break;
        case 'getDeltaFindsIds':
            echo $dao->getDeltaFindsIds($authKey, $request["projectId"]);
            break;
        case 'recordSync':
            $projectId = -1;
            if ($request["projectId"]) {
                $projectId = (int) $request["projectId"];
            }
            echo $dao->recordSync($request["imei"], $authKey, $projectId);
            //echo $dao->recordSync($deviceIdentifier, $authKey);
            break;
        case 'registerDevice':
            $imei = $request["imei"];
            $name = null;
            if (strstr($authKey, "sb_")) {
                $result = $dao->addSandboxDevice($authKey, $imei);
            } else {
                $result = $dao->confirmDevice($authKey, $imei, $name);
            }
            echo json_encode($result);
            break;
        case 'addExpedition':
            echo $dao->addExpedition($request["projectId"]);
            break;
        case 'addExpeditionPoint':
            echo $request["expedition"] . ",";
            echo $dao->addExpeditionPoint($request["expedition"], $request["latitude"], $request["longitude"], $request["altitude"], $request["swath"], $request["time"]);
            break;
        case 'getPendingDeviceStatus':
            $device = $dao->getDeviceByAuthKey($authKey);
            if ($device["status"] == "ok") {
                echo json_encode($device);
            } else {
                echo json_encode(false);
            }
            break;
        case 'listOpenProjects':
            $result = $dao->getProjects(PROJECTS_OPEN);
            echo json_encode($result);
            break;
        case 'listMyProjects':
            $result = $dao->getUserProjects($deviceUserId);
            echo json_encode($result);
            break;
        case 'newProject':
            extract($request);
            if (!$name) {
                jsonError(ERR_NAME_INVALID, "Project name is invalid.");
            }
            $result = $dao->newProject($name, $description, $deviceUserId);
            if (is_string($result)) {
                jsonMessage(PROJ_CREATE_SUCCESS, "Project created successfully.");
            } else {
                jsonError(PROJ_CREATE_FAIL, "Project creation failed.");
            }
            break;
        case 'projectExists':
            if ($request["projectId"]) {
                echo $dao->projectExists($request["projectId"]);
            }
            break;
        case 'listFinds':
            echo json_encode($dao->getFinds($request["project_id"]));
            break;
        case 'getFind':
            $result = $dao->getFind($request["guid"]);
            echo json_encode($result);
            break;
        case 'deleteFind':
            echo $dao->deleteFind($request["id"]);
            break;
        case 'deleteProject':
            $dao->deleteProject($request["projectId"]);
            break;
        case 'deleteAllFinds':
            $dao->deleteAllFinds($request["projectId"]);
            break;
        case 'createFind':
            echo $dao->createFind($authKey, $request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["latitude"], $request["longitude"], $request["revision"], $request["data"]);
            break;
        case 'updateFind':
            echo $dao->updateFind($authKey, $request["imei"], $request["guid"], $request["project_id"], $request["name"], $request["description"], $request["revision"], $request["data"], $request["latitude"], $request["longitude"]);
            break;
        case 'attachPicture':
            $imagedata = base64_decode($request["data_full"]);
            $imagethumbdata = base64_decode($request["data_thumbnail"]);
            $result = $dao->addPictureToFind($request["imei"], $request["guid"], $request["identifier"], $request["project_id"], $request["mime_type"], $request["timestamp"], $imagedata, $imagethumbdata, $authKey);
            echo json_encode($result);
            break;
        case 'attachVideo':
            $video_data = $files['file']['tmp_name'];
            $video_type = $request["mimeType"];
            $video_name = str_replace(' ', '_', $files["file"]["name"]);
            move_uploaded_file($video_data, "uploads/{$video_name}");
            $result = $dao->addVideoToFind($request['id'], $request["findId"], $video_type, $video_name);
            return $result;
            break;
        case 'attachAudio':
            $audio_data = $files['file']['tmp_name'];
            $audio_type = $request["mimeType"];
            $audio_name = str_replace(' ', '_', $files["file"]["name"]);
            move_uploaded_file($audio_data, "uploads/{$audio_name}");
            $result = $dao->addAudioClipToFind($request['id'], $request["findId"], $audio_type, $audio_name);
            return $result;
            break;
        case 'removePicture':
            $dao->deletePictureFromFind($request["id"]);
            break;
        case 'removeVideo':
            $dao->deleteVideoFromFind($request["id"]);
            break;
        case 'removeAudioClip':
            $dao->deleteAudioClipFromFind($request["id"]);
            break;
        case 'deleteAllPictures':
            $dao->deleteImages($request["findId"]);
            break;
        case 'deleteAllVideos':
            $dao->deleteVideos($request["findId"]);
            break;
        case 'deleteAllAudioClips':
            $dao->deleteAudioClips($request["findId"]);
            break;
        case 'getPicture':
            $picture = $dao->getPicture($request["id"]);
            $imageEncoded = base64_encode($picture["data_full"]);
            $imageThumbEncoded = base64_encode($picture["data_thumb"]);
            $pictureEncoded = $picture;
            if ($imageEncoded != "") {
                $pictureEncoded["data_full"] = $imageEncoded;
            }
            if ($imageThumbEncoded != "") {
                $pictureEncoded["data_thumb"] = $imageThumbEncoded;
            }
            if (count($pictureEncoded) > 0) {
                echo json_encode($pictureEncoded);
            } else {
                echo "false";
            }
            break;
        case 'getPicturesByFind':
            $pictures = $dao->getPicturesByFind($request["guid"]);
            $result = array();
            foreach ($pictures as $pic) {
                $imageEncoded = base64_encode($pic["data_full"]);
                $imageThumbEncoded = base64_encode($pic["data_thumb"]);
                $pictureEncoded = $pic;
                if ($imageEncoded != "") {
                    $pictureEncoded["data_full"] = $imageEncoded;
                }
                if ($imageThumbEncoded != "") {
                    $pictureEncoded["data_thumb"] = $imageThumbEncoded;
                }
                if (count($pictureEncoded) > 0) {
                    $result[] = $pictureEncoded;
                }
            }
            if (count($result) > 0) {
                echo json_encode($result);
            } else {
                echo "false";
            }
            break;
        case 'getVideo':
            $video = $dao->getVideo($request["id"]);
            $video_name = $video["data_path"];
            $video_path = "uploads/{$video_name}";
            $fp_v = fopen($video_path, 'r');
            $video_data = fread($fp_v, filesize($video_path));
            $videoEncoded = base64_encode($video_data);
            $clipEncoded = $video;
            $clipEncoded["data_full"] = $videoEncoded;
            echo json_encode($clipEncoded);
            break;
        case 'getAudio':
            $audio = $dao->getAudioClip($request["id"]);
            $audio_name = $audio["data_path"];
            $audio_path = "uploads/{$audio_name}";
            $fp_v = fopen($audio_path, 'r');
            $audio_data = fread($fp_v, filesize($audio_path));
            $audioEncoded = base64_encode($audio_data);
            $clipEncoded = $audio;
            $clipEncoded["data_full"] = $audioEncoded;
            echo json_encode($clipEncoded);
            break;
        case 'searchFinds':
            $search_value = $request['search_value'];
            $project_id = $request['project_id'];
            $result = $dao->searchFinds($search_value, $project_id);
            echo json_encode($result);
            break;
        case 'execCommand':
            $command = $request['command'];
            echo $dao->execCommand($command);
            break;
        default:
            break;
    }
}
 /**
  * invoked by: Controller.Player.logout()
  *             Controller.Administrator.logout()
  * @param $user
  * @return bool
  */
 public function logout($user)
 {
     session_start();
     /*
      * check what type of user that will logout.
      * unset all active session
      */
     if ($user == "SUPERUSER") {
         // check if bc_username exist in session
         if (isset($_SESSION["web_username"]) && !empty($_SESSION["web_username"])) {
             // destroy session
             unset($_SESSION['web_id']);
             unset($_SESSION['web_username']);
             unset($_SESSION['web_name']);
             unset($_SESSION['web_avatar']);
             unset($_SESSION['web_state']);
             unset($_SESSION['web_total_player']);
             unset($_SESSION['web_new_player']);
             return true;
         } else {
             return false;
         }
     } else {
         // check if ply_username exist in session
         if (isset($_SESSION["ply_username"]) && !empty($_SESSION["ply_username"])) {
             // create destroy log
             $log = Log::getInstance();
             $log->logging_web_destroy();
             // destroy session
             unset($_SESSION['ply_id']);
             unset($_SESSION['ply_username']);
             unset($_SESSION['ply_name']);
             unset($_SESSION['ply_avatar']);
             unset($_SESSION['ply_state']);
         } else {
             return false;
         }
     }
     return false;
 }
 public function add()
 {
     $db = Database::getInstance();
     $session = Session::getInstance();
     $log = Log::getInstance();
     $amount = 0;
     $res = false;
     $user = $db->escape($session->userinfo['firstname'] . " " . $session->userinfo['lastname']);
     foreach ($this->detail as $detail) {
         $amount += $detail->price * $detail->quantity;
     }
     $sql = "INSERT INTO " . TBL_SELL . " " . "(`date`,date_created,date_modified," . "customer,amount,prepayment,payment_type," . "gloss,status,nit," . "storeid,created_by,updated_by)" . " VALUES " . "('{$this->date}',NOW(),NOW()," . "'" . $db->escape($this->customer) . "',{$amount},{$this->prepayment},{$this->paymentType}," . "'" . $db->escape($this->gloss) . "'," . PURCHASE_STATUS_PENDING . ",'" . $db->escape($this->nit) . "'," . "{$this->storeid},'{$user}','{$user}')";
     $db->startTransaction();
     $res = $db->query($sql);
     if (!$res) {
         $db->rollback();
         $log->addError("No se puedo agregar Venta, verifique los datos ingresados.");
         return false;
     }
     $sellid = $db->lastID();
     if ($this->paymentType == PAYMENT_TYPE_CASH) {
         $this->prepayment = $amount;
     }
     if ($this->prepayment > 0) {
         $sql = "INSERT INTO " . TBL_SELL_PAYMENT . " (sellid,line,`date`,amount,created_by,updated_by)" . " VALUES " . "({$sellid},1,NOW(),{$this->prepayment},'{$user}','{$user}')";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("Problemas para agregar el anticipo de Venta especificado.");
             return false;
         }
     }
     foreach ($this->detail as $detail) {
         //if (!$detail->quantity || !$detail->price)
         //	continue;
         // Check available stock
         $sql = "SELECT stock,unidades units_per_box FROM " . TBL_LOT . " WHERE id={$detail->lotid}";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("No se puede verificar stock disponible de lote {$detail->lotid}.");
             return false;
         }
         if ($db->rows($res) != 1) {
             $db->dispose($res);
             $db->rollback();
             $log->addError("Lote {$detail->lotid} no est&aacute; disponible.");
             return false;
         }
         $row = $db->getRow($res);
         $quantity = $detail->quantity;
         $units = 1;
         if ($detail->unit == UNIT_TYPE_BOX) {
             $units = $row['units_per_box'];
             $quantity = $detail->quantity * $units;
         } else {
             if ($detail->unit == UNIT_TYPE_PACKAGE) {
                 // TODO
             }
         }
         if ($row['stock'] < $quantity) {
             $db->dispose($res);
             $db->rollback();
             $log->addError("Stock insuficiente en lote {$detail->lotid}.");
             return false;
         }
         // Update stock for lot
         $sql = "UPDATE " . TBL_LOT . " SET stock=stock-{$quantity} WHERE id={$detail->lotid}";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("No se puede no se puede actualizar stock de lote {$detail->lotid}.");
             return false;
         }
         // Insert detail
         $item = Item::getFromLot($detail->lotid);
         $detail->description = $item->name;
         $sql = "INSERT INTO " . TBL_SELL_DETAIL . " (sellid,line,description,quantity,price,unit_type,units)" . " VALUES " . "({$sellid},{$detail->line},'{$detail->description}',{$detail->quantity},{$detail->price},'{$detail->unit}',{$units})";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("Problemas para agregar el detalle de Venta especificado.");
             return false;
         }
     }
     if (!$db->commit()) {
         return false;
     }
     $this->id = $sellid;
     return true;
 }
Exemple #28
0
 public function __construct()
 {
     $this->log = Log::getInstance();
     $this->proc = Settings::procPath;
     $this->user = User::getInstance();
 }
Exemple #29
0
 /**
  * @desc supprime un fichier du serveur
  * @return <boolean>
  */
 public function executeDeleteFile()
 {
     if (unlink($_REQUEST["path"] . "/" . $_REQUEST["filename"])) {
         Log::getInstance()->insert(array("action" => "delete", "module" => "projects", "title" => "Suppression de fichier(s)", "message" => "Un fichier a été supprimé pour le projet #" . $_REQUEST["pid"]));
         echo $this->viewHelper->fetch(PROJECTS_VIEWS . "files.tpl", array("files" => Files::getFileContent($_REQUEST["path"] . "/"), "folder" => $_REQUEST["path"]));
     } else {
         echo json_encode(array("alert" => "Une erreur est survenue pendant la suppression du fichier."));
     }
 }
 /**
  * 
  */
 public function Add()
 {
     $db = Database::getInstance();
     $session = Session::getInstance();
     $log = Log::getInstance();
     $amount = 0;
     $res = false;
     $purchased_by = $db->escape($session->userinfo['firstname'] . " " . $session->userinfo['lastname']);
     foreach ($this->detail as $detail) {
         $amount += $detail->price * $detail->quantity;
     }
     $sql = "INSERT INTO " . TBL_PURCHASE . " " . "(code,`date`,date_created,date_modified," . "provider,amount,prepayment," . "gloss,status," . "created_by,updated_by)" . " VALUES " . "('{$this->code}','{$this->date}',NOW(),NOW()," . "'" . $db->escape($this->provider) . "',{$amount},{$this->prepayment}," . "'" . $db->escape($this->gloss) . "'," . PURCHASE_STATUS_PENDING . "," . "'{$purchased_by}','{$purchased_by}')";
     $db->startTransaction();
     $res = $db->query($sql);
     if (!$res) {
         $db->rollback();
         $log->addError("No se puedo agregar Compra, verifique los datos ingresados, el c&oacute;digo no debe repetirse.");
         return false;
     }
     $purchaseid = $db->lastID();
     if ($this->prepayment > 0) {
         $sql = "INSERT INTO " . TBL_PURCHASE_PAYMENT . " (purchaseid,line,`date`,amount,created_by,updated_by)" . " VALUES " . "({$purchaseid},1,NOW(),{$this->prepayment},'{$purchased_by}','{$purchased_by}')";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("Problemas para agregar el anticipo de Compra especificado.");
             return false;
         }
     }
     foreach ($this->detail as $detail) {
         $sql = "INSERT INTO " . TBL_PURCHASE_DETAIL . " (purchaseid,line,description,quantity,price)" . " VALUES " . "({$purchaseid},{$detail->line},'{$detail->description}',{$detail->quantity},{$detail->price})";
         $res = $db->query($sql);
         if (!$res) {
             $db->rollback();
             $log->addError("Problemas para agregar el detalle de Compra especificado.");
             return false;
         }
     }
     if (!$db->commit()) {
         return false;
     }
     $this->id = $purchaseid;
     return true;
 }