Ejemplo n.º 1
1
 /** Creates directory or throws exception on fail
  * @param string $pathname
  * @param int    $mode     Mode in octal
  * @return bool
  */
 public static function create($pathname, $mode = self::MOD_DEFAULT)
 {
     if (strpos($pathname, '/') !== false) {
         $pathname = explode('/', $pathname);
     }
     if (is_array($pathname)) {
         $current_dir = '';
         $create = array();
         do {
             $current_dir = implode('/', $pathname);
             if (is_dir($current_dir)) {
                 break;
             }
             $create[] = array_pop($pathname);
         } while (any($pathname));
         if (any($create)) {
             $create = array_reverse($create);
             $current_dir = implode('/', $pathname);
             foreach ($create as $dir) {
                 $current_dir .= '/' . $dir;
                 if (!is_dir($current_dir)) {
                     if (!($action = @mkdir($current_dir, $mode))) {
                         throw new \System\Error\Permissions(sprintf('Failed to create directory on path "%s" in mode "%s". Please check your permissions.', $current_dir, base_convert($mode, 10, 8)));
                     }
                 }
             }
         }
     } else {
         if (!($action = @mkdir($pathname, $mode, true))) {
             throw new \System\Error\Permissions(sprintf('Failed to create directory on path "%s" in mode "%s". Please check your permissions.', $pathname, base_convert($mode, 10, 8)));
         }
     }
     return $action;
 }
Ejemplo n.º 2
0
 static function get_new()
 {
     try {
         $old_items = static::get_all()->fetch();
     } catch (\System\Error $e) {
         $old_items = array();
     }
     $old = array();
     foreach ($old_items as &$m) {
         $old[] = $m->date->format('sql') . '-' . $m->seoname;
     }
     $items = self::checkout_folder($old);
     if (any($items)) {
         $sums = collect(array('attr', 'md5_sum'), $items, true);
         try {
             $old = static::get_all(array("t0.md5_sum IN ('" . implode("','", $sums) . "')"))->fetch();
         } catch (\System\Error $e) {
             $old = array();
         }
     }
     foreach ($old as $mig) {
         foreach ($items as $key => $nmig) {
             if ($mig->get_checksum() == $nmig->get_checksum()) {
                 if ($mig->status == 'ok') {
                     unset($items[$key]);
                 } else {
                     $items[$key] = $mig;
                 }
             }
         }
     }
     uasort($items, array('self', 'sort'));
     return $items;
 }
Ejemplo n.º 3
0
 function controller_waypoints($args, $output = "inline")
 {
     $location["tr"] = explode(",", $args["tr"]);
     $location["bl"] = explode(",", $args["bl"]);
     $location["tl"] = array($location["tr"][0], $location["bl"][1]);
     $location["br"] = array($location["bl"][0], $location["tr"][1]);
     $location["center"] = array($location["bl"][0] + ($location["tr"][0] - $location["bl"][0]) / 2, $location["bl"][1] + ($location["tr"][1] - $location["bl"][1]) / 2);
     $zoom = any($args["zoom"], 1);
     $yelp = new Yelp();
     $wherestr = "WHERE {NavigationLocation.lat} <= " . mysql_escape_string($location["tr"][0]) . " AND {NavigationLocation.lat} >= " . mysql_escape_string($location["bl"][0]);
     $wherestr .= " AND {NavigationLocation.lon} <= " . mysql_escape_string($location["tr"][1]) . " AND {NavigationLocation.lon} >= " . mysql_escape_string($location["bl"][1]);
     $wherestr .= " AND {NavigationLocation.zoom_min} <= " . mysql_escape_string($zoom) . " AND {NavigationLocation.zoom_max} >= " . mysql_escape_string($zoom);
     $wherestr .= " AND {NavigationLocation.name} != 'mapcenter'";
     $locations_center = $this->conn->load("NavigationLocation", "mapcenter");
     if (empty($locations_center)) {
         $locations_center = new NavigationLocation();
         $locations_center->locationid = "mapcenter";
         $locations_center->name = "mapcenter";
         $locations_center->type = "hidden";
     }
     $locations_center->lat = $location["center"][0];
     $locations_center->lon = $location["center"][1];
     $locations_center->zoom_min = $zoom;
     $locations_center->zoom_max = $zoom;
     $this->conn->save($locations_center);
     $locations_db = $this->conn->select("NavigationLocation", $wherestr);
     $locations_yelp = $yelp->getReviews($location);
     if (is_array($locations_db) && is_array($locations_yelp)) {
         $locations = array_merge($locations_yelp, $locations_db);
     } else {
         $locations = any($locations_db, $locations_yelp);
     }
     $ret = json_encode($locations);
     return $ret;
 }
Ejemplo n.º 4
0
 public static function lookup($hostname)
 {
     self::init();
     Profiler::StartTimer("DNSResolver::lookup()", 2);
     $data = DataManager::singleton();
     $records = $apc = NULL;
     $cachekey = "dnsresolver.lookup.{$hostname}";
     if (self::$cache && !empty($data->caches["apc"]) && $data->caches["apc"]["default"]->enabled) {
         $apc = $data->caches["apc"]["default"];
         $cached = $apc->get($cachekey);
         if ($cached !== false) {
             $records = unserialize($cached);
             Logger::Info("DNSResolver: found '{$hostname}' in APC cache");
         }
     }
     if ($records === NULL) {
         Logger::Info("DNSResolver: Looking up '{$hostname}'");
         foreach (self::$search as $suffix) {
             $fqdn = $hostname . (!empty($suffix) ? "." . $suffix : "");
             $records = dns_get_record($fqdn, DNS_A);
             if (!empty($records)) {
                 break;
             }
         }
         if (self::$cache && !empty($records) && $apc !== NULL && $apc->enabled) {
             $ttl = any(self::$ttl, $records[0]["ttl"]);
             $apc->set($cachekey, serialize($records), array("lifetime" => $ttl));
         }
     }
     Profiler::StopTimer("DNSResolver::lookup()");
     return $records;
 }
 private function _createMessageWithByteCount($bytes)
 {
     $this->_bytes = $bytes;
     $msg = $this->_mock('Swift_Mime_Message');
     $this->_checking(Expectations::create()->ignoring($msg)->toByteStream(any())->calls(array($this, '_write')));
     return $msg;
 }
Ejemplo n.º 6
0
 function controller_account($args)
 {
     if (!User::authorized("mail")) {
         throw new Exception("not allowed");
     }
     $vars["account"] = any($args["account"], $args["item"]);
     return $this->GetComponentResponse("./account.tpl", $vars);
 }
Ejemplo n.º 7
0
 function __construct($locations = NULL)
 {
     $dbdir = any($locations['tmp'], 'tmp');
     if (class_exists("Outlet")) {
         Outlet::init(array('connection' => array('type' => 'datamanager'), 'classes' => array()));
         $this->outlet =& Outlet::getInstance();
     }
 }
Ejemplo n.º 8
0
 public function test_any()
 {
     ensure(any(array(1, 2, 3), function ($v) {
         return $v > 2;
     }));
     ensure(!any(array(1, 2, 3), function ($v) {
         return $v > 4;
     }));
 }
Ejemplo n.º 9
0
 public function controller_irc($args)
 {
     $vars = array();
     $vars["host"] = any($args["host"], array_get($_SESSION, "irc.host"), "irc.freenode.net");
     $vars["port"] = any($args["port"], array_get($_SESSION, "irc.port"), 6667);
     $vars["nick"] = any($args["nick"], array_get($_SESSION, "irc.nickname"), sprintf("peon%04d", rand(0, 9999)));
     array_set($_SESSION, "irc.nickname", $vars["nick"]);
     return $this->GetComponentResponse("./irc.tpl", $vars);
 }
Ejemplo n.º 10
0
 /** @test */
 public function shouldNotRelyOnArryIndexesWhenUnwrappingToASingleResolutionValue()
 {
     $mock = $this->createCallableMock();
     $mock->expects($this->once())->method('__invoke')->with($this->identicalTo(2));
     $d1 = new Deferred();
     $d2 = new Deferred();
     any(['abc' => $d1->promise(), 1 => $d2->promise()])->then($mock);
     $d2->resolve(2);
     $d1->resolve(1);
 }
 /**
  * @test
  */
 public function whenTokenIsExpired()
 {
     require realpath(__DIR__ . '/../../../') . '/etc/app.php';
     $db = $this->createMockDb();
     $user = array_merge($this->createFixtureUser(), array('token_timestamp' => time() - TOKEN_VALID_TIME - 1));
     $db->expects(any())->method('findUserByToken')->will(returnValue($user));
     $checker = $this->createTokenChecker($db);
     $request = $this->createValidRequest();
     $this->assertErrorResponse(403, 'Token expired', $checker($request, $app));
 }
Ejemplo n.º 12
0
 public function testSettingCharsetClearsCache()
 {
     $headers = $this->_createHeaderSet(array(), false);
     $this->_checking(Expectations::create()->ignoring($headers)->toString()->returns("Content-Type: text/plain; charset=utf-8\r\n")->ignoring($headers));
     $cache = $this->_createCache(false);
     $this->_checking(Expectations::create()->one($cache)->clearKey(any(), 'body')->ignoring($cache));
     $entity = $this->_createEntity($headers, $this->_createEncoder(), $cache);
     $entity->setBody("blah\r\nblah!");
     $entity->toString();
     $entity->setCharset('iso-2022');
 }
Ejemplo n.º 13
0
 public function controller_exists($args)
 {
     $vars["usertype"] = any($args["usertype"], "default");
     $vars["userid"] = $args["userid"];
     $user = false;
     if (!empty($vars["userid"])) {
         $user = User::get($vars["usertype"], $vars["userid"]);
     }
     $vars["success"] = !empty($user);
     return $this->GetComponentResponse("./exists.tpl", $vars);
 }
Ejemplo n.º 14
0
 /** Run callbacks
  * @param string $trigger Name of trigger to fier
  * @param array  $args    Data to pass
  * @return void
  */
 public function run_tasks($trigger, array $args = array())
 {
     if (any($this::$callbacks[$trigger])) {
         foreach ($this::$callbacks[$trigger] as $task) {
             if (is_callable(array($this, $task))) {
                 $this->{$task}($args);
             } else {
                 throw new \System\Error\Model(sprintf('Invalid callback "%s" for "%s"', $task, $trigger));
             }
         }
     }
 }
Ejemplo n.º 15
0
 private function compile(array $tokens)
 {
     $cg = (object) ['ts' => TokenStream::fromSlice($tokens), 'parsers' => []];
     traverse(rtoken('/^(T_\\w+)·(\\w+)$/')->onCommit(function (Ast $result) use($cg) {
         $token = $result->token();
         $id = $this->lookupCapture($token);
         $type = $this->lookupTokenType($token);
         $cg->parsers[] = token($type)->as($id);
     }), ($parser = chain(rtoken('/^·\\w+$/')->as('type'), token('('), optional(ls(either(future($parser)->as('parser'), chain(token(T_FUNCTION), parentheses()->as('args'), braces()->as('body'))->as('function'), string()->as('string'), rtoken('/^T_\\w+·\\w+$/')->as('token'), rtoken('/^T_\\w+$/')->as('constant'), rtoken('/^·this$/')->as('this'), label()->as('label'))->as('parser'), token(',')))->as('args'), commit(token(')')), optional(rtoken('/^·\\w+$/')->as('label'), null)))->onCommit(function (Ast $result) use($cg) {
         $cg->parsers[] = $this->compileParser($result->type, $result->args, $result->label);
     }), $this->layer('{', '}', braces(), $cg), $this->layer('[', ']', brackets(), $cg), $this->layer('(', ')', parentheses(), $cg), rtoken('/^···(\\w+)$/')->onCommit(function (Ast $result) use($cg) {
         $id = $this->lookupCapture($result->token());
         $cg->parsers[] = layer()->as($id);
     }), token(T_STRING, '·')->onCommit(function (Ast $result) use($cg) {
         $offset = \count($cg->parsers);
         if (0 !== $this->dominance || 0 === $offset) {
             $this->fail(self::E_BAD_DOMINANCE, $offset, $result->token()->line());
         }
         $this->dominance = $offset;
     }), rtoken('/·/')->onCommit(function (Ast $result) {
         $token = $result->token();
         $this->fail(self::E_BAD_CAPTURE, $token, $token->line());
     }), any()->onCommit(function (Ast $result) use($cg) {
         $cg->parsers[] = token($result->token());
     }))->parse($cg->ts);
     // check if macro dominance '·' is last token
     if ($this->dominance === \count($cg->parsers)) {
         $this->fail(self::E_BAD_DOMINANCE, $this->dominance, $cg->ts->last()->line());
     }
     $this->specificity = \count($cg->parsers);
     if ($this->specificity > 1) {
         if (0 === $this->dominance) {
             $pattern = chain(...$cg->parsers);
         } else {
             /*
               dominat macros are partially wrapped in commit()s and dominance
               is the offset used as the 'event horizon' point... once the entry
               point is matched, there is no way back and a parser error arises
             */
             $prefix = array_slice($cg->parsers, 0, $this->dominance);
             $suffix = array_slice($cg->parsers, $this->dominance);
             $pattern = chain(...array_merge($prefix, array_map(commit::class, $suffix)));
         }
     } else {
         /*
           micro optimization to save one function call for every token on the subject
           token stream whenever the macro pattern consists of a single parser
         */
         $pattern = $cg->parsers[0];
     }
     return $pattern;
 }
Ejemplo n.º 16
0
 /**
  * @test
  */
 public function it_retries_when_processor_throws_exception()
 {
     $inner = $this->createProcessorMock();
     $strategy = $this->createStrategyMock();
     $exception = new \Exception();
     $processor = new RetryProcessor($inner, $strategy);
     $strategy->shouldReceive('retry')->once()->with(any(EnvelopeInterface::class), 2, $exception)->andReturn(true);
     $inner->shouldReceive('process')->once()->andThrow($exception);
     $envelope = $this->createEnvelopeMock(1);
     $envelope->shouldReceive('getDeliveryTag')->andReturnNull();
     $result = $processor->process($envelope);
     $this->assertTrue($result, 'The ->process() method should return the value from the strategy');
 }
Ejemplo n.º 17
0
function smarty_block_set($params, $content, &$smarty)
{
    if (!empty($params["var"])) {
        $mode = any($params["mode"], "set");
        if ($mode == "set") {
            $smarty->varreplace[$params["var"]] = $content;
        } else {
            if ($mode == "append") {
                $smarty->varreplace[$params["var"]] .= $content;
            }
        }
    }
}
Ejemplo n.º 18
0
function hygienize(TokenStream $ts, string $scope) : TokenStream
{
    $ts->reset();
    traverse(either(chain(token(T_STRING, '·unsafe'), parentheses()), either(token(T_VARIABLE)->as('target'), chain(identifier()->as('target'), token(':')), chain(token(T_GOTO), identifier()->as('target')))->onCommit(function (Ast $result) use($scope) {
        (function () use($scope) {
            if ((string) $this !== '$this') {
                $this->value = (string) $this . '·' . $scope;
            }
        })->call($result->target);
    }), any()))->parse($ts);
    $ts->reset();
    return $ts;
}
Ejemplo n.º 19
0
function smarty_block_set($params, $content, &$smarty)
{
    if (!empty($params["var"])) {
        $mode = any($params["mode"], "set");
        $realsmarty = $smarty instanceof Smarty_Internal_Template || $smarty instanceof TemplateManager ? $smarty->parent : $smarty;
        if ($mode == "set") {
            $realsmarty->varreplace[$params["var"]] = $content;
        } else {
            if ($mode == "append") {
                $realsmarty->varreplace[$params["var"]] .= $content;
            }
        }
    }
}
 public function testFirstTransportIsUsed()
 {
     $context = new Mockery();
     $message1 = $context->mock('Swift_Mime_Message');
     $message2 = $context->mock('Swift_Mime_Message');
     $t1 = $context->mock('Swift_Transport');
     $t2 = $context->mock('Swift_Transport');
     $con = $context->states('Connection')->startsAs('off');
     $context->checking(Expectations::create()->ignoring($message1)->ignoring($message2)->allowing($t1)->isStarted()->returns(false)->when($con->is('off'))->allowing($t1)->isStarted()->returns(true)->when($con->is('on'))->one($t1)->start()->when($con->isNot('on'))->then($con->is('on'))->one($t1)->send($message1, optional())->returns(1)->when($con->is('on'))->one($t1)->send($message2, optional())->returns(1)->when($con->is('on'))->ignoring($t1)->never($t2)->start()->never($t2)->send(any(), optional())->ignoring($t2));
     $transport = $this->_getTransport(array($t1, $t2));
     $transport->start();
     $this->assertEqual(1, $transport->send($message1));
     $this->assertEqual(1, $transport->send($message2));
     $context->assertIsSatisfied();
 }
Ejemplo n.º 21
0
 /** Get all users permissions
  * @return array Set of permissions (System\User\Perm)
  */
 public function get_rights()
 {
     if (is_null($this->rights)) {
         if ($this->id) {
             $conds = array("public" => true);
             $ids = collect_ids($this->groups->fetch());
             if (any($ids)) {
                 $conds[] = "id_group IN (" . implode(',', $ids) . ")";
             }
             $this->rights = \System\User\Perm::get_all()->where($conds, "t0", true)->reset_cols()->add_cols(array("trigger", "id_system_user_perm"), "t0")->assoc_with('')->fetch('trigger', 'id_system_user_perm');
         } else {
             $this->rights = array();
         }
     }
     return $this->rights;
 }
Ejemplo n.º 22
0
/**
 * Smarty {get} plugin
 *
 * Type:     function<br>
 * Name:     get<br>
 * Purpose:  Returns the value of a specified object, or from the global replace vars list. 
 *           Optionally fall back on a given default, and optionally wrap in a given HTML tag
 *
 * @author James Baicoianu
 * @param array $args
 * @param Smarty $smarty
 * @return string
 */
function smarty_function_get($params, &$smarty)
{
    if (!empty($params["from"]) && !empty($params["key"])) {
        // Usage: {get key="foo" from=$barray}
        // from can be an object or an array
        $ret = any($params["from"][$params["key"]], $params["from"]->{$params["key"]}, $params["default"], $params["key"]);
    } else {
        if (!empty($params["var"])) {
            // Usage: {get var="search.title"} - returns the requested postprocess var if registered
            $ret = $smarty->varreplace[$params["var"]];
        }
    }
    if (!empty($params["wrap"]) && !empty($ret)) {
        $ret = sprintf("<%s>%s</%s>", $params["wrap"], $ret, $params["wrap"]);
    }
    return $ret;
}
Ejemplo n.º 23
0
 /** Create request object from current hit
  * @return self
  */
 public static function from_hit()
 {
     if (\System\Status::on_cli()) {
         $data = array("time" => def($_SERVER['REQUEST_TIME_FLOAT'], microtime(true)), "cli" => true, "secure" => false);
     } else {
         $data = array("cli" => false, "ajax" => strtolower(def($_SERVER['HTTP_X_REQUESTED_WITH'])) == self::IDENT_XHR, "host" => def($_SERVER['HTTP_HOST']), "path" => def($_SERVER['REQUEST_URI']), "protocol" => def($_SERVER['REQUEST_SCHEME']), "referrer" => def($_SERVER['HTTP_REFERER']), "agent" => def($_SERVER['HTTP_USER_AGENT']), "query" => def($_SERVER['QUERY_STRING']), "time" => def($_SERVER['REQUEST_TIME_FLOAT'], microtime(true)), "secure" => any($_SERVER['HTTPS']), "method" => strtolower(def($_SERVER['REQUEST_METHOD'])), "cookies" => &$_COOKIE, "session" => &$_SESSION);
         if ($data['query']) {
             $path = explode('?', $data['path']);
             $data['path'] = $path[0];
         }
         if (isset($_GET['path'])) {
             $data['path'] = $_GET['path'];
         }
     }
     $obj = new self($data);
     return $obj->prepare_input();
 }
Ejemplo n.º 24
0
/**
 * Smarty {img} plugin
 *
 * Type:     function<br>
 * Name:     img<br>
 * Purpose:  Get the correct image (cobranded, server, etc)
 *
 * @author Ben HOLLAND!!!
 * @param array
 * @param Smarty
 * @return string|null if the assign parameter is passed, Smarty assigns the
 *                     result to a template variable
 */
function smarty_function_img($args, &$smarty)
{
    global $webapp;
    static $heirarchy;
    static $imgcache;
    Profiler::StartTimer("smarty_function_img", 2);
    if ($heirarchy === null) {
        $cfgmgr = ConfigManager::singleton();
        $heirarchy = $cfgmgr->GetConfigHeirarchy("cobrand." . $webapp->cobrand);
    }
    $imagedir = any(DependencyManager::$locations["images"], "htdocs/images");
    $imagedirwww = any(DependencyManager::$locations["imageswww"], "/images");
    if (!empty($args["src"]) && !preg_match("/^https?:/", $args["src"])) {
        if (isset($imgcache[$args["src"]])) {
            $args["src"] = $imgcache[$args["src"]];
        } else {
            $origsrc = $args["src"];
            $found = false;
            foreach ($heirarchy as $cfgname) {
                if (preg_match("/^cobrand\\.(.*)\$/", $cfgname, $m)) {
                    // FIXME - most general-purpose would be to use the cobrand key as imagedir (s/\./\//g?)
                    if (file_exists($imagedir . "/cobrands/{$m[1]}/{$args["src"]}")) {
                        $args["src"] = $imagedirwww . "/cobrands/{$m[1]}/{$args["src"]}";
                        $found = true;
                        break;
                    }
                }
            }
            if (!$found) {
                $args["src"] = $imagedirwww . "/" . $args["src"];
            }
            $imgcache[$origsrc] = $args["src"];
        }
    }
    $ret = "<img ";
    foreach ($args as $k => $v) {
        $ret .= "{$k}=\"{$v}\" ";
    }
    $ret .= "/>";
    Profiler::StopTimer("smarty_function_img");
    if (!empty($args["src"])) {
        return $ret;
    }
}
Ejemplo n.º 25
0
 function &QueryInsert($queryid, $table, $values, $extra = NULL)
 {
     $lifetime = any($args["lifetime"], $this->lifetime, 0);
     $compressed = any($this->compressed, MEMCACHE_COMPRESSED);
     $sdata = serialize($values);
     $key = $table;
     if ($queryid->hash !== NULL && $queryid->hash != $table) {
         $key .= "." . $queryid->hash;
     }
     if ($this->cache) {
         if (!$this->cache->set($key, $sdata, $compressed, $lifetime)) {
             Logger::Error('Failed to set (' . $key . ') in Memcache::setdata');
         } else {
             return true;
         }
     } else {
         Logger::Error("Could not access memcache object for '{$key}'");
     }
     return false;
 }
Ejemplo n.º 26
0
 public function run()
 {
     $ppl = \Workshop\SignUp::get_all(array("solved" => true, "lunch" => true, 'canceled' => false))->add_filter(array("attr" => 'id_assigned_to', "type" => 'is_null', "is_null" => false))->sort_by('name_first, name_last')->fetch();
     $defaults = array('2016-05-14' => array(\Food\Item::find(1), \Food\Item::find(2)), '2016-05-15' => array(\Food\Item::find(5), \Food\Item::find(7)));
     $participants = array();
     $focus = array('2016-05-14', '2016-05-15');
     foreach ($ppl as $person) {
         $days = array();
         foreach ($focus as $date_str) {
             $date = new \DateTime($date_str);
             $days[$date_str] = array("date" => $date->format('d. m. Y'), "items" => array(), 'food' => $defaults[$date->format('Y-m-d')]);
             $food = $person->food->where(array("date" => $date_str))->fetch();
             if (any($food)) {
                 $days[$date_str]['food'] = $food;
             }
         }
         $participants[] = array("days" => $days, "name" => $person->toName());
     }
     $this->partial('stats/participant-lunch', array("participants" => $participants));
 }
Ejemplo n.º 27
0
 public function to_object()
 {
     $containers = null;
     $data = array_merge($this->get_opts(), $this->get_data());
     $data['element'] = $this->get_element_name();
     if (isset($this->elements)) {
         $containers = array();
         foreach ($this->elements as $obj) {
             $containers[] = $obj->to_object();
         }
     }
     if (any($containers)) {
         $data['elements'] = $containers;
     }
     foreach ($data as $key => $value) {
         if (is_null($value)) {
             unset($data[$key]);
         }
     }
     return $data;
 }
Ejemplo n.º 28
0
 /** Ask if user has right to do this
  * @param string      $method One of created, browsed
  * @param System\User $user   User to get perms for
  * @return bool
  */
 public static function can_user($method, \System\User $user)
 {
     if ($user->is_root()) {
         return true;
     }
     $cname = get_called_class();
     $conds = array();
     if (isset($cname::$access) && isset($cname::$access[$method]) && !is_null($cname::$access[$method])) {
         return !!$cname::$access[$method];
     }
     if ($user->is_guest()) {
         $conds['public'] = true;
     } else {
         $groups = $user->get_groups();
         if (any($groups)) {
             $conds[] = 'id_group IN (' . implode(',', collect_ids($groups)) . ')';
         }
     }
     $perm = \System\User\Perm::get_first()->add_filter(array('attr' => 'trigger', 'type' => 'in', 'in' => array('model-' . $method, '*')))->add_filter(array('attr' => 'name', 'type' => 'in', 'in' => array(\System\Loader::get_model_from_class($cname) . \System\Loader::SEP_MODEL . $method, '*')))->where($conds)->fetch();
     return $perm ? $perm->allow : static::get_default_for($method);
 }
Ejemplo n.º 29
0
 function controller_deepzoom($args, $output = "inline")
 {
     $response = $this->GetComponentResponse("./deepzoom.tpl");
     $response["args"] = $args;
     $response["imgname"] = any($args["img"], "webtrendsmap");
     $response["defaultlevel"] = any($args["defaultlevel"], 0);
     if (!empty($response["imgname"])) {
         $response["xmlpath"] = $this->imagedir . "/" . $response["imgname"] . ".xml";
         if (!empty($args["url"])) {
             $pinfo = pathinfo($args["url"]);
             $response["fileext"] = $pinfo["extension"];
             $response["filename"] = $response["imgname"] . "." . $response["fileext"];
             $response["filepath"] = $this->imagedir . "/originals/" . $response["filename"];
             if (!file_exists($response["filepath"])) {
                 print "Downloading file...";
                 flush();
                 $contents = file_get_contents($args["url"]);
                 if (!empty($contents)) {
                     file_put_contents($response["filepath"], $contents);
                 }
                 print "done.\n";
             }
             if (!file_exists($response["xmlpath"])) {
                 $converter = new Oz_Deepzoom_ImageCreator(256, 1, any($args["outputext"], $response["fileext"]));
                 $converter->create(realpath($response["filepath"]), $this->imagedir . '/' . $response["imgname"] . '.xml', true);
             }
         }
         if (file_exists($response["xmlpath"])) {
             $defaultdomain = "{random}.tiles2.supcrit.net";
             //$defaultdomain = "localhost";
             $img = new SimpleXMLElement(file_get_contents($response["xmlpath"]));
             if (!empty($img)) {
                 $response["fileext"] = (string) $img["Format"];
                 $response["imgdata"] = array("size" => array((int) $img->Size["Width"], (int) $img->Size["Height"]), "tilesize" => (int) $img["TileSize"], "overlap" => (int) $img["Overlap"], "url" => !empty($img["Url"]) ? (string) $img["Url"] : sprintf("http://%s/images/components/supercritical/deepzoom/%s_files/{level}/{column}_{row}.%s", $defaultdomain, $response["imgname"], $response["fileext"]));
             }
         }
     }
     //return $this->GetTemplate("./deepzoom.tpl", $vars);
     return $response;
 }
Ejemplo n.º 30
0
/**
 * Smarty {box}{/box} block plugin
 *
 * Type:     block function<br>
 * Name:     box<br>
 * Purpose:  Generate the HTML structure needed for boxes<br>
 *
 * @param array
 * <pre>
 * Params:   id: string
 *           tag: string (div)
 *           class: string
 * </pre>
 * @param string contents of the block
 * @param Smarty clever simulation of a method
 * @return string string $content re-formatted
 */
function smarty_block_box($params, $content, &$smarty)
{
    $null = NULL;
    $placement = any($params["placement"], "default");
    $type = any($params["type"], ConfigManager::get("page.box.placements.{$placement}.type"), "default");
    $typecfg = any(ConfigManager::get("page.box.types.{$type}"), array());
    $placementcfg = any(ConfigManager::get("page.box.placements.{$placement}"), array());
    $typecfg["template"] = any($params["template"], $typecfg["template"], "box_default.tpl");
    $params = array_merge(any($params, array()), any($typecfg["params"], array()), any($placementcfg["params"], array()));
    $vars["box"] = $box = new stdClass();
    $vars["box"]->content = !empty($content) ? $content : "";
    $vars["box"]->tag = !empty($params["tag"]) ? $params["tag"] : "div";
    $vars["box"]->id = !empty($params["id"]) ? $params["id"] : NULL;
    $vars["box"]->class = !empty($params["class"]) ? $params["class"] : NULL;
    $vars["box"]->onmouseover = !empty($params["onmouseover"]) ? $params["onmouseover"] : NULL;
    $vars["box"]->onmouseout = !empty($params["onmouseout"]) ? $params["onmouseout"] : NULL;
    $vars["box"]->onclick = !empty($params["onclick"]) ? $params["onclick"] : NULL;
    if ($smarty->template_exists("boxes/{$typecfg["template"]}")) {
        return $smarty->GetTemplate("boxes/{$typecfg["template"]}", $null, $vars);
    } else {
        return '<' . $box->tag . (!empty($box->id) ? ' id="' . $box->id . '"' : '') . (!empty($box->class) ? ' class="' . $box->class . '"' : '') . (!empty($box->onmouseover) ? ' onmouseover="' . $box->onmouseover . '"' : '') . (!empty($box->onmouseout) ? ' onmouseout="' . $box->onmouseout . '"' : '') . (!empty($box->onclick) ? ' onclick="' . $box->onclick . '"' : '') . '>' . $box->content . '</' . $box->tag . '>';
    }
}