Example #1
1
function yay_parse(string $source, Directives $directives = null, BlueContext $blueContext = null) : string
{
    if ($gc = gc_enabled()) {
        gc_disable();
    }
    // important optimization!
    static $globalDirectives = null;
    if (null === $globalDirectives) {
        $globalDirectives = new ArrayObject();
    }
    $directives = $directives ?: new Directives();
    $blueContext = $blueContext ?: new BlueContext();
    $cg = (object) ['ts' => TokenStream::fromSource($source), 'directives' => $directives, 'cycle' => new Cycle($source), 'globalDirectives' => $globalDirectives, 'blueContext' => $blueContext];
    foreach ($cg->globalDirectives as $d) {
        $cg->directives->add($d);
    }
    traverse(midrule(function (TokenStream $ts) use($directives, $blueContext) {
        $token = $ts->current();
        tail_call:
        if (null === $token) {
            return;
        }
        // skip when something looks like a new macro to be parsed
        if ('macro' === (string) $token) {
            return;
        }
        // here we do the 'magic' to match and expand userland macros
        $directives->apply($ts, $token, $blueContext);
        $token = $ts->next();
        goto tail_call;
    }), consume(chain(token(T_STRING, 'macro')->as('declaration'), optional(repeat(rtoken('/^·\\w+$/')))->as('tags'), lookahead(token('{')), commit(chain(braces()->as('pattern'), operator('>>'), braces()->as('expansion')))->as('body'), optional(token(';'))), CONSUME_DO_TRIM)->onCommit(function (Ast $macroAst) use($cg) {
        $scope = Map::fromEmpty();
        $tags = Map::fromValues(array_map('strval', $macroAst->{'tags'}));
        $pattern = new Pattern($macroAst->{'declaration'}->line(), $macroAst->{'body pattern'}, $tags, $scope);
        $expansion = new Expansion($macroAst->{'body expansion'}, $tags, $scope);
        $macro = new Macro($tags, $pattern, $expansion, $cg->cycle);
        $cg->directives->add($macro);
        // allocate the userland macro
        // allocate the userland macro globally if it's declared as global
        if ($macro->tags()->contains('·global')) {
            $cg->globalDirectives[] = $macro;
        }
    }))->parse($cg->ts);
    $expansion = (string) $cg->ts;
    if ($gc) {
        gc_enable();
    }
    return $expansion;
}
Example #2
0
 public function execute(callable $next)
 {
     $this->application->getProvider()->register();
     config()->parseDir(path('app'));
     chain([Localize::class]);
     return $next();
 }
Example #3
0
 private function layer(string $start, string $end, Parser $parser, $cg) : Parser
 {
     return chain(token($start), rtoken('/^···(\\w+)$/')->as('label'), commit(token($end)))->onCommit(function (Ast $result) use($parser, $cg) {
         $id = $this->lookupCapture($result->label);
         $cg->parsers[] = (clone $parser)->as($id);
     });
 }
Example #4
0
 public function chain($chain)
 {
     if (!is_array($chain)) {
         $chain = [$chain];
     }
     return chain($chain);
 }
Example #5
0
function chain($baseItem, $items=array()) {
	if(!empty($items) && !empty($baseItem)) {
		return chain($baseItem->{f_first($items)}, f_rest($items));	
		//D::show('$baseItem->' . join('->', $items) . ';');
		//return eval('$baseItem->' . join('->', $items) . ';') ?: null;
	} else {
		return $baseItem;
	}
}
Example #6
0
 function test_two()
 {
     $f = $this->f();
     $g = $this->g();
     $c = chain($f, $g);
     $x = 3;
     // sanity check
     $this->assertTrue($g($f($x)) === ($x + 1) * 2);
     $this->assertTrue($g($f($x)) === $c($x));
 }
Example #7
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;
}
Example #8
0
 public function execute(callable $next)
 {
     try {
         /**
          * First argument is always 'console'.
          * Second argument is app name or command.
          * If it's command, we leave things as they are.
          * Id it's app, we unset it.
          */
         $argv = $_SERVER['argv'];
         /**
          * Remove application name.
          */
         if (isset($argv[1]) && !strpos($argv[1], ':')) {
             unset($argv[1]);
         }
         /**
          * Remove platform name.
          */
         if (isset($argv[2]) && !strpos($argv[2], ':') && false === strpos($argv[2], '-')) {
             unset($argv[2]);
         }
         /**
          * Get Symfony Console Application, find available commands and run app.
          */
         $application = context()->get(SymfonyConsole::class);
         try {
             /**
              * Apply global middlewares.
              */
             if ($middlewares = $this->response->getMiddlewares()) {
                 chain($middlewares, 'execute');
             }
             $application->run(new ArgvInput(array_values($argv)));
             /**
              * Apply global afterwares/decorators.
              */
             if ($afterwares = $this->response->getAfterwares()) {
                 chain($afterwares, 'execute', [$this->response]);
             }
         } catch (Throwable $e) {
             die("EXCEPTION: " . exception($e));
         }
         /**
          * This is here just for better readability. =)
          */
         echo "\n";
     } catch (Throwable $e) {
     }
     return $next();
 }
Example #9
0
 /**
  * @param $method
  * @param $args
  *
  * @return self
  */
 public function __call($method, $args)
 {
     $overloadMethod = 'overload' . ucfirst($method);
     $handlers = [];
     foreach ($this->getServices() as $service) {
         if (in_array($method, $service->getMethods())) {
             $handlers[] = $service;
         }
     }
     $context = $this->createContext();
     $context->setArgs($args);
     $result = chain($handlers, $overloadMethod, ['context' => $context], function () {
         return $this;
     });
     return $result;
 }
Example #10
0
function hygienize(TokenStream $ts, array $context) : TokenStream
{
    $ts->reset();
    $cg = (object) ['node' => null, 'context' => $context, 'ts' => $ts];
    $saveNode = function (Parser $parser) use($cg) {
        return midrule(function ($ts) use($cg, $parser) {
            $cg->node = $ts->index();
            return $parser->parse($ts);
        });
    };
    traverse(chain(token(T_STRING, '··unsafe'), either(parentheses(), braces())), either($saveNode(token(T_VARIABLE)), chain($saveNode(identifier()), token(':')), chain(token(T_GOTO), $saveNode(identifier())))->onCommit(function (Ast $result) use($cg) {
        if (($t = $cg->node->token) && ($value = (string) $t) !== '$this') {
            $cg->node->token = new Token($t->type(), "{$value}·{$cg->context['scope']}", $t->line());
        }
    }))->parse($ts);
    $ts->reset();
    return $ts;
}
 /**
  * @param $method
  * @param $args
  *
  * @return $this|mixed|null|object
  * @throws NotFound
  */
 public function __call($method, $args)
 {
     if (isset($args[0]) && $args[0] instanceof AbstractObject) {
         $arg = $args[0];
     } else {
         $arg = new AbstractObject();
         $arg->setArgs($args);
     }
     $arrChains = [];
     foreach ($this->validators as $validator) {
         if ($validator->canHandle($method)) {
             $arrChains[] = $validator;
         }
     }
     if (!$arrChains) {
         throw new Exception('Method ' . $method . " doesn't exist in " . get_class($this) . " (AbstractGroupValidator::__call)");
     }
     $result = chain($arrChains, $method, ['context' => $arg]);
     if ($result === true) {
         return $this;
     }
     return $result;
 }
Example #12
0
<?php

require_once "reasoner.php";
$kb = new KBase();
$kb->addFact("hasChild", array('A', 'B'));
$kb->addFact("hasChild", array('A', 'C'));
$kb->addFact("hasChild", array('B', 'I'));
$kb->addFact("hasChild", array('C', 'D'));
$kb->addFact("hasChild", array('E', 'F'));
$kb->addFact("hasChild", array('E', 'G'));
$kb->addFact("hasChild", array('H', 'A'));
$kb->addRule(chain('hasDesc', array('hasChild')));
$kb->addRule(chain('hasDesc', array('hasChild', 'hasDesc')));
$kb->addRule(grule(term('hasAnc', 'A', 'B'), array(term('hasDesc', 'B', 'A'))));
if ($kb->isTrue('hasAnc', array('D', 'H'))) {
    echo "true\n";
} else {
    echo "false\n";
}
$kb->setEqual('H', 'E');
/*
H = E
hasChild E A
hasChild H F
hasChild H G
hasChild H A
*/
if ($kb->isTrue('hasAnc', array('D', 'E'))) {
    echo "true\n";
} else {
    echo "false\n";
Example #13
0
 $content = "\n<!--swmenufree5.0_J1.5 " . $menustyle . " by http://www.swmenupro.com-->\n";
 if ($menu && $id && $menustyle) {
     //echo($menu);
     $final_menu = array();
     $swmenufree_array = swGetMenuLinks($menu, $id, $hybrid, 1);
     $ordered = chain('ID', 'PARENT', 'ORDER', $swmenufree_array, $parent_id, $levels);
     $moduleid = JRequest::getVar('moduleID', array(0));
     $menutype = JRequest::getVar('menutype', '');
     $swmenufree['position'] = "center";
     for ($i = 0; $i < count($ordered); $i++) {
         $swmenu = $ordered[$i];
         $swmenu['URL'] = "javascript:void(0)";
         $final_menu[] = array("TITLE" => $swmenu['TITLE'], "URL" => $swmenu['URL'], "ID" => $swmenu['ID'], "PARENT" => $swmenu['PARENT'], "ORDER" => $swmenu['ORDER'], "TARGET" => 0, "ACCESS" => $swmenu['ACCESS']);
     }
     if (count($final_menu)) {
         $ordered = chain('ID', 'PARENT', 'ORDER', $final_menu, $parent_id, $levels);
         if ($menustyle == "mygosumenu") {
             $content .= doGosuMenuPreview($ordered, $swmenufree, $active_menu, $css_load, $selectbox_hack, $padding_hack);
         }
         if ($menustyle == "tigramenu") {
             $content .= doTigraMenuPreview($ordered, $swmenufree, $active_menu, $css_load, $selectbox_hack);
         }
         if ($menustyle == "transmenu") {
             $content .= doTransMenuPreview($ordered, $swmenufree, $active_menu, $sub_indicator, $parent_id, $css_load, 0, $show_shadow, $auto_position, $padding_hack, $overlay_hack = 1);
         }
         if ($menustyle == "superfishmenu") {
             $content .= doSuperfishMenuPreview($ordered, $swmenufree, $active_menu, $css_load, $selectbox_hack, $padding_hack, $sub_active = 0, $show_shadow, $sub_indicator, $overlay_hack = 1);
         }
     }
 }
 $content .= "\n<!--End swmenufree menu module-->\n";
Example #14
0
 function testastNestedAst()
 {
     $ts = TokenStream::fromSource('<?php
         interface Foo
         {
             public abstract function foo();
             public abstract static function bar();
             function baz();
         }
     ');
     $modifier = either(token(T_PUBLIC), token(T_STATIC), token(T_PRIVATE));
     $modifiers = optional(either(chain($modifier, $modifier), $modifier));
     $ast = chain(token(T_OPEN_TAG), chain(token(T_INTERFACE), token(T_STRING)->as('name'), token('{'), optional(repeat(chain(optional(either(repeat(either(token(T_PUBLIC)->as('public'), token(T_STATIC)->as('static'), token(T_ABSTRACT)->as('abstract'))), always(new Token(T_PUBLIC, 'public'))->as('public')))->as('is'), token(T_FUNCTION), token(T_STRING)->as('name'), token('('), token(')'), token(';')), token('}')))->as('methods'), token('}'))->as('interface'))->parse($ts);
     $this->assertEquals('Foo', (string) $ast->{'interface name'});
     $this->assertEquals('foo', (string) $ast->{'interface methods 0 name'});
     $this->assertEquals('public', (string) $ast->{'interface methods 0 is public'});
     $this->assertEquals('abstract', (string) $ast->{'interface methods 0 is abstract'});
     $this->assertEmpty($ast->{'interface methods 0 is static'});
     $this->assertEquals('bar', (string) $ast->{'interface methods 1 name'});
     $this->assertEquals('public', (string) $ast->{'interface methods 1 is public'});
     $this->assertEquals('abstract', (string) $ast->{'interface methods 1 is abstract'});
     $this->assertEquals('static', (string) $ast->{'interface methods 1 is static'});
     $this->assertEquals('baz', (string) $ast->{'interface methods 2 name'});
     $this->assertEquals('public', (string) $ast->{'interface methods 2 is public'});
     $this->assertNull($ast->{'interface methods 2 is abstract'});
     $this->assertNull($ast->{'interface methods 2 is static'});
 }
Example #15
0
function sw_getsubmenu($ordered, $parent_level, $levels, $menu)
{
    global $Itemid;
    $option2 = trim(JRequest::getVar('option', 0));
    $id = trim(JRequest::getVar('id', 0));
    $i = 0;
    $indent = 0;
    $menudisplay = 0;
    $parent = 1;
    if ($menu == "swcontentmenu" && $option2 == "com_content" && $id) {
        $parent_value = $id;
    } elseif ($menu == "swcontentmenu") {
        $parent = 0;
    } else {
        $parent_value = $Itemid;
        $menudisplay = 0;
        $parent = 1;
    }
    $id = 0;
    //echo "parent ".$parent_value;
    while ($parent) {
        foreach ($ordered as $row) {
            if ($row['ID'] == $parent_value || $row['ID'] == $parent_value + 1000 || $row['ID'] == $parent_value + 10000) {
                $parent_value = $row['PARENT'];
                $indent = $row['indent'];
                $id = $row['ID'];
            }
        }
        if ($indent == $parent_level) {
            $parent = 0;
            $id = $parent_value;
        } elseif ($indent == $parent_level - 1) {
            $parent = 0;
            //$id=$parent_value;
        } elseif ($indent < $parent_level - 1) {
            $parent = 0;
            if ($parent_level == 2) {
                $id = $id;
            } else {
                $id = 0;
            }
        }
        $i++;
        if ($i > $levels) {
            $parent = 0;
        }
    }
    for ($i = 0; $i < count($ordered); $i++) {
        $row = $ordered[$i];
        if ($row['PARENT'] == $id && $row['indent'] == $parent_level) {
            $menudisplay = 1;
        }
        if ($row['PARENT'] == $id - 1000) {
            $menudisplay = 1;
        }
        if ($row['indent'] == 0) {
            $ordered[$i]['PARENT'] = 0;
        }
    }
    if ($menudisplay) {
        $ordered = chain('ID', 'PARENT', 'ORDER', $ordered, $id, $levels);
        $ordered[0]['mid'] = $id;
    } else {
        $ordered = array();
    }
    return $ordered;
}
Example #16
0
 public function init()
 {
     chain($this->initArray());
     return $this;
 }
Example #17
0
 /**
  * @param $key
  *
  * @return null
  */
 public function __get($key)
 {
     /**
      * Return value via getter
      */
     if (method_exists($this, 'get' . Convention::toPascal($key) . 'Attribute')) {
         return $this->{'get' . Convention::toPascal($key) . 'Attribute'}();
     }
     /**
      * Return value, even if it's null or not set.
      */
     if ($this->keyExists($key)) {
         return $this->getValue($key);
     }
     /**
      * Return value from existing relation (Collection or Record).
      */
     if ($this->relationExists($key)) {
         return $this->getRelation($key);
     }
     /**
      * @T00D00 - Entity is needed here just for cache, optimize this ... :/
      *         $Reflection = new ReflectionProperty(get_class($a), 'a');
      */
     $entity = $this->getEntity();
     if ($entity->getRepository()->getCache()->tableHasField($entity->getTable(), $key)) {
         return $this->getValue($key);
     }
     /**
      * Return value from empty relation.
      *
      * @T00D00 - optimize this
      */
     if (method_exists($entity, $key)) {
         $relation = $entity->{$key}();
         $relation->fillRecord($this);
         return $this->getRelation($relation->getFill());
     }
     /**
      * Return value from extension.
      */
     if ($chains = $this->getEntityChains($entity, $key, '__get')) {
         return chain($chains);
     }
     return null;
 }
Example #18
0
 private function mutate(TokenStream $ts, Ast $context, Cycle $cycle, Directives $directives, BlueContext $blueContext) : TokenStream
 {
     if ($this->constant) {
         return $ts;
     }
     static $states, $parser;
     $states = $states ?? new Stack();
     $parser = $parser ?? traverse(token(Token::CLOAKED), consume(chain(rtoken('/^··\\w+$/')->as('expander'), either(parentheses(), braces())->as('args')))->onCommit(function (Ast $result) use($states) {
         $cg = $states->current();
         $expander = $result->expander;
         if (\count($result->args) === 0) {
             $cg->this->fail(self::E_EMPTY_EXPANDER_SLICE, (string) $expander, $expander->line());
         }
         $context = Map::fromKeysAndValues(['scope' => $cg->cycle->id(), 'directives' => $cg->directives, 'blueContext' => $cg->blueContext]);
         $expansion = TokenStream::fromSlice($result->args);
         $mutation = $cg->this->mutate(clone $expansion, $cg->context, $cg->cycle, $cg->directives, $cg->blueContext);
         $mutation = $cg->this->lookupExpander($expander)($mutation, $context);
         $cg->ts->inject($mutation);
     }), consume(chain(rtoken('/^·\\w+|···\\w+$/')->as('label'), operator('···'), optional(parentheses()->as('delimiters')), braces()->as('expansion')))->onCommit(function (Ast $result) use($states) {
         $cg = $states->current();
         $context = $cg->this->lookupContext($result->label, $cg->context, self::E_UNDEFINED_EXPANSION);
         $expansion = TokenStream::fromSlice($result->expansion);
         $delimiters = $result->delimiters;
         // normalize single context
         if (array_values($context) !== $context) {
             $context = [$context];
         }
         foreach (array_reverse($context) as $i => $subContext) {
             $mutation = $cg->this->mutate(clone $expansion, (new Ast(null, $subContext))->withParent($cg->context), $cg->cycle, $cg->directives, $cg->blueContext);
             if ($i !== 0) {
                 foreach ($delimiters as $d) {
                     $mutation->push($d);
                 }
             }
             $cg->ts->inject($mutation);
         }
     }), consume(rtoken('/^(T_\\w+·\\w+|·\\w+|···\\w+)$/')->as('label'))->onCommit(function (Ast $result) use($states) {
         $cg = $states->current();
         $context = $cg->this->lookupContext($result->label, $cg->context, self::E_UNDEFINED_EXPANSION);
         if ($context instanceof Token) {
             $cg->ts->inject(TokenStream::fromSequence($context));
         } elseif (is_array($context) && \count($context)) {
             $tokens = [];
             array_walk_recursive($context, function (Token $token) use(&$tokens) {
                 $tokens[] = $token;
             });
             $cg->ts->inject(TokenStream::fromSlice($tokens));
         }
     }));
     $cg = (object) ['ts' => $ts, 'context' => $context, 'directives' => $directives, 'cycle' => $cycle, 'this' => $this, 'blueContext' => $blueContext];
     $states->push($cg);
     $parser->parse($cg->ts);
     $states->pop();
     $cg->ts->reset();
     if ($this->cloaked) {
         traverse(consume(token(Token::CLOAKED))->onCommit(function (Ast $result) use($cg) {
             $cg->ts->inject(TokenStream::fromSourceWithoutOpenTag((string) $result->token()));
         }))->parse($cg->ts);
         $cg->ts->reset();
     }
     return $cg->ts;
 }
Example #19
0
 public function provideTestAssertIterableFails()
 {
     (yield [function () {
         _assertIterable(new \stdClass(), 'Argument');
     }, 'Argument must be iterable']);
     (yield [function () {
         _assertIterable("foobar", 'Argument');
     }, 'Argument must be iterable']);
     (yield [function () {
         _assertAllIterable([[], new \stdClass()]);
     }, 'Argument 2 must be iterable']);
     (yield [function () {
         return count(new \stdClass());
     }, 'Argument must be iterable or implement Countable']);
     (yield [function () {
         return toIter(new \stdClass());
     }, 'Argument must be iterable']);
     (yield [function () {
         return map(function ($v) {
             return $v;
         }, new \stdClass());
     }, 'Second argument must be iterable']);
     (yield [function () {
         return chain([1], [2], new \stdClass());
     }, 'Argument 3 must be iterable']);
     (yield [function () {
         return zip([1], [2], new \stdClass());
     }, 'Argument 3 must be iterable']);
 }
Example #20
0
 public function run()
 {
     chain($this->runs(), 'execute', [$this]);
     return $this;
 }
Example #21
0
     }
     if ($active_menu && !$parent_level) {
         $active_menu = sw_getactive($ordered);
         $ordered = chain('ID', 'PARENT', 'ORDER', $ordered, $parent_id, $levels);
     }
 }
 if (count($ordered) && $swmenupro['orientation'] == 'horizontal/left') {
     $topcount = count(chain('ID', 'PARENT', 'ORDER', $ordered, $parent_id, 1));
     for ($i = 0; $i < count($ordered); $i++) {
         $swmenu = $ordered[$i];
         if ($swmenu['indent'] == 0) {
             $ordered[$i]['ORDER'] = $topcount;
             $topcount--;
         }
     }
     $ordered = chain('ID', 'PARENT', 'ORDER', $ordered, $parent_id, $levels);
 }
 if (count($ordered)) {
     if ($menustyle == "clickmenu") {
         $content .= doClickMenu($ordered, $swmenupro, $css_load, $active_menu, $selectbox_hack, $padding_hack);
     }
     if ($menustyle == "treemenu") {
         $content .= doTreeMenu($ordered, $swmenupro, $css_load, $active_menu, $auto_position);
     }
     if ($menustyle == "popoutmenu") {
         $content .= doPopoutMenu($ordered, $swmenupro, $css_load, $active_menu);
     }
     if ($menustyle == "gosumenu" && $editor_hack) {
         $content .= doGosuMenu($ordered, $swmenupro, $active_menu, $css_load, $selectbox_hack, $padding_hack, $auto_position);
     }
     if ($menustyle == "transmenu") {
function do_articles()
{
    global $context, $txt, $settings, $boardurl, $scripturl, $smcFunc;
    // do an update of stray articles and categories
    $acats = array();
    $request = $smcFunc['db_query']('', '
		SELECT id FROM {db_prefix}tp_variables 
		WHERE type = {string:type}', array('type' => 'category'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $acats[] = $row['id'];
        }
        $smcFunc['db_free_result']($request);
    }
    if (count($acats) > 0) {
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}tp_variables 
			SET value2 = {int:val2} 
			WHERE type = {string:type} 
			AND value2 NOT IN ({array_string:value2})', array('val2' => 0, 'type' => 'category', 'value2' => $acats));
        $smcFunc['db_query']('', '
			UPDATE {db_prefix}tp_articles 
			SET category = {int:cat} 
			WHERE category NOT IN({array_int:category}) 
			AND category > 0', array('cat' => 0, 'category' => $acats));
    }
    // first check any ajax stuff
    if (isset($_GET['arton'])) {
        checksession('get');
        $what = is_numeric($_GET['arton']) ? $_GET['arton'] : '0';
        if ($what > 0) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET off = IF(off = 0 , 1, 0) 
				WHERE id = {int:artid}', array('artid' => $what));
        } else {
            return;
        }
    } elseif (isset($_GET['artlock'])) {
        checksession('get');
        $what = is_numeric($_GET['artlock']) ? $_GET['artlock'] : '0';
        if ($what > 0) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET locked = IF(locked = 0 , 1, 0) 
				WHERE id = {int:artid}', array('artid' => $what));
        } else {
            return;
        }
    } elseif (isset($_GET['artsticky'])) {
        checksession('get');
        $what = is_numeric($_GET['artsticky']) ? $_GET['artsticky'] : '0';
        if ($what > 0) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET sticky = IF(sticky = 0 , 1, 0) 
				WHERE id = {int:artid}', array('artid' => $what));
        } else {
            return;
        }
    } elseif (isset($_GET['artfront'])) {
        checksession('get');
        $what = is_numeric($_GET['artfront']) ? $_GET['artfront'] : '0';
        if ($what > 0) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET frontpage = IF(frontpage = 0 , 1, 0) 
				WHERE id = {int:artid}', array('artid' => $what));
        } else {
            return;
        }
    } elseif (isset($_GET['artfeat'])) {
        checksession('get');
        $what = is_numeric($_GET['artfeat']) ? $_GET['artfeat'] : '0';
        if ($what > 0) {
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET featured = IF(featured = 0, 1, 0) 
				WHERE id = {int:artid}', array('artid' => $what));
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET featured = {int:featured} 
				WHERE id != {int:artid}', array('featured' => 0, 'artid' => $what));
        } else {
            return;
        }
    } elseif (isset($_GET['catdelete'])) {
        checksession('get');
        $what = is_numeric($_GET['catdelete']) ? $_GET['catdelete'] : '0';
        if ($what > 0) {
            // first get info
            $request = $smcFunc['db_query']('', '
				SELECT id, value2 FROM {db_prefix}tp_variables 
				WHERE id = {int:varid} LIMIT 1', array('varid' => $what));
            $row = $smcFunc['db_fetch_assoc']($request);
            $smcFunc['db_free_result']($request);
            $newcat = !empty($row['value2']) ? $row['value2'] : 0;
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_variables 
				SET value2 = {int:val2} 
				WHERE value2 = {int:varid}', array('val2' => $newcat, 'varid' => $what));
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}tp_variables 
				WHERE id = {int:varid}', array('varid' => $what));
            $smcFunc['db_query']('', '
				UPDATE {db_prefix}tp_articles 
				SET category = {int:cat} 
				WHERE category = {int:catid}', array('cat' => $newcat, 'catid' => $what));
            redirectexit('action=tpadmin;sa=categories');
        } else {
            redirectexit('action=tpadmin;sa=categories');
        }
    } elseif (isset($_GET['artdelete'])) {
        checksession('get');
        $what = is_numeric($_GET['artdelete']) ? $_GET['artdelete'] : '0';
        $cu = is_numeric($_GET['cu']) ? $_GET['cu'] : '';
        if ($cu == -1) {
            $strays = true;
            $cu = '';
        }
        if ($what > 0) {
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}tp_articles 
				WHERE id = {int:artid}', array('artid' => $what));
            $smcFunc['db_query']('', '
				DELETE FROM {db_prefix}tp_variables
				WHERE value5 = {int:artid}', array('artid' => $what));
        }
        redirectexit('action=tpadmin' . (!empty($cu) ? ';cu=' . $cu : '') . (isset($strays) ? ';sa=strays' . $cu : ';sa=articles'));
    }
    // for the non-category articles, do a count.
    $request = $smcFunc['db_query']('', '
		SELECT COUNT(*) as total
		FROM {db_prefix}tp_articles
		WHERE category = 0 OR category = 9999');
    $row = $smcFunc['db_fetch_assoc']($request);
    $context['TPortal']['total_nocategory'] = $row['total'];
    $smcFunc['db_free_result']($request);
    // for the submissions too
    $request = $smcFunc['db_query']('', '
		SELECT COUNT(*) as total
		FROM {db_prefix}tp_articles
		WHERE approved = 0');
    $row = $smcFunc['db_fetch_assoc']($request);
    $context['TPortal']['total_submissions'] = $row['total'];
    $smcFunc['db_free_result']($request);
    // we are on categories screen
    if (in_array($context['TPortal']['subaction'], array('categories', 'addcategory'))) {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=categories', $txt['tp-categories']);
        // first check if we simply want to copy or set as child
        if (isset($_GET['cu']) && is_numeric($_GET['cu'])) {
            $ccat = $_GET['cu'];
            if (isset($_GET['copy'])) {
                $request = $smcFunc['db_query']('', '
					SELECT * FROM {db_prefix}tp_variables 
					WHERE id = {int:varid}', array('varid' => $ccat));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $row['value1'] .= '__copy';
                    $smcFunc['db_free_result']($request);
                    $smcFunc['db_insert']('insert', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($row['value1'], $row['value2'], $row['value3'], $row['type'], $row['value4'], $row['value5'], $row['subtype'], $row['value7'], $row['value8'], $row['subtype2']), array('id'));
                }
                redirectexit('action=tpadmin;sa=categories');
            } elseif (isset($_GET['child'])) {
                $request = $smcFunc['db_query']('', '
					SELECT * FROM {db_prefix}tp_variables 
					WHERE id = {int:varid}', array('varid' => $ccat));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $row['value1'] .= '__copy';
                    $smcFunc['db_free_result']($request);
                    $smcFunc['db_insert']('INSERT', '{db_prefix}tp_variables', array('value1' => 'string', 'value2' => 'string', 'value3' => 'string', 'type' => 'string', 'value4' => 'string', 'value5' => 'int', 'subtype' => 'string', 'value7' => 'string', 'value8' => 'string', 'subtype2' => 'int'), array($row['value1'], $row['id'], $row['value3'], $row['type'], $row['value4'], $row['value5'], $row['subtype'], $row['value7'], $row['value8'], $row['subtype2']), array('id'));
                }
                redirectexit('action=tpadmin;sa=categories');
            } else {
                // get membergroups
                get_grps();
                $context['html_headers'] .= '
			<script type="text/javascript"><!-- // --><![CDATA[
				function changeIllu(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/illustrations/\' + name; 
				}

				function changeIcon(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/icons/\' + name; 
				}
			// ]]></script>';
                $request = $smcFunc['db_query']('', '
					SELECT * FROM {db_prefix}tp_variables 
					WHERE id = {int:varid} LIMIT 1', array('varid' => $ccat));
                if ($smcFunc['db_num_rows']($request) > 0) {
                    $row = $smcFunc['db_fetch_assoc']($request);
                    $o = explode('|', $row['value7']);
                    foreach ($o as $t => $opt) {
                        $b = explode('=', $opt);
                        if (isset($b[1])) {
                            $row[$b[0]] = $b[1];
                        }
                    }
                    $smcFunc['db_free_result']($request);
                    $check = array('layout', 'catlayout', 'toppanel', 'bottompanel', 'leftpanel', 'rightpanel', 'upperpanel', 'lowerpanel', 'showchild');
                    foreach ($check as $c => $ch) {
                        if (!isset($row[$ch])) {
                            $row[$ch] = 0;
                        }
                    }
                    $context['TPortal']['editcategory'] = $row;
                }
                // fetch all categories and subcategories
                $request = $smcFunc['db_query']('', '
					SELECT	id, value1 as name, value2 as parent, value3, value4, 
						value5, subtype, value7, value8, subtype2 
					FROM {db_prefix}tp_variables
					WHERE type = {string:type}', array('type' => 'category'));
                $context['TPortal']['editcats'] = array();
                $allsorted = array();
                $alcats = array();
                if ($smcFunc['db_num_rows']($request) > 0) {
                    while ($row = $smcFunc['db_fetch_assoc']($request)) {
                        $row['indent'] = 0;
                        $allsorted[$row['id']] = $row;
                        $alcats[] = $row['id'];
                    }
                    $smcFunc['db_free_result']($request);
                    if (count($allsorted) > 1) {
                        $context['TPortal']['editcats'] = chain('id', 'parent', 'name', $allsorted);
                    } else {
                        $context['TPortal']['editcats'] = $allsorted;
                    }
                }
                TPadd_linktree($scripturl . '?action=tpadmin;sa=categories;cu=' . $ccat, $txt['tp-editcategory']);
            }
            return;
        }
        // fetch all categories and subcategories
        $request = $smcFunc['db_query']('', '
			SELECT id, value1 as name, value2 as parent, value3, value4,
				value5, subtype, value7, value8, subtype2 
			FROM {db_prefix}tp_variables
			WHERE type = {string:type}', array('type' => 'category'));
        $context['TPortal']['editcats'] = array();
        $allsorted = array();
        $alcats = array();
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $row['indent'] = 0;
                $allsorted[$row['id']] = $row;
                $alcats[] = $row['id'];
            }
            $smcFunc['db_free_result']($request);
            if (count($allsorted) > 1) {
                $context['TPortal']['editcats'] = chain('id', 'parent', 'name', $allsorted);
            } else {
                $context['TPortal']['editcats'] = $allsorted;
            }
        }
        // get the filecount as well
        if (count($alcats) > 0) {
            $request = $smcFunc['db_query']('', '
				SELECT	art.category as id, COUNT(art.id) as files 
				FROM {db_prefix}tp_articles as art
				WHERE art.category IN ({string:cats})
				GROUP BY art.category', array('cats' => implode(',', $alcats)));
            if ($smcFunc['db_num_rows']($request) > 0) {
                $context['TPortal']['cats_count'] = array();
                while ($row = $smcFunc['db_fetch_assoc']($request)) {
                    $context['TPortal']['cats_count'][$row['id']] = $row['files'];
                }
                $smcFunc['db_free_result']($request);
            }
        }
        if ($context['TPortal']['subaction'] == 'addcategory') {
            TPadd_linktree($scripturl . '?action=tpadmin;sa=addcategory', $txt['tp-addcategory']);
        }
        return;
    }
    TPadd_linktree($scripturl . '?action=tpadmin;sa=articles', $txt['tp-articles']);
    // are we inside a category?
    if (isset($_GET['cu']) && is_numeric($_GET['cu'])) {
        $where = $_GET['cu'];
    }
    // show the no category articles?
    if (isset($_GET['sa']) && $_GET['sa'] == 'strays') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=strays', $txt['tp-strays']);
        $show_nocategory = true;
    }
    // submissions?
    if (isset($_GET['sa']) && $_GET['sa'] == 'submission') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=submission', $txt['tp-submissions']);
        $show_submission = true;
    }
    // single article?
    if (isset($_GET['sa']) && substr($_GET['sa'], 0, 11) == 'editarticle') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=' . $_GET['sa'], $txt['tp-editarticle']);
        $whatarticle = substr($_GET['sa'], 11);
    }
    // are we starting a new one?
    if (isset($_GET['sa']) && substr($_GET['sa'], 0, 11) == 'addarticle_') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=' . $_GET['sa'], $txt['tp-addarticle']);
        $context['TPortal']['editarticle'] = array('id' => '', 'date' => time(), 'body' => '', 'intro' => '', 'useintro' => 0, 'category' => !empty($_GET['cu']) ? $_GET['cu'] : 0, 'frontpage' => 1, 'author_id' => $context['user']['id'], 'subject' => '', 'author' => $context['user']['name'], 'frame' => 'theme', 'approved' => 0, 'off' => 1, 'options' => 'date,title,author,linktree,top,cblock,rblock,lblock,bblock,tblock,lbblock,category,catlist,comments,commentallow,commentupshrink,views,rating,ratingallow,avatar,inherit,social,nofrontsetting', 'parse' => 0, 'comments' => 0, 'comments_var' => '', 'views' => 0, 'rating' => 0, 'voters' => '', 'id_theme' => 0, 'shortname' => '', 'sticky' => 0, 'fileimport' => '', 'topic' => 0, 'locked' => 0, 'illustration' => '', 'headers' => '', 'type' => substr($_GET['sa'], 11), 'featured' => 0, 'realName' => $context['user']['name'], 'authorID' => $context['user']['id'], 'articletype' => substr($_GET['sa'], 11), 'ID_THEME' => 0, 'pub_start' => 0, 'pub_end' => 0);
        $context['html_headers'] .= '
			<script type="text/javascript"><!-- // --><![CDATA[
				function changeIllu(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/illustrations/\' + name; 
				}

				function changeIcon(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/icons/\' + name; 
				}
			// ]]></script>';
        // Add in BBC editor before we call in template so the headers are there
        if (substr($_GET['sa'], 11) == 'bbc') {
            $context['TPortal']['editor_id'] = 'tp_article_body';
            TP_prebbcbox($context['TPortal']['editor_id']);
        }
    }
    // fetch categories and subcategories
    if (!isset($show_nocategory)) {
        $request = $smcFunc['db_query']('', '
			SELECT DISTINCT var.id as id, var.value1 as name, var.value2 as parent 
			FROM {db_prefix}tp_variables AS var
			WHERE var.type = {string:type}
			' . (isset($where) ? 'AND var.value2 = {int:whereval}' : '') . '
			ORDER BY parent, id DESC', array('type' => 'category', 'whereval' => isset($where) ? $where : 0));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $context['TPortal']['basecats'] = isset($where) ? array($where) : array('0', '9999');
            $cats = array();
            $context['TPortal']['cats'] = array();
            $sorted = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $sorted[$row['id']] = $row;
                $cats[] = $row['id'];
            }
            $smcFunc['db_free_result']($request);
            if (count($sorted) > 1) {
                $context['TPortal']['cats'] = chain('id', 'parent', 'name', $sorted);
            } else {
                $context['TPortal']['cats'] = $sorted;
            }
        }
    }
    if (isset($show_submission) && $context['TPortal']['total_submissions'] > 0) {
        // check if we have any start values
        $start = !empty($_GET['p']) && is_numeric($_GET['p']) ? $_GET['p'] : 0;
        // sorting?
        $sort = $context['TPortal']['sort'] = !empty($_GET['sort']) && in_array($_GET['sort'], array('date', 'id', 'author_id', 'type', 'subject', 'parse')) ? $_GET['sort'] : 'date';
        $context['TPortal']['pageindex'] = TPageIndex($scripturl . '?action=tpadmin;sa=submission;sort=' . $sort, $start, $context['TPortal']['total_submissions'], 15);
        $request = $smcFunc['db_query']('', '
			SELECT	art.id, art.date, art.frontpage, art.category, art.author_id as authorID, 
				IFNULL(mem.real_name, art.author) as author, art.subject, art.approved,
				art.sticky, art.type, art.featured, art.locked, art.off, art.parse as pos	
			FROM {db_prefix}tp_articles AS art
			LEFT JOIN {db_prefix}members AS mem ON (art.author_id = mem.id_member)
			WHERE art.approved = {int:approved}
			ORDER BY art.{raw:col} {raw:sort}
			LIMIT {int:start}, 15', array('approved' => 0, 'col' => $sort, 'start' => $start, 'sort' => in_array($sort, array('sticky', 'locked', 'frontpage', 'date', 'active')) ? 'DESC' : 'ASC'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $context['TPortal']['arts_submissions'] = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['arts_submissions'][] = $row;
            }
            $smcFunc['db_free_result']($request);
        }
    }
    if (isset($show_nocategory) && $context['TPortal']['total_nocategory'] > 0) {
        // check if we have any start values
        $start = !empty($_GET['p']) && is_numeric($_GET['p']) ? $_GET['p'] : 0;
        // sorting?
        $sort = $context['TPortal']['sort'] = !empty($_GET['sort']) && in_array($_GET['sort'], array('off', 'date', 'id', 'author_id', 'locked', 'frontpage', 'sticky', 'featured', 'type', 'subject', 'parse')) ? $_GET['sort'] : 'date';
        $context['TPortal']['pageindex'] = TPageIndex($scripturl . '?action=tpadmin;sa=articles;sort=' . $sort, $start, $context['TPortal']['total_nocategory'], 15);
        $request = $smcFunc['db_query']('', '
			SELECT	art.id, art.date, art.frontpage, art.category, art.author_id as authorID, 
				IFNULL(mem.real_name, art.author) as author, art.subject, art.approved, art.sticky,
				art.type, art.featured,art.locked, art.off, art.parse as pos	
			FROM {db_prefix}tp_articles AS art
			LEFT JOIN {db_prefix}members AS mem ON (art.author_id = mem.id_member)
			WHERE (art.category = 0 OR art.category = 9999)
			ORDER BY art.{raw:col} {raw:sort} 
			LIMIT {int:start}, 15', array('col' => $sort, 'sort' => in_array($sort, array('sticky', 'locked', 'frontpage', 'date', 'active')) ? 'DESC' : 'ASC', 'start' => $start));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $context['TPortal']['arts_nocat'] = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['arts_nocat'][] = $row;
            }
            $smcFunc['db_free_result']($request);
        }
    }
    // ok, fetch single article
    if (isset($whatarticle)) {
        $request = $smcFunc['db_query']('', '
			SELECT	art.*, IFNULL(mem.real_name, art.author) as realName, art.author_id as authorID,
				art.type as articletype, art.id_theme as ID_THEME 
			FROM {db_prefix}tp_articles as art
			LEFT JOIN {db_prefix}members as mem ON (art.author_id = mem.id_member)
			WHERE art.id = {int:artid}', array('artid' => is_numeric($whatarticle) ? $whatarticle : 0));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $context['TPortal']['editarticle'] = $smcFunc['db_fetch_assoc']($request);
            $context['TPortal']['editing_article'] = true;
            $context['TPortal']['editarticle']['body'] = $smcFunc['htmlspecialchars']($context['TPortal']['editarticle']['body'], ENT_QUOTES);
            $smcFunc['db_free_result']($request);
        }
        // Add in BBC editor before we call in template so the headers are there
        if ($context['TPortal']['editarticle']['articletype'] == 'bbc') {
            $context['TPortal']['editor_id'] = 'tp_article_body';
            TP_prebbcbox($context['TPortal']['editor_id'], strip_tags($context['TPortal']['editarticle']['body']));
        }
        // fetch the WYSIWYG value
        $request = $smcFunc['db_query']('', '
			SELECT value1 FROM {db_prefix}tp_variables 
			WHERE subtype2 = {int:subtype}  
			AND type = {string:type} LIMIT 1', array('subtype' => $whatarticle, 'type' => 'editorchoice'));
        if ($smcFunc['db_num_rows']($request) > 0) {
            $row = $smcFunc['db_fetch_assoc']($request);
            $smcFunc['db_free_result']($request);
            $context['TPortal']['editorchoice'] = $row['value1'];
        } else {
            $context['TPortal']['editorchoice'] = 1;
        }
        $context['html_headers'] .= '
			<script type="text/javascript"><!-- // --><![CDATA[
				function changeIllu(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/illustrations/\' + name; 
				}

				function changeIcon(node,name)
				{
					node.src = \'' . $boardurl . '/tp-files/tp-articles/icons/\' + name; 
				}
			// ]]></script>';
    }
    // fetch article count for these
    if (isset($cats)) {
        $request = $smcFunc['db_query']('', '
			SELECT	art.category as id, COUNT(art.id) as files 
			FROM {db_prefix}tp_articles as art
			WHERE art.category IN ({array_int:cat})
			GROUP BY art.category', array('cat' => $cats));
        $context['TPortal']['cats_count'] = array();
        if ($smcFunc['db_num_rows']($request) > 0) {
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['cats_count'][$row['id']] = $row['files'];
            }
            $smcFunc['db_free_result']($request);
        }
    }
    // get the icons needed
    tp_collectArticleIcons();
    // fetch all categories and subcategories
    $request = $smcFunc['db_query']('', '
		SELECT	id, value1 as name, value2 as parent 
		FROM {db_prefix}tp_variables
		WHERE type = {string:type}', array('type' => 'category'));
    $context['TPortal']['allcats'] = array();
    $allsorted = array();
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            $allsorted[$row['id']] = $row;
        }
        $smcFunc['db_free_result']($request);
        if (count($allsorted) > 1) {
            $context['TPortal']['allcats'] = chain('id', 'parent', 'name', $allsorted);
        } else {
            $context['TPortal']['allcats'] = $allsorted;
        }
    }
    // not quite done yet lol, now we need to sort out if articles are to be listed
    if (isset($where)) {
        // check if we have any start values
        $start = !empty($_GET['p']) && is_numeric($_GET['p']) ? $_GET['p'] : 0;
        // sorting?
        $sort = $context['TPortal']['sort'] = !empty($_GET['sort']) && in_array($_GET['sort'], array('off', 'date', 'id', 'author_id', 'locked', 'frontpage', 'sticky', 'featured', 'type', 'subject', 'parse')) ? $_GET['sort'] : 'date';
        $context['TPortal']['categoryID'] = $where;
        // get the name
        $request = $smcFunc['db_query']('', '
			SELECT value1 
			FROM {db_prefix}tp_variables 
			WHERE id = {int:varid} LIMIT 1', array('varid' => $where));
        $f = $smcFunc['db_fetch_assoc']($request);
        $smcFunc['db_free_result']($request);
        $context['TPortal']['categoryNAME'] = $f['value1'];
        // get the total first
        $request = $smcFunc['db_query']('', '
			SELECT	COUNT(*) as total
			FROM {db_prefix}tp_articles
			WHERE category = {int:cat}', array('cat' => $where));
        $row = $smcFunc['db_fetch_assoc']($request);
        $context['TPortal']['pageindex'] = TPageIndex($scripturl . '?action=tpadmin;sa=articles;sort=' . $sort . ';cu=' . $where, $start, $row['total'], 15);
        $smcFunc['db_free_result']($request);
        $request = $smcFunc['db_query']('', '
			SELECT art.id, art.date, art.frontpage, art.category, art.author_id as authorID,
				IFNULL(mem.real_name, art.author) as author, art.subject, art.approved, art.sticky,
				art.type, art.featured, art.locked, art.off, art.parse as pos	
			FROM {db_prefix}tp_articles AS art
			LEFT JOIN {db_prefix}members AS mem ON (art.author_id = mem.id_member)
			WHERE art.category = {int:cat}
			ORDER BY art.{raw:sort} {raw:sorter} 
			LIMIT {int:start}, 15', array('cat' => $where, 'sort' => $sort, 'sorter' => in_array($sort, array('sticky', 'locked', 'frontpage', 'date', 'active')) ? 'DESC' : 'ASC', 'start' => $start));
        TPadd_linktree($scripturl . '?action=tpadmin;sa=articles;cu=' . $where, $txt['tp-blocktype19']);
        if ($smcFunc['db_num_rows']($request) > 0) {
            $context['TPortal']['arts'] = array();
            while ($row = $smcFunc['db_fetch_assoc']($request)) {
                $context['TPortal']['arts'][] = $row;
            }
            $smcFunc['db_free_result']($request);
        }
    }
    $context['html_headers'] .= '
	<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/editor.js?rc1"></script>
	<script type="text/javascript"><!-- // --><![CDATA[
		function getXMLHttpRequest()
		{
			if (window.XMLHttpRequest)
				return new XMLHttpRequest;
			else if (window.ActiveXObject)
				return new ActiveXObject("MICROSOFT.XMLHTTP");
			else
				alert("Sorry, but your browser does not support Ajax");
		}
		
		window.onload = startToggle;
		
		function startToggle()
		{
			var img = document.getElementsByTagName("img");
			
			for(var i = 0; i < img.length; i++)
			{
				if (img[i].className == "toggleFront")
					img[i].onclick = toggleFront;
				else if (img[i].className == "toggleSticky")
					img[i].onclick = toggleSticky;
				else if (img[i].className == "toggleLock")
					img[i].onclick = toggleLock;
				else if (img[i].className == "toggleActive")
					img[i].onclick = toggleActive;
				else if (img[i].className == "toggleFeatured")
					img[i].onclick = toggleFeatured;
			}
		}
		
		function toggleActive(e)
		{ 
			var e = e ? e : window.event;
			var target = e.target ? e.target : e.srcElement;
		
			while(target.className != "toggleActive")
				  target = target.parentNode;
			
			var id = target.id.replace("artActive", "");
			var Ajax = getXMLHttpRequest();
			
			Ajax.open("POST", "?action=tpadmin;arton=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '");
			Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencode");
			
			var source = target.src;
			target.src = "' . $settings['tp_images_url'] . '/ajax.gif"
			
			Ajax.onreadystatechange = function()
			{
				if(Ajax.readyState == 4)
				{
					target.src = source == "' . $settings['tp_images_url'] . '/TPactive2.gif" ? "' . $settings['tp_images_url'] . '/TPactive1.gif" : "' . $settings['tp_images_url'] . '/TPactive2.gif";
				}
			}
			
			var params = "?action=tpadmin;arton=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '";
			Ajax.send(params);
		}
		function toggleFront(e)
		{ 
			var e = e ? e : window.event;
			var target = e.target ? e.target : e.srcElement;
		
			while(target.className != "toggleFront")
				  target = target.parentNode;
			
			var id = target.id.replace("artFront", "");
			var Ajax = getXMLHttpRequest();
			
			Ajax.open("POST", "?action=tpadmin;artfront=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '");
			Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencode");
			
			var source = target.src;
			target.src = "' . $settings['tp_images_url'] . '/ajax.gif"
			
			Ajax.onreadystatechange = function()
			{
				if(Ajax.readyState == 4)
				{
					target.src = source == "' . $settings['tp_images_url'] . '/TPfront.gif" ? "' . $settings['tp_images_url'] . '/TPfront2.gif" : "' . $settings['tp_images_url'] . '/TPfront.gif";
				}
			}
			
			var params = "?action=tpadmin;artfront=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '";
			Ajax.send(params);
		}
		function toggleSticky(e)
		{ 
			var e = e ? e : window.event;
			var target = e.target ? e.target : e.srcElement;
		
			while(target.className != "toggleSticky")
				  target = target.parentNode;
			
			var id = target.id.replace("artSticky", "");
			var Ajax = getXMLHttpRequest();
			
			Ajax.open("POST", "?action=tpadmin;artsticky=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '");
			Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencode");
			
			var source = target.src;
			target.src = "' . $settings['tp_images_url'] . '/ajax.gif"
			
			Ajax.onreadystatechange = function()
			{
				if(Ajax.readyState == 4)
				{
					target.src = source == "' . $settings['tp_images_url'] . '/TPsticky1.gif" ? "' . $settings['tp_images_url'] . '/TPsticky2.gif" : "' . $settings['tp_images_url'] . '/TPsticky1.gif";
				}
			}
			
			var params = "?action=tpadmin;artsticky=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '";
			Ajax.send(params);
		}
		function toggleLock(e)
		{ 
			var e = e ? e : window.event;
			var target = e.target ? e.target : e.srcElement;
		
			while(target.className != "toggleLock")
				  target = target.parentNode;
			
			var id = target.id.replace("artLock", "");
			var Ajax = getXMLHttpRequest();
			
			Ajax.open("POST", "?action=tpadmin;artlock=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '");
			Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencode");
			
			var source = target.src;
			target.src = "' . $settings['tp_images_url'] . '/ajax.gif"
			
			Ajax.onreadystatechange = function()
			{
				if(Ajax.readyState == 4)
				{
					target.src = source == "' . $settings['tp_images_url'] . '/TPlock1.gif" ? "' . $settings['tp_images_url'] . '/TPlock2.gif" : "' . $settings['tp_images_url'] . '/TPlock1.gif";
				}
			}
			
			var params = "?action=tpadmin;artlock=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '";
			Ajax.send(params);
		}
		function toggleFeatured(e)
		{ 
			var e = e ? e : window.event;
			var target = e.target ? e.target : e.srcElement;
		
			var aP=document.getElementsByTagName(\'img\');
			for(var i=0; i<aP.length; i++) 
			{
				if(aP[i].className===\'toggleFeatured\' && aP[i] != target) 
				{
					aP[i].src=\'' . $settings['tp_images_url'] . '/TPflag2.gif\';
				}
			}

			
			while(target.className != "toggleFeatured")
				  target = target.parentNode;
			
			var id = target.id.replace("artFeatured", "");
			var Ajax = getXMLHttpRequest();
			
			Ajax.open("POST", "?action=tpadmin;artfeat=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '");
			Ajax.setRequestHeader("Content-type", "application/x-www-form-urlencode");
			
			var source = target.src;
			target.src = "' . $settings['tp_images_url'] . '/ajax.gif"
			
			Ajax.onreadystatechange = function()
			{
				if(Ajax.readyState == 4)
				{
					target.src = source == "' . $settings['tp_images_url'] . '/TPflag.gif" ? "' . $settings['tp_images_url'] . '/TPflag2.gif" : "' . $settings['tp_images_url'] . '/TPflag.gif";
				}
			}
			
			var params = "?action=tpadmin;artfeat=" + id + ";' . $context['session_var'] . '=' . $context['session_id'] . '";
			Ajax.send(params);
		}
	// ]]></script>';
    if ($context['TPortal']['subaction'] == 'artsettings') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=artsettings', $txt['tp-settings']);
    } elseif ($context['TPortal']['subaction'] == 'articons') {
        TPadd_linktree($scripturl . '?action=tpadmin;sa=articons', $txt['tp-adminicons']);
    }
}
function TP_dlftpfiles()
{
    global $context, $boarddir;
    $count = 1;
    $sorted = array();
    if ($handle = opendir($boarddir . '/tp-downloads')) {
        while (false !== ($file = readdir($handle))) {
            if ($file != '.' && $file != '..' && $file != '.htaccess' && $file != 'icons') {
                $size = floor(filesize($boarddir . '/tp-downloads/' . $file) / 1024);
                $sorted[$count] = array('id' => $count, 'file' => $file, 'size' => $size);
                $count++;
            }
        }
        closedir($handle);
    }
    $context['TPortal']['tp-downloads'] = array();
    // sort them
    if (count($sorted) > 1) {
        $context['TPortal']['tp-downloads'] = chain('id', 'size', 'file', $sorted);
    } else {
        $context['TPortal']['tp-downloads'] = $sorted;
    }
}
Example #24
0
function TP_article_categories($use_sorted = false)
{
    global $smcFunc, $context, $txt;
    $context['TPortal']['caticons'] = array();
    $context['TPortal']['catnames'] = array();
    $context['TPortal']['categories_shortname'] = array();
    //first : fetch all allowed categories
    $sorted = array();
    // for root category
    $sorted[9999] = array('id' => 9999, 'name' => '&laquo;' . $txt['tp-noname'] . '&raquo;', 'parent' => '0', 'access' => '-1, 0, 1', 'indent' => 1);
    $total = array();
    $request2 = $smcFunc['db_query']('', '
		SELECT category, COUNT(*) as files
		FROM {db_prefix}tp_articles 
		WHERE category > {int:category} GROUP BY category', array('category' => 0));
    if ($smcFunc['db_num_rows']($request2) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request2)) {
            $total[$row['category']] = $row['files'];
        }
        $smcFunc['db_free_result']($request2);
    }
    $total2 = array();
    $request2 = $smcFunc['db_query']('', '
		SELECT value2, COUNT(*) as siblings
		FROM {db_prefix}tp_variables 
		WHERE type = {string:type} GROUP BY value2', array('type' => 'category'));
    if ($smcFunc['db_num_rows']($request2) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request2)) {
            $total2[$row['value2']] = $row['siblings'];
        }
        $smcFunc['db_free_result']($request2);
    }
    $request = $smcFunc['db_query']('', '
		SELECT cats.*
		FROM {db_prefix}tp_variables as cats
		WHERE cats.type = {string:type} 
		ORDER BY cats.value1 ASC', array('type' => 'category'));
    if ($smcFunc['db_num_rows']($request) > 0) {
        while ($row = $smcFunc['db_fetch_assoc']($request)) {
            // set the options up
            $options = array('layout' => '1', 'width' => '100%', 'cols' => '1', 'sort' => 'date', 'sortorder' => 'desc', 'showchild' => '1', 'articlecount' => '5', 'catlayout' => '1', 'leftpanel' => '0', 'rightpanel' => '0', 'toppanel' => '0', 'bottompanel' => '0', 'upperpanel' => '0', 'lowerpanel' => '0');
            $opts = explode('|', $row['value7']);
            foreach ($opts as $op => $val) {
                if (substr($val, 0, 7) == 'layout=') {
                    $options['layout'] = substr($val, 7);
                } elseif (substr($val, 0, 6) == 'width=') {
                    $options['width'] = substr($val, 6);
                } elseif (substr($val, 0, 5) == 'cols=') {
                    $options['cols'] = substr($val, 5);
                } elseif (substr($val, 0, 5) == 'sort=') {
                    $options['sort'] = substr($val, 5);
                } elseif (substr($val, 0, 10) == 'sortorder=') {
                    $options['sortorder'] = substr($val, 10);
                } elseif (substr($val, 0, 10) == 'showchild=') {
                    $options['showchild'] = substr($val, 10);
                } elseif (substr($val, 0, 13) == 'articlecount=') {
                    $options['articlecount'] = substr($val, 13);
                } elseif (substr($val, 0, 10) == 'catlayout=') {
                    $options['catlayout'] = substr($val, 10);
                } elseif (substr($val, 0, 10) == 'leftpanel=') {
                    $options['leftpanel'] = substr($val, 10);
                } elseif (substr($val, 0, 11) == 'rightpanel=') {
                    $options['rightpanel'] = substr($val, 11);
                } elseif (substr($val, 0, 9) == 'toppanel=') {
                    $options['toppanel'] = substr($val, 9);
                } elseif (substr($val, 0, 12) == 'bottompanel=') {
                    $options['bottompanel'] = substr($val, 12);
                } elseif (substr($val, 0, 11) == 'upperpanel=') {
                    $options['centerpanel'] = substr($val, 11);
                } elseif (substr($val, 0, 11) == 'lowerpanel=') {
                    $options['lowerpanel'] = substr($val, 11);
                }
            }
            // check the parent
            if ($row['value2'] == $row['id'] || $row['value2'] == '' || $row['value2'] == '0') {
                $row['value2'] = 9999;
            }
            // check access
            $show = get_perm($row['value3']);
            if ($show) {
                $sorted[$row['id']] = array('id' => $row['id'], 'shortname' => !empty($row['value8']) ? $row['value8'] : $row['id'], 'name' => $row['value1'], 'parent' => $row['value2'], 'access' => $row['value3'], 'icon' => $row['value4'], 'totalfiles' => !empty($total[$row['id']][0]) ? $total[$row['id']][0] : 0, 'children' => !empty($total2[$row['id']][0]) ? $total2[$row['id']][0] : 0, 'options' => array('layout' => $options['layout'], 'catlayout' => $options['catlayout'], 'width' => $options['width'], 'cols' => $options['cols'], 'sort' => $options['sort'], 'sortorder' => $options['sortorder'], 'showchild' => $options['showchild'], 'articlecount' => $options['articlecount'], 'leftpanel' => $options['leftpanel'], 'rightpanel' => $options['rightpanel'], 'toppanel' => $options['toppanel'], 'bottompanel' => $options['bottompanel'], 'upperpanel' => $options['upperpanel'], 'lowerpanel' => $options['lowerpanel']));
                $context['TPortal']['caticons'][$row['id']] = $row['value4'];
                $context['TPortal']['catnames'][$row['id']] = $row['value1'];
                $context['TPortal']['categories_shortname'][$sorted[$row['id']]['shortname']] = $row['id'];
            }
        }
        $smcFunc['db_free_result']($request);
    }
    $context['TPortal']['article_categories'] = array();
    if ($use_sorted) {
        // sort them
        if (count($sorted) > 1) {
            $context['TPortal']['article_categories'] = chain('id', 'parent', 'name', $sorted);
        } else {
            $context['TPortal']['article_categories'] = $sorted;
        }
        unset($context['TPortal']['article_categories'][0]);
    } else {
        $context['TPortal']['article_categories'] = $sorted;
        unset($context['TPortal']['article_categories'][0]);
    }
}
Example #25
0
function findPar($ordered, $sub)
{
    $submenu = chain('ID', 'PARENT', 'ORDER', $ordered, $sub['PARENT'], 1);
    if ($sub['indent'] == 1) {
        return $submenu[0]['PARENT'];
    } else {
        return $submenu[0]['ID'];
    }
}
Example #26
0
 public function testToArrayWithKeys()
 {
     $this->assertSame(['a' => 1, 'b' => 2, 'c' => 3], toArrayWithKeys(['a' => 1, 'b' => 2, 'c' => 3]));
     $this->assertSame(['a' => 1, 'b' => 2, 'c' => 3], toArrayWithKeys(new \ArrayIterator(['a' => 1, 'b' => 2, 'c' => 3])));
     $this->assertSame(['a' => 3, 'b' => 2], toArrayWithKeys(chain(['a' => 1, 'b' => 2], ['a' => 3])));
 }
Example #27
0
         if ($swmenu['SHOWITEM'] == null || $swmenu['SHOWITEM'] == 1) {
             $swmenu['SHOWITEM'] = 1;
         } else {
             $swmenu['SHOWITEM'] = 0;
         }
         if ($swmenu['SHOWITEM']) {
             $final_menu[] = array("TITLE" => $swmenu['TITLE'], "URL" => 'javascript:void(0);', "ID" => $swmenu['ID'], "PARENT" => $swmenu['PARENT'], "ORDER" => $swmenu['ORDER'], "IMAGE" => $swmenu['IMAGE'], "IMAGEOVER" => $swmenu['IMAGEOVER'], "SHOWNAME" => $swmenu['SHOWNAME'], "IMAGEALIGN" => $swmenu['IMAGEALIGN'], "TARGETLEVEL" => $swmenu['TARGETLEVEL'], "TARGET" => 0, "ACCESS" => $swmenu['ACCESS'], "NCSS" => $swmenu['NCSS'], "OCSS" => $swmenu['OCSS'], "SHOWITEM" => $swmenu['SHOWITEM']);
         }
     }
 }
 if (count($final_menu)) {
     $swmenupro['position'] = "center";
     if ($preview) {
         $ordered = chain('ID', 'PARENT', 'ORDER', $final_menu, $parent_id, $levels);
     } else {
         $ordered = chain('ID', 'PARENT', 'ORDER', $final_menu, 0, $levels);
     }
     if ($menustyle == "clickmenu") {
         $content .= doClickMenuPreview($ordered, $swmenupro, $css_load, $active_menu, $selectbox_hack, $padding_hack);
     }
     if ($menustyle == "clicktransmenu") {
         $content .= doClickTransMenuPreview($ordered, $swmenupro, $css_load, $active_menu, $selectbox_hack, $padding_hack);
     }
     if ($menustyle == "slideclick") {
         $content .= doSlideClickPreview($ordered, $swmenupro, $css_load, $active_menu, $selectbox_hack, $padding_hack);
     }
     if ($menustyle == "treemenu") {
         $content .= doTreeMenuPreview($ordered, $swmenupro, $css_load, $active_menu);
     }
     if ($menustyle == "popoutmenu") {
         $content .= doPopoutMenuPreview($ordered, $swmenupro, $css_load, $active_menu);