Example #1
0
 function ensureAdmin($f3)
 {
     $adminSecret = $this->getAdminSecret($f3);
     if ($f3->exists('COOKIE.admin_secret') && $f3->get('COOKIE.admin_secret') === $adminSecret) {
         $f3->set('isAdmin', true);
         return true;
     } else {
         $user = "";
         if (isset($_SERVER['PHP_AUTH_USER'])) {
             $user = $_SERVER['PHP_AUTH_USER'];
         }
         $password = "";
         if (isset($_SERVER['PHP_AUTH_PW'])) {
             $password = $_SERVER['PHP_AUTH_PW'];
         }
         $source = "unknown";
         if (isset($_SERVER['REMOTE_ADDR'])) {
             $source = $_SERVER['REMOTE_ADDR'];
         }
         Logger::Info($f3, "HandlerBase.ensureAdmin", "Login attempt with user '{$user}', pass '{$password}' from '{$source}'");
         if ($user == 'admin' && $password == $f3->get('settings.adminPassword')) {
             $f3->set('COOKIE.admin_secret', $adminSecret);
             $f3->set('isAdmin', true);
             return true;
         } else {
             Logger::Warn($f3, "HandlerBase.ensureAdmin", "Root access denied to IP {$_SERVER['REMOTE_ADDR']}");
             header('WWW-Authenticate: Basic realm="Elternsprechtag St. Rupert"');
             header('HTTP/1.0 401 Unauthorized');
             echo "You must enter a valid login ID and password to access this resource\n";
             $f3->set('isAdmin', false);
             return false;
         }
     }
 }
Example #2
0
 /**
  * Execute a delete query
  *
  * @param string $queryid
  * @param string $table
  * @param string $where_condition
  * @param array $bind_vars
  * @return int
  */
 function &QueryDelete($queryid, $table, $where_condition, $bind_vars = array())
 {
     // If we passed an array for the where clause, we need to synthesize a string and populate the appropriate bind_vars
     if (is_array($where_condition)) {
         $new_wheres = array();
         foreach ($where_condition as $k => $v) {
             $bind_vars[':where' . $k] = $v;
             $new_wheres[] = $k . "=:where" . $k;
         }
         $where_condition = implode(" AND ", $new_wheres);
     }
     $servers = $this->HashToServer($queryid);
     //print_pre($servers);
     foreach ($servers as $server) {
         $servernum = $server[0];
         // If we're not connected and we're in lazy mode, open the connection.  Bail out if lazy connect fails.
         if (!$this->LazyOpen($servernum)) {
             Logger::Info("Database connection '{$this->name}:{$servernum}' marked as failed, skipping DELETE query");
         } else {
             Profiler::StartTimer("DBWrapper:QueryDelete()");
             // Double check that conn exists before using it (FIXME - could be smarter here)
             $rows_affected = null;
             if ($this->conn[$servernum]) {
                 $realtable = $table . ($server[1] !== NULL ? "_" . $server[1] : "");
                 /*
                 print_pre($realtable);
                 print_pre($where_condition);
                 print_pre($bind_vars);
                 */
                 //Logger::Error("Execute querydelete: $realtable $where_condition");
                 //Logger::Error($bind_vars);
                 try {
                     $rows_affected = $this->conn[$servernum]->delete($realtable, $where_condition, $bind_vars);
                     Logger::Notice("Execute delete query on table {$table} (Using " . $this->dsn . ")");
                 } catch (Exception $e) {
                     Logger::Error("Failed to delete '{$queryid->id}' from '{$realtable}': " . $e->getMessage());
                 }
             } else {
                 Logger::Warn("Tried to use db '{$this->name}:{$servernum}', but no connection was active");
             }
         }
     }
     Profiler::StopTimer("DBWrapper:QueryDelete()");
     return $rows_affected;
 }
 public function loadFromCache()
 {
     $cachekey = "config.{$this->role}.{$this->name}";
     $data = DataManager::singleton();
     $cachewrapper =& $data->caches["apc"]["default"];
     if (($cachedresult = $cachewrapper->get($cachekey)) !== false) {
         $configobj = unserialize($cachedresult);
         Logger::Info("Found '{$cachekey}' in apc cache (revision=" . $cacheobj->revision . ")");
         $allversions = $this->GetAllRevisions($role);
         Logger::Debug($allversions);
         foreach ($cacheobj->heirarchy as $i => $inc) {
             if ($cacheobj->versions[$inc] < $allversions[$inc]) {
                 Logger::Warn("Revision number for '{$name}' parent '{$inc}' is out of date (old revision=" . $cacheobj->versions[$inc] . " new revision=" . $allversions[$inc] . ")");
                 $ret = array();
                 $skipcache = true;
                 for ($j = $i; $j >= 0; $j--) {
                     // Clear cache entries for anything above this one
                     Logger::Info("Delete cache: {$includes[$j]}");
                     /*
                      // FIXME - need to invalidate instead of deleting
                       $cachewrapper->delete("config.$role.{$includes[$j]}");
                       $cachewrapper->delete("config.$role.{$includes[$j]}.heirarchy");
                       $cachewrapper->delete("config.$role.{$includes[$j]}.versions");
                     */
                 }
             }
         }
     }
 }
Example #4
0
 public static function ImportarCSV($raw_contents)
 {
     Logger::log("----- importando como csv ------- ");
     //      array str_getcsv ( string $input [, string $delimiter = ',' [, string $enclosure = '"' [, string $escape = '\\' ]]] )
     $firstLine = strpos($raw_contents, "\n");
     $head = str_getcsv(substr($raw_contents, 0, $firstLine), ',', '"');
     $data = str_getcsv(substr($raw_contents, $firstLine), ',', '"');
     $soh = sizeof($head);
     $indices_names = array("razon_social", "clasificacion_cliente", "codigo_cliente", "cuenta_de_mensajeria", "curp", "denominacion_comercial", "descuento_general", "direcciones", "email", "extra_params", "id_cliente_padre", "id_moneda", "id_tarifa_compra", "id_tarifa_venta", "limite_credito", "password", "representante_legal", "rfc", "sitio_web", "telefono_personal1", "telefono_personal2", "calle", "numero_exterior", "numero_interior", "colonia", "codigo_postal", "telefono1", "telefono2", "id_ciudad", "referencia");
     for ($i = 0; $i < sizeof($indices_names); $i++) {
         $indices[$indices_names[$i]] = array_search($indices_names[$i], $head);
         /*if( $indices[$indices_names[$i]] !== FALSE ) 
         		Logger::log("there is NORMAL param at $i => " . $head[ $indices[$indices_names[$i]] ]  );*/
     }
     //indices, del 0 al max_indice
     //quitar los que esten en $indices[*]
     $extra_params_indices = array();
     for ($i = 0; $i < sizeof($head); $i++) {
         if (array_search($i, $indices) !== FALSE) {
             continue;
         }
         array_push($extra_params_indices, $i);
         /*Logger::log("there is extra param at $i => " . $head[ $i ] );*/
     }
     $iteraciones = sizeof($data) / $soh;
     /*var_dump($indices);
     		var_dump($head);
     		var_dump($data);*/
     Logger::log("soh=" . $soh . " , sod=" . sizeof($data) . " , " . " it=" . $iteraciones);
     $i = 0;
     while ($i < $iteraciones) {
         try {
             /*
             					for ($h=0; $h < sizeof($indices_names); $h++) { 
             						//$indices_names[$h]
             						if($indices[$indices_names[$h]] !== FALSE)
             						Logger::log($indices_names[$h] . " =   ($i * $soh) + " . $indices[$indices_names[$h]]  . " = " . (($i * $soh) + $indices[$indices_names[$h]] ) . " = " .   ($data[ ($i * $soh) + $indices[$indices_names[$h]] ])    );     
             					}*/
             /*
             					if( (($i * $soh) + $indices["razon_social"]) >= $soh ){
             						//ya no hay campos 
             						Logger::log("//ya no hay campos ");
             						break;
             					}*/
             //buscar todos los demas parametros que no estan en
             //$indicies, y mandarlos como un arreglo asociativo
             //a extra_params
             $extra_params = array();
             for ($j = 0; $j < sizeof($extra_params_indices); $j++) {
                 $extra_params[$head[$extra_params_indices[$j]]] = $data[$i * $soh + $extra_params_indices[$j]];
             }
             $nc = self::Nuevo($indices["razon_social"] !== FALSE ? $data[$i * $soh + $indices["razon_social"]] : NULL, $indices["clasificacion_cliente"] !== FALSE ? $data[$i * $soh + $indices["clasificacion_cliente"]] : NULL, $indices["codigo_cliente"] !== FALSE ? $data[$i * $soh + $indices["codigo_cliente"]] : NULL, $indices["cuenta_de_mensajeria"] !== FALSE ? $data[$i * $soh + $indices["cuenta_de_mensajeria"]] : NULL, $indices["curp"] !== FALSE ? $data[$i * $soh + $indices["curp"]] : NULL, $indices["denominacion_comercial"] !== FALSE ? $data[$i * $soh + $indices["denominacion_comercial"]] : NULL, $indices["descuento_general"] !== FALSE ? $data[$i * $soh + $indices["descuento_general"]] : NULL, array(array("calle" => $indices["calle"] !== FALSE ? $data[$i * $soh + $indices["calle"]] : NULL, "numero_exterior" => $indices["numero_exterior"] !== FALSE ? $data[$i * $soh + $indices["numero_exterior"]] : NULL, "numero_interior" => $indices["numero_interior"] !== FALSE ? $data[$i * $soh + $indices["numero_interior"]] : NULL, "colonia" => $indices["colonia"] !== FALSE ? $data[$i * $soh + $indices["colonia"]] : NULL, "codigo_postal" => $indices["codigo_postal"] !== FALSE ? $data[$i * $soh + $indices["codigo_postal"]] : NULL, "telefono1" => $indices["telefono1"] !== FALSE ? $data[$i * $soh + $indices["telefono1"]] : NULL, "telefono2" => $indices["telefono2"] !== FALSE ? $data[$i * $soh + $indices["telefono2"]] : NULL, "id_ciudad" => $indices["id_ciudad"] !== FALSE ? $data[$i * $soh + $indices["id_ciudad"]] : NULL, "referencia" => $indices["referencia"] !== FALSE ? $data[$i * $soh + $indices["referencia"]] : NULL)), $indices["email"] !== FALSE ? $data[$i * $soh + $indices["email"]] : NULL, $extra_params, $indices["id_cliente_padre"] !== FALSE ? $data[$i * $soh + $indices["id_cliente_padre"]] : NULL, $indices["id_moneda"] !== FALSE ? $data[$i * $soh + $indices["id_moneda"]] : NULL, $indices["id_tarifa_compra"] !== FALSE ? $data[$i * $soh + $indices["id_tarifa_compra"]] : NULL, $indices["id_tarifa_venta"] !== FALSE ? $data[$i * $soh + $indices["id_tarifa_venta"]] : NULL, $indices["limite_credito"] !== FALSE ? $data[$i * $soh + $indices["limite_credito"]] : NULL, $indices["password"] !== FALSE ? $data[$i * $soh + $indices["password"]] : NULL, $indices["representante_legal"] !== FALSE ? $data[$i * $soh + $indices["representante_legal"]] : NULL, $indices["rfc"] !== FALSE ? $data[$i * $soh + $indices["rfc"]] : NULL, $indices["sitio_web"] !== FALSE ? $data[$i * $soh + $indices["sitio_web"]] : NULL, $indices["telefono_personal1"] !== FALSE ? $data[$i * $soh + $indices["telefono_personal1"]] : NULL, $indices["telefono_personal2"] !== FALSE ? $data[$i * $soh + $indices["telefono_personal2"]] : NULL);
         } catch (Exception $e) {
             Logger::Warn($e);
             //continuar
         }
         $i++;
     }
     //for
 }
Example #5
0
 /** 
  * Determine source for a given id, then pass on all arguments to wrapper
  *
  * @param string $id (query identifier)
  * @param any $query
  * @param any $args
  * @param any $extras
  * @return object resultset
  **/
 static function &Query($id, $query, $args = NULL, $extras = NULL)
 {
     global $webapp;
     Profiler::StartTimer("DataManager::Query()");
     Profiler::StartTimer("DataManager::Query({$id})", 3);
     $result = NULL;
     $qstart = microtime(true);
     $queryid = new DatamanagerQueryID($id);
     $source = DataManager::PickSource($queryid);
     if (empty($source)) {
         Logger::Error("Unable to determine source to serve request: %s", $queryid->name);
         Profiler::StopTimer("DataManager::Query()");
         Profiler::StopTimer("DataManager::Query({$id})");
         return $result;
     }
     // Pull default caching policy from connection object, then force enabled/disable as requested
     $cache = $source->cachepolicy;
     if (!empty($queryid->args["nocache"])) {
         $cache = false;
     }
     if (!empty($queryid->args["cache"])) {
         $cache = any($source->cachepolicy, true);
     }
     // If the query string contains nocache, force to no cache
     if (!empty($webapp->request["args"]["nocache"])) {
         $cache = false;
     }
     $foundincache = false;
     if ($cache) {
         //Profiler::StartTimer("DataManager::Query() - Check cache");
         if (($cacheresult = $source->CacheGet($queryid, $query, $args)) !== NULL) {
             if ($cacheresult && !$cacheresult->isExpired()) {
                 $result = $cacheresult->getPayload(false);
                 $foundincache = true;
             }
         }
         //Profiler::StopTimer("DataManager::Query() - Check cache");
     }
     //Logger::Error("cache for $id: $cache");
     //Logger::Error("is result false ? " . ($result === false));
     if ($result === NULL && empty($queryid->args["nosource"])) {
         //Profiler::StartTimer("DataManager::Query() - Check Original Source");
         // We failed to retrieve anything from the cache - perform the real query
         if ($source) {
             $result = $source->query($queryid, $query, $args, $extras);
             //print_pre("replace $resourcename ($foundincache)");
             if ($cache && !$foundincache) {
                 if (!empty($result)) {
                     // Only cache "positive" responses (FIXME - maybe this should be an option?  We should observe and make sure this change doesn't hurt more than it helps)
                     $source->CacheSet($queryid, $query, $args, $result);
                 }
                 /*
                 else
                   Logger::Error("Tried to cache empty dataset for key '{$queryid->name}' (query: $query, args: " . print_ln($args, true) . ")");
                 */
             }
         }
         //Profiler::StopTimer("DataManager::Query() - Check Original Source");
     }
     // If result is STILL null, and we're in soft-expire-cache mode, let's use the expired data and throw a warning
     if ($result === NULL) {
         if ($cache == 2 && $cacheresult instanceof CacheEntry) {
             $result = $cacheresult->getPayload(true);
             Logger::Warn("Cache for '%s' was soft-expired but we couldn't refresh it (%d seconds stale)", $queryid->name, time() - $cacheresult->timestamp - $cacheresult->timeout);
         }
     }
     Profiler::StopTimer("DataManager::Query()");
     Profiler::StopTimer("DataManager::Query({$id})");
     self::log("query", $id, $query, $qstart, microtime(true), $foundincache);
     return $result;
 }
 function &CacheSet($queryid, $query, $args = NULL, $result)
 {
     if ($this->cache) {
         switch ($this->cachepolicy) {
             case 1:
                 $this->cache->set($queryid->id, $result);
                 break;
             case 2:
                 $this->cache->set($queryid->id, new CacheEntry($queryid->id, $result, true, $this->cachetimeout));
                 break;
         }
     } else {
         Logger::Warn("Cannot set '{$queryid->id}' in cache - no cache associated with this connection");
     }
 }
 /**
  * Initialize the session.
  * Start the session.
  */
 protected function init()
 {
     //some al-qada shit here...
     global $webapp;
     $this->data = DataManager::singleton();
     Profiler::StartTimer("SessionManager::Init()", 2);
     $cfgmgr = ConfigManager::singleton();
     $sessionsource = array_get($cfgmgr->servers, "session.datasource");
     if (!empty($sessionsource)) {
         $this->sessionsource = $sessionsource;
     }
     $sessiontable = array_get($cfgmgr->servers, "session.table");
     if (!empty($sessiontable)) {
         $this->sessiontable = $sessiontable;
     }
     /*
     if ($this->data->caches["memcache"]["session"] !== NULL) {
       $this->cache_obj = $this->data->caches["memcache"]["session"];
       //$this->session_cache_expire = $this->data->caches["memcache"]["session"]->lifetime;
     } else {
       // Continue anyway even if cannot connect to memcache.
       // Point the cache_obj to NoCache object
       //print_pre($this->data);
       Logger::Error("SessionManager::init() - Cannot connect to session memcache - " . $this->data->sources);
       $this->cache_obj =& NoCache::singleton();
     }
     */
     // instantiate the pandora object
     $pandora = PandoraLog::singleton();
     // check to see if there is an existing cookie for flsid
     $has_flsid = isset($_COOKIE['flsid']) || isset($_REQUEST['flsid']);
     $this->is_new_session = $has_flsid == 1 ? 0 : 1;
     // register_shutdown_function('session_write_close');
     // Set session cookie params
     $domain = null;
     $sessioncfg = any($cfgmgr->servers["session"], array());
     $sessionpath = any($sessioncfg["cookiepath"], "/");
     if ($sessioncfg["domaincookie"]) {
         // Determine second-level domain, taking into account any known ccSLDs (.co.uk, etc)
         $FQDN = $webapp->request["host"];
         $knownccSLDs = explode(" ", any($sessioncfg["ccSLDs"], ""));
         $parts = explode(".", $FQDN);
         $TLD = array_pop($parts);
         $SLD = array_pop($parts);
         $domain = $SLD . "." . $TLD;
         if (in_array($domain, $knownccSLDs)) {
             $TLD = $domain;
             $SLD = array_pop($parts);
             $domain = $SLD . "." . $domain;
         }
         $excludeDomains = explode(" ", any($sessioncfg["domaincookie_exception"], ""));
         if (in_array($domain, $excludeDomains)) {
             $domain = null;
         }
     }
     session_set_cookie_params(0, $sessionpath, $domain);
     // if flsid was passed via the URL, set it as a cookie
     if (!empty($_GET['flsid'])) {
         setcookie("flsid", $_GET['flsid'], 0, '/', $domain);
         $this->flsid = $_COOKIE['flsid'] = $_GET['flsid'];
     }
     session_set_save_handler(array(&$this, 'open'), array(&$this, 'close'), array(&$this, 'read'), array(&$this, 'write'), array(&$this, 'destroy'), array(&$this, 'gc'));
     // set the garbage collection lifetime (on the DB persist data)
     ini_set('session.gc_maxlifetime', 31536000);
     // 31536000 = 60 * 60 * 24 * 365
     // set the session cookie name
     session_name($this->cookiename);
     // set the cache limiter to 'private' - keeps us from sending Pragma: no-cache
     session_cache_limiter('private');
     // initiate sessionization
     if (!headers_sent()) {
         session_start();
     }
     /**
      * Read the permanent session ID from cookie.
      * If there isn't one, create one.
      */
     // read the permanent cookie
     if (isset($_REQUEST['fluid'])) {
         $fluid_str = $_REQUEST['fluid'];
     } else {
         if (isset($_COOKIE['fl-uid'])) {
             $fluid_str = $_COOKIE['fl-uid'];
         } else {
             if (isset($_SESSION['fluid'])) {
                 $fluid_str = $_SESSION['fluid'];
             }
         }
     }
     $fluid_data = explode(",", $fluid_str);
     $this->fluid = $fluid_data[0];
     $this->session_count = $fluid_data[1] ? $fluid_data[1] : 0;
     $this->last_access = $fluid_data[2] ? $fluid_data[2] : 0;
     $this->first_session_for_day = 0;
     $this->days_since_last_session = 0;
     $this->is_new_user = 0;
     if (empty($this->fluid)) {
         // create new permanent cookie
         $this->is_new_user = 1;
         $this->fluid = $this->generate_fluid();
         $this->session_count = 0;
         $this->last_access = time();
         $this->first_session_for_day = 1;
         $this->days_since_last_session = 0;
         $fluid_data = $this->fluid . ',' . $this->session_count . ',' . $this->last_access;
         //setcookie('fl-uid', $fluid_data, time()+31536000, "/", $domain); // (1 year)
         $pdata_serialize = serialize($_SESSION["persist"]);
         $this->crc = strlen($pdata_serialize) . crc32($pdata_serialize);
     }
     if (!$has_flsid) {
         // new session -- update the permanent cookie
         // Deal with errant mis-named 'fl_uid' cookies...
         // (this code can safely be removed in a year or so, e.g. February 2010)
         // ^^^ perhaps not?
         if ($fluid_data_recover = explode(",", $_COOKIE['fl_uid'])) {
             $this->fluid = any($this->fluid, $fluid_data_recover[0]);
             $this->session_count = $fluid_data_recover[1];
             $this->last_access = $fluid_data_recover[2];
             //setcookie('fl_uid', '', 0, "/", $domain); // delete the errant cookie
         }
         $this->session_count++;
         if (time() > $this->last_access + 86400) {
             $this->days_since_last_session = floor((time() - $this->last_access) / 86400);
             $this->last_access = time();
             $this->first_session_for_day = 1;
         }
         $fluid_data = $this->fluid . ',' . $this->session_count . ',' . $this->last_access;
         if (!headers_sent()) {
             setcookie('fl-uid', $fluid_data, time() + 31536000, "/", $domain);
             // (update the permanent cookie)
         }
     }
     // debugging
     // print "<hr>In SessionManager::init() - cache_obj extended stats = " . print_pre($this->cache_obj->GetExtendedStats());
     /**
      * First, check to see if there is an entry in the memcache for this fluid.
      * If so, use it.
      * If not, query the DB to get the persistent session data.
      * If not in the DB, create a new session.
      */
     //$session_memcache = $this->cache_obj->get($this->flsid);
     // force new flsid/session id regardless if flsid is passed in url
     if ($_REQUEST['event'] == 'new') {
         $this->flsid = session_regenerate_id();
     } else {
         $this->flsid = session_id();
     }
     $session_memcache = DataManager::fetch("memcache.session#{$this->flsid}", $this->flsid);
     //$tmpsession = unserialize($session_memcache);
     if (!empty($session_memcache["fluid"])) {
         $this->fluid = $session_memcache["fluid"];
     }
     if (empty($session_memcache) && !$this->is_new_user) {
         $result = DataManager::QueryFetch($this->sessionsource . "#{$this->fluid}", $this->sessiontable, array("fl_uid" => $this->fluid));
         if ($result && count($result) == 1) {
             $data = current($result);
             $_SESSION["persist"] = unserialize($data["data"]);
             $this->has_db_record = true;
             if (!$_SESSION["persist"]["has_db_record"]) {
                 $_SESSION["persist"]["has_db_record"] = true;
             }
         }
     } else {
         $_SESSION = $session_memcache;
         //Logger::Error(print_r($_SESSION, true));
     }
     $this->has_db_record = $_SESSION["persist"]["has_db_record"] ? true : false;
     // Store permenant session id, actual (temporary) session id,
     // and create pointers to $_SESSION memory space
     $this->flsid = session_id();
     $this->persist =& $_SESSION["persist"];
     $this->temporary =& $_SESSION["temporary"];
     // get from the persist session data if this is a new or registered user
     $userid = $_SESSION["persist"]["user"]["userid"];
     $usertype = $_SESSION["persist"]["user"]["usertype"];
     $userTypeArray = User::$usertypes;
     $pandoraUserTypeNum = any($userTypeArray[$usertype], 0);
     // log this into Pandora
     $pandora_session = array("timestamp" => time(), "session_id" => $this->flsid, "fluid" => $this->fluid, "is_new_user" => $this->is_new_user, "is_registered_user" => $userid ? 1 : 0, "ip_addr" => $_SERVER['REMOTE_ADDR'], "user_agent" => $_SERVER['HTTP_USER_AGENT'], "referrer_url" => $_SERVER['HTTP_REFERER'], "landing_page_url" => "http" . (!empty($_SERVER["HTTPS"]) ? "s" : "") . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], "referrer_id" => $webapp->request["args"]["rid"], "widget_id" => $webapp->request["args"]["wid"], "user_registration_id" => "{$pandoraUserTypeNum}.{$userid}", "version" => 0, "cobrand" => $this->root->cobrand, "first_session_for_day" => $this->first_session_for_day, "session_count" => $this->session_count, "days_since_last_session" => $this->days_since_last_session);
     // log this session for data warehouse (once per session)
     if (!$has_flsid) {
         //store the session start time in session
         $_SESSION['session_start_time'] = time();
         $pandora->addData("session", $pandora_session);
     } else {
         Logger::Notice("Pandora: Session already has an flsid. Current start time from session is: " . var_export($_SESSION['session_start_time'], true));
         if (!array_key_exists('session_start_time', $_SESSION)) {
             $_SESSION['session_start_time'] = time();
             Logger::Warn("Pandora: Set or reset the session start time as one did not exist before. Time is: " . var_export($_SESSION['session_start_time'], true));
         } else {
             Logger::Notice("Pandora: Session start time was not reset. Time is: " . var_export($_SESSION['session_start_time'], true));
         }
     }
     //save session data once per session
     //    if(!array_key_exists('pandora_session_data_added', $_SESSION)) {
     //      $pandora->addData("session", $pandora_session);
     //      $_SESSION['pandora_session_data_added'] = true;
     //    }
     $_SESSION["fluid"] = $this->fluid;
     // set the script session ID
     $this->flssid = $this->generate_fluid();
     Profiler::StopTimer("SessionManager::Init()");
 }
Example #8
0
 /**
  * Returns the memcache key value.
  *
  * @param string $key
  * @return mixed
  */
 protected function getData($key)
 {
     $diskcache = $this->getCachePaths($key);
     $ret = false;
     if (file_exists($diskcache["fullpath"])) {
         if (filemtime($diskcache["fullpath"]) < $this->lifetime) {
             Logger::Warn("Unlinking stale cachefile '" . $diskcache["fullpath"] . "'");
             unlink($diskcache["fullpath"]);
         } else {
             $fp = fopen($diskcache["fullpath"], "r");
             if (flock($fp, LOCK_SH)) {
                 //$cachedresult = file_get_contents($diskcache["fullpath"]);
                 $cachedresult = fread($fp, filesize($diskcache["fullpath"]));
                 flock($fp, LOCK_UN);
                 if (!empty($cachedresult)) {
                     Profiler::StartTimer("DataManager::Query() - load from cachefile");
                     Logger::Info("Loaded cached result for '%s' from file: '%s'", $key, $diskcache["fullpath"]);
                     $result = unserialize(gzdecode($cachedresult));
                     if ($result !== false) {
                         $ret = $result;
                     }
                     Profiler::StopTimer("DataManager::Query() - load from cachefile");
                 }
             } else {
                 Logger::Error("Failed to get shared lock for '%s' (%s)", $key, $diskcache["fullpath"]);
             }
         }
     }
     return $ret;
 }
 /**
  * dbConnection::query()
  * Execute the passed query on the database and determine if insert_id or affected_rows or numrows has to be called.
  * @param String $query Query to be executed.
  * @returns mixed ID if inserted row, false on error
  */
 function query($query)
 {
     if ($this->adapter->connection == false) {
         logger::getInstance()->LogEmail('Not connected');
         return false;
     }
     if ($this->debug) {
         Logger::getInstance()->log[] = "executing: {$query}";
     }
     $result = $this->adapter->query($query);
     if (!$result) {
         $error = $this->adapter->getError();
         if ($error != '' && $this->adapter->connection != false) {
             Logger::Warn("Error '{$error}' during execution of query {$query}");
         }
         return false;
     }
     $query = trim(strtolower($query));
     $firstpart = substr($query, 0, 6);
     $this->insertID = false;
     $this->affected = false;
     $this->numrows = false;
     switch ($firstpart) {
         case 'insert':
             $this->insertID = $this->adapter->getInsertID();
             break;
         case 'delete':
         case 'replac':
         case 'update':
             $this->affected = $this->adapter->numAffected();
             break;
         case 'select':
             $this->numrows = $this->adapter->numRows();
             break;
     }
     if ($this->insertID != false) {
         return $this->insertID;
     }
     return true;
 }
Example #10
0
 private static function importarCSV($raw_contents)
 {
     Logger::log("Importando como CSV");
     $firstLine = strpos($raw_contents, "\n");
     $head = str_getcsv(substr($raw_contents, 0, $firstLine), ',', '"');
     $data = str_getcsv(substr($raw_contents, $firstLine), ',', '"');
     $soh = sizeof($head);
     $indices_names = array("activo", "codigo_producto", "compra_en_mostrador", "id_unidad_compra", "metodo_costeo", "nombre_producto", "codigo_de_barras", "control_de_existencia", "costo_estandar", "descripcion_producto", "foto_del_producto", "garantia", "id_categoria", "id_empresas", "id_unidad", "impuestos", "precio_de_venta");
     for ($i = 0; $i < sizeof($indices_names); $i++) {
         $indices[$indices_names[$i]] = array_search($indices_names[$i], $head);
         /*if( $indices[$indices_names[$i]] !== FALSE )
         		Logger::log("there is NORMAL param at $i => " . $head[ $indices[$indices_names[$i]] ]  );*/
     }
     //indices, del 0 al max_indice
     //quitar los que esten en $indices[*]
     $extra_params_indices = array();
     for ($i = 0; $i < sizeof($head); $i++) {
         if (array_search($i, $indices) !== FALSE) {
             continue;
         }
         array_push($extra_params_indices, $i);
         /*Logger::log("there is extra param at $i => " . $head[ $i ] );*/
     }
     $iteraciones = sizeof($data) / $soh;
     //Logger::log("soh=" . $soh . " , sod=" . sizeof($data) . " , " . " it=" . $iteraciones);
     $i = 0;
     while ($i < $iteraciones) {
         try {
             /*
             					for ($h=0; $h < sizeof($indices_names); $h++) {
             						//$indices_names[$h]
             						if($indices[$indices_names[$h]] !== FALSE)
             						Logger::log($indices_names[$h] . " =   ($i * $soh) + " . $indices[$indices_names[$h]]  . " = " . (($i * $soh) + $indices[$indices_names[$h]] ) . " = " .   ($data[ ($i * $soh) + $indices[$indices_names[$h]] ])    );
             					}*/
             /*
             					if( (($i * $soh) + $indices["razon_social"]) >= $soh ){
             						//ya no hay campos
             						Logger::log("//ya no hay campos ");
             						break;
             					}*/
             //buscar todos los demas parametros que no estan en
             //$indicies, y mandarlos como un arreglo asociativo
             //a extra_params
             $extra_params = array();
             for ($j = 0; $j < sizeof($extra_params_indices); $j++) {
                 $extra_params[$head[$extra_params_indices[$j]]] = $data[$i * $soh + $extra_params_indices[$j]];
             }
             $nc = self::Nuevo($indices["activo"] !== FALSE ? $data[$i * $soh + $indices["activo"]] : 1, $indices["codigo_producto"] !== FALSE ? $data[$i * $soh + $indices["codigo_producto"]] : NULL, $indices["compra_en_mostrador"] !== FALSE ? $data[$i * $soh + $indices["compra_en_mostrador"]] : 0, $indices["id_unidad_compra"] !== FALSE ? $data[$i * $soh + $indices["id_unidad_compra"]] : 6, $indices["metodo_costeo"] !== FALSE ? $data[$i * $soh + $indices["metodo_costeo"]] : "precio", $indices["nombre_producto"] !== FALSE ? $data[$i * $soh + $indices["nombre_producto"]] : NULL, $indices["codigo_de_barras"] !== FALSE ? $data[$i * $soh + $indices["codigo_de_barras"]] : NULL, $indices["control_de_existencia"] !== FALSE ? $data[$i * $soh + $indices["control_de_existencia"]] : NULL, $indices["costo_estandar"] !== FALSE ? $data[$i * $soh + $indices["costo_estandar"]] : NULL, $indices["descripcion_producto"] !== FALSE ? $data[$i * $soh + $indices["descripcion_producto"]] : NULL, $indices["foto_del_producto"] !== FALSE ? $data[$i * $soh + $indices["foto_del_producto"]] : NULL, $indices["garantia"] !== FALSE ? $data[$i * $soh + $indices["garantia"]] : NULL, $indices["id_categoria"] !== FALSE ? $data[$i * $soh + $indices["id_categoria"]] : NULL, $indices["id_empresas"] !== FALSE ? $data[$i * $soh + $indices["id_empresas"]] : NULL, $indices["id_unidad"] !== FALSE ? $data[$i * $soh + $indices["id_unidad"]] : NULL, $indices["impuestos"] !== FALSE ? $data[$i * $soh + $indices["impuestos"]] : NULL, $indices["precio_de_venta"] !== FALSE ? $data[$i * $soh + $indices["precio_de_venta"]] : NULL);
         } catch (Exception $e) {
             Logger::Warn($e);
             //continuar
         }
         $i++;
     }
     //for
 }
 /**
  * Create a new persist record in the userdata.usersssion table
  */
 protected function create_new_persist_record($force = false)
 {
     // if bot, don't create a db record
     if (function_exists("isBot") && isBot()) {
         return;
     }
     // insert a record into userdata.usersession
     if ($force || !empty($_SESSION["persist"])) {
         $_SESSION["persist"]["has_db_record"] = true;
         $pdata_serialize = serialize($_SESSION["persist"]);
         $ip = $_SERVER['REMOTE_ADDR'];
         Logger::Warn("Creating session in database");
         $result = DataManager::QueryInsert($this->sessionsource . "#{$this->fluid}", $this->sessiontable, array($this->fluid => array("fl_uid" => $this->fluid, "data" => $pdata_serialize, "ip_addr" => $ip)));
         // set the $_SESSION
         $this->has_db_record = true;
     }
 }