Exemplo n.º 1
0
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => '', 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => (int) $row[$start], 'end' => (int) $row[$end], 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? $row[$resource] : '');
     }
     return $response;
 }
Exemplo n.º 2
0
function wikiplugin_fitnesse($data, $params)
{
    $runner = Tracker_Field_Math::getRunner();
    $mock = new FixtureMockTrackerField();
    $runner->mockFunction('tracker-field', $mock);
    $fixtures = array('trackermath' => 'wp_fixture_tracker_math', 'trackerdata' => function ($data, $params) use($mock) {
        return wp_fixture_tracker_data($data, $params, $mock);
    });
    $matches = WikiParser_PluginMatcher::match($data);
    $argParser = new WikiParser_PluginArgumentParser();
    foreach ($matches as $table) {
        $fixture = $table->getName();
        $arguments = $table->getArguments();
        $arguments = $argParser->parse($arguments);
        $body = trim($table->getBody());
        if (isset($fixtures[$fixture])) {
            $replace = call_user_func($fixtures[$fixture], $body, new JitFilter($arguments));
            $table->replaceWith($replace);
        } else {
            $data = new FixtureTable($body);
            $table->replaceWith('__' . tr('Fixture not found: %0', $fixture) . "__\n{$data}");
        }
    }
    Tracker_Field_Math::resetRunner();
    return $matches->getText();
}
Exemplo n.º 3
0
function wikiplugin_list($data, $params)
{
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $query = new Search_Query();
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->enableAggregate();
    $builder->apply($matches);
    if (!empty($_REQUEST['sort_mode'])) {
        $query->setOrder($_REQUEST['sort_mode']);
    }
    if (!($index = $unifiedsearchlib->getIndex())) {
        return '';
    }
    $result = $query->search($index);
    $paginationArguments = $builder->getPaginationArguments();
    $resultBuilder = new Search_ResultSet_WikiBuilder($result);
    $resultBuilder->setPaginationArguments($paginationArguments);
    $resultBuilder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $formatter->setDataSource($unifiedsearchlib->getDataSource());
    $out = $formatter->format($result);
    return $out;
}
Exemplo n.º 4
0
function wikiplugin_map($data, $params)
{
    global $tikilib, $prefs;
    if (isset($params['mapfile'])) {
        return wp_map_mapserver($params);
    }
    $smarty = TikiLib::lib('smarty');
    $smarty->loadPlugin('smarty_modifier_escape');
    $width = '100%';
    if (isset($params['width'])) {
        $width = intval($params['width']) . 'px';
    }
    $height = '100%';
    if (isset($params['height'])) {
        $height = intval($params['height']) . 'px';
    }
    if (!isset($params['controls'])) {
        $params['controls'] = wp_map_default_controls();
    }
    if (!is_array($params['controls'])) {
        $params['controls'] = explode(',', $params['controls']);
    }
    if (!isset($params['popupstyle'])) {
        $params['popupstyle'] = 'bubble';
    }
    if (!empty($params['tooltips']) && $params['tooltips'] === 'y') {
        $tooltips = ' data-tooltips="1"';
    } else {
        $tooltips = '';
    }
    $popupStyle = smarty_modifier_escape($params['popupstyle']);
    $controls = array_intersect($params['controls'], wp_map_available_controls());
    $controls = array_intersect($params['controls'], wp_map_available_controls());
    $controls = implode(',', $controls);
    $center = null;
    $geolib = TikiLib::lib('geo');
    if (isset($params['center'])) {
        if ($coords = $geolib->parse_coordinates($params['center'])) {
            $center = ' data-geo-center="' . smarty_modifier_escape($geolib->build_location_string($coords)) . '" ';
        }
    } else {
        $center = $geolib->get_default_center();
    }
    TikiLib::lib('header')->add_map();
    $scope = smarty_modifier_escape(wp_map_getscope($params));
    $output = "<div class=\"map-container\" data-marker-filter=\"{$scope}\" data-map-controls=\"{$controls}\" data-popup-style=\"{$popupStyle}\" style=\"width: {$width}; height: {$height};\" {$center}{$tooltips}>";
    $argumentParser = new WikiParser_PluginArgumentParser();
    $matches = WikiParser_PluginMatcher::match($data);
    foreach ($matches as $match) {
        $name = $match->getName();
        $arguments = $argumentParser->parse($match->getArguments());
        $function = 'wp_map_plugin_' . $name;
        if (function_exists($function)) {
            $output .= $function($match->getBody(), new JitFilter($arguments));
        }
    }
    $output .= "</div>";
    return $output;
}
Exemplo n.º 5
0
function wikiplugin_listexecute($data, $params)
{
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $actions = array();
    $factory = new Search_Action_Factory();
    $factory->register(array('change_status' => 'Search_Action_ChangeStatusAction', 'delete' => 'Search_Action_Delete', 'email' => 'Search_Action_EmailAction', 'wiki_approval' => 'Search_Action_WikiApprovalAction', 'tracker_item_modify' => 'Search_Action_TrackerItemModify'));
    $query = new Search_Query();
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    foreach ($matches as $match) {
        $name = $match->getName();
        if ($name == 'action') {
            $action = $factory->fromMatch($match);
            if ($action && $action->isAllowed(Perms::get()->getGroups())) {
                $actions[$action->getName()] = $action;
            }
        }
    }
    if (!empty($_REQUEST['sort_mode'])) {
        $query->setOrder($_REQUEST['sort_mode']);
    }
    $index = $unifiedsearchlib->getIndex();
    $result = $query->search($index);
    $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/wiki-plugins/wikiplugin_listexecute.tpl');
    $paginationArguments = $builder->getPaginationArguments();
    $dataSource = $unifiedsearchlib->getDataSource();
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $builder->setFormatterPlugin($plugin);
    $formatter = $builder->getFormatter();
    $reportSource = new Search_Action_ReportingTransform();
    if (isset($_POST['list_action'], $_POST['objects'])) {
        $action = $_POST['list_action'];
        $objects = (array) $_POST['objects'];
        if (isset($actions[$action])) {
            $tx = TikiDb::get()->begin();
            $action = $actions[$action];
            $plugin->setFields(array_fill_keys($action->getFields(), null));
            $list = $formatter->getPopulatedList($result);
            foreach ($list as $entry) {
                $identifier = "{$entry['object_type']}:{$entry['object_id']}";
                if (in_array($identifier, $objects) || in_array('ALL', $objects)) {
                    $success = $action->execute($entry);
                    $reportSource->setStatus($entry['object_type'], $entry['object_id'], $success);
                }
            }
            $tx->commit();
        }
    }
    $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/wiki-plugins/wikiplugin_listexecute.tpl');
    $plugin->setFields(array('report_status' => null));
    $plugin->setData(array('actions' => array_keys($actions)));
    $formatter = new Search_Formatter($plugin);
    $result->applyTransform($reportSource);
    return $formatter->format($result);
}
Exemplo n.º 6
0
 function prepareEntry($valueFormatter)
 {
     $matches = WikiParser_PluginMatcher::match($this->template);
     foreach ($matches as $match) {
         $name = $match->getName();
         if ($name === 'display') {
             $match->replaceWith((string) $this->processDisplay($valueFormatter, $match->getBody(), $match->getArguments()));
         }
     }
     return $matches->getText();
 }
Exemplo n.º 7
0
 function action_list($input)
 {
     global $prefs;
     $unifiedsearchlib = TikiLib::lib('unifiedsearch');
     $index = $unifiedsearchlib->getIndex();
     $dataSource = $unifiedsearchlib->getDataSource();
     $start = 'tracker_field_' . $input->beginField->word();
     $end = 'tracker_field_' . $input->endField->word();
     if ($resource = $input->resourceField->word()) {
         $resource = 'tracker_field_' . $resource;
     }
     if ($coloring = $input->coloringField->word()) {
         $coloring = 'tracker_field_' . $coloring;
     }
     $query = $unifiedsearchlib->buildQuery(array());
     $query->filterRange($input->start->int(), $input->end->int(), array($start, $end));
     $query->setRange(0, $prefs['unified_lucene_max_result']);
     if ($body = $input->filters->none()) {
         $builder = new Search_Query_WikiBuilder($query);
         $builder->apply(WikiParser_PluginMatcher::match($body));
     }
     $result = $query->search($index);
     $result = $dataSource->getInformation($result, array('title', $start, $end));
     $response = array();
     $fields = array();
     if ($definition = Tracker_Definition::get($input->trackerId->int())) {
         foreach ($definition->getPopupFields() as $fieldId) {
             if ($field = $definition->getField($fieldId)) {
                 $fields[] = $field;
             }
         }
     }
     $smarty = TikiLib::lib('smarty');
     $smarty->loadPlugin('smarty_modifier_sefurl');
     $trklib = TikiLib::lib('trk');
     foreach ($result as $row) {
         $item = Tracker_Item::fromId($row['object_id']);
         $description = '';
         foreach ($fields as $field) {
             if ($item->canViewField($field['fieldId'])) {
                 $val = trim($trklib->field_render_value(array('field' => $field, 'item' => $item->getData(), 'process' => 'y')));
                 if ($val) {
                     if (count($fields) > 1) {
                         $description .= "<h5>{$field['name']}</h5>";
                     }
                     $description .= $val;
                 }
             }
         }
         $response[] = array('id' => $row['object_id'], 'trackerId' => isset($row['tracker_id']) ? $row['tracker_id'] : null, 'title' => $row['title'], 'description' => $description, 'url' => smarty_modifier_sefurl($row['object_id'], $row['object_type']), 'allDay' => false, 'start' => $this->getTimestamp($row[$start]), 'end' => $this->getTimestamp($row[$end]), 'editable' => $item->canModify(), 'color' => $this->getColor(isset($row[$coloring]) ? $row[$coloring] : ''), 'textColor' => '#000', 'resource' => $resource && isset($row[$resource]) ? strtolower($row[$resource]) : '');
     }
     return $response;
 }
Exemplo n.º 8
0
function wikiplugin_list($data, $params)
{
    global $prefs;
    static $i;
    $i++;
    $unifiedsearchlib = TikiLib::lib('unifiedsearch');
    $query = new Search_Query();
    if (!isset($params['searchable_only']) || $params['searchable_only'] == 1) {
        $query->filterIdentifier('y', 'searchable');
    }
    $unifiedsearchlib->initQuery($query);
    $matches = WikiParser_PluginMatcher::match($data);
    $tsret = applyTablesorter($matches, $query);
    $builder = new Search_Query_WikiBuilder($query);
    $builder->enableAggregate();
    if (!empty($tsret['max']) || !empty($_GET['numrows'])) {
        $max = !empty($_GET['numrows']) ? $_GET['numrows'] : $tsret['max'];
        $builder->wpquery_pagination_max($query, $max);
    }
    $builder->apply($matches);
    $paginationArguments = $builder->getPaginationArguments();
    if (!empty($_REQUEST[$paginationArguments['sort_arg']])) {
        $query->setOrder($_REQUEST[$paginationArguments['sort_arg']]);
    }
    if (!($index = $unifiedsearchlib->getIndex())) {
        return '';
    }
    $result = $query->search($index);
    $result->setId('wplist-' . $i);
    $resultBuilder = new Search_ResultSet_WikiBuilder($result);
    $resultBuilder->setPaginationArguments($paginationArguments);
    $resultBuilder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->setId('wplist-' . $i);
    $builder->setCount($result->count());
    $builder->setTsOn($tsret['tsOn']);
    $builder->apply($matches);
    $result->setTsSettings($builder->getTsSettings());
    $formatter = $builder->getFormatter();
    $result->setTsOn($tsret['tsOn']);
    $out = $formatter->format($result);
    return $out;
}
Exemplo n.º 9
0
 function getData($string)
 {
     $matches = WikiParser_PluginMatcher::match($string);
     $parser = new WikiParser_PluginArgumentParser();
     $data = array();
     foreach ($matches as $m) {
         $name = $m->getName();
         $arguments = $m->getArguments();
         if (isset($data[$name])) {
             if (!is_int(key($data[$name]))) {
                 $data[$name] = array($data[$name]);
             }
             $data[$name][] = $parser->parse($arguments);
         } else {
             $data[$name] = $parser->parse($arguments);
         }
     }
     return $data;
 }
Exemplo n.º 10
0
 public static function search_plugin_content(Tiki_Profile_Writer $writer, $content)
 {
     $searchlib = TikiLib::lib('unifiedsearch');
     $dataSource = $searchlib->getProfileExportHelper();
     $argumentParser = new WikiParser_PluginArgumentParser();
     $matches = WikiParser_PluginMatcher::match($content);
     $justReplace = false;
     foreach ($matches as $match) {
         if ($justReplaced) {
             $justReplaced = false;
             continue;
         }
         $name = $match->getName();
         $args = $argumentParser->parse($match->getArguments());
         if ($name === 'filter') {
             $args = $dataSource->replaceFilterReferences($writer, $args);
             $match->replaceWithPlugin('filter', $args, $match->getBody());
             $justReplaced = true;
         }
     }
     return $matches->getText();
 }
Exemplo n.º 11
0
 function action_render(JitFilter $request)
 {
     $encoded = $request->stream->none();
     $page = $request->page->int() ?: 1;
     if (!($baseQuery = Tiki_Security::get()->decode($encoded))) {
         throw new Services_Exception_Denied('Invalid request performed.');
     }
     $query = new Search_Query();
     $this->lib->initQuery($query);
     $query->filterType('activity');
     $matches = WikiParser_PluginMatcher::match($baseQuery['body']);
     $builder = new Search_Query_WikiBuilder($query);
     $builder->enableAggregate();
     $builder->apply($matches);
     if ($builder->isNextPossible()) {
         $query->setPage($page);
     }
     $query->setOrder('modification_date_desc');
     if (!($index = $this->lib->getIndex())) {
         throw new Services_Exception_NotAvailable(tr('Activity stream currently unavailable.'));
     }
     $result = $query->search($index);
     $paginationArguments = $builder->getPaginationArguments();
     $resultBuilder = new Search_ResultSet_WikiBuilder($result);
     $resultBuilder->setPaginationArguments($paginationArguments);
     $resultBuilder->apply($matches);
     try {
         $plugin = new Search_Formatter_Plugin_SmartyTemplate('templates/activity/activitystream.tpl');
         $plugin->setFields(array('like_list' => true, 'user_groups' => true, 'contributors' => true));
         $formatter = new Search_Formatter($plugin);
         $formatter->setDataSource($this->lib->getDataSource());
         $out = $formatter->format($result);
     } catch (SmartyException $e) {
         throw new Services_Exception_NotAvailable($e->getMessage());
     }
     return array('autoScroll' => $request->autoscroll->int(), 'pageNumber' => $page, 'nextPossible' => $builder->isNextPossible(), 'stream' => $encoded, 'body' => TikiLib::lib('parser')->parse_data($out, array('is_html' => true)));
 }
Exemplo n.º 12
0
    function testReplacePluginInsideOther()
    {
        $init = <<<CONTENT
{BOX(a=1)}
  {LIST()}
    {filter categories=12}
  {LIST}
{BOX}
CONTENT;
        $expect = <<<CONTENT
{BOX(a="1")}
  {LIST()}
    {filter categories="abc1234567890abc1234567890"}
  {LIST}
{BOX}
CONTENT;
        $matches = WikiParser_PluginMatcher::match($init);
        $justReplaced = false;
        foreach ($matches as $m) {
            if ($justReplaced) {
                $justReplaced = false;
                continue;
            }
            if ($m->getName() == 'box') {
                $m->replaceWithPlugin('box', array('a' => 1), $m->getBody());
                $justReplaced = true;
            } elseif ($m->getName() == 'list') {
                $m->replaceWithPlugin('list', array(), "\n    {filter categories=abc1234567890abc1234567890}\n  ");
                $justReplaced = true;
            } elseif ($m->getName() == 'filter') {
                $m->replaceWithPlugin('filter', array('categories' => 'abc1234567890abc1234567890'), "");
                $justReplaced = true;
            }
        }
        $this->assertEquals($expect, $matches->getText());
    }
Exemplo n.º 13
0
 /**
  * Foreach plugin used in a object content call its save handler,
  * if one exist, and send email notifications when it has pending
  * status, if preference is enabled.
  *
  * A plugin save handler is a function defined on the plugin file
  * with the following format: wikiplugin_$pluginName_save()
  *
  * This function is called from object_post_save. Do not call directly.
  *
  * @param array $context object type and id
  * @param array $data
  * @return void
  */
 private function plugin_post_save_actions($context, $data = null)
 {
     global $prefs;
     $parserlib = TikiLib::lib('parser');
     if (is_null($data)) {
         $content = array();
         if (isset($context['values'])) {
             $content = $context['values'];
         }
         if (isset($context['data'])) {
             $content[] = $context['data'];
         }
         $data['content'] = implode(' ', $content);
     }
     $argumentParser = new WikiParser_PluginArgumentParser();
     $matches = WikiParser_PluginMatcher::match($data['content']);
     foreach ($matches as $match) {
         $plugin_name = $match->getName();
         $body = $match->getBody();
         $arguments = $argumentParser->parse($match->getArguments());
         $dummy_output = '';
         if ($parserlib->plugin_enabled($plugin_name, $dummy_output)) {
             $status = $parserlib->plugin_can_execute($plugin_name, $body, $arguments, true);
             // when plugin status is pending, $status equals plugin fingerprint
             if ($prefs['wikipluginprefs_pending_notification'] == 'y' && $status !== true && $status != 'rejected') {
                 $this->plugin_pending_notification($plugin_name, $body, $arguments, $context);
             }
             $alias = new WikiPlugin_Negotiator_Wiki_Alias();
             $alias->findImplementation($plugin_name, $body, $arguments);
             $func_name = 'wikiplugin_' . $plugin_name . '_save';
             if (function_exists($func_name)) {
                 $func_name($context, $body, $arguments);
             }
         }
     }
 }
Exemplo n.º 14
0
    function testMessProvidedByJonny()
    {
        $content = <<<WIKI
{HTML()}<img style="margin-bottom: 10px" src="Web-Images/headers/Directory-Header_wide.jpg" border="0" />{HTML}{DIV(class="dark_acme1")}{DIV(class="wrapper")}{DIV(class="halffloat clearfix")}{DIV(class="box")}~tc~directory item photo~/tc~{\$f_130}

! {\$f_126}

{\$f_132}
Neighborhood: __{\$f_133}__
{DIV(class="clearfix contact_and_map")}{DIV(float="left", width="33%", class="contact_info")}
{\$f_134}{TRACKERITEMFIELD(trackerId=3,fieldId=135,test=1)}{\$f_135}{TRACKERITEMFIELD}
{\$f_136}, {\$f_137}
{\$f_139}

{\$f_128}
{\$f_140}

!!! {DIV(type="span",class="dark2headingB")}What's nearby?{DIV}
{\$f_149}
{SHARETHIS() /}
{DIV} || | | | | ~tc~Google Map~/tc~{\$f_150}|  || {DIV}

{DIV(class="clearfix galleries_and_articles")}{DIV(class="directory_box directory_photo_galleries")}
!!! {DIV(type="span",class="dark2headingA")}Related {DIV}{DIV(type="span",class="dark2headingB")}Articles{DIV}{DIV}
----
{FREETAGGED(type="article",sort_mode="created_asc",titles_only="y",maxRecords="5",h_level="5")}{FREETAGGED}
{DIV}
!!! {DIV(type="span",class="dark2headingA")}Related {DIV}{DIV(type="span",class="dark2headingB")}Wikis{DIV}
----
{FREETAGGED(type="wiki page",maxRecords="5",sort_mode="created_asc",titles_only="y",h_level="5")}{FREETAGGED}

{DIV}{DIV(class="box directory_box")}
!!! {DIV(type="span",class="dark2headingA")}Hot Spot{DIV} Directories {DIV(type="span",class="dark2headingB")}{\$f_126}{DIV}
----
{DIV(class="directory_item_menu")}
{\$f_188}{DIV}
{DIV(class="directory_item_events")}
!!! {DIV(type="span",class="dark2headingA")} {\$f_126} {DIV}{DIV(type="span",class="dark2headingB")}Events{DIV}
----
{TABS(name="user_tabset_01",tabs="July|Aug|Sept")}
{TRACKERLIST(trackerId="7",fields="218:193:201",sort="y",showceated="n",showlastmodif="n",showfieldname="y",showitemrank="n",status="o",filterfield=201:218,filtervalue="{{page}}:2010-07-%",silent="y")}{TRACKERLIST}
/////{TRACKERLIST(trackerId="7",fields="218:193:201",sort="y",showceated="n",showlastmodif="n",showfieldname="y",showitemrank="n",status="o",filterfield=201:218,filtervalue="{{page}}:2010-08-%",silent="y")}{TRACKERLIST}
/////{TRACKERLIST(trackerId="7",fields="218:193:201",sort="y",showceated="n",showlastmodif="n",showfieldname="y",showitemrank="n",status="o",filterfield=201:218,filtervalue="{{page}}:2010-09-%",silent="y")}{TRACKERLIST}
{TABS}
{DIV}
{DIV()}{DIV}
{DIV(class="directory_box twitterfeeds")}
!!! {DIV(type="span",class="dark2headingA")} {\$f_126} {DIV}{DIV(type="span",class="dark2headingB")}Twitter Feed{DIV}
{\$f_67}
{DIV}

{DIV(class="directory_box community")}
!!! {DIV(type="span",class="dark2headingA")}~tc~ {\$f_126} ~/tc~{DIV}~tc~{DIV(type="span",class="dark2headingB")}community{DIV}~/tc~
~tc~*{TRACKERITEMFIELD(trackerId=3,fieldId=145,test=1)}__Awards: __{\$f_145}{TRACKERITEMFIELD}
*{TRACKERITEMFIELD(trackerId=3,fieldId=144,test=1)}__Supportors of: __{\$f_144}{TRACKERITEMFIELD}
*{TRACKERITEMFIELD(trackerId=3,fieldId=148,test=1)}__Affiliations: __{\$f_148}{TRACKERITEMFIELD}
*__Reviews: __{\$f_75}~/tc~
{DIV}{DIV}{DIV}{DIV}{DIV}
WIKI;
        $matches = WikiParser_PluginMatcher::match($content);
        $this->assertGreaterThan(0, count($matches));
    }
Exemplo n.º 15
0
function wikiplugin_customsearch($data, $params)
{
    global $prefs;
    if (!isset($params['wiki'])) {
        return tra('Template is not specified');
    } elseif (!TikiLib::lib('tiki')->page_exists($params['wiki'])) {
        return tra('Template page not found');
    }
    if (isset($params['id'])) {
        $id = $params['id'];
    } else {
        $id = '0';
    }
    if (isset($params['recalllastsearch']) && $params['recalllastsearch'] == 1 && (!isset($_REQUEST['forgetlastsearch']) || $_REQUEST['forgetlastsearch'] != 'y')) {
        $recalllastsearch = 1;
    } else {
        $recalllastsearch = 0;
    }
    if (isset($params['searchfadediv'])) {
        $searchfadediv = $params['searchfadediv'];
    } else {
        $searchfadediv = '';
    }
    if (!isset($_REQUEST["offset"])) {
        $offset = 0;
    } else {
        $offset = (int) $_REQUEST["offset"];
    }
    if (isset($_REQUEST['maxRecords'])) {
        $maxRecords = (int) $_REQUEST['maxRecords'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['maxRecords'])) {
        $maxRecords = (int) $_SESSION["customsearch_{$id}"]['maxRecords'];
    } else {
        $maxRecords = (int) $prefs['maxRecords'];
    }
    if (!empty($_REQUEST['sort_mode'])) {
        $sort_mode = $_REQUEST['sort_mode'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['sort_mode'])) {
        $sort_mode = $_SESSION["customsearch_{$id}"]['sort_mode'];
    } else {
        $sort_mode = '';
    }
    if (!isset($params['searchonload'])) {
        $params['searchonload'] = 1;
    }
    $definitionKey = md5($data);
    $matches = WikiParser_PluginMatcher::match($data);
    $query = new Search_Query();
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    $builder = new Search_Formatter_Builder();
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $cachelib = TikiLib::lib('cache');
    $cachelib->cacheItem($definitionKey, serialize(array('query' => $query, 'formatter' => $formatter)), 'customsearch');
    $wikitpl = "tplwiki:" . $params['wiki'];
    $wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
    TikiLib::lib('parser')->parse_wiki_argvariable($wikicontent);
    $matches = WikiParser_PluginMatcher::match($wikicontent);
    $fingerprint = md5($wikicontent);
    $sessionprint = "customsearch_{$id}_{$fingerprint}";
    if (isset($_SESSION[$sessionprint]) && $_SESSION[$sessionprint] != $fingerprint) {
        unset($_SESSION["customsearch_{$id}"]);
    }
    $_SESSION[$sessionprint] = $fingerprint;
    // important that offset from session is set after fingerprint check otherwise blank page might show
    if ($recalllastsearch && !isset($_REQUEST['offset']) && !empty($_SESSION["customsearch_{$id}"]["offset"])) {
        $offset = (int) $_SESSION["customsearch_{$id}"]["offset"];
    }
    $options = array('searchfadetext' => tr('Loading...'), 'searchfadediv' => $searchfadediv, 'results' => empty($params['destdiv']) ? "#customsearch_{$id}_results" : "#{$params['destdiv']}", 'autosearchdelay' => isset($params['autosearchdelay']) ? max(1500, (int) $params['autosearchdelay']) : 0, 'searchonload' => (int) $params['searchonload']);
    /**
     * NOTES: Search Execution
     *
     * There is a global delay on execution of 1 second. This makes sure
     * multiple submissions will never trigger multiple requests.
     *
     * There is an additional autosearchdelay configuration that can trigger the search
     * on field change rather than explicit request. Explicit requests will still work.
     */
    $script = "\nvar customsearch = {\n\toptions: " . json_encode($options) . ",\n\tid: " . json_encode($id) . ",\n\toffset: 0,\n\tsearchdata: {},\n\tdefinition: " . json_encode((string) $definitionKey) . ",\n\tautoTimeout: null,\n\tadd: function (fieldId, filter) {\n\t\tthis.searchdata[fieldId] = filter;\n\t\tthis.auto();\n\t},\n\tremove: function (fieldId) {\n\t\tdelete this.searchdata[fieldId];\n\t\tthis.auto();\n\t},\n\tload: function () {\n\t\tthis._executor(this);\n\t},\n\tauto: function () {\n\t},\n\t_executor: delayedExecutor(1000, function (cs) {\n\t\tvar selector = '#' + cs.options.searchfadediv;\n\t\tif (cs.options.searchfadediv.length <= 1 && \$(selector).length === 0) {\n\t\t\tselector = '#customsearch_' + cs.id;\n\t\t}\n\n\t\t\$(selector).modal(cs.options.searchfadetext);\n\n\t\tcs._load(function (data) {\n\t\t\t\$(selector).modal();\n\t\t\t\$(cs.options.results).html(data);\n\t\t\t\$(document).trigger('pageSearchReady');\n\t\t});\n\t}),\n\tinit: function () {\n\t\tvar that = this;\n\t\tif (that.options.searchonload) {\n\t\t\tthat.load();\n\t\t}\n\n\t\tif (that.options.autosearchdelay) {\n\t\t\tthat.auto = delayedExecutor(that.options.autosearchdelay, function () {\n\t\t\t\tthat.load();\n\t\t\t});\n\t\t}\n\t}\n};\n\$('#customsearch_{$id}').click(function() {\n\tcustomsearch.offset = 0;\n});\n\$('#customsearch_{$id}').submit(function() {\n\tcustomsearch.load();\n\treturn false;\n});\n\ncustomsearch_{$id} = customsearch;\n";
    $parser = new WikiParser_PluginArgumentParser();
    foreach ($matches as $match) {
        $name = $match->getName();
        $arguments = $parser->parse($match->getArguments());
        $key = $match->getInitialStart();
        $fieldid = "customsearch_{$id}_{$key}";
        if (isset($arguments['id'])) {
            $fieldid = $arguments['id'];
        }
        if ($name == 'sort' && !empty($arguments['mode']) && empty($sort_mode)) {
            $sort_mode = $arguments['mode'];
            $match->replaceWith('');
            continue;
        }
        if (!empty($arguments['_field']) && $arguments['_filter'] == 'content') {
            $filter = $arguments['_field'];
        } elseif (!empty($arguments['_field']) && $arguments['_filter'] == 'content') {
            $filter = 'content';
        } else {
            $filter = '';
        }
        if ($filter && !empty($_REQUEST['default'][$filter])) {
            $default = $_REQUEST['default'][$filter];
        } elseif ($recalllastsearch && isset($_SESSION["customsearch_{$id}"][$fieldid])) {
            $default = $_SESSION["customsearch_{$id}"][$fieldid];
        } elseif (!empty($arguments['_default'])) {
            if (strpos($arguments['_default'], ',') !== false) {
                $default = explode(',', $arguments['_default']);
            } else {
                $default = $arguments['_default'];
            }
        } else {
            $default = '';
        }
        if ($name == 'categories') {
            $parent = $arguments['_parent'];
            if (!empty($_REQUEST['defaultcat'][$parent])) {
                $default = $_REQUEST['defaultcat'][$parent];
            }
        }
        $function = "cs_design_{$name}";
        if (function_exists($function)) {
            if (isset($arguments['_group'])) {
                $fieldname = "customsearch_{$id}_gr" . $arguments['_group'];
            } elseif (isset($arguments['_textrange'])) {
                $fieldname = "customsearch_{$id}_textrange" . $arguments['_textrange'];
            } elseif (isset($arguments['_daterange'])) {
                $fieldname = "customsearch_{$id}_daterange" . $arguments['_daterange'];
            } else {
                $fieldname = $fieldid;
            }
            $match->replaceWith($function($id, $fieldname, $fieldid, $arguments, $default, $script));
        }
    }
    $callbackScript = null;
    if (!empty($params['callbackscript']) && TikiLib::lib('tiki')->page_exists($params['callbackscript'])) {
        $callbackscript_tpl = "wiki:" . $params['callbackscript'];
        $callbackScript = TikiLib::lib('smarty')->fetch($callbackscript_tpl);
    }
    global $page;
    $script .= "\ncustomsearch._load = function (receive) {\n\tvar datamap = {\n\t\tdefinition: this.definition,\n\t\tadddata: \$.toJSON(this.searchdata),\n\t\tsearchid: this.id,\n\t\toffset: customsearch.offset,\n\t\tmaxRecords: this.maxRecords,\n\t\tpage: " . json_encode($page) . ",\n\t\trecalllastsearch: {$recalllastsearch}\n\t};\n\tif (customsearch.sort_mode) {\n\t\t// blank sort_mode is not allowed by Tiki input filter\n\t\tdatamap.sort_mode = customsearch.sort_mode;\n\t}\n\t\$.ajax({\n\t\ttype: 'POST',\n\t\turl: \$.service('search_customsearch', 'customsearch'),\n\t\tdata: datamap,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\treceive(data);\n\t\t\t{$callbackScript};\n\t\t}\n\t});\n};\ncustomsearch.sort_mode = " . json_encode($sort_mode) . ";\ncustomsearch.offset = {$offset};\ncustomsearch.maxRecords = {$maxRecords};\ncustomsearch.init();\n";
    TikiLib::lib('header')->add_jq_onready($script);
    $out = '<div id="customsearch_' . $id . '_form"><form id="customsearch_' . $id . '">' . $matches->getText() . '</form></div>';
    if (empty($params['destdiv'])) {
        $out .= '<div id="customsearch_' . $id . '_results"></div>';
    }
    return $out;
}
Exemplo n.º 16
0
function wikiplugin_customsearch($data, $params)
{
    global $prefs;
    static $instance_id = null;
    if (empty($params['wiki']) && empty($params['tpl'])) {
        return tra('Template is not specified');
    } elseif (!empty($params['wiki']) && !TikiLib::lib('tiki')->page_exists($params['wiki'])) {
        return tra('Template page not found');
    }
    if (isset($params['id'])) {
        $id = $params['id'];
    } else {
        if ($instance_id === null) {
            $instance_id = 0;
        } else {
            $instance_id++;
        }
        $id = (string) $instance_id;
    }
    if (isset($params['recalllastsearch']) && $params['recalllastsearch'] == 1 && (!isset($_REQUEST['forgetlastsearch']) || $_REQUEST['forgetlastsearch'] != 'y')) {
        $recalllastsearch = 1;
    } else {
        $recalllastsearch = 0;
    }
    $defaults = array();
    $plugininfo = wikiplugin_customsearch_info();
    foreach ($plugininfo['params'] as $key => $param) {
        $defaults["{$key}"] = $param['default'];
    }
    $params = array_merge($defaults, $params);
    if (!isset($_REQUEST["offset"])) {
        $offset = 0;
    } else {
        $offset = (int) $_REQUEST["offset"];
    }
    if (isset($_REQUEST['maxRecords'])) {
        $maxRecords = (int) $_REQUEST['maxRecords'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['maxRecords'])) {
        $maxRecords = (int) $_SESSION["customsearch_{$id}"]['maxRecords'];
    } else {
        $maxRecords = (int) $prefs['maxRecords'];
        $maxDefault = true;
    }
    if (!empty($_REQUEST['sort_mode'])) {
        $sort_mode = $_REQUEST['sort_mode'];
    } elseif ($recalllastsearch && !empty($_SESSION["customsearch_{$id}"]['sort_mode'])) {
        $sort_mode = $_SESSION["customsearch_{$id}"]['sort_mode'];
    } else {
        $sort_mode = '';
    }
    $definitionKey = md5($data);
    $matches = WikiParser_PluginMatcher::match($data);
    $query = new Search_Query();
    if (!isset($params['searchable_only']) || $params['searchable_only'] == 1) {
        $query->filterIdentifier('y', 'searchable');
    }
    $builder = new Search_Query_WikiBuilder($query);
    $builder->apply($matches);
    $paginationArguments = $builder->getPaginationArguments();
    // Use maxRecords set in LIST parameters rather then global default if set.
    if (isset($maxDefault) && $maxDefault) {
        if (!empty($paginationArguments['max'])) {
            $maxRecords = $paginationArguments['max'];
        }
    }
    // setup AJAX pagination
    $paginationArguments['offset_jsvar'] = "customsearch_{$id}.offset";
    $paginationArguments['sort_jsvar'] = "customsearch_{$id}.sort_mode";
    $paginationArguments['_onclick'] = "\$('#customsearch_{$id}').submit();return false;";
    $builder = new Search_Formatter_Builder();
    $builder->setPaginationArguments($paginationArguments);
    $builder->apply($matches);
    $formatter = $builder->getFormatter();
    $facets = new Search_Query_FacetWikiBuilder();
    $facets->apply($matches);
    $cachelib = TikiLib::lib('cache');
    $cachelib->cacheItem($definitionKey, serialize(array('query' => $query, 'formatter' => $formatter, 'facets' => $facets)), 'customsearch');
    if (!empty($params['wiki'])) {
        $wikitpl = "tplwiki:" . $params['wiki'];
    } else {
        $wikitpl = $params['tpl'];
    }
    $wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
    TikiLib::lib('parser')->parse_wiki_argvariable($wikicontent);
    $matches = WikiParser_PluginMatcher::match($wikicontent);
    $fingerprint = md5($wikicontent);
    $sessionprint = "customsearch_{$id}_{$fingerprint}";
    if (isset($_SESSION[$sessionprint]) && $_SESSION[$sessionprint] != $fingerprint) {
        unset($_SESSION["customsearch_{$id}"]);
    }
    $_SESSION[$sessionprint] = $fingerprint;
    // important that offset from session is set after fingerprint check otherwise blank page might show
    if ($recalllastsearch && !isset($_REQUEST['offset']) && !empty($_SESSION["customsearch_{$id}"]["offset"])) {
        $offset = (int) $_SESSION["customsearch_{$id}"]["offset"];
    }
    $options = array('searchfadetext' => tr('Loading...'), 'searchfadediv' => $params['searchfadediv'], 'results' => empty($params['destdiv']) ? "#customsearch_{$id}_results" : "#{$params['destdiv']}", 'autosearchdelay' => isset($params['autosearchdelay']) ? max(1500, (int) $params['autosearchdelay']) : 0, 'searchonload' => (int) $params['searchonload'], 'requireinput' => (bool) $params['requireinput'], 'origrequireinput' => (bool) $params['requireinput'], 'forcesortmode' => (bool) $params['forcesortmode']);
    /**
     * NOTES: Search Execution
     *
     * There is a global delay on execution of 1 second. This makes sure
     * multiple submissions will never trigger multiple requests.
     *
     * There is an additional autosearchdelay configuration that can trigger the search
     * on field change rather than explicit request. Explicit requests will still work.
     */
    $script = "\nvar customsearch = {\n\toptions: " . json_encode($options) . ",\n\tid: " . json_encode($id) . ",\n\toffset: 0,\n\tsearchdata: {},\n\tdefinition: " . json_encode((string) $definitionKey) . ",\n\tautoTimeout: null,\n\tadd: function (fieldId, filter) {\n\t\tthis.searchdata[fieldId] = filter;\n\t\tthis.auto();\n\t},\n\tremove: function (fieldId) {\n\t\tdelete this.searchdata[fieldId];\n\t\tthis.auto();\n\t},\n\tload: function () {\n\t\tthis._executor(this);\n\t},\n\tauto: function () {\n\t},\n\t_executor: delayedExecutor(1000, function (cs) {\n\t\tvar selector = '#' + cs.options.searchfadediv;\n\t\tif (cs.options.searchfadediv.length <= 1 && \$(selector).length === 0) {\n\t\t\tselector = '#customsearch_' + cs.id;\n\t\t}\n\n\t\t\$(selector).tikiModal(cs.options.searchfadetext);\n\n\t\tcs._load(function (data) {\n\t\t\t\$(selector).tikiModal();\n\t\t\t\$(cs.options.results).html(data);\n\t\t\t\$(document).trigger('pageSearchReady');\n\t\t});\n\t\tcs.store_query = '';\n\t}),\n\tinit: function () {\n\t\tvar that = this;\n\t\tif (that.options.searchonload) {\n\t\t\tthat.load();\n\t\t}\n\n\t\tif (that.options.autosearchdelay) {\n\t\t\tthat.auto = delayedExecutor(that.options.autosearchdelay, function () {\n\t\t\t\tif (that.options.requireinput && (!\$('#customsearch_{$id}').find(':text').val() || \$('#customsearch_{$id}').find(':text').val().indexOf('...') > 0)) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tthat.load();\n\t\t\t});\n\t\t}\n\t}\n};\n\$('#customsearch_{$id}').click(function() {\n\tcustomsearch.offset = 0;\n});\n\$('#customsearch_{$id}').submit(function() {\n\tif (customsearch.options.requireinput && (!\$(this).find(':text').val() || \$(this).find(':text').val().indexOf('...') > 0)) {\n\t\talert(tr('Please enter a search query'));\n\t\treturn false;\n\t}\n\tif (customsearch.options.origrequireinput != customsearch.options.requireinput) {\n\t\tcustomsearch.options.requireinput = customsearch.options.origrequireinput;\n\t}\n\tcustomsearch.load();\n\treturn false;\n});\n\nwindow.customsearch_{$id} = customsearch;\n\$(document).trigger('formSearchReady');\n";
    $parser = new WikiParser_PluginArgumentParser();
    $dr = 0;
    foreach ($matches as $match) {
        $name = $match->getName();
        $arguments = $parser->parse($match->getArguments());
        $key = $match->getInitialStart();
        $fieldid = "customsearch_{$id}_{$key}";
        if (isset($arguments['id'])) {
            $fieldid = $arguments['id'];
        }
        if ($name == 'sort' && !empty($arguments['mode']) && empty($sort_mode)) {
            $sort_mode = $arguments['mode'];
            $match->replaceWith('');
            continue;
        }
        if (!empty($arguments['_field']) && !empty($arguments['_filter']) && $arguments['_filter'] == 'content') {
            $filter = $arguments['_field'];
        } elseif (empty($arguments['_field']) && !empty($arguments['_filter']) && $arguments['_filter'] == 'content') {
            $filter = 'content';
        } else {
            $filter = '';
        }
        if ($filter && !empty($_REQUEST['default'][$filter])) {
            $default = $_REQUEST['default'][$filter];
        } elseif ($recalllastsearch && isset($_SESSION["customsearch_{$id}"][$fieldid])) {
            $default = $_SESSION["customsearch_{$id}"][$fieldid];
        } elseif (!empty($arguments['_default'])) {
            if (strpos($arguments['_default'], ',') !== false) {
                $default = explode(',', $arguments['_default']);
            } else {
                $default = $arguments['_default'];
            }
        } else {
            $default = '';
        }
        if ($name == 'categories') {
            $parent = $arguments['_parent'];
            if (!empty($_REQUEST['defaultcat'][$parent])) {
                $default = $_REQUEST['defaultcat'][$parent];
            }
        }
        $function = "cs_design_{$name}";
        if (function_exists($function)) {
            if (isset($arguments['_group'])) {
                $fieldname = "customsearch_{$id}_gr" . $arguments['_group'];
            } elseif (isset($arguments['_textrange'])) {
                $fieldname = "customsearch_{$id}_textrange" . $arguments['_textrange'];
            } elseif (isset($arguments['_daterange'])) {
                $fieldname = "customsearch_{$id}_daterange" . $arguments['_daterange'];
            } else {
                $fieldname = $fieldid;
            }
            $html = $function($id, $fieldname, $fieldid, $arguments, $default, $script);
            if ($params['trimlinefeeds']) {
                $html = trim($html);
            }
            $match->replaceWith($html);
        }
        if ($name == 'daterange') {
            $dr++;
        }
    }
    $callbackScript = null;
    if (!empty($params['callbackscript']) && TikiLib::lib('tiki')->page_exists($params['callbackscript'])) {
        $callbackscript_tpl = "wiki:" . $params['callbackscript'];
        $callbackScript = TikiLib::lib('smarty')->fetch($callbackscript_tpl);
    }
    //get iconset icon if daterange is one of the fields
    if ($dr) {
        $smarty = TikiLib::lib('smarty');
        $smarty->loadPlugin('smarty_function_js_insert_icon');
        $iconinsert = smarty_function_js_insert_icon(['type' => 'jscalendar', 'return' => 'y'], $smarty);
    } else {
        $iconinsert = '';
    }
    global $page;
    $script .= "\ncustomsearch._load = function (receive) {\n\tvar datamap = {\n\t\tdefinition: this.definition,\n\t\tadddata: \$.toJSON(this.searchdata),\n\t\tsearchid: this.id,\n\t\toffset: customsearch.offset,\n\t\tmaxRecords: this.maxRecords,\n\t\tstore_query: this.store_query,\n\t\tpage: " . json_encode($page) . ",\n\t\trecalllastsearch: {$recalllastsearch}\n\t};\n\tif (!customsearch.options.forcesortmode && \$('#customsearch_{$id}').find(':text').val() && \$('#customsearch_{$id}').find(':text').val().indexOf('...') <= 0) {\n\t\tcustomsearch.sort_mode = 'score_desc';\n\t}\n\tif (customsearch.sort_mode) {\n\t\t// blank sort_mode is not allowed by Tiki input filter\n\t\tdatamap.sort_mode = customsearch.sort_mode;\n\t}\n\t\$.ajax({\n\t\ttype: 'POST',\n\t\turl: \$.service('search_customsearch', 'customsearch'),\n\t\tdata: datamap,\n\t\tdataType: 'html',\n\t\tsuccess: function(data) {\n\t\t\treceive(data);\n\t\t\t{$callbackScript};\n\t\t},\n\t\terror: function ( jqXHR, textStatus, errorThrown ) {\n\t\t\tvar selector = '#' + customsearch.options.searchfadediv;\n\t\t\tif (customsearch.options.searchfadediv.length <= 1 && \$(selector).length === 0) {\n\t\t\t\tselector = '#customsearch_' + customsearch.id;\n\t\t\t}\n\t\t\t\$(selector).tikiModal();\n\n\t\t\t\$('#customsearch_{$id}').showError(jqXHR)\n\t\t}\n\t});\n};\ncustomsearch.sort_mode = " . json_encode($sort_mode) . ";\ncustomsearch.offset = {$offset};\ncustomsearch.maxRecords = {$maxRecords};\ncustomsearch.store_query ='';\ncustomsearch.init();\n{$iconinsert}";
    TikiLib::lib('header')->add_jq_onready($script);
    if ($params['customsearchjs']) {
        TikiLib::lib('header')->add_jsfile('lib/jquery_tiki/customsearch.js');
    }
    $out = '<div id="customsearch_' . $id . '_form"><form id="customsearch_' . $id . '">' . $matches->getText() . '</form></div>';
    if (empty($params['destdiv'])) {
        $out .= '<div id="customsearch_' . $id . '_results"></div>';
    }
    if (!empty($params['wiki'])) {
        return $out;
    } else {
        // If using smarty tpl should assume it's all HTML
        $out = str_replace('~np~', '', $out);
        $out = str_replace('~/np~', '', $out);
        return '~np~' . $out . '~/np~';
    }
}
Exemplo n.º 17
0
 private function assertIs($expect, $content)
 {
     $matches = WikiParser_PluginMatcher::match($content);
     foreach ($matches as $plugin) {
         $this->assertEquals(trim($expect), trim($plugin->getBody()));
     }
 }
Exemplo n.º 18
0
function wikiplugin_appframe($data, $params)
{
    $minHeight = isset($params['min']) ? (int) $params['min'] : 300;
    $maxHeight = isset($params['max']) ? (int) $params['max'] : -1;
    $fullPage = 0;
    if (isset($params['fullpage']) && $params['fullpage'] == 'y') {
        $fullPage = 1;
    }
    $fullscreen = 0;
    if (isset($params['fullscreen']) && $params['fullscreen'] == 'y') {
        $fullscreen = 1;
    }
    $absolute = intval(isset($params['absolute']) ? $params['absolute'] == 'y' : false);
    $top = isset($params['top']) ? $params['top'] : 0;
    $headerlib = TikiLib::lib('header');
    if (isset($params['hideleft']) && $params['hideleft'] == 'y') {
        $headerlib->add_js(<<<JS
hideCol('col2','left', 'col1');
JS
);
    }
    if (isset($params['hideright']) && $params['hideright'] == 'y') {
        $headerlib->add_js(<<<JS
hideCol('col3','right', 'col1');
JS
);
    }
    $headerlib->add_js(<<<JS
\$(window).resize(function () {
\tvar viewportHeight = \$(window).height(), appframe = \$('#appframe'), footerSize, centerHeader, surplus, target;

\tif ({$absolute}) {
\t\t\$('#appframe')
\t\t\t.css('position', 'absolute')
\t\t\t.css('top', {$top})
\t\t\t.css('left', 0)
\t\t\t.css('bottom', 0)
\t\t\t.css('right', 0)
\t\t\t;
\t} else {
\t\tappframe.height(0);

\t\tcenterHeader = \$('#appframe').position().top - \$('#tiki-center').position().top;
\t\tsurplus = \$('#show-errors-button').height();
\t\tfooterSize = \$('#footer').height() + \$('#tiki-center').height() - centerHeader + surplus;
\t\ttarget = viewportHeight - appframe.position().top - footerSize;

\t\tvar min = {$minHeight};
\t\tif (target < min) {
\t\t\ttarget = min;
\t\t}

\t\tvar max = {$maxHeight};
\t\tif ((max != -1) && (target > max)) {
\t\t\ttarget = max;
\t\t}

\t\tappframe.height(target);
\t}

\t\$('#appframe .tab').each(function () {
\t\t\$(this).data('available-height', \$('#appframe').height() - \$(this).position().top).addClass('height-size');
\t});

\t\$('#appframe .anchor-container')
\t\t.css('z-index', 100000)
\t\t.css('position', 'absolute')
\t\t.css('top', 150)
\t\t.css('right', 0)
\t\t;
});
\$('#appframe .tab').parent().each(function () {
\tvar tabs = \$(this).children('.tab').wrapAll('<div class="tabs" style="height: 100%;"/>');
\tvar list = \$('<ul/>');
\ttabs.parent().prepend(list);
\ttabs.each(function () {
\t\tvar link = \$('<a/>').attr('href', '#' + \$(this).attr('id')).text(\$(this).data('label'));
\t\tlist.append(\$('<li/>').append(link));
\t});
\ttabs.parent().tabs();
});
\$('#appframe .accordion').parent().each(function () {
\t\$('.accordion', this).wrapAll('<div/>').parent().accordion({
\t\theightStyle: "content"
\t});
});
\$('#appframe .anchor').wrapAll('<div/>').parent()
\t.addClass('anchor-container')
\t;

\$('#appframe .anchor').each(function () {
\tvar anchor = this;
\t\$('.anchor-head, .anchor-content', anchor)
\t\t.css('text-align', 'right')
\t\t;

\t\$('.anchor-toggle', anchor).click(function () {
\t\t\$('.anchor-head .label', anchor).toggle('fast');
\t\t\$('.anchor-content', anchor).toggle('fast');
\t\treturn false;
\t});

\tif (location.hash == "#" + \$("img", anchor).attr("alt")) {
\t\tsetTimeout( function() { \$('.anchor-toggle', anchor).click(); }, 2000);
\t}
});

if ({$fullPage}) {
\t\$('#role_main').append(\$('#appframe'));
\t\$('#role_main').children().not(\$('#appframe')).remove();
}

if ({$fullscreen}) {
\t\$('.header_outer').hide();
\t\$('#topbar_modules').hide();
\t\$('#footer').hide();
\t\$('#error_report').hide();
\t\$('.share').hide();
\t\$('.tellafriend').hide();
}

\$(window).resize();
JS
);
    $matches = WikiParser_PluginMatcher::match($data);
    foreach ($matches as $plugin) {
        if ($output = wikiplugin_appframe_execute($plugin)) {
            $plugin->replaceWith($output);
        }
    }
    $data = $matches->getText();
    return <<<HTML
<div id="appframe">{$data}</div>
HTML;
}
Exemplo n.º 19
0
function wikiplugin_list($data, $params)
{
	$unifiedsearchlib = TikiLib::lib('unifiedsearch');

	$alternate = null;
	$output = null;
	$subPlugins = array();

	$query = new Search_Query;
	$query->setWeightCalculator($unifiedsearchlib->getWeightCalculator());

	if (isset($_REQUEST['maxRecords'])) {
		if (isset($_REQUEST['offset'])) {
			$query->setRange($_REQUEST['offset'], $_REQUEST['maxRecords']);
		} else {
			$query->setRange(0, $_REQUEST['maxRecords']);
		}
	} elseif (isset($_REQUEST['offset'])) {
		$query->setRange($_REQUEST['offset']);
	}

	$matches = WikiParser_PluginMatcher::match($data);
	$argumentParser = new WikiParser_PluginArgumentParser;

	$onclick = '';
	$offset_jsvar = '';

	foreach ($matches as $match) {
		$name = $match->getName();
		$arguments = $argumentParser->parse($match->getArguments());

		foreach ($arguments as $key => $value) {
			$function = "wpquery_{$name}_{$key}";

			if (function_exists($function)) {
				$function($query, $value, $arguments);
			}

			$function = "wpformat_{$name}_{$key}";

			if (function_exists($function)) {
				$function($subPlugins, $value, $match->getBody());
			}
		}

		if ($name == 'output') {
			$output = $match;
		}

		if ($name == 'alternate') {
			$alternate = $match->getBody();
		}

		if ($name == 'pagination' && isset($arguments['onclick'])) {
			$onclick = $arguments['onclick'];
		}
		if ($name == 'pagination' && isset($arguments['offset_jsvar'])) {
			$offset_jsvar = $arguments['offset_jsvar'];
		}
	}

	if (! Perms::get()->admin) {
		$query->filterPermissions(Perms::get()->getGroups());
	}

	if (!empty($_REQUEST['sort_mode'])) {
		$query->setOrder($_REQUEST['sort_mode']);
	}

	$index = $unifiedsearchlib->getIndex();

	$result = $query->search($index);

	if (count($result)) {
		if (!empty($output)) {
			$arguments = $argumentParser->parse($output->getArguments());

			if (isset($arguments['template'])) {
				if ($arguments['template'] == 'table') {
					$arguments['template'] = dirname(__FILE__) . '/../../templates/table.tpl';
				} else if (!file_exists($arguments['template'])) {
					TikiLib::lib('errorreport')->report(tr('Missing template "%0"', $arguments['template']));
					return '';
				}
				$builder = new Search_Formatter_ArrayBuilder;
				$templateData = $builder->getData($output->getBody());

				$plugin = new Search_Formatter_Plugin_SmartyTemplate($arguments['template']);
				$plugin->setData($templateData);
				$plugin->setFields(wp_list_findfields($templateData));
			} elseif (isset($arguments['wiki']) && TikiLib::lib('tiki')->page_exists($arguments['wiki'])) {	
				$wikitpl = "tplwiki:" . $arguments['wiki'];
				$wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
				$plugin = new Search_Formatter_Plugin_WikiTemplate($wikicontent);
			} else {
				$plugin = new Search_Formatter_Plugin_WikiTemplate($output->getBody());
			}

			if (isset($arguments['pagination'])) {
				$plugin = new WikiPlugin_List_AppendPagination($plugin, $onclick, $offset_jsvar);
			}
		} else {
			$plugin = new Search_Formatter_Plugin_WikiTemplate("* {display name=title format=objectlink}\n");
		}

		$formatter = new Search_Formatter($plugin);
		$formatter->setDataSource($unifiedsearchlib->getDataSource());

		foreach ($subPlugins as $key => $plugin) {
			$formatter->addSubFormatter($key, $plugin);
		}

		$out = $formatter->format($result);
	} elseif (!empty($alternate)) {
		$out = $alternate;
	} else {
		$out = '^' . tra('No results for query.') . '^';
	}

	return $out;
}
function wikiplugin_customsearch($data, $params)
{
	global $prefs;
	if (!isset($params['wiki'])) {
		return tra('Template is not specified');
	} elseif (!TikiLib::lib('tiki')->page_exists($params['wiki'])) {
		return tra('Template page not found');
	}
	if (isset($params['id'])) {
		$id = $params['id'];
	} else {
		$id = '0';
	}
	if (isset($params['recalllastsearch']) && $params['recalllastsearch'] == 1 && (!isset($_REQUEST['forgetlastsearch']) || $_REQUEST['forgetlastsearch'] != 'y')) {
		$recalllastsearch = 1;
	} else {
		$recalllastsearch = 0;
	}
	if (isset($params['autosearchdelay'])) {
		$autosearchdelay = $params['autosearchdelay'];
	} else {
		$autosearchdelay = 0;
	}
	if (isset($params['searchfadediv'])) {
		$searchfadediv = $params['searchfadediv'];
	} else {
		$searchfadediv = '';
	}
	if (!isset($_REQUEST["offset"])) {
		$offset = 0;
	} else {
		$offset = $_REQUEST["offset"];
	} 
	if (isset($_REQUEST['maxRecords'])) {
		$maxRecords = $_REQUEST['maxRecords'];
	} elseif ($recalllastsearch && !empty($_SESSION["customsearch_$id"]['maxRecords'])) {
		$maxRecords = $_SESSION["customsearch_$id"]['maxRecords'];
	} else {
		$maxRecords = $prefs['maxRecords']; 
	}		
	if (!empty($_REQUEST['sort_mode'])) {
		$sort_mode = $_REQUEST['sort_mode'];
	} elseif ($recalllastsearch && !empty($_SESSION["customsearch_$id"]['sort_mode'])) {
		$sort_mode = $_SESSION["customsearch_$id"]['sort_mode'];
	} else {
		$sort_mode = '';
	}
	if (!isset($params['searchonload'])) {
		$params['searchonload'] = 1;
	}

	$wikitpl = "tplwiki:" . $params['wiki'];
	$wikicontent = TikiLib::lib('smarty')->fetch($wikitpl);
	TikiLib::lib('parser')->parse_wiki_argvariable($wikicontent);

	$matches = WikiParser_PluginMatcher::match($wikicontent);

	$parser = new WikiParser_PluginArgumentParser;
	$fingerprint = md5(print_r($matches, true));
	$sessionprint = "customsearch_{$id}_$fingerprint";
	if (isset($_SESSION[$sessionprint]) && $_SESSION[$sessionprint] != $fingerprint) {
		unset($_SESSION["customsearch_$id"]);
	} 
	$_SESSION[$sessionprint] = $fingerprint;

	// important that offset from session is set after fingerprint check otherwise blank page might show
	if ($recalllastsearch && !isset($_REQUEST['offset']) && !empty($_SESSION["customsearch_$id"]["offset"])) {
		$offset = $_SESSION["customsearch_$id"]["offset"];
	}
	
	$groups = array();
	$textrangegroups = array();
	$daterangegroups = array();

	$script = "
function add_customsearch_$id(fieldid, filter) {
	customsearch_{$id}_searchdata[fieldid] = filter;
}
function remove_customsearch_$id(fieldid) {
	delete customsearch_{$id}_searchdata[fieldid];
}
customsearch_{$id}_searchdata = new Object();
customsearch_{$id}_basedata = " . json_encode((string) $data) . ";
$('#customsearch_$id').click(function() {
	// reset offset on reclick of form since new search should always start from 0 offset
	customsearch_offset_$id = 0;
});
$('#customsearch_$id').submit(function() {
	load_customsearch_$id($.toJSON(customsearch_{$id}_searchdata));
	return false;
});
";
		
	foreach ($matches as $k => $match) {
		$name = $match->getName(); 
		$arguments = $parser->parse($match->getArguments());
		$fieldid = "customsearch_{$id}_$k";
		if ($name == 'sort' && !empty($arguments['mode']) && empty($sort_mode)) {
			$sort_mode = $arguments['mode'];
			$match->replaceWith('');
			continue;
		} 
		if ($arguments['_filter'] == 'content' && !empty($arguments['_field'])) {
			$filter = $arguments['_field'];
		} elseif ($arguments['_filter'] == 'content' && empty($arguments['_field'])) {
			$filter = 'content';
		} else {
			$filter = '';
		}
		if ( $filter && !empty($_REQUEST['default'][$filter]) ) {
			$default = $_REQUEST['default'][$filter];
		} elseif ($recalllastsearch && isset($_SESSION["customsearch_$id"][$fieldid])) { 
			$default = $_SESSION["customsearch_$id"][$fieldid]; 
		} elseif (!empty($arguments['_default'])) {
			if (strpos($arguments['_default'], ',') !== false) {
				$default = explode(',', $arguments['_default']);
			} else {
				$default = $arguments['_default'];
			}
		} else {
			$default = '';
		}
		if ( $name == 'categories' ) {
			$parent = $arguments['_parent'];
			if (!empty($_REQUEST['defaultcat'][$parent])) {
				$default = $_REQUEST['defaultcat'][$parent];
			}
		}
		$function = "cs_design_{$name}";
		if (function_exists($function)) {
			if (isset($arguments['_group'])) {
				$groups[$fieldid] = $arguments['_group']; 
				$fieldname = "customsearch_{$id}_gr" . $arguments['_group'];
			} elseif (isset($arguments['_textrange'])) {
				$textrangegroups[$fieldid] = $arguments['_textrange'];
				$fieldname = "customsearch_{$id}_textrange" . $arguments['_textrange'];
			} elseif (isset($arguments['_daterange'])) {
				$daterangegroups[$fieldid] = $arguments['_daterange'];
				$fieldname = "customsearch_{$id}_daterange" . $arguments['_daterange'];
			} else {
				$fieldname = $fieldid;
			}
			$match->replaceWith($function($id, $fieldname, $fieldid, $arguments, $default, $script, $groups, $autosearchdelay));
		} 
	}

	if (!empty($params['callbackscript']) && TikiLib::lib('tiki')->page_exists($params['callbackscript'])) {
		$callbackscript_tpl = "wiki:" . $params['callbackscript'];
		$callbackScript = TikiLib::lib('smarty')->fetch($callbackscript_tpl); 
	}

	$script .= "function load_customsearch_$id(searchdata) {\n";
	$searchfadetext = tr('Searching...');
	if ($searchfadediv) { 
		$script .= "	if ($('#$searchfadediv').length) $('#$searchfadediv').modal('$searchfadetext');\n";
		$script .= "	else $('#customsearch_$id').modal('$searchfadetext');\n";
	} else {
		$script .= "	$('#customsearch_$id').modal('$searchfadetext');\n";
	}
	$script .= "
	var datamap = {
		basedata: customsearch_{$id}_basedata,
		adddata: searchdata,
		searchid: '$id',
		groups: '" . json_encode($groups) . "',
		textrangegroups: '" . json_encode($textrangegroups) . "',
		daterangegroups: '" . json_encode($daterangegroups) . "',
		offset: customsearch_offset_$id,
		maxRecords: customsearch_maxRecords_$id
	};
	if (customsearch_sort_mode_$id) {
		// blank sort_mode is not allowed by Tiki input filter
		datamap['sort_mode'] = customsearch_sort_mode_$id;
	}
	$.ajax({
		type: 'POST',
		url: $.service('tracker_search', 'customsearch'),
		data: datamap,
		dataType: 'html',
		success: function(data){
";

	if ($searchfadediv) {
		$script .= "			if ($('#$searchfadediv').length) $('#$searchfadediv').modal();\n";
		$script .= "			else $('#customsearch_$id').modal();\n";
	} else {
		$script .= "			$('#customsearch_$id').modal();\n";
	}
	if (!empty($params['destdiv'])) {
		$script .= "			$('#{$params['destdiv']}').html(data); customsearch_quiet_$id = false;\n";
	} else {
		$script .= "			$('#customsearch_{$id}_results').html(data); customsearch_quiet_$id = false;\n";
	}

	$script .= "			$(document).trigger('pageSearchReady');\n";
	if (!empty($callbackScript)) $script .= $callbackScript;		
	$script .= "
		}
	});
};
customsearch_sort_mode_$id = '$sort_mode';
customsearch_offset_$id = $offset;
customsearch_maxRecords_$id = $maxRecords;
";

	if ($params['searchonload']) {
		$script .= "$('#customsearch_$id').submit();
";
	}
	TikiLib::lib('header')->add_jq_onready($script);

	$form = '<div id="' . "customsearch_$id" . '_form' . '"><form id="' . "customsearch_$id" . '">' . $matches->getText() . '</form></div>';

	if (empty($params['destdiv'])) {
		$results = '<div id="' . "customsearch_$id" . '_results"></div>';
	}

	$out = $form . $results;


	return $out;
}
Exemplo n.º 21
0
 public static function fitnesse_content(Tiki_Profile_Writer $writer, $content)
 {
     $searchlib = TikiLib::lib('unifiedsearch');
     $argumentParser = new WikiParser_PluginArgumentParser();
     $matches = WikiParser_PluginMatcher::match($content);
     $justReplaced = false;
     foreach ($matches as $match) {
         if ($justReplaced) {
             $justReplaced = false;
             continue;
         }
         $name = $match->getName();
         $args = $argumentParser->parse($match->getArguments());
         if (isset($args['trackerId'])) {
             $args['trackerId'] = $writer->getReference('tracker', $args['trackerId']);
             $match->replaceWithPlugin($name, $args, $match->getBody());
             $justReplaced = true;
         }
     }
     return $matches->getText();
 }
Exemplo n.º 22
0
 function get_pages($data, $withReltype = false)
 {
     global $page_regex, $prefs, $tikilib;
     $matches = WikiParser_PluginMatcher::match($data);
     foreach ($matches as $match) {
         if ($match->getName() == 'code') {
             $match->replaceWith('');
         }
     }
     $data = $matches->getText();
     preg_match_all("/\\(([a-z0-9-]+)?\\( *({$page_regex}) *\\)\\)/", $data, $normal);
     preg_match_all("/\\(([a-z0-9-]+)?\\( *({$page_regex}) *\\|(.+?)\\)\\)/", $data, $withDesc);
     preg_match_all('/<a class="wiki" href="tiki-index\\.php\\?page=([^\\?&"]+)[^"]*"/', $data, $htmlLinks);
     preg_match_all('/<a class="wiki wikinew" href="tiki-editpage\\.php\\?page=([^\\?&"]+)"/', $data, $htmlWantedLinks);
     // TODO: revise the need to call modified urldecode() (shouldn't be needed after r37568). 20110922
     foreach ($htmlLinks[1] as &$h) {
         $h = $tikilib->urldecode($h);
     }
     foreach ($htmlWantedLinks[1] as &$h) {
         $h = $tikilib->urldecode($h);
     }
     if ($prefs['feature_wikiwords'] == 'y') {
         preg_match_all("/([ \n\t\r\\,\\;]|^)?([A-Z][a-z0-9_\\-]+[A-Z][a-z0-9_\\-]+[A-Za-z0-9\\-_]*)(\$|[ \n\t\r\\,\\;\\.])/", $data, $wikiLinks);
         $pageList = array_merge($normal[2], $withDesc[2], $wikiLinks[2], $htmlLinks[1], $htmlWantedLinks[1]);
         if ($withReltype) {
             $relList = array_merge($normal[1], $withDesc[1], count($wikiLinks[2]) ? array_fill(0, count($wikiLinks[2]), null) : array(), count($htmlLinks[1]) ? array_fill(0, count($htmlLinks[1]), null) : array(), count($htmlWantedLinks[1]) ? array_fill(0, count($htmlWantedLinks[1]), null) : array());
         }
     } else {
         $pageList = array_merge($normal[2], $withDesc[2], $htmlLinks[1], $htmlWantedLinks[1]);
         if ($withReltype) {
             $relList = array_merge($normal[1], $withDesc[1], count($htmlLinks[1]) ? array_fill(0, count($htmlLinks[1]), null) : array(), count($htmlWantedLinks[1]) ? array_fill(0, count($htmlWantedLinks[1]), null) : array());
         }
     }
     if ($withReltype) {
         $complete = array();
         foreach ($pageList as $idx => $name) {
             if (!array_key_exists($name, $complete)) {
                 $complete[$name] = array();
             }
             if (!empty($relList[$idx]) && !in_array($relList[$idx], $complete[$name])) {
                 $complete[$name][] = $relList[$idx];
             }
         }
         return $complete;
     } else {
         return array_unique($pageList);
     }
 }
Exemplo n.º 23
0
 public function convertData($data)
 {
     //we store the original matches because we are about to change and update them, we need to get their fingerprint
     $oldMatches = WikiParser_PluginMatcher::match($data);
     // HTML-decode pages
     $data = htmlspecialchars_decode($data);
     // find the plugins
     $matches = WikiParser_PluginMatcher::match($data);
     $replaced = array();
     $fingerPrintsOld = array();
     foreach ($oldMatches as $match) {
         $name = $match->getName();
         $meta = $this->parserlib->plugin_info($name);
         // only check fingerprints of plugins requiring validation
         if (!empty($meta['validate'])) {
             $args = $this->argumentParser->parse($match->getArguments());
             //RobertPlummer - pre 9, latest findings from v8 is that the < and > chars are THE ONLY ones converted to &lt; and &gt; everything else seems to be decoded
             $body = $match->getBody();
             // jonnyb - pre 9.0, Tiki 6 (?) fingerprints are calculated with the undecoded body
             $fingerPrint = $this->parserlib->plugin_fingerprint($name, $meta, $body, $args);
             // so check the db for previously recorded plugins
             if (!$this->parserlib->getOne('SELECT COUNT(*) FROM tiki_plugin_security WHERE fingerprint = ?', array($fingerPrint))) {
                 // jb but v 7 & 8 fingerprints may be calculated differently, so check both fully decoded and partially
                 $body = htmlspecialchars_decode($body);
                 $fingerPrint = $this->parserlib->plugin_fingerprint($name, $meta, $body, $args);
                 if (!$this->parserlib->getOne('SELECT COUNT(*) FROM tiki_plugin_security WHERE fingerprint = ?', array($fingerPrint))) {
                     $body = str_replace(array('<', '>'), array('&lt;', '&gt;'), $body);
                     $fingerPrint = $this->parserlib->plugin_fingerprint($name, $meta, $body, $args);
                     if (!$this->parserlib->getOne('SELECT COUNT(*) FROM tiki_plugin_security WHERE fingerprint = ?', array($fingerPrint))) {
                         // old fingerprint not found - what to do? Might be worth trying &quot; chars too...
                         $fingerPrint = '';
                     }
                 }
             }
             $fingerPrintsOld[] = $fingerPrint;
         }
     }
     $fingerPrintsNew = array();
     // each plugin
     foreach ($matches as $match) {
         $name = $match->getName();
         $meta = $this->parserlib->plugin_info($name);
         $argsRaw = $match->getArguments();
         //Here we detect if a plugin was double encoded and this is the second decode
         //try to detect double encoding
         if (preg_match("/&amp;&/i", $argsRaw) || preg_match("/&quot;/i", $argsRaw) || preg_match("/&gt;/i", $argsRaw)) {
             $argsRaw = htmlspecialchars_decode($argsRaw);
             // decode entities in the plugin args (usually &quot;)
         }
         $args = $this->argumentParser->parse($argsRaw);
         $plugin = (string) $match;
         $key = '§' . md5(TikiLib::genPass()) . '§';
         // by replace whole plugin with a guid
         $data = str_replace($plugin, $key, $data);
         $body = $match->getBody();
         // leave the bodies alone
         $key2 = '§' . md5(TikiLib::genPass()) . '§';
         // by replacing it with a guid
         $plugin = str_replace($body, $key2, $plugin);
         //Here we detect if a plugin was double encoded and this is the second decode
         //try to detect double encoding
         if (preg_match("/&amp;&/i", $plugin) || preg_match("/&quot;/i", $plugin) || preg_match("/&gt;/i", $plugin)) {
             $plugin = htmlspecialchars_decode($plugin);
             // decode entities in the plugin args (usually &quot;)
         }
         $plugin = str_replace($key2, $body, $plugin);
         // finally put the body back
         $replaced['key'][] = $key;
         $replaced['data'][] = $plugin;
         // store the decoded-args plugin for replacement later
         // only check fingerprints of plugins requiring validation
         if (!empty($meta['validate'])) {
             $fingerPrintsNew[] = $this->parserlib->plugin_fingerprint($name, $meta, $body, $args);
         }
     }
     $this->parserlib->plugins_replace($data, $replaced);
     // put the plugins back into the page
     return array("data" => $data, "fingerPrintsOld" => $fingerPrintsOld, "fingerPrintsNew" => $fingerPrintsNew);
 }
Exemplo n.º 24
0
 private function cs_process_group(&$dataappend, $grouped, $id, $grouping_keys, $min_match = 2, $max_match = 99, $checksimilar = true, $drop_if_no_match = false)
 {
     $parser = new WikiParser_PluginArgumentParser();
     $to_reconstruct = array();
     foreach ($grouped as $group_id => $grp) {
         if (count($grp) > 1) {
             $args = array();
             $args_checked = array();
             // just for consistency checking
             $query_vals = array();
             foreach ($grp as $g) {
                 $matches = WikiParser_PluginMatcher::match($dataappend[$g]);
                 foreach ($matches as $match) {
                     if ($match->getName() != 'filter') {
                         $query_vals = array();
                         break 2;
                     }
                     $args = $parser->parse($match->getArguments());
                     // double check that they are the same filter other than the query itself, to avoid errornous mixing
                     if ($checksimilar) {
                         $args_to_check = $args;
                         foreach ($grouping_keys as $k) {
                             unset($args_to_check[$k]);
                         }
                         if (!empty($args_checked) && $args_checked != $args_to_check) {
                             $query_vals = array();
                             break 2;
                         } else {
                             $args_checked = $args_to_check;
                         }
                     }
                     foreach ($grouping_keys as $k) {
                         if (array_key_exists($k, $args)) {
                             $query_vals[] = $args[$k];
                             break;
                         }
                     }
                 }
             }
             if (count($query_vals) >= $min_match && count($query_vals) <= $max_match) {
                 $to_reconstruct[$group_id] = array('args' => $args, 'query_vals' => $query_vals);
             } elseif ($drop_if_no_match) {
                 foreach ($grouped[$group_id] as $to_drop) {
                     unset($dataappend[$to_drop]);
                 }
             }
         }
     }
     return $to_reconstruct;
 }
Exemplo n.º 25
0
}
if (!($meta = $parserlib->plugin_info($plugin))) {
    exit;
}
if (!isset($_POST['message'])) {
    $_POST['message'] = (isset($meta['name']) ? tra($meta['name']) : $plugin) . ' ' . tra('Plugin modified by editor.');
}
$info = $tikilib->get_page_info($page);
$tikilib->get_perm_object($page, 'wiki page', $info, true);
if ($tiki_p_edit != 'y') {
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit;
}
$content = $_POST['content'];
$current = $info['data'];
$matches = WikiParser_PluginMatcher::match($current);
$count = 0;
foreach ($matches as $match) {
    if ($match->getName() !== $plugin) {
        continue;
    }
    ++$count;
    if ($_POST['index'] == $count) {
        //by using content of "~same~", it will not replace the body that is there
        $content = $content == "~same~" ? $match->getBody() : $content;
        $params = $match->getArguments();
        // If parameters are provided, rebuild the parameter line
        if (isset($_POST['params']) && is_array($_POST['params'])) {
            // $values was relaxed to accept any argument rather than those defined up front
            // in the plugin's parameter list. This facilitates the use of modules as plugins.
            $params = $_POST['params'];
Exemplo n.º 26
0
 function moveWikiUpToFgal($page_info, $fgalId, &$errors, &$feedbacks)
 {
     global $user;
     $tikilib = TikiLib::lib('tiki');
     include_once 'lib/mime/mimelib.php';
     $argumentParser = new WikiParser_PluginArgumentParser();
     $files = array();
     if (strpos($page_info['data'], 'img/wiki_up') === false) {
         return;
     }
     $matches = WikiParser_PluginMatcher::match($page_info['data']);
     foreach ($matches as $match) {
         $modif = false;
         $plugin_name = $match->getName();
         if ($plugin_name == 'img') {
             $arguments = $argumentParser->parse($match->getArguments());
             $newArgs = array();
             foreach ($arguments as $key => $val) {
                 if ($key == 'src') {
                     if (false === ($data = @file_get_contents($val))) {
                         $errors[] = tra('Cannot open this file:') . ' ' . $val . ' ' . tra('Page:') . ' ' . $page_info['pageName'];
                         continue;
                     }
                     $name = preg_replace('|.*/([^/]*)|', '$1', $val);
                     $fileId = $this->insert_file($fgalId, $name, 'Used in ' . $page_info['pageName'], $name, $data, strlen($data), tiki_get_mime($name, 'application/octet-stream', $val), $user, '', 'wiki_up conversion');
                     if (empty($fileId)) {
                         $errors[] = tra('Cannot upload this file') . ' ' . $val . ' ' . tra('Page:') . ' ' . $page_info['pageName'];
                         continue;
                     } else {
                         $files[] = $val;
                         $modif = true;
                         $newArgs[] = 'fileId="' . $fileId . '"';
                     }
                 } else {
                     $newArgs[] = "{$key}=\"{$val}\"";
                 }
             }
             if ($modif) {
                 $match->replaceWith('{img ' . implode(' ', $newArgs) . '}');
             }
         }
     }
     if (!empty($files)) {
         $tikilib->update_page($page_info['pageName'], $matches->getText(), 'wiki_up conversion', $user, $tikilib->get_ip_address());
         foreach ($files as $file) {
             unlink($file);
         }
         $feedbacks[] = $page_info['pageName'];
     }
 }
Exemplo n.º 27
0
 function __construct($template)
 {
     $this->template = WikiParser_PluginMatcher::match($template);
     $this->format = self::FORMAT_WIKI;
 }
Exemplo n.º 28
0
 function testWithPrettyVariablePrior()
 {
     $strings = '{$f_13}{foo hello=world}';
     $matches = WikiParser_PluginMatcher::match($strings);
     foreach ($matches as $m) {
         $m->replaceWith('X');
     }
     $this->assertEquals('{$f_13}X', $matches->getText());
 }
Exemplo n.º 29
0
 private function loadYaml($content)
 {
     $this->pageContent = $content;
     $pos = 0;
     $this->data = array();
     $matches = WikiParser_PluginMatcher::match($content);
     $parser = new WikiParser_PluginArgumentParser();
     foreach ($matches as $match) {
         $arguments = $parser->parse($match->getArguments());
         if ($match->getName() == 'code' && isset($arguments['caption']) && $arguments['caption'] == 'YAML' || $match->getName() == 'profile') {
             $yaml = $match->getBody();
             $data = Horde_Yaml::load($yaml);
             foreach ($data as $key => $value) {
                 if (array_key_exists($key, $this->data)) {
                     $this->data[$key] = $this->mergeData($this->data[$key], $value);
                 } else {
                     $this->data[$key] = $value;
                 }
             }
         }
     }
     $this->fetchExternals();
     $this->getObjects();
 }
Exemplo n.º 30
0
 function get_pages($data, $withReltype = false)
 {
     global $page_regex, $prefs;
     $tikilib = TikiLib::lib('tiki');
     $matches = WikiParser_PluginMatcher::match($data);
     foreach ($matches as $match) {
         if ($match->getName() == 'code') {
             $match->replaceWith('');
         }
     }
     $data = $matches->getText();
     $htmlLinks = array("0" => "dummy");
     $htmlLinksSefurl = array("0" => "dummy");
     preg_match_all("/\\(([a-z0-9-]+)?\\( *({$page_regex}) *\\)\\)/", $data, $normal);
     preg_match_all("/\\(([a-z0-9-]+)?\\( *({$page_regex}) *\\|(.+?)\\)\\)/", $data, $withDesc);
     preg_match_all('/<a class="wiki[^\\"]*" href="tiki-index\\.php\\?page=([^\\?&"]+)[^"]*"/', $data, $htmlLinks1);
     preg_match_all('/<a href="tiki-index\\.php\\?page=([^\\?&"]+)[^"]*"/', $data, $htmlLinks2);
     $htmlLinks[1] = array_merge($htmlLinks1[1], $htmlLinks2[1]);
     preg_match_all('/<a class="wiki[^\\"]*" href="([^\\?&"]+)[^"]*"/', $data, $htmlLinksSefurl1);
     preg_match_all('/<a href="([^\\?&"]+)[^"]*"/', $data, $htmlLinksSefurl2);
     $htmlLinksSefurl[1] = array_merge($htmlLinksSefurl1[1], $htmlLinksSefurl2[1]);
     preg_match_all('/<a class="wiki wikinew" href="tiki-editpage\\.php\\?page=([^\\?&"]+)"/', $data, $htmlWantedLinks);
     // TODO: revise the need to call modified urldecode() (shouldn't be needed after r37568). 20110922
     foreach ($htmlLinks[1] as &$h) {
         $h = $tikilib->urldecode($h);
     }
     foreach ($htmlLinksSefurl[1] as &$h) {
         $h = $tikilib->urldecode($h);
     }
     foreach ($htmlWantedLinks[1] as &$h) {
         $h = $tikilib->urldecode($h);
     }
     // Post process SEFURL for html wiki pages
     if (count($htmlLinksSefurl[1])) {
         // Remove any possible "tiki-index.php" in the SEFURL link list.
         //	Non-sefurl links will be mapped as "tiki-index.php"
         $tikiindex = array();
         foreach ($htmlLinksSefurl[1] as $pageName) {
             if (strpos($pageName, 'tiki-index.php') !== false) {
                 $tikiindex[] = $pageName;
             }
         }
         $htmlLinksSefurl[1] = array_diff($htmlLinksSefurl[1], $tikiindex);
         if (count($htmlLinksSefurl[1])) {
             // The case <a href=" ... will catch manually entered links. Only add links to wiki pages
             $pages = $tikilib->get_all_pages();
             $tikiindex = array();
             foreach ($htmlLinksSefurl[1] as $link) {
                 // Validate that the link is to a wiki page
                 if (!in_array($link, $pages)) {
                     // If it's not referring to a wiki page, add it to the removal list
                     $tikiindex[] = $link;
                 }
             }
             $htmlLinksSefurl[1] = array_diff($htmlLinksSefurl[1], $tikiindex);
         }
     }
     if ($prefs['feature_wikiwords'] == 'y') {
         preg_match_all("/([ \n\t\r\\,\\;]|^)?([A-Z][a-z0-9_\\-]+[A-Z][a-z0-9_\\-]+[A-Za-z0-9\\-_]*)(\$|[ \n\t\r\\,\\;\\.])/", $data, $wikiLinks);
         $pageList = array_merge($normal[2], $withDesc[2], $wikiLinks[2], $htmlLinks[1], $htmlLinksSefurl[1], $htmlWantedLinks[1]);
         if ($withReltype) {
             $relList = array_merge($normal[1], $withDesc[1], count($wikiLinks[2]) ? array_fill(0, count($wikiLinks[2]), null) : array(), count($htmlLinks[1]) ? array_fill(0, count($htmlLinks[1]), null) : array(), count($htmlLinksSefurl[1]) ? array_fill(0, count($htmlLinksSefurl[1]), null) : array(), count($htmlWantedLinks[1]) ? array_fill(0, count($htmlWantedLinks[1]), null) : array());
         }
     } else {
         $pageList = array_merge($normal[2], $withDesc[2], $htmlLinks[1], $htmlLinksSefurl[1], $htmlWantedLinks[1]);
         if ($withReltype) {
             $relList = array_merge($normal[1], $withDesc[1], count($htmlLinks[1]) ? array_fill(0, count($htmlLinks[1]), null) : array(), count($htmlLinksSefurl[1]) ? array_fill(0, count($htmlLinksSefurl[1]), null) : array(), count($htmlWantedLinks[1]) ? array_fill(0, count($htmlWantedLinks[1]), null) : array());
         }
     }
     if ($withReltype) {
         $complete = array();
         foreach ($pageList as $idx => $name) {
             if (!array_key_exists($name, $complete)) {
                 $complete[$name] = array();
             }
             if (!empty($relList[$idx]) && !in_array($relList[$idx], $complete[$name])) {
                 $complete[$name][] = $relList[$idx];
             }
         }
         return $complete;
     } else {
         return array_unique($pageList);
     }
 }