Beispiel #1
0
 function __initialize()
 {
     parent::__initialize();
     $ds = model_datasource('system');
     $ds->ExecuteSql("CREATE TABLE IF NOT EXISTS blog(id INTEGER,title VARCHAR(50),body TEXT,PRIMARY KEY(id))");
     $this->content(new Anchor(buildQuery('blog', 'newpost'), 'New post'));
 }
 /**
  * @param string $culture_code Culture code (see <CultureInfo>)
  * @param mixed $selected_date_format The currently selected date format or false
  * @param mixed $selected_time_format The currently selected time format or false
  * @param string $timezone Timezone identifier or false
  */
 function __initialize($culture_code, $selected_date_format = false, $selected_time_format = false, $timezone = false)
 {
     parent::__initialize();
     $this->script("Locale_Settings_Init();");
     $this->setData('role', 'datetimeformat');
     $this->setData('controller', buildQuery($this->id));
     $this->culture_code = $culture_code;
     if ($selected_date_format || $selected_time_format) {
         $this->SetCurrentValue(json_encode(array($selected_date_format ? $selected_date_format : false, $selected_time_format ? $selected_time_format : false)));
     }
     $df = array(DateTimeFormat::DF_LONGDATE, DateTimeFormat::DF_SHORTDATE, DateTimeFormat::DF_MONTHDAY, DateTimeFormat::DF_YEARMONTH);
     $tf = array(DateTimeFormat::DF_LONGTIME, DateTimeFormat::DF_SHORTTIME);
     $value = time();
     $ci = Localization::getCultureInfo($culture_code);
     if ($timezone) {
         $ci->SetTimezone($timezone);
         $value = $ci->GetTimezoneDate($value);
     }
     $dtf = $ci->DateTimeFormat;
     foreach ($df as $d) {
         foreach ($tf as $t) {
             $sv = $dtf->Format($value, $d) . " " . $dtf->Format($value, $t);
             $this->AddOption(json_encode(array($d, $t)), $sv);
         }
     }
 }
 /**
  * @param string $culture_code Code of current <CultureInfo>
  * @param mixed $date_format Chosen date format
  * @param mixed $time_format Chosen time format
  * @param string $timezone Currently chosen timezone
  * @param bool $append_timezone If true timezome will be appended
  */
 function __initialize($culture_code, $date_format, $time_format, $timezone = false, $append_timezone = false)
 {
     parent::__initialize();
     $this->script("Locale_Settings_Init();");
     store_object($this);
     if (!$timezone) {
         $timezone = Localization::getTimeZone();
     }
     $this->timezone = $timezone;
     $this->culture_code = $culture_code;
     $txt = $this->_sample(false, $date_format, $time_format);
     if ($append_timezone) {
         $txt .= " {$timezone}";
     }
     $sample = new Control('span');
     $sample->append("({$txt})")->css('color', 'gray');
     $cb = new CheckBox();
     $cb->setData('role', 'timeformatex')->setData('controller', buildQuery($this->id));
     $cb->value = 1;
     if ($append_timezone) {
         $cb->checked = "checked";
     }
     $lab = $cb->CreateLabel(tds("TXT_APPEND_TIMEZONE", "Append timezone") . " ");
     $lab->content($sample);
     $this->append($cb)->append($lab);
 }
 /**
  * Shows product details
  * @attribute[RequestParam('id','int')]
  */
 function Details($id)
 {
     // check if product really exists
     $ds = model_datasource('system');
     $prod = $ds->Query('products')->eq('id', $id)->current();
     if (!$prod) {
         redirect('Products', 'Index', array('error' => 'Product not found'));
     }
     // create a template with product details
     $this->content(Template::Make('product_details'))->set('title', $prod->title)->set('description', $prod->body)->set('image', resFile($prod->image))->set('link', buildQuery('Basket', 'Add', array('id' => $prod->id)));
 }
 /**
  * @param mixed $current_language_code Currently selected language
  * @param type $current_region_code Currently selected region
  */
 function __initialize($current_language_code = false, $current_region_code = false)
 {
     parent::__initialize();
     $this->script("Locale_Settings_Init();");
     $this->setData('role', 'region');
     $this->setData('controller', buildQuery($this->id));
     if ($current_language_code) {
         if ($current_language_code instanceof CultureInfo) {
             $lang = $current_language_code->ResolveToLanguage();
         } else {
             $lang = Localization::getLanguageCulture($current_language_code);
         }
         if (!$lang) {
             $lang = Localization::detectCulture()->ResolveToLanguage();
         }
         $regions = $lang->GetRegions(false);
         if (!$current_region_code) {
             $current_region_code = $lang->DefaultRegion()->Code;
         }
     } else {
         $regions = Localization::get_all_regions(false);
     }
     if ($current_region_code) {
         if ($current_region_code instanceof CultureInfo) {
             $this->SetCurrentValue($current_region_code->DefaultRegion()->Code);
         } else {
             $this->SetCurrentValue($current_region_code);
         }
     }
     if (count($regions) > 0) {
         $cc = current_controller(false);
         $translations_active = $cc instanceof Renderable && $cc->_translate;
         $sorted = array();
         foreach ($regions as $reg) {
             if (!$reg) {
                 continue;
             }
             $code = $reg->Code;
             if ($translations_active) {
                 $sorted[$code] = array("name" => tds("TXT_COUNTRY_" . strtoupper($code), $reg->EnglishName), "code", $code);
             } else {
                 $sorted[$code] = array("name" => $reg->EnglishName, "code", $code);
             }
         }
         uasort($sorted, __CLASS__ . "::compareCountryNames");
         foreach ($sorted as $code => $item) {
             $this->AddOption($code, $item['name']);
         }
     }
 }
 /**
  * @param string $currency_code A valid currency code
  * @param mixed $selected_format The currently selected format
  */
 function __initialize($currency_code, $selected_format = false)
 {
     parent::__initialize();
     $this->script("Locale_Settings_Init();");
     $this->setData('role', 'currenyformat');
     $this->setData('controller', buildQuery($this->id));
     if ($selected_format) {
         $this->SetCurrentValue($selected_format);
     }
     $samples = $this->getCurrencySamples($currency_code, 1234.56, true);
     foreach ($samples as $code => $label) {
         $this->AddOption($code, $label);
     }
 }
 /**
  * @attribute[RequestParam('f','string')]
  */
 function Linked($f)
 {
     if ($f) {
         $md = file_get_contents(__DIR__ . "/out/{$f}.md");
     } else {
         $md = "# Scavix WDF Home\n- [Alphabetical function listing](functions)\n- [Alphabetical class listing](classes)\n- [Inheritance tree](inheritance)\n- [Interfaces](interfaces)\n- [Folder tree](foldertree)\n- [Namespace tree](namespacetree)";
     }
     $q = buildQuery('Preview', 'Linked');
     $s = "\$('.markdown-body').html(marked(" . json_encode($md) . "));";
     $s .= "\$('.markdown-body a[id]').each(function(){ \$(this).attr('id','wiki-'+\$(this).attr('id')); });";
     $s .= "\$('.markdown-body a[href]').each(function(){ if( \$(this).attr('href').match(/^http/)) return; \$(this).attr('href','{$q}?f='+\$(this).attr('href')); });";
     $s .= "\$('.markdown-body a[id='+location.hash.substr(1)+']').get(0).scrollIntoView();";
     $this->addDocReady("{$s}");
 }
Beispiel #8
0
function mysqlQuery($config, $request, $report)
{
    $mysql = mysqlAccess($config);
    $start_time = getMicrotime();
    //		$show_time = true;
    if (!isset($request['mode'])) {
        $request['mode'] = 'SELECT';
    }
    $request['model'] = $GLOBALS['model'][$GLOBALS['controller']]['model'];
    if ($GLOBALS['debug'] == true) {
        print_r($request);
    }
    $db_result = buildQuery($mysql, $request, $start_time, $report);
    // Return MySQL query result and query:
    return array('result' => $db_result['result'], 'query' => $db_result['query']);
    // Close MySQL connection:
    $mysql->close();
}
Beispiel #9
0
function buildQuery($data, $separator = '&amp;', $key = '')
{
    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    $p = array();
    foreach ($data as $k => $v) {
        $k = urlencode($k);
        if (!empty($key)) {
            $k = $key . '[' . $k . ']';
        }
        if (is_array($v) || is_object($v)) {
            $p[] = buildQuery($v, $separator, $k);
        } else {
            $p[] = $k . '=' . urlencode($v);
        }
    }
    return implode($separator, $p);
}
Beispiel #10
0
$found_order = strrpos($query1, "order");
$target1 = buildTarget($query1);
$from1 = buildFrom($found_where, $found_group, $found_order, $query1);
$where1 = buildWhere($found_where, $found_group, $found_order, $query1);
$group1 = buildGroup($found_group, $found_order, $query1);
$order1 = buildOrder($found_order, $query1);
//******************************************************EXTRACTION 2
$found_group = strrpos($query2, "group");
$found_where = strrpos($query2, "where");
$found_order = strrpos($query2, "order");
$target2 = buildTarget($query2);
$from2 = buildFrom2($found_where, $found_group, $found_order, $query2);
$where2 = buildWhere($found_where, $found_group, $found_order, $query2);
$group2 = buildGroup($found_group, $found_order, $query2);
$order2 = buildOrder($found_order, $query2);
$query = buildQuery($cubetablenameB, $join_final, $target1, $target2, $from1, $from2, $where1, $where2, $group1, $group2, $order1, $order2);
$result = exec_query($query);
buildReport($result);
//*****************************************************************************************************************************************
function buildFrom($found_where, $found_group, $found_order, $query1)
{
    //FROM
    if ($found_where == true) {
        $a = eregi("from (.+) where", $query1, $regs);
    } elseif ($found_group == true) {
        $a = eregi("from (.+) group", $query1, $regs);
    } elseif ($found_order == true) {
        $a = eregi("from (.+) order", $query1, $regs);
    } else {
        $a = eregi("from (.+)\$", $query1, $regs);
    }
 * Scavix Web Development Framework
 *
 * Copyright (c) since 2012 Scavix Software Ltd. & Co. KG
 *
 * This library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General
 * Public License as published by the Free Software Foundation;
 * either version 3 of the License, or (at your option) any
 * later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>
 *
 * @author Scavix Software Ltd. & Co. KG http://www.scavix.com <*****@*****.**>
 * @copyright since 2012 Scavix Software Ltd. & Co. KG
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 */
?>
<form action="<?php 
echo buildQuery('blog', 'addpost');
?>
" method="post">
	Title: <input type="text" name="title"/><br/>
	Text: <textarea name="body"></textarea><br/>
	<input type="submit" value="Create post"/>
</form>
<?php

include_once 'src/database-config.php';
if ($_REQUEST['qtype'] == 'search') {
    $rawquery = trim($_REQUEST['q']);
    $limit = $_REQUEST['page_limit'];
    $query = $rawquery;
    while (preg_match('/  /', $rawquery)) {
        $query = preg_replace('/  /', ' ', $rawquery);
        $rawquery = $query;
    }
    $sql = buildQuery($query, false);
    $jsonObject = array();
    $result = queryPostgres($sql);
    if (pg_num_rows($result) < 1) {
        $sql = buildQuery($query, true);
        $result = queryPostgres($sql);
    }
    while ($row = pg_fetch_object($result)) {
        $address = preg_replace('/~/', ' ', $row->address);
        $jsonObject[] = array('id' => $row->pid, 'text' => $address);
    }
    header('Content-type: application/json');
    echo json_encode($jsonObject);
} else {
    if ($_REQUEST['qtype'] == 'retrieve') {
        $query = trim($_REQUEST['address']);
        $sql = "select\n                to_char((now() - '1 day'::INTERVAL) - ((now()::date - SeedDate::date - 1)%days)*'1 day'::INTERVAL,'Day Mon FMDD, YYYY') as \"lastpickup\",\n                to_char((now() - '1 day'::INTERVAL) + ((Days) * '1 day'::INTERVAL)  - ((now()::date - SeedDate::date - 1)%days)*'1 day'::INTERVAL,'Day Mon FMDD, YYYY') as \"nextpickup\",\n\t\t\t\taddress,\n\t\t\t\tST_AsGeoJSON(ST_Transform(geom, 4326), 5) AS geom,\n                servicecode,\n                day,\n                week,\n                frequency,\n                containersdescription\nfrom dbo.\"WastePickup\"\nwhere PID = {$query}";
        $result = pg_query($dbConn, $sql);
        $addressObj = array();
        $servicesObj = array();
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>
 *
 * @author Scavix Software Ltd. & Co. KG http://www.scavix.com <*****@*****.**>
 * @copyright since 2012 Scavix Software Ltd. & Co. KG
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 */
?>
<form id="frm_add_product" method="post" action="<?php 
echo buildQuery('Admin', 'AddProduct');
?>
" enctype="multipart/form-data">
	<table>
		<tr>
			<td>Title</td>
			<td><input type="text" name="title" value=""/></td>
		</tr>
		<tr>
			<td>Tagline</td>
			<td><input type="text" name="tagline" value=""/></td>
		</tr>
		<tr>
			<td>Description</td>
			<td><textarea name="body"></textarea></td>
		</tr>
Beispiel #14
0
function buildQuery(&$node)
{
    if (!is_array($node) || count($node) < 1) {
        return;
    }
    $hasChild = count($node) > 1;
    if ($hasChild) {
        $sub .= "[";
    }
    $i = 0;
    foreach ($node as $key => $subnode) {
        $sub .= "{$key}";
        if (is_array($subnode) && count($subnode) >= 1) {
            $sub .= ".";
            $sub .= buildQuery($subnode);
        }
        if ($i < count($node) - 1) {
            $sub .= ",";
        }
        ++$i;
    }
    if ($hasChild) {
        $sub .= "]";
    }
    return $sub;
}
Beispiel #15
0
            $updated_session = [SessionOperator::SORT => $sort];
        } else {
            HelperOperator::redirectTo("../views/search_view.php");
            return;
        }
    }
}
$cats = getCatIdAndType($searchCategory);
// Set up pagination object
$total = QueryOperator::countFoundAuctions(buildQuery($searchString, $cats, null));
$page = isset($_GET["page"]) ? $_GET["page"] : 1;
$page = $page <= $total ? $page : 1;
$per_page = 15;
$pagination = new Pagination($page, $per_page, $total);
// Get paginated search results
$catsAndAuctions = QueryOperator::searchAuctions(buildQuery($searchString, $cats, $sort, $per_page, $pagination->offset()));
// Update search sessions
$updated_session = array_merge([SessionOperator::SEARCH_RESULT => $catsAndAuctions], $updated_session);
$updated_session = array_merge([SessionOperator::SEARCH_PAGINATION => $pagination], $updated_session);
SessionOperator::setSearch($updated_session);
// Return back to search page
HelperOperator::redirectTo("../views/search_view.php");
function buildQuery($searchString, $searchCategory, $sortOption, $limit = null, $offset = null)
{
    $query = null;
    // Prepare count query
    if (is_null($limit) && is_null($offset)) {
        $query = "SELECT COUNT(*) ";
    } else {
        $query = "SELECT auctions.auctionId, quantity, startPrice, reservePrice, startTime,\n            endTime, itemName, itemBrand, itemDescription, items.image, auctions.views,\n            item_categories.categoryName as subCategoryName, superCategoryName,\n            item_categories.superCategoryId, item_categories.categoryId,\n            conditionName, countryName, COUNT(DISTINCT (bids.bidId)) AS numBids,\n            COUNT(DISTINCT (auction_watches.watchId)) AS numWatches,\n            MAX(bids.bidPrice) AS highestBid,\n            case\n                when MAX(bids.bidPrice)is not null THEN MAX(bids.bidPrice)\n                else startPrice\n            end AS currentPrice ";
    }
Beispiel #16
0
 function Prepare($async = false, &$handler = false, $method = false)
 {
     global $CONFIG;
     if ($async) {
         if (!$handler || !$method) {
             WdfException::Raise("Data handler and method needed for asynchronous charts");
         }
         $data_url = buildQuery($handler->id, $method);
     } else {
         if ($handler && $method) {
             $data = $handler->{$method}($this);
         }
         //			else
         //				$data = $this->CleanupXML($this->RenderXML());
     }
     $str_data = $this->Title ? $this->Title : '';
     $swfurl = $CONFIG['system']['system_uri'] . appendVersion("/modules/charting/charts/" . $this->Type . ".swf");
     $swfurl .= "?PBarLoadingText=" . urlencode($str_data . ":\n" . getString(tds("TXT_CHART_LOADING", 'loading')));
     $swfurl .= "&ChartNoDataText=" . urlencode($str_data . ":\n" . getString(tds("TXT_NO_DATA_FOUND", 'no data found')));
     $swfurl .= "&InvalidXMLText=" . urlencode($str_data . ":\n" . getString(tds("TXT_CHART_INVALID_XML", 'invalid XML')));
     $settings = array('swfurl' => $swfurl, 'chartid' => $this->id, 'width' => $this->Width, 'height' => $this->Height, 'debug' => 0);
     if (isset($data)) {
         $settings['data'] = $data;
     } elseif (isset($data_url)) {
         $settings['dataurl'] = $data_url;
     }
     $this->_script = array();
     $this->script("initFusionChart(" . json_encode($settings) . ");");
 }
Beispiel #17
0
 /**
  * Creates javascript code to redirect elsewhere on button click.
  * 
  * @param mixed $controller The controller to be loaded (can be <Renderable> or string)
  * @param string $method The method to be executed
  * @param array|string $data Optional data to be passed
  * @return uiButton `$this`
  */
 function LinkTo($controller, $method = '', $data = array())
 {
     $q = buildQuery($controller, $method, $data);
     $this->onclick = "document.location.href = '{$q}';";
     return $this;
 }
Beispiel #18
0
echo buildQuery('Preview', 'Linked', 'f=classes');
?>
">Classes</a>
	&nbsp;&nbsp;
	<a href="<?php 
echo buildQuery('Preview', 'Linked', 'f=inheritance');
?>
">Inheritance</a>
	&nbsp;&nbsp;
	<a href="<?php 
echo buildQuery('Preview', 'Linked', 'f=interfaces');
?>
">Interfaces</a>
	&nbsp;&nbsp;
	<a href="<?php 
echo buildQuery('Preview', 'Linked', 'f=foldertree');
?>
">Folder tree</a>
	&nbsp;&nbsp;
	<a href="<?php 
echo buildQuery('Preview', 'Linked', 'f=namespacetree');
?>
">Namespace tree</a>
</div>
<div class="markdown-body">
<?php 
foreach ($content as $c) {
    echo $c;
}
?>
</div>
Beispiel #19
0
 /**
  * Persists current basket to the database and starts checkout process.
  * @attribute[RequestParam('fname','string')]
  * @attribute[RequestParam('lname','string')]
  * @attribute[RequestParam('street','string')]
  * @attribute[RequestParam('zip','string')]
  * @attribute[RequestParam('city','string')]
  * @attribute[RequestParam('email','string')]
  * @attribute[RequestParam('provider','string')]
  */
 function StartCheckout($fname, $lname, $street, $zip, $city, $email, $provider)
 {
     log_debug("StartCheckout({$fname},{$lname},{$street},{$zip},{$city},{$email},{$provider})");
     if (!$fname || !$lname || !$street || !$zip || !$city || !$email) {
         redirect('Basket', 'Index', array('error' => 'Missing some data'));
     }
     // create a new customer. note that we do not check for existance or stuff.
     // this should be part of a real shop system!
     $cust = new SampleCustomer();
     $cust->fname = $fname;
     $cust->lname = $lname;
     $cust->street = $street;
     $cust->zip = $zip;
     $cust->city = $city;
     $cust->email = $email;
     $cust->price_total = 0;
     $cust->Save();
     // create a new order and assign the customer (from above)
     $order = new SampleShopOrder();
     $order->customer_id = $cust->id;
     $order->created = 'now()';
     $order->Save();
     // now loop thru the basket-items and add them to the order...
     $ds = model_datasource('system');
     foreach ($_SESSION['basket'] as $id => $amount) {
         //... by creating a dataset for each item
         $prod = $ds->Query('products')->eq('id', $id)->current();
         $item = new SampleShopOrderItem();
         $item->order_id = $order->id;
         $item->price = $prod->price;
         $item->amount = $amount;
         $item->title = $prod->title;
         $item->tagline = $prod->tagline;
         $item->body = $prod->body;
         $item->Save();
         $order->price_total += $amount * $prod->price;
     }
     // save the order again to persist the total amount
     $order->Save();
     $_SESSION['basket'] = array();
     // finally start the checkout process using the given payment provider
     log_debug("Handing control over to payment provider '{$provider}'");
     $p = new $provider();
     $p->StartCheckout($order, buildQuery('Basket', 'PostPayment'));
 }
Beispiel #20
0
 *
 * @author Scavix Software Ltd. & Co. KG http://www.scavix.com <*****@*****.**>
 * @copyright since 2012 Scavix Software Ltd. & Co. KG
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 */
?>
<div id="page">
	<div id="navigation">
		<a href="<?php 
echo buildQuery('Products');
?>
">Products</a>
		<a href="<?php 
echo buildQuery('Basket');
?>
">Basket</a>
		<a href="<?php 
echo buildQuery('Admin');
?>
">Administration (normally hidden)</a>
	</div>
	<div id="content">
		<?php 
foreach ($content as $c) {
    echo $c;
}
?>
	
	</div>
</div>
/**
 * buildSimpleQuery
 *
 * This is a simplified version of buildQuery for use on one table.  The
 * arguments are specified as strings in most cases instead of arrays.
 *
 * Example:  The following db abstract code -
 *
 * $column = &$pntable['authors_column'];
 * $result = $dbconn->query ("SELECT $column[aid], $column[name]
 *                              FROM $pntable['authors']
 *                              WHERE $column[radminarticle]=1
 *                              ORDER BY $column[aid]
 *                              LIMIT 1");
 *
 * Could be re-written as:
 *
 * $column = &$pntable['authors_column'];
 * $myquery = buildSimpleQuery ('authors', array ('aid', 'name'), "$column[radminarticle]=1", "$column[aid]", 1);
 * $result = $dbconn->query($myquery);
 *
 * (you could, of course, skip storing the string in $myquery...but for
 *  illustration I included it)
 *
 * The nice thing about using this is that it takes care of db-specific
 * ways of handling the "LIMIT" clause because it uses buildQuery internally.
 * 
 * ARGUMENTS:
 *  Strings: $tablename  = $pntable mapping name
 *           $where      = WHERE clause conditions ('WHERE' added automatically)
 *           $orderby    = ORDERBY sort order ('ORDER BY' added automatically)
 *
 *  int:     $limitmax   = The maximum number of rows to return
 *           $limitmin   = the offset in the result set to start at
 *
 *  array:   $columnames = array of $pntable mapping names to return from the query
 */
function buildSimpleQuery($tablename, $columnnames, $where = '', $orderby = '', $limitmax = '', $limitmin = '')
{
    // get the database connection
    $dbconn =& pnDBGetConn(true);
    $pntable =& pnDBGetTables();
    if ($orderby) {
        $orderby = array($orderby);
    }
    // pull out fully qualified columnnames
    $column =& $pntable["{$tablename}_column"];
    foreach ($columnnames as $idx => $name) {
        $columnnames[$idx] = "{$column[$name]} AS \"{$name}\"";
    }
    return buildQuery(array($tablename), $columnnames, $where, $orderby, $limitmax, $limitmin);
}
Beispiel #22
0
 function Run()
 {
     $summary = $this->content(new Control('div'));
     $run = new Anchor(buildQuery('DocMain', 'Run'), 'Run again');
     $down = new Anchor(buildQuery('DocMain', 'Download'), 'Download');
     $preview = new Anchor(buildQuery('Preview'), 'Preview');
     $this->content('<div style="text-align: center; font-size: 18px; font-weight: bold">');
     $this->content($run->WdfRender() . "&nbsp;&nbsp;" . $down->WdfRender() . "&nbsp;&nbsp;" . $preview->WdfRender());
     $this->content('</div>');
     if (!file_exists(__DIR__ . '/out')) {
         mkdir(__DIR__ . '/out');
     }
     foreach (system_glob_rec(__DIR__ . '/out', '*') as $file) {
         unlink($file);
     }
     cache_clear();
     $path = realpath(__DIR__ . '/../../system/');
     $i = 1;
     global $home, $processed_files;
     $home = array('funcs' => array(), 'classes' => array(), 'methods' => array(), 'tree' => array(), 'interfaces' => array(), 'namespaces' => array());
     $processed_files = array();
     $all_files = system_glob_rec($path, '*.php');
     $cnt_all_files = count($all_files);
     foreach ($all_files as $file) {
         if ($this->skip($file)) {
             $cnt_all_files--;
             continue;
         }
         $title = str_replace($path . '/', '', $file);
         $fn_cls = __DIR__ . '/out/classes_' . str_replace('.php.md', '.md', str_replace('/', '_', $title) . '.md');
         $fn_fnc = __DIR__ . '/out/functions_' . str_replace('.php.md', '.md', str_replace('/', '_', $title) . '.md');
         $this->_startSection("FILE: {$file}");
         $data = $this->process($file);
         if ($i++ > self::MAX_FILES) {
             $this->content("<h1>Stopping, still " . ($cnt_all_files - self::MAX_FILES) . " missing</h1>");
             break;
         }
         // functions
         $lines = array();
         foreach ($data['functions'] as $func) {
             $l = $this->funcToMd($func);
             if ($l) {
                 $home['funcs'][$func['name']] = basename($fn_fnc, '.md') . "#wiki-" . md5($func['name']);
                 $lines[] = $l;
                 //					$processed_files[$title][] = $func['name']; // we do not want functions in the folder tree
             }
         }
         if (count($lines) > 0) {
             file_put_contents($fn_fnc, $this->escapeMd("# Functions in file {$title}\n" . implode("\n", $lines)));
         }
         // classes
         $lines = array();
         foreach ($data['classes'] as $class) {
             //				log_if($class['name']=="uiControl",$class['name'],$class);
             $lines[] = $this->classToMd($class, basename($fn_cls, '.md'));
             if ($class['type'] == 'interface' && !isset($home['interfaces'][$class['type']])) {
                 $home['interfaces'][$class['name']] = array();
             }
             if (isset($class['implements'])) {
                 foreach ($class['implements'] as $int) {
                     if (!isset($home['interfaces'][$int])) {
                         $home['interfaces'][$int] = array($class['name']);
                     } else {
                         $home['interfaces'][$int][] = $class['name'];
                     }
                 }
             }
             $processed_files[$title][] = $class['name'];
         }
         if (count($lines) > 0) {
             file_put_contents($fn_cls, $this->escapeMd("# Classes in file {$title}\n" . implode("\n", $lines)));
         }
     }
     $this->_endSection();
     $this->writeIndexes();
     $this->createLinks();
     $this->writeZip();
     if (array_sum($this->sums) > 0 || count($this->errors) > 0) {
         $summary->addClass('summary');
         $summary->content("<b>Summary:</b><br/>");
         if ($this->sums['comment'] > 0) {
             $summary->content("Missing comments: {$this->sums['comment']}<br/>");
         }
         if ($this->sums['short'] > 0) {
             $summary->content("Missing short descriptions: {$this->sums['short']}<br/>");
         }
         if ($this->sums['long'] > 0) {
             $summary->content("Missing long descriptions: {$this->sums['long']}<br/>");
         }
         if ($this->sums['param'] > 0) {
             $summary->content("Missing param descriptions: {$this->sums['param']}<br/>");
         }
         if ($this->sums['return'] > 0) {
             $summary->content("Missing return value descriptions: {$this->sums['return']}<br/>");
         }
         foreach ($this->errors as $err) {
             $summary->content("{$err}<br/>");
         }
     }
 }
?>
" method="post" class="login">
    <table>
        <thead>
            <tr>
                <td colspan="2">Login first</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Username</td>
                <td align="right"><input name="username" type="text"/></td>
            </tr>
            <tr>
                <td>Password</td>
                <td align="right"><input name="password" type="password"/></td>
            </tr>
        </tbody>
        <tfoot>
            <tr>
                <td colspan="2" align="right">
                    <a href="<?php 
echo buildQuery('', '');
?>
"/>Back to app</a>
                    <input type="submit" value="Login"/>
                </td>
            </tr>
        </tfoot>
    </table>
</form>
Beispiel #24
0
/**
 * Executed a header redirect to another page.
 * 
 * Calls buildQuery internally to build an URL to the current route, but will also work
 * if `$controller` already is an URL.
 * Note: Will terminate the current processing silently and sent a "Location" header!
 * @param string $controller The page to be called
 * @param string $event The event to be executed
 * @param array|string $data Optional data to be passed
 * @param string $url_root Optional root, will use system-wide detected/set one if not given
 * @return void
 */
function redirect($controller, $event = "", $data = "", $url_root = false)
{
    if (is_array($controller)) {
        $url = array();
        foreach ($controller as $key => &$val) {
            $url[] = "{$key}={$val}";
        }
        $url = '?' . implode("&", $url);
    } else {
        $url = buildQuery($controller, $event, $data, $url_root);
    }
    header("Location: " . $url);
    exit;
}
Beispiel #25
0
 /**
  * @override
  */
 public function StartCheckout(IShopOrder $order, $ok_url = false, $cancel_url = false)
 {
     global $CONFIG;
     if (!$ok_url) {
         WdfException::Raise('PayPal needs a return URL');
     }
     if (!$cancel_url) {
         $cancel_url = $ok_url;
     }
     $invoice_id = false;
     if ($tmp = $order->GetInvoiceId()) {
         $invoice_id = $tmp;
     }
     $this->SetVar("cmd", "_cart");
     $this->SetVar("upload", "1");
     $order_currency = $this->EnsureCurrency($order);
     $order->SetCurrency($order_currency);
     $this->SetVar("currency_code", $order_currency);
     $this->SetVar("charset", "utf-8");
     //		set language of paypal UI:
     //		$this->SetVar("lc", );
     if ($CONFIG["payment"]["paypal"]["use_sandbox"] == true) {
         $this->SetVar("sandbox", "1");
         $checkoutUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr";
     } else {
         $checkoutUrl = "https://www.paypal.com/cgi-bin/webscr";
     }
     $this->SetVar('business', $CONFIG["payment"]["paypal"]["paypal_id"]);
     $this->SetVar('custom', $CONFIG["payment"]["paypal"]["custom"]);
     if ($invoice_id) {
         $ok_url .= (stripos($ok_url, '?') !== false ? '&' : '?') . "order_id={$invoice_id}";
         $cancel_url .= (stripos($cancel_url, '?') !== false ? '&' : '?') . "order_id={$invoice_id}";
     }
     $this->SetVar('return', $ok_url);
     $this->SetVar('cancel_return', $cancel_url);
     $params = array("provider" => "paypal");
     $notify_url = buildQuery($CONFIG["payment"]["paypal"]["notify_handler"][0], $CONFIG["payment"]["paypal"]["notify_handler"][1], $params);
     $this->SetVar('notify_url', $notify_url);
     // customer details
     $address = $order->GetAddress();
     if ($address->Firstname) {
         $this->SetVar('first_name', $address->Firstname);
     }
     if ($address->Lastname) {
         $this->SetVar('last_name', $address->Lastname);
     }
     if ($address->Email) {
         $this->SetVar('email', $address->Email);
     }
     if ($address->Address1) {
         $this->SetVar('address1', $address->Address1);
     }
     if ($address->Address2) {
         $this->SetVar('address2', $address->Address2);
     }
     if ($address->Country) {
         $this->SetVar('country', $address->Country);
     }
     if ($address->State) {
         $this->SetVar('state', $address->State);
     }
     if ($address->Zip) {
         $this->SetVar('zip', $address->Zip);
     }
     if ($address->City) {
         $this->SetVar('city', $address->City);
     }
     // tell paypal to use this entered address:
     $this->SetVar('address_override', 1);
     $this->SetVar('bn', $CONFIG["payment"]["paypal"]["custom"]);
     // do not let users add notes in paypal:
     $this->SetVar('no_note', 1);
     /* Return method. The  FORM METHOD used to send data to the 
     		URL specified by the  return variable. 
     		Allowable values are: 
     		0 – all shopping cart payments use the GET  method 
     		1 – the buyer’s browser is re directed to the return URL 
     		by using the GET  method, but no payment variables are 
     		included 
     		2 – the buyer’s browser is re directed to the return URL 
     		by using the POST method, and all payment variables are 
     		included */
     $this->SetVar('rm', 1);
     if ($invoice_id) {
         $this->SetVar('invoice', $invoice_id);
     }
     $items = $order->ListItems();
     if (count($items) > 0) {
         $i = 1;
         foreach ($items as $item) {
             $price = $item->GetAmount();
             $this->SetVar("item_name_{$i}", $item->GetName());
             $this->SetVar("amount_{$i}", round($item->GetAmount($order_currency), 2));
             if ($order->DoAddVat()) {
                 $this->SetVar("tax_{$i}", round($item->GetAmount($order_currency) * ($CONFIG['model']['vat_percent'] / 100), 2));
             }
             $this->SetVar("quantity_{$i}", 1);
             $i++;
         }
     }
     $this->SetVar("tax_cart", round($order->GetTotalVat(), 2));
     return $this->CheckoutForm($checkoutUrl);
 }
 /**
  * Let the client redirect.
  * 
  * @param mixed $controller The controller to be loaded (can be <Renderable> or string)
  * @param string $event The event to be executed
  * @param mixed $data Optional data to be passed (string or array)
  * @return AjaxResponse The created response
  */
 public static function Redirect($controller, $event = '', $data = '')
 {
     $q = buildQuery($controller, $event, $data);
     return AjaxResponse::Js("wdf.redirect('{$q}');");
 }
 /**
  * @internal Entry point for translation admin.
  * @attribute[RequestParam('lang','string',false)]
  * @attribute[RequestParam('offset','int',0)]
  * @attribute[RequestParam('search','text','')]
  * @attribute[RequestParam('untranslated','bool',false)]
  */
 function Translate($lang, $offset, $search, $untranslated)
 {
     global $CONFIG;
     if ($untranslated) {
         $search = '';
     }
     $lang = $lang ? $lang : $CONFIG['localization']['default_language'];
     $_SESSION['trans_admin_lang'] = $lang;
     $_SESSION['trans_admin_offset'] = $offset;
     $_SESSION['trans_admin_search'] = $search;
     $form = $this->content(new Form());
     $form->css('margin-bottom', '20px')->action = buildQuery('TranslationAdmin', 'Translate');
     $form->content("Select language: ");
     $form->content($this->_languageSelect($lang))->script("\$('#{self}').change(function(){ \$('#{$form->id}').submit(); });")->name = 'lang';
     $form->content("&nbsp;&nbsp;&nbsp;And/Or search: ");
     $form->AddText('search', $search);
     $form->AddHidden('offset', 0);
     $form->AddSubmit('Search');
     $form->content("<span style='color:gray'>(?:=single char, *:=any/no char)</span>");
     if ($lang != $CONFIG['localization']['default_language']) {
         $form->content("&nbsp;&nbsp;&nbsp;Or ");
         $form->AddHidden('untranslated', 0)->id = 'untranslated';
         Button::Make("Show untranslated", "\$('#untranslated').val('1').closest('form').submit();")->appendTo($form);
     }
     $tab = Table::Make()->addClass('translations')->SetHeader('Term', 'Default', 'Content', '', '')->setData('lang', $lang)->appendTo($this);
     $rs = $this->_searchQuery($offset, $lang, $search, $untranslated);
     foreach ($rs as $term) {
         $def = nl2br(htmlspecialchars($term['def']));
         $ta = new TextArea($untranslated ? '' : $term['trans']);
         $ta->class = $term['id'];
         $ta->rows = count(explode('<br />', $def)) + 1;
         $btn = new Button('Save');
         $btn->addClass('save')->setData('term', $term['id']);
         $tab->AddNewRow($term['id'], $def, $ta, $btn, '');
         $c = $tab->GetCurrentRow()->GetCell(4);
         $c->css('white-space', 'nowrap');
         $c->content(Control::Make("span"))->addClass('term_action rename')->setData('term', $term['id'])->content('rename');
         $c->content("&nbsp;");
         $c->content(Control::Make("span"))->addClass('term_action remove')->setData('term', $term['id'])->content('remove');
     }
     if ($tab->GetCurrentRow()) {
         $tab->GetCurrentRow()->GetCell(1)->style = 'width: 40%';
     }
     $pi = $rs->GetPagingInfo();
     for ($page = 1; $page <= $pi['total_pages']; $page++) {
         $offset = ($page - 1) * $pi['rows_per_page'];
         $label = $offset + 1 . "-" . $page * $pi['rows_per_page'];
         $label = "{$page}";
         if ($page == $pi['current_page']) {
             $this->content("<b>{$label}</b>");
         } else {
             $this->content(new Anchor(buildQuery('TranslationAdmin', 'Translate', "lang={$lang}&offset={$offset}&search={$search}&untranslated=" . ($untranslated ? 1 : 0)), "{$label}"));
         }
         $this->content("&nbsp;");
     }
 }
 /**
  * @override
  */
 function PreRender($args = array())
 {
     if (count($this->_data) > 1) {
         $id = $this->id;
         $opts = json_encode($this->gvOptions);
         if (count($this->_data) > 0) {
             array_walk_recursive($this->_data, function (&$item, &$key) {
                 if ($item instanceof DateTime) {
                     $item = "[jscode]new Date(" . $item->getTimestamp() * 1000 . ")";
                 }
             });
             $d = system_to_json($this->_data);
             $js = "var d=google.visualization.arrayToDataTable({$d});" . "var c=new google.visualization.{$this->gvType}(\$('#{$id}').get(0));" . "google.visualization.events.addListener(c, 'ready', function(){ \$('#{$id}').data('ready',true); });" . "c.draw(d,{$opts});" . "\$('#{$id}').data('googlechart', c);";
         } else {
             $q = buildQuery($this->id, 'Query');
             $js = "var {$id} = new google.visualization.Query('{$q}');" . "{$id}.setQuery('{$this->gvQuery}');" . "{$id}.send(function(r){ if(r.isError()){ \$('#{$id}').html(r.getDetailedMessage()); }else{ var c=new google.visualization.{$this->gvType}(\$('#{$id}').get(0));" . "google.visualization.events.addListener(c, 'ready', function(){ \$('#{$id}').data('ready',true); });" . "c.draw(r.getDataTable(),{$opts});" . "\$('#{$id}').data('googlechart', c);}});";
         }
         $this->_addLoadCallback('visualization', $js, true);
     } else {
         $t = $this->opt('title');
         $this->css('text-align', 'center')->content(($t ? "<b>{$t}:</b> " : "") . tds("TXT_NO_DATA", "No data found"), true);
     }
     if (isset($this->gvOptions['width'])) {
         $this->css('width', "{$this->gvOptions['width']}px");
     }
     if (isset($this->gvOptions['height'])) {
         $this->css('height', "{$this->gvOptions['height']}px");
     }
     return parent::PreRender($args);
 }
Beispiel #29
0
function sparql_navigator($c)
{
    global $timer;
    extract($c);
    ##
    #React to the triples individually.
    #
    $crew = array('subject', 'predicate', 'object');
    #
    #no answer just yet
    #
    $ans = array();
    $triple_vars = array();
    $q = '';
    $fromSpace = array_map('switchToCore', array_keys($GLOBALS['COREids']));
    $whereSpace = array_combine(array('D', 'G', 'U', 'P', 'C', 'R', 'I', 'S'), $GLOBALS['queriable']);
    $selectSpace = $GLOBALS['queriable'];
    #
    #first we'll try to answer the question with the captain himself - the subject has the most chances of winning the game; the subject can answer the question totally or partially. In case it is partially, predicate and object will complete it.
    #
    $from = $fromSpace;
    foreach ($crew as $crew_member) {
        ##if any of the triples is just 'a', replace by rdf:type
        if ($triple[$crew_member] == 'a') {
            $triple[$crew_member] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
        }
        $isCore = false;
        $isCore = isS3DBCore($triple[$crew_member], true, 'php');
        if ($isCore) {
            $collected_data[$isCore['letter'] . $isCore['value']] = $isCore['data'];
            ##save it for later
        }
        switch ($crew_member) {
            case 'subject':
                #
                #subject can tells us for sure where the query should target; relationships associated with this core member					can be retrieved.
                #
                if ($isCore) {
                    #
                    #Because the core allows only collections and items as subjects
                    #
                    list($from, $where) = trimBasedOnSub(compact('from', 'isCore', 'where', 'triple', 'fromSpace'));
                    ##Where cannot be determined yet, but we can constrain the where space
                    $whereSpace = array_intersect_key($whereSpace, array_flip(array_map('switchToCore', $from)));
                } elseif (isSPARQLVar($triple[$crew_member])) {
                    #If ?var was not found already, assign it to empty vars
                    array_push($triple_vars, $triple[$crew_member]);
                } elseif ($triple[$crew_member]) {
                    if (isCoreOntology($triple[$crew_member])) {
                        #The query is to be oriented towards the core. Since the core is already part of the model.n3, we need						to leave the form and where empty. Model reamians as was an query is porformed on top of it.
                        $from = array();
                        $where = array();
                    }
                } else {
                    #the only time subject is not in the core is if the rdf comes from external sources. These will be left						to the sparql enggine
                }
                ##P and O can be used to trim the answer if they are constants; otherwise they can be dicovered
                if ($timer) {
                    $timer->setMarker('subject ' . $triple[$crew_member] . ' interpreted');
                }
                break;
            case 'predicate':
                #Which in the core? Predicate can now choose between rule or item, otherwise it does not make sense within the core
                if ($isCore) {
                    list($from, $where, $varType, $varTypeWhere) = trimBasedOnPred(compact('isCore', 'where', 'triple', 'varType', 'varTypeWhere'));
                } elseif (isSPARQLVar($triple[$crew_member])) {
                    array_push($triple_vars, $triple[$crew_member]);
                } elseif (ereg('^http', $triple[$crew_member])) {
                    #When the predicate is a known property, "from" can be trimmed to involve those that do have that property.
                    #try to translate which property if being requested via uri:
                    $tmp = $triple[$crew_member];
                    if ($tmp == 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type') {
                        ##When predicate is "type" something, query can be either on core or on a particular collections
                        $objectIsCore = isS3DBCore($triple['object']);
                        if ($objectIsCore) {
                            switch ($objectIsCore['letter']) {
                                case 'C':
                                    $from = array_intersect($from, array('I'));
                                    ##Where will be resolved when we look at the object
                                    #if(!is_array($where['I'])) $where['I'] = array();
                                    #array_push($where['I'], array('collection_id'=>$objectIsCore['value']));
                                    $varType[$triple['subject']][] = 'I';
                                    $varTypeWhere[$triple['subject']][] = 'C' . $objectIsCore['value'];
                                    break;
                                case 'P':
                                    $varType[$triple['subject']][] = 'P';
                                    $varTypeWhere[$triple['subject']][] = 'P' . $objectIsCore['value'];
                                    break;
                            }
                        }
                        $objectIsEntity = isCoreOntology($triple['object']);
                        if ($objectIsEntity) {
                            $varType[$triple['subject']][] = letter($objectIsEntity);
                        }
                    } elseif ($tmp == 'http://www.w3.org/2000/01/rdf-schema#subClassOf') {
                        $from = array_intersect($from, array('C', 'R', 'P', 'U', 'G'));
                        $objectIsCore = isS3DBCore($triple['object']);
                        $objectDiscovered = WasDiscovered($triple['object'], $varType);
                        $subjectType = WasDiscovered($triple['subject'], $varType);
                        if ($objectIsCore) {
                            switch ($objectIsCore['letter']) {
                                case 'P':
                                    $from = array_intersect($from, array('C', 'R'));
                                    $varTypeWhere[$triple['subject']][] = 'P' . $objectIsCore['value'];
                                    #if(!is_array($where['I'])) $where['I'] = array();
                                    #array_push($where['I'], array('collection_id'=>$objectIsCore['value']));
                                    break;
                                case 'D':
                                    $from = array_intersect($from, array('P', 'U', 'G'));
                                    break;
                                case 'G':
                                    $from = array_intersect($from, array('U'));
                                    break;
                            }
                        } elseif ($objectType) {
                            foreach ($objectType as $gold) {
                                $isObjectCore = isS3DBCore($gold);
                                if ($isObjectCore) {
                                    list($from, $where) = trimBasedOnObj(array('from' => $from, 'isCore' => $isObjectCore, 'where' => $where));
                                }
                            }
                        }
                    } elseif (in_array($tmp, $GLOBALS['not_uid_specific'])) {
                        #is subject found?
                        $subjDiscovered = WasDiscovered($triple['subject'], $varType, $varTypeWhere);
                        #how about object?
                        $objDiscovered = WasDiscovered($triple['object'], $varType, $varTypeWhere);
                        #$subjDataDiscovered = $discoveredData[$triple['subject']];
                        if ($subjDiscovered) {
                            #echo 'ola';exit;
                            #$from = array();
                            $where = array();
                            foreach ($subjDiscovered as $g => $gold) {
                                $isSubjectCore = isS3DBCore($gold);
                                if ($isSubjectCore) {
                                    list($from, $where) = trimBasedOnSub(array('fromSpace' => $fromSpace, 'from' => $from, 'isCore' => $isSubjectCore, 'where' => $where));
                                } elseif (in_array($gold, array('P', 'C', 'R', 'I', 'S'))) {
                                    $from = array_intersect($from, array($gold));
                                    if ($varTypeWhere[$triple['subject']][$g]) {
                                        if (!is_array($where[$gold])) {
                                            $where[$gold] = array();
                                        }
                                        $eid = $GLOBALS['COREletterInv'][letter($varTypeWhere[$triple['subject']][$g])];
                                        array_push($where[$gold], array($eid => substr($varTypeWhere[$triple['subject']][$g], 1, strlen($varTypeWhere[$triple['subject']][$g]))));
                                    }
                                }
                            }
                            #echo '<pre>';print_r($from);
                            #echo '<pre>';print_r($where);
                            #exit;
                        }
                        #echo '<pre>';print_r($from);echo '<pre>';print_r($where);exit;
                    } else {
                        foreach ($from as $E) {
                            if (in_array($tmp, $GLOBALS['propertyURI'][$E])) {
                                $fromSubSpace[] = $E;
                                #
                                #The object's help here will matter, as it will encapsulate the value to be read into the query
                                #
                                $objectIsCore = isS3DBCore($triple['object']);
                                if (!is_array($where[$E])) {
                                    $where[$E] = array();
                                }
                                if ($triple['object']) {
                                    array_push($where[$E], array(array_search($tmp, $GLOBALS['propertyURI'][$E]) => $triple['object']));
                                } elseif ($objectIsCore) {
                                    array_push($where[$E], array(array_search($tmp, $GLOBALS['propertyURI'][$E]) => $objectIsCore['value']));
                                }
                            }
                            #$from = array_intersect($from,$fromSubSpace);
                        }
                        if (count($from) == 8 || empty($where)) {
                            $from = array();
                        }
                    }
                    #echo '<pre>';print_r($from);
                    #echo '<pre>';print_r($where);exit;
                } elseif ($triple[$crew_member]) {
                } else {
                }
                break;
            case 'object':
                #echo '<pre>';print_r($where);exit;
                if ($isCore) {
                    ##Who can be connected to an element of the core? The object can eliminate some "from" options by discarding those that,according to the core, cannot be connected to this property as object
                    #attr is always the same: it i sthe ID of the core element specified. For example, if it is rule, then attr is rule_id, etc.
                    ##Where can finally be retrieved;
                    switch ($isCore['letter']) {
                        case 'D':
                            $subSpace = array('P', 'U', 'G', 'D');
                            $from = array_intersect($from, $subSpace);
                            break;
                        case 'P':
                            #$subSpace = array('R','C','U','G','P');
                            $subSpace = array('R', 'C', 'P');
                            $from = array_intersect($from, $subSpace);
                            foreach ($from as $e) {
                                if (!is_array($where[$e])) {
                                    $where[$e] = array();
                                }
                                array_push($where[$e], array('project_id' => $isCore['value']));
                            }
                            break;
                        case 'R':
                            #$subSpace = array('U','G','R');
                            $subSpace = array('R');
                            $from = array_intersect($from, $subSpace);
                            foreach ($from as $e) {
                                array_push($where[$e], array('rule_id' => $isCore['value']));
                            }
                            break;
                        case 'C':
                            #$subSpace =array('I','R','U','G','C');
                            $subSpace = array('I', 'R', 'C');
                            $from = array_intersect($from, $subSpace);
                            foreach ($from as $e) {
                                switch ($e) {
                                    case 'R':
                                        if (!is_array($where[$e])) {
                                            $where[$e] = array();
                                        }
                                        array_push($where[$e], array('object_id' => $isCore['value']));
                                        #$where['R'][end+1]['object_id'] = $isCore['value'];
                                        break;
                                    default:
                                        if (!is_array($where[$e])) {
                                            $where[$e] = array();
                                        }
                                        array_push($where[$e], array('collection_id' => $isCore['value']));
                                        break;
                                }
                                #if(!is_array($where[$e])) $where[$e]=array();
                                #array_push($where[$e], array('collection_id' => $isCore['value']));
                            }
                            break;
                        case 'I':
                            #$subSpace=array('S','R','U','G','I');
                            $subSpace = array('S', 'R', 'I');
                            $from = array_intersect($from, $subSpace);
                            foreach ($from as $e) {
                                switch ($e) {
                                    case 'S':
                                        array_push($where['S'], array('value' => $isCore['value']));
                                        break;
                                    case 'R':
                                        array_push($where['R'], array('verb_id' => $isCore['value']));
                                        break;
                                    default:
                                        array_push($where[$e], array('item_id' => $isCore['value']));
                                        break;
                                }
                            }
                            break;
                        case 'S':
                            #$subSpace=array('S','U','G');
                            $subSpace = array('S');
                            $from = array_intersect($from, $subSpace);
                            foreach ($from as $e) {
                                array_push($where[$e], array('statement_id' => $isCore['value']));
                            }
                            break;
                    }
                    #$from = array_intersect($from, $subSpace);
                } elseif (isSPARQLVar($triple[$crew_member])) {
                    array_push($triple_vars, $triple[$crew_member]);
                } elseif (ereg('^http', $triple[$crew_member])) {
                    #Is this an element of the CoreOntology
                    $isOnt = isCoreOntology($triple[$crew_member]);
                    if ($isOnt) {
                        $from = array($GLOBALS['s3codesInv'][strtolower($isOnt)]);
                        $where[$GLOBALS['s3codesInv'][strtolower($isOnt)]] = array();
                    } else {
                        #to be parsed by SPARQL algebra;
                    }
                } elseif (!ereg('^http', $triple[$crew_member])) {
                    $ob = $triple[$crew_member];
                    ereg('"(.*)"', $ob, $ob_parts);
                    if ($ob_parts) {
                        $ob = $ob_parts[1];
                    }
                    foreach ($from as $e) {
                        switch ($e) {
                            case 'S':
                                if (!is_array($where[$e])) {
                                    $where[$e] = array('value' => $ob);
                                } else {
                                    $where[$e][max(array_keys($where[$e]))]['value'] = $ob;
                                }
                                #this is one of the few cases when we do want the			object to be inthe same query as that for the predicate
                                break;
                            case 'R':
                                #$where[$e][end]['object']=$triple[$crew_member]->label;
                                break;
                        }
                    }
                }
                break;
        }
    }
    ##Once we go through all the triples, we should have reached a from and a where space; It's time to build the queries necessary for assigning values to variables; constraining the query space
    #fisrt thing first: let's think about efficiency? Is it the local deployment that is being queries? if so, let's call S3QLaction right here.
    if ($s3ql['url'] == S3DB_URI_BASE || $s3ql['url'] == S3DB_URI_BASE . '/') {
        $s3ql['user_id'] = $user_id;
        $s3ql['db'] = $db;
        $remote = 0;
    } else {
        $s3ql['user_id'] = S3DB_URI_BASE . '/U' . $user_id;
        $remote = 1;
    }
    $bQ = buildQuery(compact('s3ql', 'from', 'where', 'remote', 'performedQueries', 'it'));
    extract($bQ);
    return compact('remoteQueries', 'localQueries', 'S3QL', 'varType', 'varTypeWhere', 'element', 'collected_data', 'performedQueries');
}
    if (filter_var_array($data, $args) == false) {
        echo "The inputs did not pass php form validation.";
    }
}
//set up a connection to the database.
//create a user that is 6 foot 18 lbs. (it is assumed that he works out lightly 1-3 hours per week.
//He needs 21g P, 64g C, 9g Fat per meal if I eat 6 meals a day.
//That is 126g P, 384g C, 54g F
include "connect-to-database.php";
include "functions.php";
//These arrays will store the results of the queries
$protein = array();
$carbs = array();
$fat = array();
$name = array();
$sql = buildQuery();
if ($errorReporting) {
    echo "<br>The Query looks like:";
    echo "<br>" . $sql . " <br>";
}
$res = $mysqli->query($sql);
# This will be the two dimensional array, that will store the result of the query.
while ($row = $res->fetch_assoc()) {
    if ($errorReporting) {
        echo print_r($row) . "<br>";
    }
    $protein[] = $row['protein'];
    $carbs[] = $row['carbs'];
    $fat[] = $row['fat'];
    $name[] = $row['name'];
}