Beispiel #1
0
 public static function send($subject, $content)
 {
     // 十分钟一次
     $redis = Yaf\Registry::get('redis');
     $hash = $subject . '|' . intval(time() / 600);
     if ($redis->get(self::$redis_latest_mail_key) == $hash) {
         return false;
     } else {
         // send mail
         $mail = new PHPMailer();
         $mail->isSMTP();
         $mail->Host = "smtp.163.com";
         $mail->Port = 25;
         $mail->SMTPAuth = true;
         $mail->Username = "ideawebcn@163.com";
         $mail->Password = "rabbitAimsam52";
         $mail->setFrom('ideawebcn@163.com', 'AutoTrade');
         // TODO
         $mail->addAddress('', '');
         $mail->Subject = $subject;
         $mail->Body = $content;
         if ($mail->send()) {
             $redis->set(self::$redis_latest_mail_key, $hash);
             return true;
         } else {
             Logger::Log('Send mail failed' . $mail->ErrorInfo, Logger::ERROR_LOG);
             return false;
         }
     }
 }
Beispiel #2
0
 /**
  * @desc 执行交易
  */
 public function run()
 {
     Logger::Log('Start place Order: ' . $this->__toString());
     $action = $this->action;
     usleep(400000);
     $result = $this->account->market->{$action}($this->price, $this->amount);
     Logger::Log("order result :" . var_export($result));
     //false 代表下单不成功,直接再次尝试
     //TODO 如果非常长的时间整个报警
     while ($result === false) {
         Logger::Log("Place " . get_class($this->account->market) . " order failed, try again.");
         $this->status = self::ORDER_PLACE_FAILED;
         return $this->run();
     }
     if ($result === true) {
         Logger::Log("Place " . get_class($this->account->market) . " order successful and deal!");
         //下单成功并且交易成功
         $this->status = self::ORDER_DEAL_SUCCESS;
     } else {
         $this->order_id = $result;
         Logger::Log("Place " . get_class($this->account->market) . " order successful order_id[{$this->order_id}]");
         $this->status = self::ORDER_PLACE_SUCCESS;
     }
     return null;
 }
Beispiel #3
0
 public static function GeocodeLocation($locationName)
 {
     if (static::$geocoder == null) {
         static::$geocoder = new OpenCage\Geocoder(self::Key, self::Options);
     }
     Logger::Log("Resolving : " . $locationName);
     $result = static::$geocoder->geocode($locationName);
     $ret = new GeocodingResult();
     if (!isset($result)) {
         Logger::Log("Address: " . $locationName . " was not resolved: No result recieved");
     } else {
         if (isset($result) && $result['status']['message'] == "OK" && count($result['results']) > 0) {
             $ret->valid = true;
             $res = $result['results'][0]['geometry'];
             $ret->lat = $res['lat'];
             $ret->lon = $res['lng'];
             Logger::Log("Address: " . $locationName . " was resolved as: " . $res['lat'] . " , " . $res['lng']);
         } else {
             $ret->valid = false;
             $message = "«" . $result['status']['code'] . " " . $result['status']['message'] . "»";
             Logger::Log("Address: " . $locationName . " was not resolved: " . $message . ".");
         }
     }
     // Logger::Log( print_r ( $result, true ) );
     return $ret;
 }
Beispiel #4
0
 public function logout()
 {
     $datetime = new DateTime();
     $this->logoutTime = $datetime->format('Y/m/d H:i:s a');
     Logger::Log(get_class($this), 'OK', $this->user->username . ' logs out at ' . $this->logoutTime . ' from terminal XXX');
     //$this::__destroy();
 }
Beispiel #5
0
 public static function Log($class, $category, $message)
 {
     $datetime = new DateTime();
     $stamp = $datetime->format('YmdHis');
     try {
         $sql = 'INSERT INTO logs (class, category, message, stamp) VALUES ("' . $class . '", "' . $category . '", "' . $message . '", ' . $stamp . ')';
         DatabaseHandler::Execute($sql);
     } catch (Exception $e) {
         Logger::Log(get_class($this), 'Exception', $e->getMessage());
     }
 }
Beispiel #6
0
 /**
  * Logs messages depending on the ids trace level.
  *
  * @param TraceLevel $idsTraceLevel IDS Trace Level
  * @param string messageToWrite The message to write.
  */
 public function Log($idsTraceLevel, $messageToWrite)
 {
     if ((int) $this->traceSwitchLevel < (int) $idsTraceLevel) {
         return;
     }
     $backTrace = debug_backtrace();
     $callerFileName = $backTrace[0]['file'];
     $callerFileLineNumber = $backTrace[0]['line'];
     $callerFunctionName = $backTrace[0]['function'];
     $logMessage = implode(" - ", array(date('Y-m-d H:i:s'), $callerFileName, $callerFileLineNumber, $callerFunctionName, $messageToWrite));
     parent::Log($idsTraceLevel, $logMessage);
 }
Beispiel #7
0
 /**
  * The function checks whether an input list of arguments, has the correct data type
  * If not, the slim instance terminates with a 412 error code
  *
  * @param Slim $app a running slim instance
  */
 public static function checkInput()
 {
     $args = func_get_args();
     // the first argument ist the slim instance, remove from the test list
     $app =& $args[0];
     $args = array_slice($args, 1, count($args));
     foreach ($args as $a) {
         // search a argument, which is not true
         if (!$a) {
             // one of the arguments isn't true, abort progress
             Logger::Log('access denied', LogLevel::ERROR);
             $app->response->setBody('[]');
             $app->response->setStatus(412);
             $app->stop();
             break;
         }
     }
 }
Beispiel #8
0
 private function exchange($account_group_id, $to_usd_rate, $to_cny_rate)
 {
     $account_group = new AccountGroupModel($account_group_id);
     $trades = $account_group->availableTrades();
     if (count($trades) > 0) {
         foreach ($trades as $trade) {
             Logger::Log("Judge Trade: " . $trade->__toString());
             if ($trade->tacticsTransport($to_usd_rate, $to_cny_rate)) {
                 $trade->run(TradeModel::MODE_LOOSE);
                 Logger::Log('finished 1 time, next trade.');
                 return $this->runAction();
             } else {
                 Logger::Log('no chance, next trade.');
             }
         }
         return $this->exchange($account_group_id, $to_usd_rate, $to_cny_rate);
     } else {
         throw new Exception('no possible trade, fix it!');
     }
 }
Beispiel #9
0
 private function restart()
 {
     //暂时做个定时重启策略
     $time = time();
     $pid = getmypid();
     $hedge = json_decode(Yaf\Registry::get('redis')->get('hedge'), true);
     if (empty($hedge)) {
         Yaf\Registry::get('redis')->set('hedge', json_encode(array('time' => $time, 'pid' => $pid)));
     } else {
         if ($time - $hedge['time'] > 500) {
             Logger::Log("restart Hedge");
             $path = APPLICATION_PATH . "/scripts/Hedge";
             Yaf\Registry::get('redis')->del('hedge');
             system("{$path}");
             system("kill -9 {$hedge['pid']}");
             system("kill -9 {$pid}");
         } else {
             if ($hedge['pid'] != $pid) {
                 system("kill -9 {$hedge['pid']}");
                 Yaf\Registry::get('redis')->set('hedge', json_encode(array('time' => $time, 'pid' => $pid)));
             }
         }
     }
 }
Beispiel #10
0
 /**
  * Handle & log exceptions
  *
  * @param  Throwable  $e
  * @return void
  * @see http://php.net/manual/en/function.set-exception-handler.php
  */
 public static function handleException($e)
 {
     Logger::Log(get_class($e), $e->getMessage(), $e->getFile(), $e->getLine());
     self::render($e)->send();
 }
Beispiel #11
0
 /**
  * performs a custom request
  *
  * @param string $method the request type (POST, DELETE, PUT, GET, ...) 
  * @param string $target the taget URL
  * @param string $header an array with header informations
  * @param string $content the request content/body
  *
  * @return an array with the request result (status, header, content)
  * - ['headers'] = an array of header informations e.g. ['headers']['Content-Type']
  * - ['content'] = the response content
  * - ['status'] = the status code e.g. 200,201,404,409,...
  */
 public static function custom($method, $target, $header, $content, $authbool = true, $sessiondelete = false)
 {
     $begin = microtime(true);
     $done = false;
     if (!CConfig::$onload && strpos($target, 'http://localhost/') === 0 && file_exists(dirname(__FILE__) . '/request_cconfig.json')) {
         if (self::$components === null) {
             self::$components = CConfig::loadStaticConfig('', '', dirname(__FILE__), 'request_cconfig.json');
         }
         $coms = self::$components->getLinks();
         if ($coms != null) {
             if (!is_array($coms)) {
                 $coms = array($coms);
             }
             $e = strlen(rtrim($_SERVER['DOCUMENT_ROOT'], '/'));
             $f = substr(str_replace("\\", "/", dirname(__FILE__)), $e);
             $g = substr(str_replace("\\", "/", $_SERVER['SCRIPT_FILENAME']), $e);
             $a = 0;
             for (; $a < strlen($g) && $a < strlen($f) && $f[$a] == $g[$a]; $a++) {
             }
             $h = substr(str_replace("\\", "/", $_SERVER['PHP_SELF']), 0, $a - 1);
             foreach ($coms as $com) {
                 if ($com->getPrefix() === null || $com->getLocalPath() == null || $com->getClassFile() == null || $com->getClassName() == null) {
                     Logger::Log('nodata: ' . $method . ' ' . $target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log');
                     continue;
                 }
                 $url = 'http://localhost' . $h . '/' . $com->getLocalPath();
                 if (strpos($target, $url . '/') === 0) {
                     $result = array();
                     $tar = dirname(__FILE__) . '/../' . $com->getLocalPath() . '/' . $com->getClassFile();
                     $tar = str_replace("\\", "/", $tar);
                     if (!file_exists($tar)) {
                         continue;
                     }
                     $add = substr($target, strlen($url));
                     $sid = CacheManager::getNextSid();
                     CacheManager::getTree($sid, $target, $method);
                     $cachedData = CacheManager::getCachedDataByURL($sid, $target, $method);
                     if ($cachedData !== null) {
                         $result['content'] = $cachedData->content;
                         $result['status'] = $cachedData->status;
                         ///Logger::Log('out>> '.$method.' '.$target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log');
                         CacheManager::cacheData($sid, $com->getTargetName(), $target, $result['content'], $result['status'], $method);
                     } else {
                         $args = array('REQUEST_METHOD' => $method, 'PATH_INFO' => $add, 'slim.input' => $content);
                         if (isset($_SERVER['HTTP_SESSION'])) {
                             $args['HTTP_SESSION'] = $_SERVER['HTTP_SESSION'];
                         }
                         if (isset($_SERVER['HTTP_USER'])) {
                             $args['HTTP_USER'] = $_SERVER['HTTP_USER'];
                         }
                         if ($authbool) {
                             if (isset($_SESSION['UID'])) {
                                 $args['HTTP_USER'] = $_SESSION['UID'];
                                 $_SERVER['HTTP_USER'] = $_SESSION['UID'];
                             }
                             if (isset($_SESSION['SESSION'])) {
                                 $args['HTTP_SESSION'] = $_SESSION['SESSION'];
                                 $_SERVER['HTTP_SESSION'] = $_SESSION['SESSION'];
                             }
                             if ($sessiondelete) {
                                 if (isset($_SERVER['REQUEST_TIME'])) {
                                     $args['HTTP_DATE'] = $_SERVER['REQUEST_TIME'];
                                     $_SERVER['HTTP_DATE'] = $_SERVER['REQUEST_TIME'];
                                 }
                             } else {
                                 if (isset($_SESSION['LASTACTIVE'])) {
                                     $args['HTTP_DATE'] = $_SESSION['LASTACTIVE'];
                                     $_SERVER['HTTP_DATE'] = $_SESSION['LASTACTIVE'];
                                 }
                             }
                         }
                         if (isset($_SERVER['HTTP_DATE'])) {
                             $args['HTTP_DATE'] = $_SERVER['HTTP_DATE'];
                         }
                         $oldArgs = array('REQUEST_METHOD' => \Slim\Environment::getInstance()->offsetGet('REQUEST_METHOD'), 'PATH_INFO' => \Slim\Environment::getInstance()->offsetGet('PATH_INFO'), 'slim.input' => \Slim\Environment::getInstance()->offsetGet('slim.input'), 'HTTP_DATE' => \Slim\Environment::getInstance()->offsetGet('HTTP_DATE'), 'HTTP_USER' => \Slim\Environment::getInstance()->offsetGet('HTTP_USER'), 'HTTP_SESSION' => \Slim\Environment::getInstance()->offsetGet('HTTP_SESSION'), 'REQUEST_TIME' => \Slim\Environment::getInstance()->offsetGet('REQUEST_TIME'));
                         $oldRequestURI = $_SERVER['REQUEST_URI'];
                         $oldScriptName = $_SERVER['SCRIPT_NAME'];
                         ///$oldRedirectURL = $_SERVER['REDIRECT_URL'];
                         ///echo "old: ".$_SERVER['REQUEST_URI']."\n";
                         $_SERVER['REQUEST_URI'] = substr($target, strlen('http://localhost/') - 1);
                         //$tar.$add;
                         ///$_SERVER['REDIRECT_URL']= substr($target,strlen('http://localhost/')-1);
                         ///echo "mein: ".substr($target,strlen('http://localhost/')-1)."\n";
                         $_SERVER['SCRIPT_NAME'] = $h . '/' . $com->getLocalPath() . '/' . $com->getClassFile();
                         //$tar;
                         $_SERVER['QUERY_STRING'] = '';
                         $_SERVER['REQUEST_METHOD'] = $method;
                         \Slim\Environment::mock($args);
                         include_once $tar;
                         $oldStatus = http_response_code();
                         $oldHeader = array_merge(array(), headers_list());
                         header_remove();
                         http_response_code(0);
                         $name = $com->getClassName();
                         try {
                             ob_start();
                             $obj = new $name();
                             if (isset($obj)) {
                                 unset($obj);
                             }
                             $result['content'] = ob_get_contents();
                             CacheManager::setETag($result['content']);
                             $result['headers'] = array_merge(array(), self::http_parse_headers_short(headers_list()));
                             header_remove();
                             if (!isset($result['headers']['Cachesid'])) {
                                 $newSid = CacheManager::getNextSid();
                                 $result['headers']['Cachesid'] = $newSid;
                             }
                             ob_end_clean();
                             //header_remove();
                             $result['status'] = http_response_code();
                         } catch (Exception $e) {
                             error_log($e->getMessage());
                             header_remove();
                             $result['status'] = '500';
                             $result['content'] = '';
                             $result['headers'] = array();
                         }
                         $_SERVER['REQUEST_URI'] = $oldRequestURI;
                         $_SERVER['SCRIPT_NAME'] = $oldScriptName;
                         //$_SERVER['REDIRECT_URL'] = $oldRedirectURL;
                         \Slim\Environment::mock($oldArgs);
                         $_SERVER['REQUEST_METHOD'] = $oldArgs['REQUEST_METHOD'];
                         http_response_code($oldStatus);
                         header('Content-Type: text/html; charset=utf-8');
                         foreach ($oldHeader as $head) {
                             header($head);
                         }
                         CacheManager::setCacheSid($sid);
                         $targetSid = isset($result['headers']['Cachesid']) ? $result['headers']['Cachesid'] : null;
                         CacheManager::addPath($sid, $targetSid, $com->getTargetName(), $target, $method, $result['status']);
                         CacheManager::finishRequest($targetSid, $h . '/' . $com->getLocalPath(), $com->getTargetName(), $target, $result['content'], $result['status'], $method, $content);
                         CacheManager::cacheData($sid, $com->getTargetName(), $target, $result['content'], $result['status'], $method);
                         ///Logger::Log('in<< '.$method.' '.$com->getClassName().$add, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log');
                     }
                     $done = true;
                     break;
                 }
             }
         }
     }
     if (!$done) {
         // creates a custom request
         Logger::Log("--" . $method . ' ' . $target, LogLevel::DEBUG, false, dirname(__FILE__) . '/../calls.log');
         $ch = Request_CreateRequest::createCustom($method, $target, $header, $content, $authbool, $sessiondelete)->get();
         $content = curl_exec($ch);
         // get the request result
         $result = curl_getinfo($ch);
         $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
         // splits the received header info, to create an entry
         // in the $result['headers'] for each part of the header
         $result['headers'] = self::http_parse_headers(substr($content, 0, $header_size));
         // seperates the content part
         $result['content'] = substr($content, $header_size);
         // sets the received status code
         $result['status'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
         curl_close($ch);
     }
     Logger::Log($target . ' ' . round(microtime(true) - $begin, 2) . 's', LogLevel::DEBUG, false, dirname(__FILE__) . '/../executionTime.log');
     return $result;
 }
Beispiel #12
0
 /**
  * Return the the template as a string.
  *
  * Content is inserted into the template in this function
  */
 public function __toString()
 {
     // make the content available as if variables with the names of its
     // attributes had been declared
     $extractedCount = extract($this->content);
     if ($extractedCount != count($this->content)) {
         Logger::Log("Unable to extract all content.", LogLevel::WARNING);
     }
     // buffer the output
     ob_start();
     // evaluate the template as a php script
     // a closing php tag is needed before the template, so HTML can be
     // used in the template.
     $success = true;
     /*$success = eval("?>" . $this->template);*/
     include $this->templateFile;
     // stop buffering and return the buffer's content
     $s = ob_get_contents();
     ob_end_clean();
     if ($success === FALSE) {
         Logger::Log("Parse error in template: " . $this->template, LogLevel::WARNING);
     }
     return $s;
 }
 /**
  *
  *Este metodo creara una caja asociada a una sucursal. Debe haber una caja por CPU. 
  *
  * @param token string el token que pos_client otorga por equipo
  * @param codigo_caja string El codigo de uso interno de la caja
  * @param impresoras json Un objeto con las impresoras asociadas a esta sucursal.
  * @param basculas json Un objeto con las basculas conectadas a esta caja.
  * @param descripcion string Descripcion de esta caja
  * @return id_caja int Id de la caja generada por la isnercion
  **/
 public static function NuevaCaja($token, $basculas = null, $control_billetes = 0, $descripcion = null, $id_sucursal = null, $impresoras = null)
 {
     Logger::log("Creando nueva caja");
     //Se validan los parametros de caja, si no se recibe sucursal, se intenta
     //tomar de la sesion
     $validar = self::validarParametrosCaja(null, $id_sucursal, $token, $descripcion);
     if (is_string($validar)) {
         Logger::error($validar);
         throw new Exception($validar);
     }
     if (is_null($id_sucursal)) {
         $id_sucursal = self::getSucursal();
         if (is_null($id_sucursal)) {
             Logger::error("No se pudo obtener la sucursal actual y no se obtuvo ninguna sucursal");
             throw new Exception("No se pudo obtener la sucursal actual y no se obtuvo ninguna sucursal");
         }
     }
     //si no recibimos control de billetes, lo ponemos en cero.
     if (is_null($control_billetes)) {
         $control_billetes = 0;
     }
     $caja = ContabilidadController::BuscarCuenta(1, $afectable = "", $clasificacion = "Activo Circulante", $clave = "", $consecutivo_en_nivel = "", $es_cuenta_mayor = "", $es_cuenta_orden = "", $id_cuenta_contable = "", $id_cuenta_padre = "", $naturaleza = "Deudora", $nivel = "", $nombre_cuenta = "Caja", $tipo_cuenta = "Balance");
     if (count($caja["resultados"]) < 1) {
         Logger::Log("Debe de existir la cuenta contable 'Caja' para dar de alta una caja");
         throw new BusinessLogicException("Debe de existir la cuenta contable 'Caja' para dar de alta una caja");
     }
     //se inserta la cuenta contable
     $res = ContabilidadController::NuevaCuenta($caja["resultados"][0]->getAbonosAumentan(), $caja["resultados"][0]->getCargosAumentan(), $caja["resultados"][0]->getClasificacion(), $caja["resultados"][0]->getEsCuentaMayor(), $caja["resultados"][0]->getEsCuentaOrden(), $caja["resultados"][0]->getIdCatalogoCuentas(), $caja["resultados"][0]->getNaturaleza(), $descripcion, $caja["resultados"][0]->getTipoCuenta(), $caja["resultados"][0]->getIdCuentaContable());
     //Se inicializa el registro de caja
     $caja = new Caja();
     $caja->setIdSucursal($id_sucursal);
     $caja->setAbierta(0);
     $caja->setActiva(1);
     $caja->setControlBilletes($control_billetes);
     $caja->setDescripcion($descripcion);
     $caja->setIdSucursal($id_sucursal);
     $caja->setSaldo(0);
     $caja->setToken($token);
     $caja->setIdCuentaContable($res["id_cuenta_contable"]);
     DAO::transBegin();
     try {
         //Se guarda el registro de caja y si se recibieron impresoras se registran con la caja
         //en la tabla impresora_caja.
         CajaDAO::save($caja);
         if (!is_null($impresoras)) {
             $impresoras = object_to_array($impresoras);
             if (!is_array($impresoras)) {
                 throw new Exception("Las impresoras son invalidas", 901);
             }
             $impresora_caja = new ImpresoraCaja(array("id_caja" => $caja->getIdCaja()));
             foreach ($impresoras as $id_impresora) {
                 if (is_null(ImpresoraDAO::getByPK($id_impresora))) {
                     throw new Exception("La impresora con id: " . $id_impresora . " no existe", 901);
                 }
                 $impresora_caja->setIdImpresora($id_impresora);
                 ImpresoraCajaDAO::save($impresora_caja);
             }
         }
     } catch (Exception $e) {
         DAO::transRollback();
         Logger::error("No se pudo crear la caja: " . $e);
         if ($e->getCode() == 901) {
             throw new Exception("No se pudo crear la caja: " . $e->getMessage(), 901);
         }
         throw new Exception("No se pudo crear la caja", 901);
     }
     DAO::transEnd();
     Logger::log("caja creada exitosamente");
     return array("id_caja" => $caja->getIdCaja());
 }
 public static function can_see($persona_id, $owner_uid, $viewer_uid)
 {
     Logger::log("Enter: function PersonaHelper::can_see() persona_id: {$persona_id}, owner_uid; {$owner_uid}, viewer_uid: {$viewer_uid}");
     // load the persona to see it's privacy data
     try {
         $persona = new Persona();
         $persona->load($persona_id);
     } catch (PAException $e) {
         Logger::Log($e->getMessage());
         Logger::log("Exit: function PersonaHelper::can_see() with NULL");
         return null;
         // no persona!
     }
     $data = $persona->get_configuration_data();
     $perm = intval($data->perm);
     if ($viewer_uid == 0) {
         // anon users don't have relations
         $relation = 0;
         // and are definetly not family
         $in_family = 0;
     } else {
         if ($owner_uid == $viewer_uid) {
             $relation = 2;
             $in_family = 1;
         } else {
             // $relation = Relation::get_relation($owner_uid, $viewer_uid);
             $relations = Relation::get_relations($owner_uid);
             $relation = in_array($viewer_uid, $relations);
             $in_family = Relation::is_relation_in_family($owner_uid, $viewer_uid);
         }
     }
     Logger::log("PersonaHelper::can_see() perm: {$perm}, relation: {$relation}, in_family: {$in_family}");
     if (!$perm) {
         // permissions weren't set or are 0 == nobody
         Logger::log("Exit: function PersonaHelper::can_see() with NULL");
         return null;
     } else {
         if ($perm == 1) {
             // show to world (everybody)
             Logger::log("Exit: function PersonaHelper::can_see() with Persona");
             return $persona;
         } else {
             if ($perm == 2) {
                 // show to relations
                 if ($relation) {
                     Logger::log("Exit: function PersonaHelper::can_see() with Persona");
                     return $persona;
                 }
             } else {
                 if ($perm == 3) {
                     // show to family
                     if ($in_family) {
                         Logger::log("Exit: function PersonaHelper::can_see() with Persona");
                         return $persona;
                     }
                 } else {
                     Logger::log("Exit: function PersonaHelper::can_see() with NULL");
                     return null;
                 }
             }
         }
     }
 }
Beispiel #15
0
<?php

/**
 * @file index.php executes the DBUser component on calling via rest api
 *
 * @author Till Uhlig
 * @date 2014
 */
require_once dirname(__FILE__) . '/DBUser.php';
Logger::Log('begin DBUser', LogLevel::DEBUG);
new DBUser();
Logger::Log('end DBUser', LogLevel::DEBUG);
Beispiel #16
0
<?php

/**
 * @file index.php executes the CHelp component on calling via rest api
 *
 * @author Till Uhlig
 * @date 2015
 */
require_once dirname(__FILE__) . '/CHelp.php';
Logger::Log('begin CHelp', LogLevel::DEBUG);
new CHelp();
Logger::Log('end CHelp', LogLevel::DEBUG);
Beispiel #17
0
 /**
  * Deletes a submission.
  *
  * Called when this component revceives an HTTP DELETE request to
  * /submissions/$submissionid(/).
  *
  * @param int $submissionid The submission that is beeing deleted.
  *
  * @note Files are completely removed from the system. This is not intended
  * behaviour as this prevents lecturers and admins from seeing them in the
  * user's submission history.
  *
  * @author Till Uhlig
  * @date 2014
  */
 public function deleteSubmission($submissionid)
 {
     $result = Request::routeRequest('DELETE', '/submission/' . $submissionid, array(), '', $this->_submission, 'submission');
     if ($result['status'] >= 200 && $result['status'] <= 299) {
         // submission is deleted
         $this->app->response->setStatus(201);
         $this->app->response->setBody('');
         if (isset($result['headers']['Content-Type'])) {
             $this->app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
         }
     } else {
         Logger::Log('DELETE DeleteSubmission failed', LogLevel::ERROR);
         $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
         $this->app->response->setBody('');
         $this->app->stop();
     }
 }
Beispiel #18
0
 /**
  * Adds a form.
  *
  * Called when this component receives an HTTP POST request to
  * /form(/).
  */
 public function addForm()
 {
     Logger::Log('starts POST AddForm', LogLevel::DEBUG);
     $header = $this->app->request->headers->all();
     $body = $this->app->request->getBody();
     $this->app->response->setStatus(201);
     $forms = Form::decodeForm($body);
     // always been an array
     $arr = true;
     if (!is_array($forms)) {
         $forms = array($forms);
         $arr = false;
     }
     // this array contains the indices of the inserted objects
     $res = array();
     $choices = array();
     foreach ($forms as $key => $form) {
         $choices[] = $form->getChoices();
         $forms[$key]->setChoices(null);
     }
     $resForms = array();
     foreach ($forms as $form) {
         $method = 'POST';
         $URL = '/form';
         if ($form->getFormId() !== null) {
             $method = 'PUT';
             $URL = '/form/' . $form->getFormId();
         }
         $result = Request::routeRequest($method, $URL, array(), Form::encodeForm($form), $this->_form, 'form');
         // checks the correctness of the query
         if ($result['status'] >= 200 && $result['status'] <= 299 && isset($result['content'])) {
             $newform = Form::decodeForm($result['content']);
             if ($form->getFormId() === null) {
                 $form->setFormId($newform->getFormId());
             }
             $resForms[] = $form;
         } else {
             $f = new Form();
             $f->setStatus(409);
             $resForms[] = $f;
         }
     }
     $forms = $resForms;
     $i = 0;
     foreach ($choices as &$choicelist) {
         foreach ($choicelist as $key2 => $choice) {
             if ($forms[$i]->getFormId() !== null) {
                 $formId = $forms[$i]->getFormId();
                 $choicelist[$key2]->setFormId($formId);
                 $method = 'POST';
                 $URL = '/choice';
                 if ($choicelist[$key2]->getChoiceId() !== null) {
                     $method = 'PUT';
                     $URL = '/choice/' . $choice->getChoiceId();
                 }
                 $result = Request::routeRequest($method, $URL, array(), Choice::encodeChoice($choicelist[$key2]), $this->_choice, 'choice');
                 if ($result['status'] >= 200 && $result['status'] <= 299) {
                     $newchoice = Choice::decodeChoice($result['content']);
                     if ($choicelist[$key2]->getChoiceId() === null) {
                         $choicelist[$key2]->setChoiceId($newchoice->getChoiceId());
                     }
                     $choicelist[$key2]->setStatus(201);
                 } else {
                     $choicelist[$key2]->setStatus(409);
                 }
             }
         }
         $forms[$i]->setChoices($choicelist);
         $i++;
     }
     // checks the correctness of the query
     /*if ( $result['status'] >= 200 && 
                  $result['status'] <= 299 && isset($result['content'])){
                 $newforms = Form::decodeForm($result['content']);
                 if ( !is_array( $newforms ) )
                     $newforms = array($newforms);
                     
                 $i=0;    
                 foreach ($forms as &$form){
                     if ($form->getFormId() === null)
                         $form->setFormId($newforms[$i]->getFormId());
                     $i++;
                 }            
     
                 $sendChoices = array();
                 $i=0;
                 foreach ( $choices as $choicelist ){
                     foreach ( $choicelist as $choice ){
                         $choice->setFormId($forms[$i]->getFormId());
                         $sendChoices[] = $choice;
                     }
                 $i++; 
                 }
                 $choices = $sendChoices;
                 
                 $result = Request::routeRequest( 
                                                 'POST',
                                                 '/choice',
                                                 $this->app->request->headers->all( ),
                                                 Choice::encodeChoice($choices),
                                                 $this->_choice,
                                                 'choice'
                                                 );
                                 
                 // checks the correctness of the query
                 if ( $result['status'] >= 200 && 
                      $result['status'] <= 299 ){
                     $newchoices = Choice::decodeChoice($result['content']);
     
                     $choicelist = array();
                     $i=0;
                     foreach ( $choices as &$choice ){
                         $choice->setChoiceId($newchoices[$i]->getChoiceId());
                         
                         if (!isset($choicelist[$choice->getFormId()]))
                             $choicelist[$choice->getFormId()] = array();
                           
                         $choicelist[$choice->getFormId()][] = $choice;
                         
                         $i++;
                     }
                     
                     foreach ( $forms as &$form ){
                         $form->setChoices($choicelist[$form->getFormId()]);
                     }
                     
                     $res[] = $forms;
                     
                 } else{
                     // remove forms on failure
                     foreach ($forms as $form){
                         $result = Request::routeRequest( 
                                         'DELETE',
                                         '/form/'.$form->getFormId(),
                                         $this->app->request->headers->all( ),
                                         '',
                                         $this->_form,
                                         'form'
                                         );
                     }
                     
                     $res[] = null;
                     $this->app->response->setStatus( 409 );
                 }
                           
             } else {
                 $res[] = null;
                 $this->app->response->setStatus( 409 );
             }*/
     if ($this->app->response->getStatus() != 201) {
         Logger::Log('POST AddForms failed', LogLevel::ERROR);
     }
     if (!$arr && count($res) == 1) {
         $this->app->response->setBody(Form::encodeForm($res[0]));
     } else {
         $this->app->response->setBody(Form::encodeForm($res));
     }
 }
Beispiel #19
0
 /**
  * Deletes a marking.
  *
  * Called when this component receives an HTTP DELETE request to
  * /marking/marking/$markingid(/).
  *
  * @param int $markingid The id of the marking that is being deleted.
  *
  * @author Till Uhlig
  * @date 2014
  */
 public function deleteMarking($markingid)
 {
     $result = Request::routeRequest('DELETE', '/marking/' . $markingid, $this->app->request->headers->all(), '', $this->_marking, 'marking');
     if ($result['status'] >= 200 && $result['status'] <= 299) {
         // marking is deleted
         $this->app->response->setStatus(201);
         $this->app->response->setBody('');
         if (isset($result['headers']['Content-Type'])) {
             $this->app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
         }
     } else {
         Logger::Log('DELETE DeleteMarking failed', LogLevel::ERROR);
         $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
         $this->app->response->setBody('');
         $this->app->stop();
     }
 }
Beispiel #20
0
 function ProcessingErrorCsv($processingId)
 {
     $status = self::ReadStatus($processingId);
     if ($status->Status != self::StatusProcessedErrorCsv) {
         Logger::Log("ProcessingErrorCsv: wrong state :" . $status->Status);
         return $status;
     }
     if ($status->ReevCsvNextLineToProcess >= $status->ReevCsvLinesCount) {
         $status->Status = self::StatusFinishedGeoCsv;
         self::WriteStatus($status);
         return $status;
     }
     $status->Status = self::StatusProcessingErrorCsv;
     self::WriteStatus($status);
     $id = $processingId;
     $maxRows = 2;
     $startRow = $status->ReevCsvNextLineToProcess;
     $toRead = $status->ReevCsvLinesCount - $startRow;
     if ($maxRows < $toRead) {
         $toRead = $maxRows;
     }
     Logger::Log("ProcessingErrorCsv started, from line " . $startRow . " to line " . ($startRow + $toRead));
     // Find indexes in the files. This is important as it will show us which items are already processed
     // and should not be added again (because this can happen, human can make mistake :)
     $finished = file(self::ProcessedDataFileName($id));
     $finishedIndexes = self::GetIndexesFromCsvLines($finished);
     fclose($finished);
     $toReevaluate = file(self::ReevaluatingErrorsDataFileName($id));
     $toReevaluateIndexes = self::GetIndexesFromCsvLines($toReevaluate);
     $errorCsv = fopen(self::ErrorsDataFileName($id), 'a+');
     $processedCsv = fopen(self::ProcessedDataFileName($id), 'a+');
     $endRow = $startRow + $toRead;
     for ($rowNumber = $startRow; $rowNumber < $endRow; ++$rowNumber) {
         $status->ReevCsvNextLineToProcess = $rowNumber + 1;
         $toReevaluateIndex = $toReevaluateIndexes[$rowNumber];
         if (in_array($toReevaluateIndex, $finishedIndexes)) {
             // skip this item, it is already processed, instead process another.
             Logger::Log("Skipping line " . $rowNumber . ", because index " . $toReevaluateIndex . " is already in output.");
             continue;
         }
         $csvLineItems = str_getcsv($toReevaluate[$rowNumber]);
         $geocoded = GeoCoding::GeocodeLocation($csvLineItems[4]);
         Logger::Log("Parsing line " . $rowNumber . ", result: " . ($geocoded->valid ? "OK" : "Failed"));
         if ($geocoded->valid) {
             // add coordinates to end
             $csvLineItems[] = $geocoded->lat;
             $csvLineItems[] = $geocoded->lon;
             // store items to 'good' csv
             fputcsv($processedCsv, $csvLineItems);
             // increase number of correct count, decrease it from error count where it was already
             ++$status->LinesConverted;
             --$status->LinesConversionFailed;
         } else {
             // store items to 'bad' csv
             fputcsv($errorCsv, $csvLineItems);
             // no need to increase error count, it is already written there
         }
     }
     fclose($toReevaluate);
     fclose($errorCsv);
     fclose($processedCsv);
     $status->Status = self::StatusProcessedErrorCsv;
     self::WriteStatus($status);
     return $status;
 }
Beispiel #21
0
Authentication::checkRights(PRIVILEGE_LEVEL::STUDENT, $cid, $uid, $globalUserData);
$langTemplate = 'Upload_Controller';
Language::loadLanguageFile('de', $langTemplate, 'json', dirname(__FILE__) . '/');
if (isset($_POST['action']) && $_POST['action'] == 'submit') {
    // handle uploading files
    /**
     * @todo don't automatically accept the submission
     */
    $timestamp = time();
    $URL = $databaseURI . '/group/user/' . $uid . '/exercisesheet/' . $sid;
    $group = http_get($URL, true);
    $group = json_decode($group, true);
    if (!isset($group['leader'])) {
        $errormsg = Language::Get('main', 'errorNoGroup', $langTemplate, array('status' => 500));
        $notifications[] = MakeNotification('error', $errormsg);
        Logger::Log('error', "No group set for user {$uid} in course {$cid}!");
    } else {
        $URL = $databaseURI . '/exercisesheet/exercisesheet/' . $sid;
        $sheet = http_get($URL, true);
        $sheet = json_decode($sheet, true);
        $isExpired = null;
        $hasStarted = null;
        if (isset($sheet['endDate']) && isset($sheet['startDate'])) {
            // bool if endDate of sheet is greater than the actual date
            $isExpired = date('U') > date('U', $sheet['endDate']);
            // bool if startDate of sheet is greater than the actual date
            $hasStarted = date('U') > date('U', $sheet['startDate']);
            if ($isExpired) {
                // empty
            } elseif (!$hasStarted) {
                set_error(Language::Get('main', 'noExercisePeriod', $langTemplate, array('startDate' => date('d.m.Y  -  H:i', $sheet['startDate']))));
 /**
  * (non-PHPdoc)
  * @see classes/connectionengine/Connect_STH#procedure($procedureName, $params)
  */
 public function &procedure($procedureName = 0, $params = array())
 {
     $objReturned = null;
     $result = null;
     if ($procedureName != 0) {
         throw new ConnectionengineException('$procedureName is null.', __FILE__, __LINE__, sqlsrv_errors());
     }
     $callString = sprintf('EXEC %s ', $procedureName);
     if (count($params) > 0) {
         //$callString .= ' (';
         for ($index = 0, $indexMax = count($params); $index < $indexMax; $index++) {
             if ($index != $indexMax - 1) {
                 $callString .= $params[$index][0] . ',';
             } else {
                 $callString .= $params[$index][0];
             }
         }
         // foreach
         //$callString .= ' )';
     }
     // if
     //$callString .= ' }';
     /* Create the statement. */
     $stmt = sqlsrv_prepare($this->connection, $callString, null);
     if (!$stmt) {
         throw new ConnectionengineException('Error in preparing statement.', __FILE__, __LINE__, sqlsrv_errors());
     }
     $result = sqlsrv_execute($stmt);
     if ($this->debug == true) {
         echo Logger::Log($callString);
     }
     // Traitement erreurs
     if ($result === false && $procedureName != 'sp_start_job') {
         print_r(sqlsrv_errors());
         //echo "Error in query preparation/execution.\n";
         throw new ConnectionengineException('Error on query (KO):' . $callString, __FILE__, __LINE__, sqlsrv_errors());
     } else {
         $objReturned = true;
     }
     //	$objReturned = new Sqlsrv_result_STH ( & $result , $this->defaultAssocType, $query );
     //	$objReturned->debug = $this->debug;
     return $objReturned;
 }
Beispiel #23
0
 public static function request2($sqlStatement, $checkSession, $config = null, $useDbOperator = false)
 {
     if ($config === null) {
         // loads the mysql server config from file
         $config = parse_ini_file('config.ini', TRUE);
     }
     //ini_set('mysql.connect_timeout','60');
     // creates a new connection to database
     if (!isset($config['ZV']['zv_type']) || isset($config['ZV']['zv_type']) && $config['ZV']['zv_type'] == 'local') {
         $path = strpos($config['PL']['urlExtern'], $config['DB']['db_path']) === false ? $config['DB']['db_path'] : 'localhost';
     } else {
         $path = $config['DB']['db_path'];
     }
     if (!$useDbOperator) {
         $dbconn = @mysqli_connect($path, $config['DB']['db_user'], $config['DB']['db_passwd'], $config['DB']['db_name']);
     } else {
         $dbconn = @mysqli_connect($path, $config['DB']['db_user_operator'], $config['DB']['db_passwd_operator'], $config['DB']['db_name']);
     }
     if (!$dbconn) {
         $query_result['errno'] = 10;
         return $query_result;
     }
     // use UTF8
     mysqli_set_charset($dbconn, "utf8");
     $currentTime = $_SERVER['REQUEST_TIME'];
     // check session
     ///if (error_reporting() & E_NOTICE)
     $checkSession = false;
     // remove the comment this line to disable the session examination
     // Storing whether or not a session condition is not satisfied
     $sessionFail = false;
     if ($checkSession === true) {
         Logger::Log('starts session validation', LogLevel::DEBUG);
         if (isset($_SERVER['HTTP_SESSION']) && isset($_SERVER['HTTP_USER']) && isset($_SERVER['HTTP_DATE']) && ctype_digit($_SERVER['HTTP_USER']) && (int) $_SERVER['REQUEST_TIME'] <= (int) $_SERVER['HTTP_DATE'] + 45 * 60) {
             $content = mysqli_query($dbconn, 'select SE_sessionID from Session where U_id = ' . $_SERVER['HTTP_USER']);
             // evaluates the session
             $errno = mysqli_errno($dbconn);
             if ($errno == 0 && gettype($content) != 'boolean') {
                 $data = DBJson::getRows2($content);
                 if ($data != null && $data[0]['SE_sessionID'] == $_SERVER['HTTP_SESSION']) {
                     $sessionFail = false;
                 } else {
                     $sessionFail = true;
                 }
             } else {
                 $sessionFail = true;
             }
         } else {
             $sessionFail = true;
         }
     }
     // if a condition is not met, the request is invalid
     if ($sessionFail == true) {
         $query_result['content'] = '';
         $query_result['errno'] = 401;
         $query_result['error'] = 'access denied';
         $query_result['numRows'] = 0;
         mysqli_close($dbconn);
         $dbconn = null;
         return array($query_result);
     }
     // performs the request
     $answ = mysqli_multi_query($dbconn, $sqlStatement);
     $query_result = array();
     if ($answ === false) {
         $result = array();
         $result['affectedRows'] = mysqli_affected_rows($dbconn);
         $result['insertId'] = mysqli_insert_id($dbconn);
         $result['errno'] = mysqli_errno($dbconn);
         $result['error'] = mysqli_error($dbconn);
         $query_result[] = $result;
     } else {
         do {
             $result = array();
             $res = null;
             if ($res = mysqli_use_result($dbconn)) {
                 $hash = '';
                 $result['content'] = DBJson::getRows2($res, $hash);
                 $result['hash'] = $hash;
                 $result['numRows'] = count($result['content']);
                 // evaluates the request
                 $result['affectedRows'] = mysqli_affected_rows($dbconn);
                 $result['insertId'] = mysqli_insert_id($dbconn);
                 $result['errno'] = mysqli_errno($dbconn);
                 $result['error'] = mysqli_error($dbconn);
                 mysqli_free_result($res);
             } else {
                 $hash = '';
                 $result['content'] = null;
                 $result['hash'] = $hash;
                 $result['affectedRows'] = mysqli_affected_rows($dbconn);
                 $result['insertId'] = mysqli_insert_id($dbconn);
                 $result['errno'] = mysqli_errno($dbconn);
                 $result['error'] = mysqli_error($dbconn);
             }
             $query_result[] = $result;
         } while (mysqli_more_results($dbconn) && mysqli_next_result($dbconn));
     }
     // closes the connection and returns the result
     mysqli_close($dbconn);
     $dbconn = null;
     return $query_result;
 }
Beispiel #24
0
 /**
  * Removes the component from a given course
  *
  * Called when this component receives an HTTP DELETE request to
  * /course/$courseid(/).
  */
 public function deleteCourse($courseid)
 {
     Logger::Log('starts DELETE DeleteCourse', LogLevel::DEBUG);
     $courseid = DBJson::mysql_real_escape_string($courseid);
     foreach ($this->_createCourse as $_link) {
         $result = Request::routeRequest('DELETE', '/course/' . $courseid, array(), '', $_link, 'course');
         // checks the correctness of the query
         if ($result['status'] >= 200 && $result['status'] <= 299) {
             $this->app->response->setStatus(201);
             if (isset($result['headers']['Content-Type'])) {
                 $this->app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
             }
         } else {
             Logger::Log('POST DeleteCourse failed', LogLevel::ERROR);
             $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
             $this->app->stop();
         }
     }
 }
Beispiel #25
0
 /**
  * Adds the component to a course
  *
  * Called when this component receives an HTTP POST request to
  * /course(/).
  */
 public function addCourse()
 {
     Logger::Log('starts POST AddCourse', LogLevel::DEBUG);
     $header = $this->app->request->headers->all();
     $body = $this->app->request->getBody();
     $courses = Course::decodeCourse($body);
     $processes = array();
     if (!is_array($courses)) {
         $courses = array($courses);
     }
     foreach ($courses as $course) {
         $process = new Process();
         $exercise = new Exercise();
         $exercise->setCourseId($course->getId());
         $process->setExercise($exercise);
         $component = new Component();
         $component->setId($this->_conf->getId());
         $process->setTarget($component);
         $processes[] = $process;
     }
     foreach ($this->_postProcess as $_link) {
         $result = Request::routeRequest('POST', '/process', $header, Process::encodeProcess($processes), $_link, 'process');
         // checks the correctness of the query
         if ($result['status'] >= 200 && $result['status'] <= 299) {
             $this->app->response->setStatus(201);
             if (isset($result['headers']['Content-Type'])) {
                 $this->app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
             }
         } else {
             /* if ($courses->getId()!==null){
                    $this->deleteCourse($courses->getId());
                }*/
             Logger::Log('POST AddCourse failed', LogLevel::ERROR);
             $this->app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
             $this->app->response->setBody(Course::encodeCourse($courses));
             $this->app->stop();
         }
     }
     $this->app->response->setBody(Course::encodeCourse($courses));
 }
Beispiel #26
0
 /**
  * Adds the component to a course
  */
 public function addCourse($pre = '')
 {
     $this->loadConfig($pre);
     $pre = ($pre === '' ? '' : '_') . $pre;
     Logger::Log('starts POST AddCourse', LogLevel::DEBUG);
     // decode the received course data, as an object
     $insert = Course::decodeCourse($this->_app->request->getBody());
     // always been an array
     $arr = true;
     if (!is_array($insert)) {
         $insert = array($insert);
         $arr = false;
     }
     // this array contains the indices of the inserted objects
     $res = array();
     foreach ($insert as $in) {
         // starts a query, by using a given file
         $result = DBRequest::getRoutedSqlFile($this->query, dirname(__FILE__) . '/Sql/AddCourse.sql', array('object' => $in, 'pre' => $pre));
         // checks the correctness of the query
         if ($result['status'] >= 200 && $result['status'] <= 299) {
             $queryResult = Query::decodeQuery($result['content']);
             $res[] = $in;
             $this->_app->response->setStatus(201);
             if (isset($result['headers']['Content-Type'])) {
                 $this->_app->response->headers->set('Content-Type', $result['headers']['Content-Type']);
             }
         } else {
             Logger::Log('POST AddCourse failed', LogLevel::ERROR);
             $this->_app->response->setStatus(isset($result['status']) ? $result['status'] : 409);
             $this->_app->response->setBody(Course::encodeCourse($res));
             $this->_app->stop();
         }
     }
     if (!$arr && count($res) == 1) {
         $this->_app->response->setBody(Course::encodeCourse($res[0]));
     } else {
         $this->_app->response->setBody(Course::encodeCourse($res));
     }
 }
Beispiel #27
0
 /**
  * Adds the component to the platform
  *
  * Called when this component receives an HTTP POST request to
  * /platform.
  */
 public function addPlatform($callName, $input, $params = array())
 {
     Logger::Log('starts POST AddPlatform', LogLevel::DEBUG);
     $file = dirname(__FILE__) . '/config.ini';
     $text = "[DIR]\n" . "temp = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), str_replace("\\", "/", $input->getTempDirectory())) . "\"\n" . "files = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), str_replace("\\", "/", $input->getFilesDirectory())) . "\"\n";
     if (!@file_put_contents($file, $text)) {
         Logger::Log('POST AddPlatform failed, config.ini no access', LogLevel::ERROR);
         return Model::isProblem();
     }
     $platform = new Platform();
     $platform->setStatus(201);
     return Model::isCreated($platform);
 }
Beispiel #28
0
 /**
  * Adds the component to the platform
  *
  * Called when this component receives an HTTP POST request to
  * /platform.
  */
 public function addPlatform($callName, $input, $params = array())
 {
     Logger::Log('starts POST AddPlatform', LogLevel::DEBUG);
     //$this->loadConfig($name);
     // decode the received course data, as an object
     $insert = $input;
     $result = Model::isOK();
     // always been an array
     $arr = true;
     if (!is_array($insert)) {
         $insert = array($insert);
         $arr = false;
     }
     // this array contains the indices of the inserted objects
     $res = array();
     foreach ($insert as $in) {
         $file = dirname(__FILE__) . '/config.ini';
         $text = "[DB]\n" . "db_path = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getDatabaseUrl()) . "\"\n" . "db_user = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getDatabaseOperatorUser()) . "\"\n" . "db_passwd = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getDatabaseOperatorPassword()) . "\"\n" . "db_name = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getDatabaseName()) . "\"\n" . "[PL]\n" . "urlExtern = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getExternalUrl()) . "\"\n" . "url = \"" . str_replace(array("\\", "\""), array("\\\\", "\\\""), $in->getBaseUrl()) . "\"";
         if (!@file_put_contents($file, $text)) {
             Logger::Log('POST AddPlatform failed, config.ini no access', LogLevel::ERROR);
             $result = Model::isProblem();
         }
         $platform = new Platform();
         $platform->setStatus(201);
         $res[] = $platform;
         $result = Model::isCreated();
     }
     $return['content'] = $res;
     return $return;
 }
Beispiel #29
0
 /**
  * Logs the report download request.
  * @param string $requestHeaders the HTTP request headers
  * @param integer $responseCode the HTTP response code
  * @param array $params the parameters that were sent, if any
  * @param Exception $exception the exception that will be thrown, if any
  */
 private static function LogRequest($requestHeaders, $responseCode, $params = NULL, $exception = NULL)
 {
     $level = isset($exception) ? Logger::$ERROR : Logger::$INFO;
     $messageParts = array();
     $messageParts[] = trim($requestHeaders);
     $messageParts[] = '';
     // Blank line for readability.
     $messageParts[] = "Parameters:";
     foreach ($params as $name => $value) {
         $messageParts[] = sprintf('%s: %s', $name, $value);
     }
     $messageParts[] = '';
     // Blank line for readability.
     $messageParts[] = sprintf('Response Code: %s', $responseCode);
     if (isset($exception)) {
         $messageParts[] = sprintf('Error Message: %s', $exception->GetMessage());
     }
     $messageParts[] = '';
     // Blank line for readability.
     $message = implode("\n", $messageParts);
     Logger::Log(self::$LOG_NAME, $message, $level);
 }
Beispiel #30
0
 /**
  * @param int $mode
  */
 public function run($mode = self::MODE_LOOSE)
 {
     foreach ($this->orders as $order) {
         $order->start();
     }
     $place_start_time = time();
     // 小睡一下,等待挂单结果
     sleep(1);
     check_again:
     foreach ($this->orders as $order) {
         if ($order->status == OrderModel::ORDER_PLACE_FAILED) {
             // 如果超过市场的挂单市场限制放弃挂单,发邮件
             if (time() - $place_start_time > $order->getAccount()->market->place_order_timeout) {
                 Mail::send('Place order ' . get_class($order->getAccount()->market) . ' timeout', Logger::log('Place order timeout, give up check:' . $order->__toString(), Logger::WARNING_LOG));
                 continue;
             }
             Logger::Log("Wait place order result.");
             sleep(1);
             goto check_again;
         }
         if ($mode == self::MODE_STRICT) {
             // 所有单子必须全部交易成功 可以根据需要注释掉下面这个 while
             while ($order->status !== OrderModel::ORDER_DEAL_SUCCESS) {
                 Logger::Log(get_class($order->getAccount()->market) . " order[" . $order->getId() . "] is dealing, check again.");
                 $order->checkDealing();
             }
             Logger::Log(get_class($order->getAccount()->market) . " order deal success.");
         }
     }
     $this->save();
     // 交易完成之后刷新 info
     foreach ($this->orders as $order) {
         $order->getAccount()->getInfo();
     }
     return true;
 }