Example #1
14
 public function authorize(HeaderInterface $authHeader)
 {
     list($jwt) = sscanf($authHeader->toString(), 'Authorization: Bearer %s');
     if ($jwt) {
         try {
             /*
              * decode the jwt using the key from config
              */
             $secretKey = base64_decode($this->config->get('jwt')->get('key'));
             $this->token = JWT::decode($jwt, $secretKey, [$this->config->get('jwt')->get('algorithm')]);
             $this->isAuthorized = true;
             $this->response = Response::createMessage("10");
         } catch (Exception $e) {
             /*
              * the token was not able to be decoded.
              * this is likely because the signature was not able to be verified (tampered token)
              */
             $this->isAuthorized = false;
             $this->response = Response::createMessage("03");
             $this->response["data"] = $jwt;
         }
     } else {
         /*
          * No token was able to be extracted from the authorization header
          */
         $this->isAuthorized = false;
         $this->response = Response::createMessage("01");
     }
 }
Example #2
1
function get_product($url, $page = 0)
{
    global $save_folder;
    $html = curl_get($url);
    //Загружает страницу товара
    $dom = str_get_html($html);
    $article = $dom->find('article', 0);
    //Берем артикул
    $str = $article->attr['id'];
    sscanf($str, 'post-%d', $art);
    $scripts = $dom->find('script');
    foreach ($scripts as $script) {
        if (strpos($script->src, "script.js")) {
            $str = "script[src='" . $script->src . "']";
        }
    }
    $dom->find($str, 0)->outertext = '';
    //Ajax запрос
    $html = get_ajax($art);
    //Получили данные из ajax
    $dom2 = str_get_html($html);
    //Ищем в 1-й странице div куда будем вставлять данные из ajax
    $dom->find('div[id=order-variables]', 0)->innertext = $dom2;
    //Сохраняем HTML
    file_put_contents($save_folder . 'product--' . $page . '.html', $dom);
}
 public static function store()
 {
     self::check_logged_in(array("asiakas", "tyontekija", "johtaja"));
     $params = $_POST;
     $palvelu = Palvelu::find($params['palvelu_id']);
     $aloitusaika = strtotime($params['paiva'] . ' ' . $params['kellonaika']);
     list($tunnit, $minuutit, $sekunnit) = sscanf($palvelu->kesto, '%d:%d:%d');
     $kesto = new DateInterval(sprintf('PT%dH%dM', $tunnit, $minuutit));
     $lopetusaika = date_timestamp_get(date_add(new DateTime('@' . $aloitusaika), $kesto));
     $attributes = array('asiakas_id' => $params['asiakas_id'], 'palvelu_id' => $params['palvelu_id'], 'tyontekija_id' => $params['tyontekija_id'], 'toimitila_id' => $params['toimitila_id'], 'aloitusaika' => date('Y-m-d H:i', $aloitusaika), 'lopetusaika' => date('Y-m-d H:i', $lopetusaika), 'on_peruutettu' => NULL);
     $varaus = new Varaus($attributes);
     $errors = $varaus->errors();
     // tarkistetaan resurssien ja asiakkaan saatavuus varausajalle
     if (count($errors) == 0) {
         $errors = $varaus->check_overlaps();
     }
     if (count($errors) > 0) {
         $tyontekijat = Tyontekija::all();
         $palvelut = Palvelu::all();
         $toimitilat = Toimitila::all();
         $asiakkaat = Asiakas::all();
         View::make('varaus/varaus_lisaa.html', array('errors' => $errors, 'varaus' => $varaus, 'tyontekijat' => $tyontekijat, 'palvelut' => $palvelut, 'toimitilat' => $toimitilat, 'asiakkaat' => $asiakkaat));
     } else {
         $varaus->save();
         Redirect::to('/', array('message' => 'Varaus tallennettu.'));
     }
 }
Example #4
0
function detectFormatDate($date_a_convertir, $compl = "01")
{
    global $msg;
    if (preg_match("#\\d{4}-\\d{2}-\\d{2}#", $date_a_convertir)) {
        $date = $date_a_convertir;
    } else {
        if (preg_match(getDatePattern(), $date_a_convertir)) {
            $date = extraitdate($date_a_convertir);
        } elseif (preg_match(getDatePattern("short"), $date_a_convertir)) {
            $format = str_replace("%", "", $msg["format_date_short"]);
            $format = str_replace("-", "", $format);
            $format = str_replace("/", "", $format);
            $format = str_replace("\\", "", $format);
            $format = str_replace(".", "", $format);
            $format = str_replace(" ", "", $format);
            $format = str_replace($msg["format_date_input_separator"], "", $format);
            list($date[substr($format, 0, 1)], $date[substr($format, 1, 1)], $date[substr($format, 2, 1)]) = sscanf($date_a_convertir, $msg["format_date_short_input"]);
            if ($date['Y'] && $date['m']) {
                $date = sprintf("%04d-%02s-%02s", $date['Y'], $date['m'], $compl);
            } else {
                $date = "0000-00-00";
            }
        } elseif (preg_match(getDatePattern("year"), $date_a_convertir, $matches)) {
            $date = $matches[0] . "-" . $compl . "-" . $compl;
        } else {
            $date = "0000-00-00";
        }
    }
    return $date;
}
 /**
  * Beautifes a range label and returns the pretty result.
  *
  * @param string $value The range string. This must be in either a '$min-$max' format
  *                      a '$min+' format.
  * @return string The pretty range label.
  */
 public function beautify($value)
 {
     // if there's more than one element, handle as a range w/ an upper bound
     if (strpos($value, "-") !== false) {
         // get the range
         sscanf($value, "%d - %d", $lowerBound, $upperBound);
         // if the lower bound is the same as the upper bound make sure the singular label
         // is used
         if ($lowerBound == $upperBound) {
             return $this->getSingleUnitLabel($value, $lowerBound);
         } else {
             return $this->getRangeLabel($value, $lowerBound, $upperBound);
         }
     } else {
         // get the lower bound
         sscanf($value, "%d", $lowerBound);
         if ($lowerBound !== NULL) {
             $plusEncoded = urlencode('+');
             $plusLen = strlen($plusEncoded);
             $len = strlen($value);
             // if the label doesn't end with a '+', append it
             if ($len < $plusLen || substr($value, $len - $plusLen) != $plusEncoded) {
                 $value .= $plusEncoded;
             }
             return $this->getUnboundedLabel($value, $lowerBound);
         } else {
             // if no lower bound can be found, this isn't a valid range. in this case
             // we assume its a translation key and try to translate it.
             return Piwik_Translate(trim($value));
         }
     }
 }
Example #6
0
function formatPhone($phone)
{
    if (empty($phone)) {
        return "";
    }
    if (strlen($phone) == 7) {
        sscanf($phone, "%3s%4s", $prefix, $exchange);
    } else {
        if (strlen($phone) == 10) {
            sscanf($phone, "%3s%3s%4s", $area, $prefix, $exchange);
        } else {
            if (strlen($phone) > 10) {
                if (substr($phone, 0, 1) == '1') {
                    sscanf($phone, "%1s%3s%3s%4s", $country, $area, $prefix, $exchange);
                } else {
                    sscanf($phone, "%3s%3s%4s%s", $area, $prefix, $exchange, $extension);
                }
            } else {
                return "unknown phone format: {$phone}";
            }
        }
    }
    $out = "";
    $out .= isset($country) ? $country . ' ' : '';
    $out .= isset($area) ? '(' . $area . ') ' : '';
    $out .= $prefix . '-' . $exchange;
    $out .= isset($extension) ? ' x' . $extension : '';
    return $out;
}
Example #7
0
 /**
  * Processes cell value
  *
  * @param   var in
  * @return  var
  * @throws  lang.FormatException
  */
 public function process($in)
 {
     if (1 !== sscanf($in, '%f', $out)) {
         throw new \lang\FormatException('Cannot parse "' . $in . '" into an double');
     }
     return $this->proceed($out);
 }
Example #8
0
 public function hydrate(RawObject $raw_object)
 {
     $commit = new Commit();
     $commit->setSha($raw_object->getSha());
     list($meta, $message) = explode("\n\n", $raw_object->getData());
     $commit->setMessage($message);
     foreach (explode("\n", $meta) as $meta_line) {
         sscanf($meta_line, "%s ", $attribute);
         $attribute_value = substr($meta_line, strlen($attribute) + 1);
         switch ($attribute) {
             case 'tree':
                 $commit->setTree(new TreeProxy($this->repo, $attribute_value));
                 break;
             case 'parent':
                 $commit->addParent(new CommitProxy($this->repo, $attribute_value));
                 break;
             case 'author':
                 preg_match('/(.*?) <(.*?)> ([0-9]*)( (.+))?/', $attribute_value, $matches);
                 $commit->setAuthor(new User($matches[1], $matches[2]));
                 $commit->setAuthorTime(\DateTime::createFromFormat('U O', $matches[3] . ' ' . $matches[5]));
                 break;
             case 'committer':
                 preg_match('/(.*?) <(.*?)> ([0-9]*)( (.+))?/', $attribute_value, $matches);
                 $commit->setCommitter(new User($matches[1], $matches[2]));
                 $commit->setCommitTime(\DateTime::createFromFormat('U O', $matches[3] . ' ' . $matches[5]));
                 break;
         }
     }
     return $commit;
 }
 /**
  * @throws SQLException
  * @return void
  */
 protected function initTables()
 {
     include_once 'creole/drivers/pgsql/metadata/PgSQLTableInfo.php';
     // Get Database Version
     // TODO: www.php.net/pg_version
     $result = pg_query($this->conn->getResource(), "SELECT version() as ver");
     if (!$result) {
         throw new SQLException("Failed to select database version");
     }
     // if (!$result)
     $row = pg_fetch_assoc($result, 0);
     $arrVersion = sscanf($row['ver'], '%*s %d.%d');
     $version = sprintf("%d.%d", $arrVersion[0], $arrVersion[1]);
     // Clean up
     $arrVersion = null;
     $row = null;
     pg_free_result($result);
     $result = null;
     $result = pg_query($this->conn->getResource(), "SELECT c.oid, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tcase when n.nspname='public' then c.relname else n.nspname||'.'||c.relname end as relname \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tFROM pg_class c join pg_namespace n on (c.relnamespace=n.oid)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tWHERE c.relkind = 'r'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND n.nspname NOT IN ('information_schema','pg_catalog')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND n.nspname NOT LIKE 'pg_temp%'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  AND n.nspname NOT LIKE 'pg_toast%'\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tORDER BY relname");
     if (!$result) {
         throw new SQLException("Could not list tables", pg_last_error($this->dblink));
     }
     while ($row = pg_fetch_assoc($result)) {
         $this->tables[strtoupper($row['relname'])] = new PgSQLTableInfo($this, $row['relname'], $version, $row['oid']);
     }
     $this->tablesLoaded = true;
 }
Example #10
0
 /**
  * Parse a string of the form "number unit" where unit is optional. The
  * results are stored in the $number and $unit parameters. Returns an
  * error code.
  * @param $value string to parse
  * @param $number call-by-ref parameter that will be set to the numerical value
  * @param $unit call-by-ref parameter that will be set to the "unit" string (after the number)
  * @return integer 0 (no errors), 1 (no number found at all), 2 (number
  * too large for this platform)
  */
 protected static function parseNumberValue($value, &$number, &$unit)
 {
     // Parse to find $number and (possibly) $unit
     $decseparator = NumberFormatter::getInstance()->getDecimalSeparatorForContentLanguage();
     $kiloseparator = NumberFormatter::getInstance()->getThousandsSeparatorForContentLanguage();
     $parts = preg_split('/([-+]?\\s*\\d+(?:\\' . $kiloseparator . '\\d\\d\\d)*' . '(?:\\' . $decseparator . '\\d+)?\\s*(?:[eE][-+]?\\d+)?)/u', trim(str_replace(array('&nbsp;', '&#160;', '&thinsp;', ' '), '', $value)), 2, PREG_SPLIT_DELIM_CAPTURE);
     if (count($parts) >= 2) {
         $numstring = str_replace($kiloseparator, '', preg_replace('/\\s*/u', '', $parts[1]));
         // simplify
         if ($decseparator != '.') {
             $numstring = str_replace($decseparator, '.', $numstring);
         }
         list($number) = sscanf($numstring, "%f");
         if (count($parts) >= 3) {
             $unit = self::normalizeUnit($parts[2]);
         }
     }
     if (count($parts) == 1 || $numstring === '') {
         // no number found
         return 1;
     } elseif (is_infinite($number)) {
         // number is too large for this platform
         return 2;
     } else {
         return 0;
     }
 }
Example #11
0
	/**
	 * Returns whether image manipulations will be performed using GD or not.
	 *
	 * @return bool|null
	 */
	public function isGd()
	{
		if ($this->_isGd === null)
		{
			if (craft()->config->get('imageDriver') == 'gd')
			{
				$this->_isGd = true;
			}
			else if (extension_loaded('imagick'))
			{
				// Taken from Imagick\Imagine() constructor.
				$imagick = new \Imagick();
				$v = $imagick->getVersion();
				list($version, $year, $month, $day, $q, $website) = sscanf($v['versionString'], 'ImageMagick %s %04d-%02d-%02d %s %s');

				// Update this if Imagine updates theirs.
				if (version_compare('6.2.9', $version) <= 0)
				{
					$this->_isGd = false;
				}
				else
				{
					$this->_isGd = true;
				}
			}
			else
			{
				$this->_isGd = true;
			}
		}

		return $this->_isGd;
	}
Example #12
0
 /**
  * Find named pipe
  *
  * @return  string or NULL if no file can be found
  */
 protected function locate()
 {
     $pipes = '\\\\.\\pipe\\';
     // Check well-known pipe name
     if (file_exists($pipes . 'mysql')) {
         return $pipes . 'mysql';
     }
     // Locate my.ini in %WINDIR%, C: or the MySQL install dir, the latter of
     // which we determine by querying the registry using the "REG" tool.
     do {
         foreach ([getenv('WINDIR'), 'C:'] as $location) {
             $ini = new File($location, 'my.ini');
             if ($ini->exists()) {
                 break 2;
             }
         }
         exec('reg query "HKLM\\SOFTWARE\\MySQL AB" /s /e /f Location', $out, $ret);
         if (0 === $ret && 1 === sscanf($out[2], "    Location    REG_SZ    %[^\r]", $location)) {
             $ini = new File($location, 'my.ini');
             break;
         }
         return null;
     } while (0);
     $options = $this->parse($ini);
     return isset($options['client']['socket']) ? $pipes . $options['client']['socket'] : null;
 }
Example #13
0
function get_mem_usage()
{
    global $free_memory, $total_memory;
    $file = fopen('/proc/meminfo', 'r');
    if (FALSE === $file) {
        return -1;
    }
    $type = '';
    $val = 0;
    $unit = '';
    while (!feof($file)) {
        $line = fgets($file);
        sscanf($line, "%s%d%s", $type, $val, $unit);
        if (stristr($type, 'MemTotal') !== false) {
            $total_memory = $val;
        } else {
            if (stristr($type, 'MemFree') !== false) {
                $free_memory += $val;
            } else {
                if (stristr($type, 'Buffers') !== false) {
                    $free_memory += $val;
                } else {
                    if (stristr($type, 'Cached') !== false) {
                        $free_memory += $val;
                    }
                }
            }
        }
    }
    fclose($file);
}
Example #14
0
 /**
  *
  */
 private function getPolygons()
 {
     $output = [];
     $matches = explode('endfacet', $this->raw);
     foreach ($matches as $match) {
         $output[] = sscanf($match, '  facet normal %s %s %s
         outer loop
           vertex   %s %s %s
           vertex   %s %s %s
           vertex   %s %s %s
         endloop
       endfacet');
     }
     array_shift($output);
     if (!is_array($output)) {
         return false;
     }
     array_walk($output, function (&$value) {
         if (!is_array($value)) {
             return false;
         }
         array_walk($value, function (&$item) {
             $item = pack('l', $item);
         });
         $this->polygons[] = $this->createPolygon(implode('', $value) . "");
     });
 }
Example #15
0
 public function deleteMultiple(array $quads)
 {
     $response = $this->doRequest(self::URL_DELETE, json_encode($quads));
     $result = $response->json();
     list($count) = sscanf($result['result'], 'Successfully deleted %d triples.');
     return $count;
 }
Example #16
0
 /**
  * Processes an escape sequence
  *
  * @param  int $pos The position
  * @param  int $len The string length
  * @param  int &$offset How many bytes were consumed
  * @return string
  * @throws lang.FormatException
  */
 protected function escaped($pos, $len, &$offset)
 {
     if ($len - $pos < 2) {
         throw new FormatException('Unclosed escape sequence');
     }
     $escape = $this->bytes[$pos + 1];
     if (isset(self::$escapes[$escape])) {
         $offset = 2;
         return self::$escapes[$escape];
     } else {
         if ('u' === $escape) {
             if (1 !== sscanf(substr($this->bytes, $pos + 2, 4), '%4x', $hex)) {
                 throw new FormatException('Illegal unicode escape sequence ' . substr($this->bytes, $pos, 6));
             } else {
                 if ($hex > 0xd800 && $hex < 0xdfff) {
                     $offset = 12;
                     $surrogate = hexdec(substr($this->bytes, $pos + 8, 4));
                     $char = ($hex << 10) + $surrogate + 0xfca02400;
                     // surrogate offset: 0x10000 - (0xd800 << 10) - 0xdc00
                     return iconv('ucs-4be', $this->encoding, pack('N', $char));
                 } else {
                     $offset = 6;
                     return iconv('ucs-4be', $this->encoding, pack('N', $hex));
                 }
             }
         } else {
             throw new FormatException('Illegal escape sequence \\' . $escape . '...');
         }
     }
 }
Example #17
0
 /**
  * Set default controller
  *
  * @return void
  */
 protected function _set_default_controller()
 {
     if (empty($this->default_controller)) {
         show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
     }
     // Is the method being specified?
     if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) {
         $method = 'index';
     }
     // This is what I added, checks if the class is a directory
     if (is_dir(APPPATH . 'controllers/' . $class)) {
         // Set the class as the directory
         $this->set_directory($class);
         // $method is the class
         $class = $method;
         // Re check for slash if method has been set
         if (sscanf($method, '%[^/]/%s', $class, $method) !== 2) {
             $method = 'index';
         }
     }
     if (!file_exists(APPPATH . 'controllers/' . $this->directory . ucfirst($class) . '.php')) {
         // This will trigger 404 later
         return;
     }
     $this->set_class($class);
     $this->set_method($method);
     // Assign routed segments, index starting from 1
     $this->uri->rsegments = array(1 => $class, 2 => $method);
     log_message('debug', 'No URI present. Default controller set.');
 }
Example #18
0
 /**
  * Статический метод для формирования и получения данных бля боксов
  * @param string $classOpen Класс-css для открытых боксов
  * @param string $classClose Класс-css для закрытых боксов
  * @return array Вернет многомерный массив
  */
 public static function getDataBox($classOpen = null, $classClose = null)
 {
     $databox = [];
     //обнуляем или задаем значения прошлой игры, если пользователь залогинился
     if (isset($_SESSION['bitcoin'])) {
         $_SESSION['claimAmount'] = !empty($_SESSION['claimAmountBefore']) ? $_SESSION['claimAmountBefore'] : 0;
         $_SESSION['bonusMinutes'] = !empty($_SESSION['bonusMinutesBefore']) ? $_SESSION['bonusMinutesBefore'] : 0;
     }
     for ($i = 0; $i < Config::NUM_BOXES; $i++) {
         //проверяем клики
         if (isset($_SESSION['clicksBox']) && in_array($i, $_SESSION['clicksBox'])) {
             $val = $_SESSION['boxes'][$i];
             $class = $classOpen;
             //если выбраны сатоши то пишем в сессию
             if (strpos($val, strtolower(Config::COIN)) !== false) {
                 sscanf($val, '%d %s', $numCA, $str);
                 $_SESSION['claimAmount'] += $numCA;
             }
             //если выбраны бонусы пишем в сессию
             if (strpos($val, 'bonus') !== false) {
                 sscanf($val, '%d %s', $numBM, $str);
                 $_SESSION['bonusMinutes'] += $numBM;
             }
         } else {
             $class = $classClose;
             $val = '';
         }
         $databox[$i] = ['class' => $class, 'val' => $val];
     }
     return $databox;
 }
Example #19
0
function GetAliasList($order = 'login,asc', $customer = NULL, $domain = '')
{
    global $DB;
    list($order, $direction) = sscanf($order, '%[^,],%s');
    $direction != 'desc' ? $direction = 'asc' : ($direction = 'desc');
    switch ($order) {
        case 'id':
            $sqlord = " ORDER BY a.id {$direction}";
            break;
        case 'domain':
            $sqlord = " ORDER BY domain {$direction}, a.login";
            break;
        default:
            $sqlord = " ORDER BY a.login {$direction}, domain";
            break;
    }
    $list = $DB->GetAll('SELECT a.id, a.login, d.name AS domain, domainid, s.accounts, s.forwards, s.cnt 
		FROM aliases a
		JOIN domains d ON (d.id = a.domainid)
		JOIN (SELECT COUNT(*) AS cnt, ' . $DB->GroupConcat('(SELECT ' . $DB->Concat('p.login', "'@'", 'pd.name') . ' 
			FROM passwd p 
			JOIN domains pd ON (p.domainid = pd.id) 
			WHERE p.id = aliasassignments.accountid)') . ' AS accounts, ' . $DB->GroupConcat('CASE WHEN mail_forward <> \'\' THEN mail_forward ELSE NULL END') . ' AS forwards, 
			aliasid 
			FROM aliasassignments GROUP BY aliasid) s ON (a.id = s.aliasid)
		WHERE 1=1' . ($customer != '' ? ' AND d.ownerid = ' . intval($customer) : '') . ($domain != '' ? ' AND a.domainid = ' . intval($domain) : '') . ($sqlord != '' ? $sqlord : ''));
    $list['total'] = sizeof($list);
    $list['order'] = $order;
    $list['customer'] = $customer;
    $list['domain'] = $domain;
    $list['direction'] = $direction;
    return $list;
}
 function timeStrToUnixModB($str)
 {
     // converts YYYY-MM-DD HH:MM:SS (MySQL TimeStamp) to unix timestamp
     sscanf($str, "%4u-%2u-%2u %2u:%2u:%2u", $year, $month, $day, $hour, $min, $sec);
     $newtstamp = mktime($hour, $min, $sec, $month, $day, $year);
     return $newtstamp;
 }
Example #21
0
 function mitterTimeToSeconds($str_time)
 {
     $str_time = preg_replace("/^([\\d]{1,2})\\:([\\d]{2})\$/", "00:\$1:\$2", $str_time);
     sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
     $time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
     return $time_seconds;
 }
 /**
  * Read a string
  *
  * @param   int limit default 8192
  * @return  string
  */
 public function read($limit = 8192)
 {
     while ($this->in->available() > 0 && strlen($this->buffer) < $limit) {
         $read = $this->in->read($limit);
         $o = 0;
         $s = strlen($read);
         while ($o < $s) {
             $p = strcspn($read, '=', $o);
             $this->buffer .= substr($read, $o, $p);
             if (($o += $p + 1) <= $s) {
                 while ($this->in->available() > 0 && $o > $s - 2) {
                     $read .= $this->in->read(2);
                     $s = strlen($read);
                 }
                 if ("\n" === $read[$o]) {
                     $o += 1;
                 } else {
                     if (1 !== sscanf($h = substr($read, $o, 2), '%x', $c)) {
                         throw new \io\IOException('Invalid byte sequence "=' . $h . '"');
                     }
                     $this->buffer .= chr($c);
                     $o += 2;
                 }
             }
         }
     }
     $chunk = substr($this->buffer, 0, $limit);
     $this->buffer = substr($this->buffer, $limit);
     return $chunk;
 }
Example #23
0
function message_context($messages, $msg)
{
    # Identify current message
    $next = '';
    $previous = '';
    $found = False;
    # Decode current Message
    sscanf($msg, '%4s-%s', $msg_id, $msg_folder);
    # Browse messages
    foreach ($messages as $key => $m) {
        if ($found && $next == '') {
            $next = sprintf('%s-%s', $m['id'], $m['folder']);
            break;
        }
        if ($m['id'] == $msg_id && $m['folder'] == $msg_folder) {
            if (!$found) {
                $message = $m;
                $index = $key;
                $found = True;
            }
        } else {
            if (!$found) {
                $previous = sprintf('%s-%s', $m['id'], $m['folder']);
            }
        }
    }
    # Return results
    return array('found' => $found, 'message' => $message, 'next' => $next, 'previous' => $previous, 'index' => $index);
}
/**
 *  @file adm_Relatorio_Movimento.php
 *  @ingroup adm_rel
 *  @brief <b>Relatório</b> que lista, por empresa, estagiários e taxas associadas para geração dívida da empresa com o CIDE.
 *
 *  Perfil: <b>adm</b><BR>
 *  Método de envio: -<BR>
 *  Método de recepção: GET<BR>
 *  Ações: Imprime relatório de estagiários e taxas, de uma dada empresa em um determinado período.<BR>Este relatório possibilita que ao clicar na linha do estagiário o contrato possa ser modificado. Isso foi adicionado porque é comum a mudança da taxa na hora da impressão.<BR>
 *  Este é executado por adm_Listagem_Movimentos.php.
 */
function formata_data_normal($data) {
	list ( $ano, $mes, $dia ) = sscanf ( $data, "%d-%d-%d" );
	
	$data_formatada = sprintf ( "%02d/%02d/%02d", $dia, $mes, $ano );
	
	return $data_formatada;
}
Example #25
0
function GetCashLog($order = 'time,asc', $regid = 0)
{
    global $DB;
    list($order, $direction) = sscanf($order, '%[^,],%s');
    $direction != 'desc' ? $direction = 'asc' : ($direction = 'desc');
    switch ($order) {
        case 'value':
            $sqlord = " ORDER BY value {$direction}";
            break;
        case 'snapshot':
            $sqlord = " ORDER BY snapshot {$direction}";
            break;
        case 'description':
            $sqlord = " ORDER BY description {$direction}";
            break;
        case 'username':
            $sqlord = " ORDER BY username {$direction}";
            break;
        default:
            $sqlord = " ORDER BY time {$direction}";
            break;
    }
    $list = $DB->GetAll('SELECT cashreglog.id, time, value, description, 
				    snapshot, userid, users.name AS username
			    FROM cashreglog
			    LEFT JOIN users ON (userid = users.id)
			    WHERE regid = ?
			    ' . ($sqlord != '' ? $sqlord : ''), array($regid));
    $list['total'] = sizeof($list);
    $list['order'] = $order;
    $list['direction'] = $direction;
    return $list;
}
Example #26
0
 public function isValid($value)
 {
     if (!is_string($value) && !is_int($value) && !is_float($value) && !is_array($value) && !$value instanceof Zend_Date) {
         $this->_error(self::INVALID);
         return false;
     }
     $this->_setValue($value);
     if ($this->_format !== null || $this->_locale !== null || is_array($value) || $value instanceof Zend_Date) {
         if (!Date::isDate($value, $this->_format, $this->_locale)) {
             if ($this->_checkFormat($value) === false) {
                 $this->_error(self::FALSEFORMAT);
             } else {
                 $this->_error(self::INVALID_DATE);
             }
             return false;
         }
     } else {
         if (!preg_match('/^\\d{4}-\\d{2}-\\d{2}$/', $value)) {
             $this->_format = 'yyyy-MM-dd';
             $this->_error(self::FALSEFORMAT);
             $this->_format = null;
             return false;
         }
         list($year, $month, $day) = sscanf($value, '%d-%d-%d');
         if (!checkdate($month, $day, $year)) {
             $this->_error(self::INVALID_DATE);
             return false;
         } else {
         }
     }
     return true;
 }
Example #27
0
 public function isValid($value)
 {
     // this line populates the "%value%" variables in the error messages
     $this->_setValue($value);
     // check for invalid date format
     $validator = new Validate_Date();
     if (!$validator->isValid($value)) {
         // this line will insert the error message in the list of errors to
         // be returned to the caller
         $this->_error(self::INVALID_DATE);
         return false;
     }
     // check if birthday is $min yrs. ago or greater
     // break up date
     list($year, $month, $day) = sscanf($value, '%d-%d-%d');
     // must compare days and years separately
     $birthday = $month . $day;
     $birthyear = $year;
     $today = date('md');
     $year = date('Y');
     if ($birthyear < $year - $this->_min) {
         return true;
     } else {
         if ($birthyear == $year - $this->_min && $birthday <= $today) {
             return true;
         } else {
             $this->_error(self::TOO_YOUNG);
             return false;
         }
     }
 }
 /**
  * Processes cell value
  *
  * @param   var in
  * @return  var
  * @throws  lang.FormatException
  */
 public function process($in)
 {
     if (1 !== sscanf($in, '%d', $out)) {
         throw new FormatException('Cannot parse "' . $in . '" into an integer');
     }
     return $this->proceed($out);
 }
Example #29
0
 public static function setNextAndPrevURLs(array &$vals, $limit, array $options = null)
 {
     extract((array) $options);
     $order = !empty($order) ? $order : false;
     $query = !empty($query) ? $query : false;
     $field = !empty($field) ? $field : false;
     $maxElements = !empty($maxElements) ? $maxElements : 20;
     $validFields = !empty($validFields) && is_array($validFields) ? $validFields : [];
     $limit = static::limitControl($limit, $maxElements);
     $queryParams = [];
     $queryParams['order'] = $order ? 'desc=' . (trim(strtolower($order)) == 'desc' ? '1' : '0') : '';
     $queryParams['query'] = $query ? 'q=' . trim(htmlspecialchars($query, ENT_QUOTES, 'UTF-8', false)) : '';
     if (static::fieldControl($field, $validFields)) {
         $queryParams['field'] = 'orderby=' . $field;
     }
     $url = '?' . implode('&amp;', array_filter($queryParams));
     if (is_numeric($limit)) {
         $vals['prev_url_n'] = '';
         $vals['next_url_n'] = count($vals['list_a']) == $maxElements ? "{$url}&amp;lim={$maxElements},{$maxElements}" : '';
     } else {
         $limitnext = $limitprev = $maxElements;
         if (2 == sscanf($_GET['lim'], '%d,%d', $a, $b)) {
             $next = $a + $maxElements;
             $prev = $a - $maxElements;
             $limitnext = "{$next},{$maxElements}";
             $limitprev = $prev > 0 ? "{$prev},{$maxElements}" : $maxElements;
         }
         $vals['next_url_n'] = count($vals['list_a']) == $maxElements ? $url . "&amp;lim={$limitnext}" : '';
         $vals['prev_url_n'] = $url . "&amp;lim={$limitprev}";
     }
 }
Example #30
0
 /**
  * @param  array  $params  Request parameters
  * @param  string $method  Request method
  * @param  array  $headers  Request headers
  * @return object|FALSE Returns false on error or the user object on success
  */
 public function check($params, $method, $headers)
 {
     if (!isset($headers['Authorization'])) {
         return false;
     }
     list($jwt) = sscanf($headers['Authorization'], 'Bearer %s');
     if (!$jwt) {
         return false;
     }
     $secret = Phramework::getSetting('jwt', 'secret');
     $algorithm = Phramework::getSetting('jwt', 'algorithm');
     try {
         $token = \Firebase\JWT\JWT::decode($jwt, $secret, [$algorithm]);
         //Call onAuthenticate callback if set
         if (($callback = Manager::getOnCheckCallback()) !== null) {
             call_user_func($callback, $token->data);
         }
         return $token->data;
     } catch (\Exception $e) {
         /*
          * the token was not able to be decoded.
          * this is likely because the signature was not able to be verified (tampered token)
          */
         return false;
     }
 }