static function upgrade($version)
 {
     log::info("aws_s3", "Commencing module upgrade (" . $version . ")");
     switch ($version) {
         case 0:
             log::info("aws_s3", "Installing version 1");
             @mkdir(VARPATH . "modules/aws_s3");
             @mkdir(VARPATH . "modules/aws_s3/log");
             // installation's unique identifier - allows multiple g3's pointing to the same s3 bucket.
             if (!module::get_var("aws_s3", "g3id")) {
                 module::set_var("aws_s3", "g3id", md5(time()));
             }
             module::set_var("aws_s3", "synced", false);
             module::set_var("aws_s3", "enabled", false);
             module::set_var("aws_s3", "access_key", "");
             module::set_var("aws_s3", "secret_key", "");
             module::set_var("aws_s3", "bucket_name", "");
             module::set_version("aws_s3", 1);
         case 1:
             log::info("aws_s3", "Upgrading to version 2");
             $db = Database::instance();
             $db->query("CREATE TABLE {aws_s3_meta} (\n                                `item_id` int(9) NOT NULL,\n                                `item_hash` varchar(32) NOT NULL DEFAULT '',\n                                `thumb_uploaded` smallint(1) NOT NULL DEFAULT 0,\n                                `resize_uploaded` smallint(1) NOT NULL DEFAULT 0,\n                                `fullsize_uploaded` smallint(1) NOT NULL DEFAULT 0,\n                                `local_deleted` smallint(1) NOT NULL DEFAULT 0,\n                                PRIMARY KEY (`item_id`)\n                ) DEFAULT CHARSET=utf8;");
             module::set_var("aws_s3", "upload_thumbs", true);
             module::set_var("aws_s3", "upload_resizes", true);
             module::set_var("aws_s3", "upload_fullsizes", true);
             module::set_var("aws_s3", "s3_storage_only", false);
             if (module::get_var("aws_s3", "synced")) {
                 // v1 has already synced this installation to s3. mark all the items with the relevant meta data
                 $items = ORM::factory("item")->find_all();
                 foreach ($items as $item) {
                     aws_s3::log("Updating S3 meta for item ID: " . $item->id);
                     $item->s3_thumb_uploaded = true;
                     if (!$item->is_album()) {
                         $item->s3_resize_uploaded = true;
                         $item->s3_fullsize_uploaded = true;
                     }
                     $item->s3_local_deleted = false;
                     $item->s3_item_hash = md5($item->relative_path());
                     $item->save_s3_meta();
                 }
             } else {
                 // check various states after upgrade from v1..
                 if (module::get_var("aws_s3", "access_key") != "" && module::get_var("aws_s3", "secret_key") != "" && module::get_var("aws_s3", "bucket_name") != "" && aws_s3::validate_access_details(module::get_var("aws_s3", "access_key"), module::get_var("aws_s3", "secret_key"), module::get_var("aws_s3", "bucket_name"))) {
                     // details are correct but hasn't been synced.
                     if (aws_s3::can_schedule()) {
                         // i can schedule this task
                         aws_s3::schedule_full_sync2();
                         site_status::warning("Your site has been scheduled for full Amazon S3 re-synchronisation. This message will clear when this has been completed.", "aws_s3_not_synced");
                     } else {
                         // i CAN'T schedule it..
                         site_status::warning(t('Your site has not been synchronised to Amazon S3. Until it has, your server will continue to serve image content to your visitors.<br />Click <a href="%url" class="g-dialog-link">here</a> to start the synchronisation task.', array("url" => html::mark_clean(url::site("admin/maintenance/start/aws_s3_task::manual_sync?csrf=__CSRF__")))), "aws_s3_not_synced");
                     }
                 } else {
                     site_status::warning(t('Amazon S3 module needs configuration. Click <a href="%url">here</a> to go to the configuration page.', array("url" => html::mark_clean(url::site("admin/aws_s3")))), "aws_s3_not_configured");
                 }
             }
             module::set_version("aws_s3", 2);
     }
     log::info("aws_s3", "Module upgrade complete");
 }
Пример #2
0
 public function addCatalog(Request $request)
 {
     log::info('add catalog');
     log::info($request);
     try {
         if ($request->get("img") != null) {
             log::info('if');
             $base64data = $request->get("img");
             $filename = str_random(60);
             $uri = substr($base64data, strpos($base64data, ",") + 1);
             $url = public_path() . '/fm_user/images/fm/catalog/' . $request->get('shop_id') . '/';
             if (!File::exists($url)) {
                 File::makeDirectory($url, $mode = 0777, true, true);
             }
             File::put($url . $filename . '.jpg', base64_decode($uri));
             $catalogData = array('media_url' => $url . $filename . '.jpg');
         }
         $catalogData['location_id'] = $request->get('location_id');
         $catalogData['description'] = $request->get('description');
         $catalogData['name'] = $request->get('name');
         $catalogId = Catalog::create($catalogData)->id;
         return Response::json($catalogId);
     } catch (Exception $e) {
         log::info($e);
         return Response::json('ERROR');
     }
 }
Пример #3
0
 public function index()
 {
     $user = user::active();
     user::logout();
     log::info("user", t("User %name logged out", array("name" => $user->name)), html::anchor("user/{$user->id}", $user->name));
     if ($this->input->get("continue")) {
         url::redirect($this->input->get("continue"));
     }
 }
Пример #4
0
 /**
  * Resume a stalled task
  * @param string $task_id
  */
 public function resume($task_id)
 {
     access::verify_csrf();
     $task = ORM::factory("task", $task_id);
     if (!$task->loaded) {
         throw new Exception("@todo MISSING_TASK");
     }
     $view = new View("admin_maintenance_task.html");
     $view->task = $task;
     log::info("tasks", t("Task %task_name resumed (task id %task_id)", array("task_name" => $task->name, "task_id" => $task->id)), html::anchor(url::site("admin/maintenance"), t("maintenance")));
     print $view;
 }
 private function createAuthForModule($markerSiteId)
 {
     $module = Session::get('module');
     Log::info('Module create a marker');
     Log::info('Module UUID: ' . $module);
     $doesAuthExist = Authorization::where('token', '=', $module)->count() > 0;
     if ($doesAuthExist) {
         log::info('Auth for this module exists for the site');
     }
     Authorization::create(array('atlas_id' => $markerSiteId, 'token' => $module, 'principal' => 'module:' . $module, 'privileges' => 'STATS'));
     Log::debug("Created auth for module");
 }
Пример #6
0
 static function item_deleted($item)
 {
     if (!$item->is_photo()) {
         return;
     }
     $name = $item->name;
     $id = $item->id;
     $path = $item->file_path();
     $orig = str_replace(VARPATH . 'albums/', VARPATH . 'originals/', $path);
     @unlink($orig);
     db::build()->from('emboss_mappings')->where('image_id', '=', $id)->delete()->execute();
     log::info('emboss', "item_deleted: {$name}");
 }
Пример #7
0
 static function logout()
 {
     $user = identity::active_user();
     if (!$user->guest) {
         try {
             Session::instance()->destroy();
         } catch (Exception $e) {
             Kohana_Log::add("error", $e);
         }
         module::event("user_logout", $user);
     }
     log::info("user", t("User %name logged out", array("name" => $user->name)), t('<a href="%url">%user_name</a>', array("url" => user_profile::url($user->id), "user_name" => html::clean($user->name))));
 }
Пример #8
0
 static function logout()
 {
     $user = identity::active_user();
     if (!$user->guest) {
         try {
             Session::instance()->destroy();
         } catch (Exception $e) {
             Kohana::log("error", $e);
         }
         module::event("user_logout", $user);
     }
     log::info("user", t("User %name logged out", array("name" => $user->name)), html::anchor("user/{$user->id}", html::clean($user->name)));
 }
Пример #9
0
 public function login()
 {
     $data = Input::all();
     Log::info($data);
     $informacion = array('datos' => 'No se han introducido los datos', 'entro' => false);
     log::info("IniciarSesion");
     if (isset($data['usuario']) && isset($data['password'])) {
         $entro = IniciarSesion::entrar($data['usuario'], md5($data['password']));
         $informacion = array('datos' => 'Usuario y/o contraseña inválidos', 'entro' => false);
         if (!empty($entro)) {
             $informacion = array('datos' => $entro, 'entro' => true);
         }
     }
     return $informacion;
 }
Пример #10
0
 public function index()
 {
     access::verify_csrf();
     $user = user::active();
     user::logout();
     log::info("user", t("User %name logged out", array("name" => p::clean($user->name))), html::anchor("user/{$user->id}", p::clean($user->name)));
     if ($this->input->get("continue")) {
         $item = url::get_item_from_uri($this->input->get("continue"));
         if (access::can("view", $item)) {
             url::redirect($this->input->get("continue"));
         } else {
             url::redirect("");
         }
     }
 }
Пример #11
0
 public static function buildHtml($tag, Num &$depth)
 {
     try {
         $tabs = "";
         //implode("", array_fill(0, $depth->_inc()->getNum(), "  "));
         $html = "";
         if ($tag instanceof Tag) {
             $beginTag = "{$tabs}<" . $tag->getTagName();
             $tagContent = "";
             $endTag = "{$tabs}</" . $tag->getTagName() . ">";
             $id = "";
             $class = "";
             $attributes = "";
             if (!Utils::isNullOrEmptyString($tag->getId())) {
                 $id = TagLabels::ID . "='" . $tag->getId() . "'";
             }
             if (count($tag->getClassList()) > 0) {
                 $class = TagLabels::_CLASS . "='";
                 for ($index = 0, $max = count($tag->getClassList()); $index < $max; $index++) {
                     $class .= $tag->getClassList()[$index] . " ";
                 }
                 $class .= "'";
             }
             if (count($tag->getAttributeList()) > 0) {
                 foreach ($tag->getAttributeList() as $key => $value) {
                     $attributes .= " {$key}=\"{$value}\" ";
                 }
             }
             $beginTag .= " " . $id . " " . $class . " " . $attributes . " >";
             if (!$tag instanceof SingleTag) {
                 for ($index = 0, $max = count($tag->getChildList()); $index < $max; $index++) {
                     $tagContent .= TagUtils::buildHtml($tag->getChildList()[$index], $depth);
                     $depth->_dec();
                 }
                 $html = $beginTag . $tagContent . $endTag;
             } else {
                 $html = $beginTag;
             }
         } else {
             if (is_string($tag) || is_numeric($tag)) {
                 return $tag;
             }
         }
     } catch (Exception $e) {
         log::info("Caught exception: ',  {$e->getMessage}()");
     }
     return $html;
 }
Пример #12
0
 public function index()
 {
     //access::verify_csrf();
     $user = user::active();
     user::logout();
     log::info("user", t("User %name logged out", array("name" => p::clean($user->name))), html::anchor("user/{$user->id}", p::clean($user->name)));
     if ($continue_url = $this->input->get("continue")) {
         $item = url::get_item_from_uri($continue_url);
         if (access::can("view", $item)) {
             // Don't use url::redirect() because it'll call url::site() and munge the continue url.
             header("Location: {$continue_url}");
         } else {
             url::redirect("albums/1");
         }
     }
 }
Пример #13
0
 public static function actualizaFechaIp()
 {
     $nro_persona = Auth::user()->nro_persona;
     //$ip = Request::getClientIp();
     if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
         $ip = $_SERVER['HTTP_CLIENT_IP'];
     } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
     } else {
         $ip = $_SERVER['REMOTE_ADDR'];
     }
     log::info("Conexion desde: '{$ip}'");
     $dt = new DateTime('NOW');
     $fecha = $dt->format('Y-m-d H:i:s');
     $resultado = DB::update("\n                 UPDATE hb_usuario\n                    SET ultima_ip = '{$ip}', ultimo_acceso =  convert(datetime ,'{$fecha}',120)\n                  WHERE nro_persona = {$nro_persona}\n                  ");
 }
Пример #14
0
 private function _try_login()
 {
     $form = $this->_login_form();
     $valid = $form->validate();
     if ($valid) {
         $user = ORM::factory("user")->where("name", $form->login->inputs["name"]->value)->find();
         if (!$user->loaded || !user::is_correct_password($user, $form->login->password->value)) {
             log::warning("user", t("Failed login for %name", array("name" => $form->login->inputs["name"]->value)));
             $form->login->inputs["name"]->add_error("invalid_login", 1);
             $valid = false;
         }
     }
     if ($valid) {
         user::login($user);
         log::info("user", t("User %name logged in", array("name" => $user->name)));
         print json_encode(array("result" => "success"));
     } else {
         print json_encode(array("result" => "error", "form" => $form->__toString()));
     }
 }
Пример #15
0
 private function _auth($url)
 {
     $form = user::get_login_form($url);
     $valid = $form->validate();
     if ($valid) {
         $user = ORM::factory("user")->where("name", $form->login->inputs["name"]->value)->find();
         if (!$user->loaded || !user::is_correct_password($user, $form->login->password->value)) {
             log::warning("user", t("Failed login for %name", array("name" => $form->login->inputs["name"]->value)));
             $form->login->inputs["name"]->add_error("invalid_login", 1);
             $valid = false;
         }
     }
     if ($valid) {
         user::login($user);
         log::info("user", t("User %name logged in", array("name" => $user->name)));
     }
     // Either way, regenerate the session id to avoid session trapping
     Session::instance()->regenerate();
     return array($valid, $form);
 }
Пример #16
0
$game_config = 'MillionFlaxScratchCard';
$game_app = 'ScratchCards';

$frameworkVersion = '2.0';
$protocolType = 'json';

if(array_key_exists('mockinvoke', $_GET)){


    include_once("../../WebkitCore/lib/class.log.php");

    $log = new log();
    $log->identifier = "touchCasino";
    $log->logger = PGC_LOG_FILE | PGC_LOG_SYSLOG;

    $log->info("main.php request");
    $log->info("GET:".var_export($_GET, true));
    $log->info("POST:".var_export($_POST, true));
    $reqParams = array_merge($_GET, $_POST);
    //$reqParams["unfinishedGame"] = 1;

    header("Access-Control-Allow-Methods: POST, GET");
    header("Access-Control-Allow-Credentials: true");
    header("Access-Control-Max-Age: 1728000");
    header("Expires: Sat, 1 Jan 2005 00:00:00 GMT");
    header("Last-Modified: ".gmdate( "D, d M Y H:i:s")."GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Cache-Control: no-cache, must-revalidate");
    header("Content-Type: application/json");
    header("iOS7-Content-Type-Hack: application/json");
    header("Pragma: no-cache");
Пример #17
0
 /**
  * Handle Post Ping from Atlas Server
  *
  */
 public function pingAtlas()
 {
     $this->createTable();
     $user = Session::get(user);
     $date = new \DateTime();
     Log::debug("DATA received: " . Request::getContent());
     $json = json_decode(Request::getContent(), true);
     $id['id'] = $json['uuid'] != '' ? $json['uuid'] : Uuid::uuid4()->toString();
     $param = array('id' => $id['id'], 'latitude' => floatval($json['latitude']), 'longitude' => floatval($json['longitude']), 'name' => $json['name'], 'url' => $json['url'], 'patients' => intval($json['patients']), 'encounters' => intval($json['encounters']), 'observations' => intval($json['observations']), 'type' => $json['type'], 'image' => $json['image'], 'contact' => $json['contact'], 'email' => $json['email'], 'notes' => $json['notes'], 'date_created' => $date, 'openmrs_version' => $json['version'], 'show_counts' => intval($json['show_counts']), 'created_by' => $user->principal, 'distribution' => intval($json['distribution']));
     $param['patients'] = is_int($param['patients']) ? $param['patients'] : '';
     $param['encounters'] = is_int($param['encounters']) ? $param['encounters'] : '';
     $param['observations'] = is_int($param['observations']) ? $param['observations'] : '';
     $privileges = DB::table('auth')->where('token', '=', $user->uid)->where('atlas_id', '=', $param['id'])->where('privileges', '=', 'ALL')->first();
     if ($user->role == 'ADMIN' && $privileges == NULL) {
         $privileges = new Privileges(array('token' => $user->uid, 'principal' => 'admin:' . $user->uid, 'privileges' => 'ADMIN'));
     }
     Log::debug("Privileges: " . $privileges->principal . "/" . $privileges->privileges);
     $site = DB::table('atlas')->where('id', '=', $param['id'])->first();
     if ($site != null) {
         DB::table('archive')->insert(array('site_uuid' => $site->id, 'id' => Uuid::uuid4()->toString(), 'archive_date' => $date, 'type' => $site->type, 'longitude' => $site->longitude, 'latitude' => $site->latitude, 'name' => $site->name, 'url' => $site->url, 'image' => $site->image, 'contact' => $site->contact, 'changed_by' => $privileges->principal, 'patients' => $site->patients, 'encounters' => $site->encounters, 'observations' => $site->observations, 'notes' => $site->notes, 'action' => 'UPDATE', 'email' => $site->email, 'show_counts' => $site->show_counts, 'data' => $site->data, 'openmrs_version' => $site->openmrs_version, 'atlas_version' => $site->atlas_version, 'date_created' => $site->date_created, 'show_counts' => $site->show_counts, 'created_by' => $site->created_by, 'distribution' => $site->distribution));
         unset($param['created_by']);
         unset($param['date_created']);
         DB::table('atlas')->where('id', '=', $site->id)->update($param);
         Log::debug("Updated " . $param['id'] . " from " . $_SERVER['REMOTE_ADDR']);
     } else {
         // new implementation
         DB::table('atlas')->insert($param);
         //insert into archive
         $param['action'] = "ADD";
         $param['site_uuid'] = Uuid::uuid4()->toString();
         $param['archive_date'] = $date;
         DB::table('archive')->insert($param);
         Log::debug("Created " . $param['id'] . " from " . $_SERVER['REMOTE_ADDR']);
         $principal = 'openmrs_id:' . $user->uid;
         $auth = DB::table('auth')->where('atlas_id', '=', $param['id'])->where('principal', '=', $principal)->first();
         if ($auth == NULL) {
             DB::table('auth')->insert(array('atlas_id' => $param['id'], 'principal' => $principal, 'token' => $user->uid, 'privileges' => 'ALL'));
             Log::debug("Created auth");
         }
         if (Session::has('module')) {
             // Add module authoritation if marker created in module
             $module = Session::get('module');
             Log::info('Module create a marker');
             Log::info('Module UUID: ' . $module);
             $privileges = DB::table('auth')->where('token', '=', $module)->count();
             if ($privileges > 0) {
                 log::info('This module is allready linked to a site');
             } else {
                 DB::table('auth')->insert(array('atlas_id' => $param['id'], 'principal' => 'module:' . $module, 'token' => $module, 'privileges' => 'STATS'));
                 Log::debug("Created auth for module");
             }
         }
     }
     return $param['id'];
 }
Пример #18
0
function log_info($str)
{
    log::info($str);
}
 public function addUser($usuario)
 {
     log::info("creacion usuario");
     $data['usuario'] = $usuario;
     $nombre = isset($data['usuario']['nombre']) ? $data['usuario']['nombre'] : '';
     $ap = isset($data['usuario']['apellido_paterno']) ? $data['usuario']['apellido_paterno'] : '';
     $am = isset($data['usuario']['apellido_materno']) ? $data['usuario']['apellido_materno'] : '';
     $id_tipo_donador = isset($data['usuario']['id_tipo_donador']) ? $data['usuario']['id_tipo_donador'] : '';
     $donacion = isset($data['usuario']['donacion_info']) ? $data['usuario']['donacion_info'] : '';
     $username = isset($data['usuario']['username']) ? $data['usuario']['username'] : '';
     $password = isset($data['usuario']['password']) ? $data['usuario']['password'] : '';
     //die();
     if (!$data['usuario']) {
         return false;
     }
     $usuario = User::select('username')->where('username', '=', $data['usuario']['username'])->first();
     if (count($usuario) > 0) {
         log::info("dada");
         return Response::json(array('error' => "500", 'error_message' => "Ya existe un usuario con esta cuenta"));
     } else {
         try {
             $usuarioInfo = new UserInfo();
             $usuarioInfo->nombre = trim($nombre);
             $usuarioInfo->apellido_paterno = trim($ap);
             $usuarioInfo->apellido_materno = trim($am);
             $usuarioInfo->id_tipo_donador = trim($id_tipo_donador);
             $usuarioInfo->donacion_info = trim($donacion);
             $usuarioInfo->save();
             log::info("inseted");
             log::info($usuarioInfo);
             if ($data['usuario']['contacto']) {
                 $usuario = UserInfo::find($usuarioInfo->id_usuario_info);
                 $arrContactos = array();
                 log::info("find");
                 log::info($usuario);
                 log::info("contacto");
                 log::info($usuario->contactos);
                 $usuario->contactos()->detach();
                 if ($data['usuario']['contacto'] && is_array($data['usuario']['contacto'])) {
                     foreach ($data['usuario']['contacto'] as $value) {
                         $arrContactos[] = array('id_tipo_contacto' => $value['tipo'], 'dato' => $value['valor']);
                     }
                 }
                 $usuario->contactos()->attach($arrContactos);
             }
             $login = new User();
             $login->username = trim($username);
             $login->password = md5(trim($password));
             $login->id_usuario_info = $usuarioInfo->id_usuario_info;
             $login->save();
             return Response::json(array('error' => "200", 'error_message' => 'Se han guardado los datos'));
         } catch (Exception $ex) {
             return Response::json(array('error' => "500", 'error_message' => $ex->getMessage()));
         }
     }
 }
Пример #20
0
 /**
  * 根据配置提取HTML代码块中的字段
  * 
  * @param mixed $confs
  * @param mixed $html
  * @param mixed $page
  * @return void
  * @author seatle <*****@*****.**> 
  * @created time :2016-09-23 17:13
  */
 public function get_fields($confs, $html, $url, $page)
 {
     $fields = array();
     foreach ($confs as $conf) {
         // 当前field抽取到的内容是否是有多项
         $repeated = isset($conf['repeated']) && $conf['repeated'] ? true : false;
         // 当前field抽取到的内容是否必须有值
         $required = isset($conf['required']) && $conf['required'] ? true : false;
         if (empty($conf['name'])) {
             log::error("The field name is null, please check your \"fields\" and add the name of the field\n");
             exit;
         }
         $values = array();
         // 如果定义抽取规则
         if (!empty($conf['selector'])) {
             // 如果这个field是上一个field的附带连接
             if (isset($conf['source_type']) && $conf['source_type'] == 'attached_url') {
                 // 取出上个field的内容作为连接,内容分页是不进队列直接下载网页的
                 if (!empty($fields[$conf['attached_url']])) {
                     $collect_url = $this->get_complete_url($url, $fields[$conf['attached_url']]);
                     log::info(date("H:i:s") . " Find attached content page: {$url}");
                     $html = $this->request_url($collect_url);
                     // 在一个attached_url对应的网页下载完成之后调用. 主要用来对下载的网页进行处理.
                     if ($this->on_attached_download_page) {
                         $return = call_user_func($this->on_attached_download_page, $html, $this);
                         if (isset($return)) {
                             $html = $return;
                         }
                     }
                     // 请求获取完分页数据后把连接删除了
                     unset($fields[$conf['attached_url']]);
                 }
             }
             // 没有设置抽取规则的类型 或者 设置为 xpath
             if (!isset($conf['selector_type']) || $conf['selector_type'] == 'xpath') {
                 // 返回值一定是多项的
                 $values = $this->get_fields_xpath($html, $conf['selector'], $conf['name']);
             } elseif ($conf['selector_type'] == 'regex') {
                 $values = $this->get_fields_regex($html, $conf['selector'], $conf['name']);
             }
             // field不为空而且存在子配置
             if (!empty($values) && !empty($conf['children'])) {
                 $child_values = array();
                 // 父项抽取到的html作为子项的提取内容
                 foreach ($values as $html) {
                     // 递归调用本方法,所以多少子项目都支持
                     $child_value = $this->get_fields($conf['children'], $url, $html, $page);
                     if (!empty($child_value)) {
                         $child_values[] = $child_value;
                     }
                 }
                 // 有子项就存子项的数组,没有就存HTML代码块
                 if (!empty($child_values)) {
                     $values = $child_values;
                 }
             }
         }
         if (empty($values)) {
             // 如果值为空而且值设置为必须项,跳出foreach循环
             if ($required) {
                 break;
             }
             // 避免内容分页时attached_url拼接时候string + array了
             $fields[$conf['name']] = '';
             //$fields[$conf['name']] = array();
         } else {
             // 不重复抽取则只取第一个元素
             $fields[$conf['name']] = $repeated ? $values : $values[0];
         }
     }
     if (!empty($fields)) {
         foreach ($fields as $fieldname => $data) {
             $pattern = "/<img.*?src=[\\'|\"](.*?(?:[\\.gif|\\.jpg|\\.jpeg|\\.png]))[\\'|\"].*?[\\/]?>/i";
             // 在抽取到field内容之后调用, 对其中包含的img标签进行回调处理
             if ($this->on_handle_img && preg_match($pattern, $data)) {
                 $return = call_user_func($this->on_handle_img, $fieldname, $data);
                 if (!isset($return)) {
                     log::warn("on_handle_img function return value can't be empty\n");
                 } else {
                     // 有数据才会执行 on_handle_img 方法,所以这里不要被替换没了
                     $data = $return;
                 }
             }
             // 当一个field的内容被抽取到后进行的回调, 在此回调中可以对网页中抽取的内容作进一步处理
             if ($this->on_extract_field) {
                 $return = call_user_func($this->on_extract_field, $fieldname, $data, $page, self::$taskid);
                 if (!isset($return)) {
                     log::warn("on_extract_field function return value can't be empty\n");
                 } else {
                     // 有数据才会执行 on_extract_field 方法,所以这里不要被替换没了
                     $fields[$fieldname] = $return;
                 }
             }
         }
     }
     return $fields;
 }
 public function DataSave()
 {
     $dataToSave = Input::get('dataToSave');
     log::info($dataToSave);
     $teamID = $dataToSave[0];
     $teamTableData = pizzaDeliveryTable::where('team_id', $teamID)->orderBy('run_count', 'DESC')->first();
     if (count($teamTableData) < 1) {
         $runCountData = 1;
     } else {
         $runCountData = $teamTableData->run_count;
         $runCountData = $runCountData + 1;
     }
     try {
         if (count($dataToSave) == 20) {
             $homeCount = $dataToSave[19];
             if (count($dataToSave[5]) == $homeCount && count($dataToSave[6]) == $homeCount) {
                 for ($i = 0; $i < $homeCount; $i++) {
                     $pizzaDeliveryTable = new pizzaDeliveryTable();
                     $pizzaDeliveryTable->team_id = $dataToSave[0];
                     $pizzaDeliveryTable->run_count = $runCountData;
                     $pizzaDeliveryTable->home_no = $dataToSave[4][$i];
                     $pizzaDeliveryTable->pizza_type = $dataToSave[5][$i];
                     $pizzaDeliveryTable->order_type = $dataToSave[6][$i];
                     $pizzaDeliveryTable->order_time = $dataToSave[7][$i];
                     $pizzaDeliveryTable->pizza_delivery_time = $dataToSave[8][$i];
                     $pizzaDeliveryTable->cd = $dataToSave[9][$i];
                     $pizzaDeliveryTable->cpd = $dataToSave[10][$i];
                     $pizzaDeliveryTable->cpcd = $dataToSave[11][$i];
                     $pizzaDeliveryTable->ipd = $dataToSave[12][$i];
                     $pizzaDeliveryTable->tip = $dataToSave[13][$i];
                     $pizzaDeliveryTable->save();
                     if (!$pizzaDeliveryTable->save()) {
                         Log::info('not saved' . $i);
                         throw new Exception("Not Saved");
                     }
                 }
                 $pizzaDeliveryResult = new pizzaDeliveryResult();
                 $pizzaDeliveryResult->team_id = $dataToSave[0];
                 $pizzaDeliveryResult->run_count = $runCountData;
                 $pizzaDeliveryResult->total_time = $dataToSave[1];
                 $pizzaDeliveryResult->score = $dataToSave[2];
                 $pizzaDeliveryResult->count_penalty = $dataToSave[3];
                 $pizzaDeliveryResult->count_cd = $dataToSave[14];
                 $pizzaDeliveryResult->count_cpd = $dataToSave[15];
                 $pizzaDeliveryResult->count_cpcd = $dataToSave[16];
                 $pizzaDeliveryResult->count_ipd = $dataToSave[17];
                 $pizzaDeliveryResult->count_tip = $dataToSave[18];
                 $pizzaDeliveryResult->save();
                 if (!$pizzaDeliveryResult->save()) {
                     Log::info('not saved');
                     throw new Exception("Not Saved");
                 }
                 return json_encode('success');
             } else {
                 throw new Exception("Inputs are not correct");
             }
         } else {
             Log::info(count($dataToSave));
             throw new Exception("Inputs are not correct");
         }
     } catch (Exception $e) {
         //DB::roleback();
         Log::info('error came');
         return json_encode(['error' => 'Not Saved!']);
     }
 }
 /**
  * Uses Laravel Validator in order to check if the attributes of the
  * $user object are valid for the given $ruleset.
  *
  * @param ConfideUserInterface $user
  * @param string               $ruleset The name of the key in the UserValidator->$rules array
  *
  * @return boolean True if the attributes are valid.
  */
 public function validateAttributes(ConfideUserInterface $user, $ruleset = 'create')
 {
     $attributes = $user->toArray();
     log::info($attributes);
     // Force getting password since it may be hidden from array form
     $attributes['password'] = $user->getAuthPassword();
     $rules = $this->rules[$ruleset];
     $validator = App::make('validator')->make($attributes, $rules);
     log::info($validator->errors());
     // Validate and attach errors
     if ($validator->fails()) {
         $user->errors = $validator->errors();
         return false;
     } else {
         return true;
     }
 }
 static function deactivate()
 {
     log::info('emboss', 'Emboss Deactivated');
 }
Пример #24
0
 static function fetch_updates()
 {
     $request->locales = array();
     $request->messages = new stdClass();
     $locales = locale::installed();
     foreach ($locales as $locale => $locale_data) {
         $request->locales[] = $locale;
     }
     // @todo Batch requests (max request size)
     foreach (Database::instance()->select("key", "locale", "revision", "translation")->from("incoming_translations")->get()->as_array() as $row) {
         if (!isset($request->messages->{$row->key})) {
             $request->messages->{$row->key} = 1;
         }
         if (!empty($row->revision) && !empty($row->translation)) {
             if (!is_object($request->messages->{$row->key})) {
                 $request->messages->{$row->key} = new stdClass();
             }
             $request->messages->{$row->key}->{$row->locale} = $row->revision;
         }
     }
     // @todo Include messages from outgoing_translations?
     $request_data = json_encode($request);
     $url = self::_server_url() . "?q=translations/fetch";
     list($response_data, $response_status) = remote::post($url, array("data" => $request_data));
     if (!remote::success($response_status)) {
         throw new Exception("@todo TRANSLATIONS_FETCH_REQUEST_FAILED " . $response_status);
     }
     if (empty($response_data)) {
         log::info("translations", "Translations fetch request resulted in an empty response");
         return;
     }
     $response = json_decode($response_data);
     // Response format (JSON payload):
     //   [{key:<key_1>, translation: <JSON encoded translation>, rev:<rev>, locale:<locale>},
     //    {key:<key_2>, ...}
     //   ]
     $count = count($response);
     log::info("translations", "Installed {$count} new / updated translation messages");
     foreach ($response as $message_data) {
         // @todo Better input validation
         if (empty($message_data->key) || empty($message_data->translation) || empty($message_data->locale) || empty($message_data->rev)) {
             throw new Exception("@todo TRANSLATIONS_FETCH_REQUEST_FAILED: Invalid response data");
         }
         $key = $message_data->key;
         $locale = $message_data->locale;
         $revision = $message_data->rev;
         $translation = serialize(json_decode($message_data->translation));
         // @todo Should we normalize the incoming_translations table into messages(id, key, message)
         // and incoming_translations(id, translation, locale, revision)? Or just allow
         // incoming_translations.message to be NULL?
         $locale = $message_data->locale;
         $entry = ORM::factory("incoming_translation")->where(array("key" => $key, "locale" => $locale))->find();
         if (!$entry->loaded) {
             // @todo Load a message key -> message (text) dict into memory outside of this loop
             $root_entry = ORM::factory("incoming_translation")->where(array("key" => $key, "locale" => "root"))->find();
             $entry->key = $key;
             $entry->message = $root_entry->message;
             $entry->locale = $locale;
         }
         $entry->revision = $revision;
         $entry->translation = $translation;
         $entry->save();
     }
 }
Пример #25
0
 /**
  *  @SWG\Operation(
  *      partial="usuarios.update",
  *      summary="Actualiza un usuario",
  *      type="User",
  *     @SWG\Parameter(
  *       name="body",
  *       description="Objeto Usuario que se necesita para guardar",
  *       required=true,
  *       type="User",
  *       paramType="body",
  *       allowMultiple=false
  *     ),
  *     @SWG\Parameter(
  *       name="id",
  *       description="Identificador del usuario",
  *       required=true,
  *       type="integer",
  *       paramType="path",
  *       allowMultiple=false
  *     ),
  *     @SWG\ResponseMessage(code=400, message="Id invalido"),
  *     @SWG\ResponseMessage(code=404, message="Usuario no encontrado"),
  *     @SWG\ResponseMessage(code=405, message="Excepción de validación")
  *  )
  */
 public function update($id)
 {
     Log::info("vengo de edicion usuarios");
     $data = Input::only('email', 'first_name', 'last_name', 'password', 'id_empleado', 'activado', 'permissions', 'grupos', 'clientes', 'activated', 'deleted_at');
     Log::info($data);
     $user = Sentry::findUserById($id);
     // Update the user details
     if (!empty($data['activado']) && $data['activado'] || !empty($data['activated']) && $data['activated']) {
         Log::info("entra al 1 if");
         $user->activated = $data['activado'];
         $user->password = $data['password'];
         //$user->email = $data['email'];
         $apellidos = explode(' ', $user->last_name);
         $total = count($apellidos);
         Log::info($total);
         $empleado['nombre'] = $user->first_name;
         $empleado['apellido_paterno'] = $apellidos[0];
         if ($total > 1) {
             $empleado['apellido_materno'] = $apellidos[1];
         } else {
             $empleado['apellido_materno'] = '';
         }
         if (!$data['id_empleado']) {
             $empleado = Empleado::create($empleado);
         } else {
             $empleado = Empleado::find($data['id_empleado']);
         }
         //$usuario=Usuario::find($user->id);
         $usuario = Usuario::withTrashed()->where('id', $user->id)->first();
         $userId = DB::Table('users')->select('password')->where('id', $user->id)->first();
         log::info("pass");
         log::info($userId->password);
         if (!empty($data['activated']) && $data['activated']) {
             $user->password = $userId->password;
         }
         $user->deleted_at = NULL;
         $user->id_empleado = $empleado->id_empleado;
         $usuario->empleado()->detach();
         $usuario->empleado()->attach(array($empleado->id_empleado));
     } else {
         if ($data['email']) {
             Log::info("entra al 2 if");
             Log::info($data);
             $user->first_name = $data['first_name'];
             $user->last_name = $data['last_name'];
             $user->email = $data['email'];
             $user->permissions = $data['permissions'];
             if (isset($data['grupos'][0])) {
                 $data['grupos'] = $data['grupos'][0]['id'];
             } else {
                 $data['grupos'] = $data['grupos']['id'];
             }
             Log::info($data['grupos']);
             if (!$data['clientes']) {
                 $data['clientes'] = array(1, 2);
             }
             $usuario = Usuario::withTrashed()->where('id', $user->id)->first();
             //$usuario=Usuario::find($user->id);
             $usuario->grupos()->detach();
             $usuario->grupos()->attach($data['grupos']);
         } else {
             if (!empty($data['activated']) && !empty($data['deleted_at'])) {
                 Log::info("Entra a activar usuario");
                 $user->activated = $data['activated'];
                 $user->deleted_at = $data['deleted_at'];
             }
         }
     }
     $user->save();
     return $user;
 }
Пример #26
0
 public function uninstall()
 {
     $items = ORM::factory('item')->find_all();
     foreach ($items as $item) {
         $path = $item->file_path() . $name;
         $orig = str_replace(VARPATH . 'albums/', VARPATH . 'originals/', $path);
         if (file_exists($orig)) {
             @unlink($path);
             @rename($orig, $path);
         }
     }
     graphics::mark_dirty(1, 1);
     Database::instance()->query('DROP TABLE {emboss_overlays}');
     Database::instance()->query('DROP TABLE {emboss_mappings}');
     Database::instancs()->query("delete from {modules} where name='emboss'");
     log::info('emboss', 'module uninstalled (database dropped/overlays removed)');
 }
Пример #27
0
 public function deallocate(Request $request, $sid)
 {
     $desde = $request->input('desde');
     $hasta = $request->input('hasta');
     if ($desde < 0) {
         $desde = 1;
     }
     $nLlamadasTot = DB::table('tokens_' . $sid)->count();
     if ($hasta > $nLlamadasTot) {
         $hasta = $nLlamadasTot;
     }
     if ($desde > $hasta) {
         return Redirect::to('survey/' . $sid . '/dispatch')->with('status', 'El limite inferior no puede ser mayor que el limite superior.');
     }
     log::info('[' . $sid . '] Eliminamos la asigancion desde el token ' . $desde . ' hasta el ' . $hasta);
     $this->liberarLlamadas($sid, $desde, $hasta);
     return Redirect::to('survey/' . $sid)->with('status', 'Eliminada la asignación de llamadas pendientes.');
 }
Пример #28
0
 static function do_embossing($id, $image_id, $overlay_id)
 {
     $gravity = module::get_var('emboss', 'gravity');
     $transparency = module::get_var('emboss', 'transparency');
     $item = ORM::factory('item')->where('id', '=', $image_id)->find();
     $path = $item->file_path() . $name;
     $orig = str_replace(VARPATH . 'albums/', VARPATH . 'originals/', $path);
     @unlink($path);
     if ($overlay_id < 0) {
         log::info('emboss', 'Remove embossing from ' . $item->name);
         @copy($orig, $path);
     } else {
         $overlay = ORM::factory('emboss_overlay')->where('id', '=', $overlay_id)->find();
         $overlay_path = VARPATH . 'modules/emboss/' . $overlay->name;
         $opts['file'] = $overlay_path;
         $opts['position'] = $gravity;
         $opts['transparency'] = 100 - $transparency;
         log::info('emboss', 'Embossing ' . $item->name . ' with ' . $overlay->name);
         gallery_graphics::composite($orig, $path, $opts);
     }
     $item->thumb_dirty = 1;
     $item->resize_dirty = 1;
     $item->save();
     graphics::generate($item);
     db::build()->update('emboss_mappings')->where('id', '=', $id)->set('cur_overlay_id', $overlay_id)->set('cur_gravity', $gravity)->set('cur_transparency', $transparency)->execute();
 }
Пример #29
0
 public function authorSave()
 {
     /* $content = Request::json();
     
               return Response::json(
               array(
               'result' => '$credentials ok',
               'msg' => 'Data:'.Request::header('Content-Type')."  isJson: ".Request::isJson().  serialize($content)
               ),
               200
               ); */
     $data = Input::json();
     $credentials = array('username' => $data->get('username'), 'password' => $data->get('password'));
     if (Auth::attempt($credentials)) {
         $authorJson = $data->get('author');
         $authorWorksJson = $data->get('authorWorks');
         //$authorObj = json_decode($authorJson);
         //$authorWorksArray = json_decode($authorWorksJson);
         log::info("JSON recevied data AUTHOR: " . json_encode($authorJson));
         log::info("JSON recevied data WORKS: " . json_encode($authorWorksJson));
         $authorsSaved = 0;
         $worksSaved = 0;
         $citationsSaved = 0;
         $CitingWorkText = "";
         $msgCurrentEntry = "";
         try {
             DB::beginTransaction();
             $author = new Author();
             $author->name = $authorJson["name"];
             $author->url = $authorJson["url"];
             $author->affiliation = $authorJson["affiliation"];
             $author->save();
             log::info("Saved author: " . $author->id);
             $authorsSaved++;
             foreach ($authorWorksJson as $authorWorkObj) {
                 $authorWork = new AuthorWork();
                 $authorWork->title = $authorWorkObj["title"];
                 $authorWork->authors = $authorWorkObj["authors"];
                 $authorWork->publisher = $authorWorkObj["publisher"];
                 $authorWork->publisher_in_google = $authorWorkObj["publisherInGoogle"];
                 $authorWork->citations_url = $authorWorkObj["citationsUrl"];
                 $authorWork->rank_publisher = $authorWorkObj["rankPublisher"];
                 $authorWork->citations = $authorWorkObj["citations"];
                 $authorWork->quality_citations = $authorWorkObj["qualityCitations"];
                 $authorWork->year = $authorWorkObj["year"];
                 $authorWork->author_id = $author->id;
                 $msgCurrentEntry = "Authorwork: " . $authorWorkObj["title"];
                 $authorWork->save();
                 log::info("Saved author work: " . $authorWork->id);
                 $worksSaved++;
                 $citingWorkObjsArray = $authorWorkObj["citingWorks"];
                 foreach ($citingWorkObjsArray as $citingWorkObj) {
                     $CitingWorkText = $CitingWorkText . $citingWorkObj["name"];
                     $citingWork = new CitingWork();
                     $citingWork->name = $citingWorkObj["name"];
                     $citingWork->publisher = $citingWorkObj["publisher"];
                     $citingWork->publisher_in_google = $citingWorkObj["publisherInGoogle"];
                     $citingWork->publisher_in_external_web = $citingWorkObj["publisherInExternalWeb"];
                     $citingWork->rank_publisher = $citingWorkObj["rankPublisher"];
                     $citingWork->authors = $citingWorkObj["authors"];
                     $citingWork->year = $citingWorkObj["year"];
                     if (array_key_exists("url", $citingWork)) {
                         $citingWork->url = $citingWorkObj["url"];
                     }
                     $citingWork->author_work_id = $authorWork->id;
                     $msgCurrentEntry = "Citingwork: " . $citingWorkObj["name"];
                     $citingWork->save();
                     log::info("Saved citing work: " . $citingWork->id);
                     $citationsSaved++;
                     unset($citingWork);
                 }
                 unset($authorWork);
             }
             DB::commit();
             AuthorToProcess::whereRaw("url=" . $author->url)->delete();
         } catch (Exception $ex) {
             // DB::rollBack(); Performed automatically if there is an exception
             return Response::json(array('result' => 'Exception: |||||||| ' . $msgCurrentEntry . ' |||||||| ', 'msg' => $ex->getMessage()), 200);
         }
         /* DEBUG
             // TODO Add exceptions ErrorException Undefined offset / Undefined index
             return Response::json(
             array(
             'result' => '$credentials ok',
             'msg' => 'Data saved: Authors('.$authorsSaved.'), works('.$worksSaved.'), citations('.$citationsSaved.')        '.$CitingWorkText
             ),
             200
             );
            */
         // TODO
         // Convert to model (Author, AuthorWork, CitingWork)
         // Save
         return Response::json(array('result' => 'ok', 'msg' => 'Data saved successfully.'), 200);
     } else {
         return Response::json(array('result' => 'error', 'msg' => 'Invalid credentials.' . '   DATA: ' . implode(Input::all())), 200);
     }
 }