" . lp("this site uses cookies and external resources for some functionality of the site") . ". $close $moreinfo" . "
";
if ($summary = $GLOBALS["csp"]->summary()){
$summary = BR . lp("origins") . CSPACE . $summary;
}
// $GLOBALS["head_warnings"] = dialog(
// lp("external resources"),
// lp("this site uses external resources for some functionality of the site") . $summary,
// "info",
// $buttons
// );
$close = fix_link($link, lp("I understand"));
$cookielink = $GLOBALS["cookie_link"] ?? "/pages/cookies";
$moreinfo = fix_link($cookielink, lp("more information"));
$GLOBALS["head_warnings"] = div(lp("this site uses cookies for some functionality of the site") . ". $close $moreinfo", "#cookie_warning");
}
}
}
}
}
function set_cookie($key, $value, $seconds = false, $warning = true){
if (!empty($warning)) cookie_warning();
header('P3P: CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'); # IE sucks!
if (!$seconds) $seconds = 60 * 60 * 24 * 14; # two weeks
$host = !empty($_SERVER["IDN_HTTP_HOST"]) ? $_SERVER["IDN_HTTP_HOST"] : $_SERVER["HTTP_HOST"];
//error_log($host);
if ($hosts = subhosts($host)){
foreach ($hosts as $h){
$time = time() + $seconds;
setcookie($key, $value, [
'expires' => $time,
'path' => '/',
'domain' => $h,
#'secure' => !empty($_SERVER['HTTPS']),
"secure" => $GLOBALS["protocol"] == "https",
'httponly' => true,
'samesite' => $GLOBALS["protocol"] === "https" ? 'Secure' : 'None',
]);
//setcookie($key, $value, $time, "/", $h);
$_COOKIE[$key] = $value;
#setcookie("name", $r['name'], time()+31536000, "/", $_SERVER['HTTP_HOST']);
}
}
}
function remove_cookie($key){
$host = $_SERVER["IDN_HTTP_HOST"] ?? $_SERVER["HTTP_HOST"];
unset($_COOKIE[$key]);
setcookie($key, "", time() - 2000, "/");
if ($hosts = subhosts($host)){
foreach ($hosts as $h){
#debug($h);
setcookie($key, "", time() - 2000, "/", $h);
}
}
}
/**
* Tabs
*
* $right" : "";
if (!empty($right)){
$tabs[] = div($right, "rightlinks");
}
$out = div(join("\n", (array)$tabs), "tabs");
return $out;
}
/**
* Help
*
* print help("atlas-information");
* Returns: a icon that can be clicked to recieve help on a specific item
* Extra: If no help exists and you are an admin, it will print a plus symbol for you to add help
*/
function helpbutton($keyword, $title = "what is this?"){
[$icon, $link] = help($keyword, 16, false, true);
return button(lp($title), $link, $icon);
}
function help($keyword, $size = 16, $align = false, $array = false, $icon = "badges/question"){
$found = 0;
$query = [
"select" => "*",
"from" => "atlas.help",
"where" => [
"keyword" => $keyword
],
"limit" => 1,
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$found++;
if (strstr($r["options"], "guide")){
$r["link"] = "javascript:visa('$r[link]','guide')";
} else {
$r["link"] = "javascript:visa('$r[link]','help')";
}
$return = [
$icon,
$r["link"],
$r["quick"]
];
$r["icon"] = "" . icon($return[0], $size, $align) . " ";
$ret_array = $r;
}
if (($found > 0) and (group("superduperadmin"))){
$ret_array["adminlink"] = "javascript:visa('http://$GLOBALS[atlas_url]/admin/edit/edit.php?module=help&keyword=$keyword&popup=yes&kort=AAA&values[kort]=AAA;$_SERVER[kort]')";
$return = [
"buttons/plus",
"javascript:visa('http://$GLOBALS[atlas_url]/admin/edit/edit.php?module=help&keyword=$keyword&popup=yes&kort=AAA&values[kort]=AAA;$_SERVER[kort]')"
];
$ret_array["icon"] = "" . icon($return[0], $size, $align) . " ";
}
if (!empty($return)){
return $array ? $ret_array : "" . icon($return[0], $size, $align) . " ";
}
return false;
}
/**
* Outputs a small infoarticle at the given spot, with the option for an admin to add one.
*
* @category Articles
*/
function info($keyword, $textheader = "#headline# "){
global $user, $information;
require_once("article.php");
# Kolla efter global text
$info = db("select * from atlas.articles where kort in('AAA','$_SERVER[kort]') and position = '$keyword' order by kort desc limit 1", 1);
if (!empty($info["id"])){
return "" . article("id=$info[id]", "position=$keyword", "textheader=$textheader", "stats=no") . "
";
} else {
return "" . article("position=$keyword", "textheader=$textheader", "stats=no") . "
";
}
}
/**
* Returns a button
*
* @category Layout
*/
function button($label, $link, $icon, $showtext = true, $iconsize = 16, $target = false, $text = false, $args = [], $class = "button"){
#$link = str_replace("&", "&", $link);
if ($label == ""){
$showtext = false;
$buttondiv = "button_loneicon";
} else {
$buttondiv = "button_icon";
}
if (!empty($target)){
$t = "target='$target'";
}
#if (!empty($text) && !strstr($text, "'")) $overlib = " onmouseover=\"return overlib('$text' $args);\" onmouseout=\"return nd();\"";
$thelabel = $showtext ? $label : "";
$slabel = strip_tags($label);
$theicon = empty($icon) ? null : icon($icon, $iconsize, false, 0, $slabel);
$nw = strlen($label) > 15 ? "" : "nowrap='nowrap'";
#if (group("superduperadmin")){
# $iconsrc = img("icons/$icon.png", 12, "return=src");
# return "$thelabel ";
#}
#return "$theicon $thelabel
";
$args["class"] = !empty($args["class"]) ? $args["class"] . SPACE . $class : $class;
$args["class"] .= " spacer";
$args["href"] = fix_url($link);
$args["target"] = $target;
$tag = "a";
if (strstr($link, "javascript:")){
$args["onclick"] = str_replace("javascript:", "", $link);
unset($args["href"]);
$args["class"] .= " textbutton";
$tag = "button";
}
if (empty($link)){
$tag = "span";
}
return tag($theicon . SPACE . $thelabel, $tag, $args);
}
function buttons($array, $sep = false, $nbutton = true){
if (!empty($nbutton)){
foreach ($array as $a){
$out[] = call_user_func_array("nbutton", $a);
}
return div(join($sep, $out), "buttonwrapper");
}
$ret = "";
foreach ($array as $b){
$b[3] = $b[3] ?? true;
$b[4] = $b[4] ?? 16;
$b[5] = $b[5] ?? false;
$b[6] = $b[6] ?? false;
$b[7] = $b[7] ?? false;
$ret .= button($b[0], $b[1], $b[2], $b[3], $b[4], $b[5], $b[6], $b[7], "vbutton");
if (!empty($sep))
$ret .= " ";
}
$ret .= "
";
return $ret;
}
function overlib($content, $link = false, $overlib = false, $class = "tooltip", $target = false){
$t = $target ? "target='$target'" : "";
if (!empty($overlib)){
$overlib = preg_replace("/(['\"])/", "", $overlib);
}
$tag = $link ? "a" : "span";
$href = $tag == "a" ? "href=\"$link\"" : "";
#return tag($content, $tag, array("class" => $class, "title" => $overlib, "href" => $link));
return "<$tag $t class='$class' title='$overlib' $href>$content$tag>";
}
function olib($overlib, $args = false){
$overlib = preg_replace("/(['\"])/", "", $overlib);
return $overlib ? "onmouseover=\"return overlib('$overlib'$args);\" onmouseout=\"return nd();\"" : "";
}
function accessinfo($groups, $all = false){
if (!empty($groups)){
$groups = explode(",", $groups); # Dom grupper vi söker efter
#foreach (db("select name from atlas.groups where kort = '$_SERVER[kort]'") as $r){
# $validgroups[] = $r["name"];
#}
foreach ($groups as $group){
if (preg_match("/type:(.*)/", $group, $m)){
$all = $m[1] == "all" ? true : false;
continue;
}
if (is_numeric($group) || is_email($group)){
$m = get_member_info($group);
$themembers[] = member_name($m, 0, 0, 0);
} else {
$thegroups[] = $group;
}
}
if (!empty($thegroups) || !empty($themembers)){
if (!empty($thegroups)){
$cond = $all ? lp("only for members of all these groups") : lp("only for members of any of these groups");
$return[] = $cond . ": " . itemlist($thegroups);
}
if (!empty($themembers)){
$return[] = lp("only for these members") . ": " . itemlist($themembers);
}
return join(BR, (array)$return);
} else {
return false;
}
} else {
return false;
}
}
function group($groups, $all = false, $member = false, $debug = false){
if (!empty($member)){
$user = new user($member);
} else {
global $user;
}
global $in;
$okgroups = 0;
$ok = false;
if (empty($user)){
return false; # default har vi ingen access
}
$mygroups = explode(",", $user["access"]); # Användarens grupper
$mygroups[] = $user["name"];
$mygroups[] = $user["email"];
$mygroups[] = $user["id"];
if (!empty($in["accessemail"]))
$mygroups[] = code($in["accessemail"]);
if (!empty($debug))
pre($mygroups);
$groups = array_filter(explode(",", $groups)); # Dom grupper vi söker efter
if (count($groups) == 0)
return true;
foreach ($groups as $group){
if (preg_match("/type:(.*)/", $group, $m)){
$all = $m[1] == "all" ? true : false;
continue;
}
$thegroups[] = trim($group);
}
if (empty($thegroups))
return true;
foreach ($thegroups as $group){
if (in_array($group, $mygroups)){
$okgroups++; # en av grupperna vi sökte efter var ok!
}
}
if (!empty($all)){
if ($okgroups == count($thegroups)){
$ok = true;
} else {
$ok = false;
}
} else {
if ($okgroups > 0){
$ok = true;
} else {
$ok = false;
}
}
return $ok;
}
function developer(){
global $user;
if (isuser(join(",", explode(" ", $GLOBALS["atlas_developers"])))){
/*
$debug = debug_backtrace();
$file = $debug[0]["file"];
$line = $debug[0]["line"];
$filetime = filemtime($file);
$text = "
File : $file: $line
Meddelande : developer() used!
";
$text .= button("Redigera filen", "bbsftp://atlas@$GLOBALS[atlas_url]/$file", "buttons/edit");
$GLOBALS["site_errors"][] = $text;
*/
return true;
} else {
return false;
}
}
function has_module($module){
return in_array($module, $GLOBALS["site_modules"]);
}
/**
* has_priv()
*
* if (has_priv("articles", "addpost", "GMC")){ ... }
* Returns: boleen
* Extra: Alla argument är valfria.
*/
function has_priv($module = false, $access = false, $kort = false, $member = false){
if (is_object($module)){
$module = $module->settings["keyword"];
}
global $user;
if (!empty($member)){
$member = new user($member);
//debug($member["email"]);
} else {
$member = $user;
}
if (!empty($module) && preg_match("/^custom:/", $module))
return true;
if (!$member)
return false;
if ((($kort) && ($kort != $_SERVER["kort"])) || empty($GLOBALS["atlas_priv"])){
if (!$kort)
$kort = $_SERVER["kort"];
#$the_access_level = "";
#$atlas_priv = array();
#debug("select * from atlas.priv where email = '$member[email]' and email is not null and email != '' and kort = '$kort'");
$q = "select * from atlas.priv where email = '$member[email]' and email is not null and email != '' and kort = '$kort'";
#print $q;
foreach (db($q) as $r){
$the_access_level = $r["access"] ? $r["access"] : "full";
$atlas_priv[$r["module"]] = $the_access_level;
}
} else {
#global $atlas_priv;
$atlas_priv = $member->priv();
}
$r = false; # default är false
if (!$module){
# ok, vi ska bara se om man har någon access över huvud taget
$r = $atlas_priv ?? false;
# superduperadmin har givetvis det, oavsett vad priv säger
# detta för att han/hon ska kunna komma åt moduler på en nystartad site.
if (group("superduperadmin"))
$r = true;
} else {
# Ok, vi ska kolla rättigheter för en specifik modul
if (!empty($access) && !empty($atlas_priv[$module])){
# Och vi vill veta om användaren har specifika rättigheter
$wanted_access_array = explode(",", $access); # Den här accessen krävs
$my_access_array = explode(",", $atlas_priv[$module]); # Den här accessen har användaren
#print "Wanted: " . join(", ", $wanted_access_array) . BR;
#print "My access: " . join(", ", $my_access_array) . BR;
if (in_array("full", $my_access_array)){
# Om användaren har full access så behöver vi inte kolla mer...
# Funkar detta...?
$r = true;
} else {
$accnr = 0; # noll träffar till att börja med
foreach ($wanted_access_array as $wanted_access){
foreach ($my_access_array as $my_access){
if ($my_access == $wanted_access){
$accnr++; # en träff!
}
}
}
# om vi fick lika många matchningar som det finns objekt i arrayen så är vi home free
$r = $accnr == count($wanted_access_array) ? true : false;
}
} else {
# Detta körs om vi inte vill kolla efter specifika rättigheter.
# som om man vill kolla om man har access till en modul, oavsett
# vilken access.
$r = !empty($atlas_priv[$module]) ? true : false;
}
}
return $r;
}
/**
* head function
*/
function head($caption = false, $sub = false, $buttons = false, $img = false, $link = false){
global $in;
if (!empty($GLOBALS["help_keyword"])){
require_once "article.php";
$articles = get_articles(0, 1, ["kort" => $GLOBALS["atlas_kort"], "keyword" => $GLOBALS["help_keyword"]]);
if (!is_array($buttons)) $buttons = [];
if (count((array)$articles) || group("superduperadmin")){
// Let's add the help link
$link = "/atlas/help/ajax/context_article.php?keyword=" . $GLOBALS["help_keyword"];
$settings = [
"width" => "700",
"height" => "700"
];
fancybox(".context_help", false, $settings);
$icon = count((array)$articles) ? "symbols/question" : "symbols/plus";
$buttons[] = [lp("guide"), $link, $icon, "class=context_help", "data-type=ajax"];
}
}
if (is_mobile_layout()){
$headbuttons = $thebuttons = "";
$buts = [];
if (is_array($buttons) && count($buttons)){
foreach ($buttons as $key => $button){
#list($title, $link, $icon, $target, $class) = $button;
if (!empty($button[3]) && !strstr($button[3], "="))
$button[3] = "target=$button[3]";
if (!empty($button[4]) && !strstr($button[4], "="))
$button[4] = "class=$button[4]";
$showtext = count($buttons) > 5 ? "no" : "yes";
$button[] = "showtext=$showtext";
$button[] = "iconsize=25";
$button[] = "textunder=yes";
$onclick = false;
#$args = array($title, $link, $icon, "target=$target", "iconsize=$iconsize", "class=$class", "showtext=$showtext", "textunder=yes");
if (in_array($button[0], [lp("back"), lp("menu"), lp("navigation"), lp("home")])){
$class = in_array($button[0], [lp("back"), lp("home")]) ? "backbutton" : false;
if (strstr($button[1], "javascript")){
$onclick = str_replace("javascript:", "", $button[1]);
} else {
$link = $button[1];
}
$headbuttons .= SPACE . tag($button[0], "a", [
"href" => $link,
"onclick" => $onclick,
"class" => "iphonebutton $class"
]);
} else {
$buts[] = $button;
}
}
$thebuttons = !empty($buts) ? nbuttons($buts, "footerbuttons") : false;
}
$return = "$thebuttons";
} else {
$image = null;
if (!empty($img)){
$image = strstr($img, "<") ? $img : img($img, 50); #, "debug=yes");
if (!empty($link)){
$image = a($link, $image);
}
}
$thebuttons = "";
if (is_array($buttons) && count($buttons)){
$iconsize = 25;
#if (is_mobile()) $iconsize = 20;
$nr = 0;
$buts = [];
foreach ($buttons as $key => $button){
#list($title, $link, $icon, $target, $class) = $button;
if (!empty($button[3]) && !strstr($button[3], "="))
$button[3] = "target=$button[3]";
if (!empty($button[4]) && !strstr($button[4], "="))
$button[4] = "class=$button[4]";
$showtext = count($buttons) > 5 ? "no" : "yes";
if (!empty($GLOBALS["popup"]))
$showtext = "no";
$button[] = "showtext=$showtext";
$button[] = "iconsize=32";
$button[] = "textunder=yes";
#$args = array($title, $link, $icon, "target=$target", "iconsize=$iconsize", "class=$class", "showtext=$showtext", "textunder=yes");
if (is_phone() && in_array($button[0], [lp("back"), lp("menu"), lp("navigation")])){
if ($button[0] == lp("back"))
$class = "backbutton";
if (strstr($button[1], "javascript")){
$onclick = str_replace("javascript:", "", $button[1]);
} else {
$link = $button[1];
}
//$iphonebuttons .= tag($button[0], "a", ["href" => $link, "onclick" => $onclick, "class" => "iphonebutton $class"]);
} else {
$buts[] = $button;
}
}
$thebuttons = nbuttons($buts, "headbuttons");
}
$imgclass = empty($image) ? "noimg" : false;
$return = "
$image
$caption
$sub
$thebuttons
";
}
return $return;
}
/**
* Get article image
*
* $image = get_article_image(1234);
* Returns: the entire image post from atlas.images
* Extra:
*/
function get_article_image($id){
foreach (db("select image from atlas.images where aid = $id and (prio = 1 or find_in_set('priority', options)") as $r){
$img = $r["image"];
}
if (!$img){
foreach (db("select image from atlas.articles where id = $id") as $r){
$img = $r["image"];
}
}
return $img ? $img : false;
}
function create_array($string, $delimiter = ",", $keys = true){
#pre($string);
if (is_array($string))
return $string;
$array = [];
foreach (explode($delimiter, $string) as $item){
if (!empty($keys)){
$array[$item] = empty($array[$item]) ? 1 : $array[$item] + 1;
} else {
$array[] = $item;
}
}
return $array;
}
/**
* Notes!
*/
function note($headline = false, $text = false, $image = false, $link = false, $linktext = false){
if (!$linktext)
$linktext = lp("read more");
$ret = "";
if (!empty($headline))
$ret .= "
$headline
";
if (!empty($image)){
if (strstr($image, "<")){
$ret .= $image;
} else {
$ret .= cimg($image, 32, "right");
}
}
if (!empty($text))
$ret .= "
$text
";
if (!empty($link))
$ret .= "
";
$ret .= "
";
return $ret;
}
function sevenbit($string, $remspaces = false, $illegal = ""){
#$string = strtr($string, "\xe1\xc1\xe0\xc0\xe2\xc2\xe4\xc4\xe3\xc3\xe5\xc5\xaa\xe7\xc7\xe9\xc9\xe8\xc8\xea\xca\xeb\xcb\xed\xcd\xec\xcc\xee\xce\xef\xcf\xf1\xd1\xf3\xd3\xf2\xd2\xf4\xd4\xf6\xd6\xf5\xd5\x8\xd8\xba\xf0\xfa\xda\xf9\xd9\xfb\xdb\xfc\xdc\xfd\xdd\xff\xe6\xc6\xdf\xf8", "aAaAaAaAaAaAacCeEeEeEeEiIiIiIiInNoOoOoOoOoOoOoouUuUuUuUyYyaAso");
$string = iconv("utf-8", 'ASCII//TRANSLIT//IGNORE', $string);
//setlocale(LC_ALL, $GLOBALS["locale"] . '.UTF-8');
$string = preg_replace('/[^a-zA-Z0-9_\s-]/', $illegal, $string);
if (!empty($remspaces)){
if ($remspaces === true) $remspaces = "";
$string = preg_replace("/\s+/", $remspaces, trim($string));
};
return $string;
}
/**
* What's new aggregation
*
* since("Texter", "Text\t/index.php", "Sandman", "mr@sandman.net", "client,private", "article")
* Returns: Nothing.
* Extra:
*/
function since($keyword, $origin, $headline, $name, $kind, $part, $email, $access, $icon, $member = 0){
global $in;
$image = $in["image"] ?? '';
db("insert into member.since (keyword, origin, headline, name, kind, date, part, kort, email, member, access, image, icon) values ('$keyword', '$origin', '$headline', '$name', '$kind', now(), '$part', '$_SERVER[kort]', '$email', '$member', '$access', '$image', '$icon')");
}
function alert($head, $msg, $icon = "badges/alert", $critical = false, $extra = false){
global $in;
$out = "
" . img($icon, 50, "align=right") . "
$head
" . format($msg) . (!empty($extra) ? spacer(20, 20) . $extra : false) . "
";
if (!empty($critical)){
print $out;
break_atlas();
}
return $out;
}
function break_atlas(){
require("postprocess.php");
die;
}
function stop_atlas($headline = false, $text = false, $icon = "badges/alert", $buttons = false){
require_once $GLOBALS["atlas_dir"] . "/include/layout.php";
if (empty($headline)) $headline = lp("error");
if (empty($text)) $text = lp("unfortunately, an error has occured");
$GLOBALS["layout"] = "stop";
$GLOBALS["page_title"] = ($_SERVER["name"] ?? false) . CSPACE . $headline;
$GLOBALS["server_name_in_title"] = "no";
$GLOBALS["override_site_stylesheet"] = "yes";
$logotype = sitelogo("src");
$favicon = sitelogo("src", false, false, false, "favicon");
$img = $favicon ?? $logotype ?? "info";
$pagehead = $_SERVER["name"] ?? "Atlas CMS";
ob_start();
header('HTTP/1.1 403 Forbidden');
print head($pagehead, "", $buttons, $img);
print dialog($headline, $text . spacer(30, 30), $icon);
break_atlas();
}
function embed_atlas(array $urls){
if (!preg_match("/(google|plain|ajax|bilder)/", $_SERVER["PHP_SELF"])){
load_js("atlas_embed.js");
}
foreach ($urls as $url){
$GLOBALS["csp"]->add("frame-ancestors", $url);
$GLOBALS["csp"]->add("frame-src", $url);
}
$GLOBALS["layout"] = "embed";
$GLOBALS["supress_page_headimage"] = true;
$GLOBALS["is_responsive"] = "yes";
unset($GLOBALS["cookie_level"]);
unset($GLOBALS["redirect_to_main_url"]);
unset($GLOBALS["page_webtracking"]);
unset($GLOBALS["google_analytics_id"]);
unset($GLOBALS["matomo_id"]);
unset($GLOBALS["devsite"]);
}
function error(){
return alert(lp("an error has occured"), lp("the page you requested could not be shown, please use the back button in your browser to go back"), "badges/stop", true);
}
function smart_date($date = false, $extra = false, $showtime = false){
if (!$date or $date == "" or $date == "0000-00-00")
return false;
if (is_numeric($date)){
$sec = $date;
} else {
$sec = strtotime($date);
}
$return = "";
# Det är endast ett datum, ingen tid
#$showtime = false;
if (date("Y", $sec) == date("Y")){
# Det är samma år som nu - då returnerar vi typ 24/12
if ((date("Y-m-d") == date("Y-m-d", $sec)) and ($extra)){
# Det är idag också!
$return = lp("today", "L");
} elseif ((date("Y-m-d", $sec) == date("Y-m-d", (time() - 86400))) and ($extra)) {
# Aha, det är igår
$return = lp("yesterday", "L");
} elseif ((date("Y-m-d", $sec) == date("Y-m-d", (time() + 86400))) and ($extra)) {
# Aha, det är imorgon
$return = lp("tomorrow", "L");
} else {
if (($sec < (time() + 518400)) and ($sec > time()) and ($extra)){
# Ok, datumet befinner sig inom den kommande sexdagarsperioden
$day = encode(format_time("%A", $sec));
$return = $day;
} else {
# Det är någon helt annan dag
$showtime = false;
#$l = localeconv();
#pre($l);
switch ($GLOBALS["language"]){
case "no":
$return = date("d.m", $sec);
break;
case "se":
$return = lc(format_time("%e %b", $sec));
break;
case "en":
$return = format_time("%h %e", $sec);
break;
}
}
}
if (date("H:i", $sec) != "00:00"){
# Det är inte bara ett datum, vi lägger till tiden också
switch ($GLOBALS["language"]){
case "en":
$return .= " " . lc(format_time("%l:%M %p", $sec));
break;
default:
$return .= " " . date("H:i", $sec);
break;
}
#$return.= " " . date("H:i", $sec);
}
} else {
# Det är ett annat år, då kör vi hela ISO: 2003-12-24
$return = date("H:i", $sec) != "00:00" ? fdate(date("Y-m-d H:i", $sec)) : fdate(date("Y-m-d", $sec));
$return = fdate(date("Y-m-d", $sec));
if (date("H:i", $sec) != "00:00" && $showtime){
# Det är inte bara ett datum, vi lägger till tiden också
$return .= " " . date("H:i", $sec);
}
}
return $return;
}
function guide($guide, $label = "guide", $form = "button"){
global $user;
require_once("article.php");
if ($form == "button"){
return button(lp($label), "javascript:svisa('/texter/popup.php?page=Guide+" . urlencode($guide) . "','guide', 600, 400)", "badges/question");
}
}
function ruta($content, $a = false): string{
$a = arguments(func_get_args(), $a);
if (empty($a['id'])) $a['id'] = '';
if (empty($a['class'])) $a['class'] = '';
return div($content, "square $a[class]", $a["id"]);
}
/**
* Make puffs
*
* print puff("headline=Extra!", "link=www.extra.com", "text=This is extra", "icon=extra");
* Returns: A small square with the icon, text and link.
* Extra: Variables: icon, size, style, text, headline, link
*/
function puff(){
$a = [
//"icon" => "badges/alert",
"size" => 32,
"style" => "default",
"width" => "100%",
"ruta" => "yes",
"cellpadding" => "3",
"textclass" => "normal",
"valign" => "top",
"iconside" => "left"
];
$a = arguments(func_get_args(), $a);
$icon = "";
if (!empty($a["icon"])){
if (strstr($a["icon"], " "icon " . $a["iconside"]]);
$text = tag(div(($a["headline"] ?? false), "headline") . ($a["text"] ?? false), "div", ["class" => "text $a[textclass]"]);
$tag = !empty($a["link"]) ? "a" : "div";
$aclass = !empty($a["class"]) ? $a["class"] : '';
$moreclass = $a["ruta"] == "yes" ? "ruta" : "";
return tag(
$icon . $text,
$tag,
[
"width" => $a["width"],
"href" => $a["link"] ?? false,
"target" => link_target($a["link"] ?? false, false),
"class" => "puff $moreclass " . $aclass
]
);
}
function notice($text, $padding = 10, $style = "default"){
if (!$_SERVER["HTTP_HOST"]){
return "\n\n$text\n\n";
} else {
return "" . ruta("
$text
", "style=$style") . "
";
}
}
function tablebuilder($data){
$a = [
"delimiter" => ",",
"fcit" => false,
"frit" => false,
"title" => false,
"align" => "no",
"valign" => "middle",
"width" => "100%",
"formatnumbers" => "yes",
"summary" => "",
"wrap" => "no"
];
$cachename = "";
for ($i = 0; $i < func_num_args(); $i++){
$arg = func_get_arg($i);
[$tag, $val] = array_pad(explode('=', $arg), 2, false);
$a[$tag] = $val;
$cachename .= "/$val";
}
$rows = explode("\n", $data);
$nrcolumns = 0;
foreach ($rows as $row){
$cols = explode($a["delimiter"], $row);
if (count($cols) > $nrcolumns)
$nrcolumns = count($cols);
}
##debug($nrcolumns);
$align = $a["align"] == "no" ? "" : "align='$a[align]'";
$out = "";
if (!empty($a["title"])){
#$out.= "$a[title] ";
$out .= "$a[title] ";
}
$nr = 0;
$table_values = [];
foreach (explode("\n", $data) as $row){
$nr++;
$trclass = 'line';
$out .= "";
$inr = 0;
$rowitems = explode($a["delimiter"], $row);
if (count($rowitems) != $nrcolumns)
continue;
$width = round(100 / count($rowitems));
foreach ($rowitems as $item){
$item = trim($item);
$wrap = $a["wrap"] == "no" ? "nowrap='nowrap'" : false;
$class = "";
$tag = "td";
$inr++;
if ($nr == 1 and $a["frit"]){
#$class = "class='alt'";
$tag = "th";
$wrap = "";
}
if ($inr == 1 and $a["fcit"]){
$class = "class='alt'";
$wrap = "";
}
$align = "left";
if (!$a["fcit"] || ($a["fcit"] && $inr != 1)){
$sum = false;
if (preg_match("/#sum#/", $item)){
$item = array_sum($table_values[$inr]);
$sum = true;
}
if ($a["formatnumbers"] == "yes" && !preg_match("/\.\d+\./", $item) && is_numeric(preg_replace("/[%,\.\s]/", "", preg_replace("/<(.*?)>/", "", $item)))){
if (!$sum){
$table_values[$inr][] = preg_replace("/[%,\.\s]/", "", preg_replace("/<(.*?)>/", "", $item));
}
$align = "right";
if (preg_match("/[\.\,](\d+)/", $item, $m)){
# Vi har kommatecken med
$number = strlen($m[1]);
//$item = preg_replace("/([\.\d]+)/e", 'number_format("\1", $number, ".", " ")', str_replace(",", ".", $item));
$item = preg_replace_callback("/([\.\d]+)/", function ($m) use ($number){
return number_format($m[1], $number, ".", " ");
}, str_replace(",", ".", $item));
} else {
//$item = preg_replace("/(\d+)/e", 'number_format("\1", 0, ".", " ")', $item);
$item = preg_replace_callback("/([\.\d]+)/", function ($m){
return number_format($m[1], 0, ".", " ");
}, $item);
}
$item = str_replace(".", ",", $item);
}
}
#if ($item == "YES") $item = icon("badges/ok", 12);
#if ($item == "NO") $item = icon("badges/no", 12);
$out .= "<$tag width='$width%' $wrap align='$align' $class >" . format($item) . "$tag>";
}
$out .= " ";
}
$out .= "
";
return "
" . $out;
}
function diagrambuilder($data){
require_once("diagram.php");
$a = [
"delimiter" => ",",
"fcit" => false,
"frit" => false,
"title" => false,
"align" => "no",
"width" => "100%",
"height" => 200,
"kind" => "line"
];
if ($a["width"] == "100%"){
$a["width"] = ($GLOBALS["contentwidth"] - 10);
}
$a = arguments(func_get_args(), $a);
$linenr = 0;
foreach (explode("\n", trim($data)) as $row){
$linenr++;
$values = array_filter(explode($a["delimiter"], trim($row)));
if ($a["fcit"] == "yes"){
$label = array_shift($values);
}
if ($a["frit"] == "yes" && $linenr == 1){
$labels = $values;
#pre($labels);
continue;
}
if (max($values) > $maxvalue)
$maxvalue = max($values);
$chart["data"][$label] = $values;
}
$chart["labels"] = $labels;
$chart["hide_legend"] = true;
$chart["top_margin"] = 1;
$chart["left_margin"] = 30;
$chart["legend_margin"] = 1;
$chart["title_margin"] = 1;
$chart["marker_font_size"] = 12;
$chart["minimum_value"] = 0;
$chart["maximum_value"] = ceiling($maxvalue, 2);
#pre($chart);
return diagram($chart, $a["kind"], $a["width"], $a["height"]);
}
function create_pass($length, $funky = false){
mt_srand(microtime(true) * 1000000);
$vowels = ["a", "e", "i", "o", "u"];
$cons = [
"b",
"c",
"d",
"g",
"h",
"j",
"k",
"l",
"m",
"n",
"p",
"r",
"s",
"t",
"u",
"v",
"w",
"tr",
"cr",
"br",
"fr",
"th",
"dr",
"ch",
"ph",
"wr",
"st",
"sp",
"sw",
"pr",
"sl",
"cl"
];
$num_vowels = count($vowels);
$num_cons = count($cons);
$password = '';
for ($i = 0; $i < $length; $i++){
$c = $cons[mt_rand(0, $num_cons - 1)];
$v = $vowels[mt_rand(0, $num_vowels - 1)];
if (!empty($funky) && mt_rand(1, 2) == 2){
$v = str_replace(["a", "e", "i", "o"], ["4", "3", "1", "0"], $v);
}
if (!empty($funky) && mt_rand(1, 2) == 2){
$v = strtoupper($v);
}
$password .= $c . $v;
}
return substr($password, 0, $length);
}
function warning($string){
$debug = debug_backtrace();
$d = array_pop($debug);
php_error(2, $string, $d["file"], $d["line"]);
}
/**
* @param $text
* @param string $type
* @param bool $module
* @param bool $data
* @param bool $kort
* @param bool $member
*/
function slog($text, $type = "alert", $module = false, $data = false, $kort = false, $member = false){
if (!$member){
global $user;
$member = $user["id"];
}
if (!$kort) $kort = $_SERVER["kort"];
//error_log("$type: $text");
if (!empty($data) && is_array($data)) $data = serialize($data);
$data = [
"date" => date("Y-m-d H:i:s"),
"event" => $text,
"type" => $type,
"member" => $member,
"ip" => $_SERVER["REMOTE_ADDR"],
"module" => $module,
"data" => $data,
"kort" => $kort
#"debug" => "yes"
];
save2db("atlas", "syslog", $data);
#db("insert into atlas.syslog (kort, date, event, member, ip, type) values ('$_SERVER[kort]', now(), '" . addslashes($text) . "', '$user[id]', '$_SERVER[REMOTE_ADDR]', '$type')");
}
function backtrace($function = false, $file = false, $line = false){
$debug = debug_backtrace();
#pre($debug);
$dlist = new itemlist();
$nr = 0;
if (!empty($file) && $line){
$dlist->addrow(
[
"text" => basename($file),
"right" => $function,
"subtext" => $file . ": " . $line,
"link" => bbe($file, true, $line)
]
);
}
foreach ($debug as $r){
$nr++;
if (in_array($r["function"], ["backtrace", "php_error"])) continue;
if (!empty($function) && $r["function"] != $function) continue;
$class = !empty($r['class']) ? $r['class'] : '';
if (!empty($r["file"])){
$dlist->addrow(
[
"text" => basename($r["file"]),
"right" => "" . $class . " / " . $r["function"],
"subtext" => $r["file"] . ": " . $r["line"],
"link" => bbe($r["file"], true, $r["line"])
]
);
}
}
return $dlist;
}
function php_timeline(){
$GLOBALS["spare_memory"] = null;
print "";
foreach ($GLOBALS["page_gauge"] as $g){
$time = sprintf("%.3f", ($g["time"] - $GLOBALS["page_loadtime_start"]));
$jump = sprintf("%.3f", $g["jump"]);
$page = a("phpstorm://open?file=" . $g["page"], basename($g["page"]));
$file = a("phpstorm://open?file=" . $g["file"], basename($g["file"]));
printf("%-50s: %-10s -> %-10s - %-20s (%s, %s)\n", $g["string"], $jump, $time, fsize($g["memory"]), $page, $file);
}
print " ";
}
function fatal_handler(){
$errfile = "unknown file";
$errstr = "shutdown";
$errno = E_CORE_ERROR;
$errline = 0;
$GLOBALS["spare_memory"] = null;
$error = error_get_last();
if ($error !== null){
$errno = $error["type"];
$errfile = $error["file"];
$errline = $error["line"];
$errstr = $error["message"];
#print "" . $errstr . " ";
#print $errno . CS . $errfile . ":" . $errline . BR;
#debug_print_backtrace();
#print "";
#print_r(debug_backtrace());
#print " ";
$trace = backtrace(false, $errfile, $errline);
foreach ($trace->rows as $r){
//print $r["text"] . CS . $r["subtext"] . BR;
}
}
}
function php_error($nr, $string, $file = false, $line = false){
global $user;
// region If we're running from the shell, just print the error
if (($GLOBALS["dev_atlas"] == "yes") && empty($_SERVER["DOCUMENT_ROOT"]) || !empty($GLOBALS["plain_errors"]) || 1 == 3){
print "Error on line $line on $file:\n";
print " - $string\n";
return false;
}
// endregion
// region Insert into DB for logging
if (!$GLOBALS["web_robot"] && !empty($file) && !empty($line) && !empty($_SERVER["HTTP_HOST"]) && !strstr($string, "is not image")){
$data = [
"file" => $file,
"code" => $nr,
"line" => $line,
"message" => $string,
"referer" => $_SERVER["HTTP_REFERER"] ?? false,
"date" => date("Y-m-d H:i:s"),
"url" => $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]
#"debug" => "yes"
];
$id = save2db("log", "php_error", $data, "duplicates=yes");
}
// endregion
$e2s = [
1 => "E_ERROR",
2 => "E_WARNING",
4 => "E_PARSE",
8 => "E_NOTICE",
16 => "E_CORE_ERROR",
32 => "E_CORE_WARNING",
64 => "E_COMPILE_ERROR",
128 => "E_COMPILE_WARNING",
256 => "E_USER_ERROR",
512 => "E_USER_WARNING",
1024 => "E_USER_NOTICE",
6143 => "E_ALL",
2048 => "E_STRICT",
4096 => "E_RECOVERABLE_ERROR",
8192 => "E_DEPRECATED"
];
$string = $e2s[$nr] . " ($nr): " . $string;
$randnr = rand(1000, 30000);
if ($GLOBALS["dev_atlas"] != "yes"){
if ($nr == 8 || $nr == 8192 || $nr == 1024){
if (!stristr($string, "undefined") && !stristr($string, "string offset")){
if (!empty($GLOBALS["site_warnings"]) && count($GLOBALS["site_warnings"]) > 100)
return false;
$GLOBALS["site_warnings"][] = [$line, $nr . ":" . $string, $file];
}
return false;
}
if ($nr == 2048 && $GLOBALS["no_strict_warnings"])
return false; # Ignore E_STRICT errors.
#if ($nr == 2 && stristr($string, "getimagesize"))
# return false;
if ($nr == 2 && stristr($string, "Illegal string offset"))
return false;
}
if (group("superduperadmin")){
if (!empty($GLOBALS["site_errors"]) && count($GLOBALS["site_errors"]) > 100) return false;
$trace = backtrace(false, $file, $line);
if ($trace->count()){
$trace->class = "hidden";
$trace->listid = "errorlist_" . $randnr;
//debug($string);
$trace->head = empty(trim($string)) ? "Error" : $string;
$trace->head = toggle("errorlist_$randnr") . SPACE . fix_link("javascript:toggle('errorlist_$randnr')", $trace->head);
$text = $trace->printlist();
$GLOBALS["site_errors"][] = $text;
}
}
return false;
}
function code($string){
if (empty($string)) return false;
$codestring = "S6DF54";
if (preg_match("/^$codestring/", $string)){
# It is already encoded
$string = preg_replace("/^$codestring/", "", $string);
return base64_decode(str_rot13(urldecode($string)));
} else {
return $codestring . urlencode(str_rot13(base64_encode($string)));
}
}
function encode_string($string){
if (empty($string)) return false;
$codestring = "S6DF54";
return $codestring . urlencode(str_rot13(base64_encode($string)));
}
function decode_string($string){
if (empty($string)) return false;
$codestring = "S6DF54";
$string = preg_replace("/^$codestring/", "", $string);
return base64_decode(str_rot13(urldecode($string)));
}
function is_coded($string){
if (empty($string)) return false;
$codestring = "S6DF54";
return preg_match("/^$codestring/", $string);
}
/**
* Date parsing, big time
*/
function parse_date($date, $format = false){
/**
* First, let's check if it's correctly written
*/
if (preg_match("/\d{4}-\d{2}-\d{2}/", $date) || preg_match("/\d{4}-\d{2}-\d{2} \d{1,2}:\d{1,2}/", $date))
return $date;
global $in;
if ($date == "")
return "";
$tr = [
"/om\s+/i" => "",
"/på /i" => "",
"/v\s{0,1}(\d+)/i" => "week $1",
"/kl (\d{1,2})/" => "kl $1:00",
"/(.*?)kl (.*?)$/" => "kl $2 $1",
"/(klockan|kl) /i" => "",
"/(\d\d)\.(\d\d)/i" => "$1:$2",
"/i\s*dag/i" => "today",
"/i\s*går/i" => "yesterday",
"/i\s*morgon/i" => "tomorrow",
"/förra/i" => "last",
"/nästa/i" => "next",
"/(veckan|vecka)/i" => "week",
"/(månader|månaden|månad)/i" => "month",
"/(året|år)/i" => "year",
"/(januari|jan)/i" => "january",
"/(februari|feb)/i" => "february",
"/(mars|mar)/i" => "march",
"/(april|apr)/i" => "april",
"/maj/i" => "may",
"/(juni|jun)/i" => "june",
"/(juli|jul)/i" => "july",
"/(augusti|aug)/i" => "august",
"/(september|sep)/i" => "september",
"/(oktober|okt)/i" => "october",
"/(november|nov)/i" => "november",
"/(december|dec)/i" => "december",
"/(måndag|mån)/i" => "monday",
"/(tisdag|tis)/i" => "tuesday",
"/(onsdag|ons)/i" => "wednesday",
"/(torsdag|tors)/i" => "thursday",
"/(fredag|fre)/i" => "friday",
"/(lördag|lör)/i" => "saturday",
"/(söndag|sön)/i" => "sunday",
];
$date = preg_replace(array_keys($tr), array_values($tr), $date);
#pre($date);
if (preg_match("/(monday|tuesday|wednesday|thursday|friday|saturday|sunday) week (\d+)/i", $date)){
$date = preg_replace("/(monday|tuesday|wednesday|thursday|friday|saturday|sunday) week (\d+)/ei", "week_to_date($2, $1)", $date);
} elseif (preg_match("/week (\d+)/", $date)) {
$date = preg_replace("/week (\d+)/ei", "week_to_date($1)", $date);
}
$time = strtotime($date);
if (!empty($format)){
return date($format, $time);
} else {
$newdate = date("Y-m-d H:i", $time);
if (date("H:i", $time) == date("H:i")){
$newdate = date("Y-m-d", $time);
}
if (date("H:i", $time) == "00:00"){
$newdate = date("Y-m-d", $time);
}
return $newdate;
}
}
function week_to_date($week, $weekday = "monday", $theyear = false){
$nowweek = format_time("%V") - 10;
if (!$theyear){
$theyear = $week < $nowweek ? date("Y") + 1 : date("Y");
}
$year = strtotime("$theyear-01-01");
for ($i = $year; $i < $year + 31536000; $i += 86400){
$thisweek = format_time("%V", $i);
if ($thisweek == $week && $weekday == lc(date("l", $i))){
return date("Y-m-d", $i);
}
}
}
function parse_mail($string){
if (preg_match("/['\"]*(.*?)['\"]*<(.*?)>/", $string, $m)){
return [$m[1], $m[2]];
} elseif (!preg_match("/\s/", $string)) {
# Assume it's a correct email...
return [false, $string];
}
return false;
}
/**
* sendmail
*
* sendmail("test@foo.com", "test2@foo.com", "Hello World!", "This is my mail...");
* Returns: nothing
* Extra:
*/
function sendmail($from, $to, $subject, $text = false, $html = false, $files = false, $headers = false, $origin = false){
$GLOBALS["no_strict_warnings"] = true;
$mail = new Zend_Mail("UTF-8");
if (is_numeric($from))
$from = new user($from);
if (is_numeric($to))
$to = new user($to);
if (is_object($from)){
$from = $from["firstname"] . SPACE . $from["surname"] . SPACE . "<" . $from["email"] . ">";
}
if (is_object($to)){
$to = $to["firstname"] . SPACE . $to["surname"] . SPACE . "<" . $to["email"] . ">";
}
if ($a = parse_mail($from)){
[$fromname, $from] = $a;
}
// SPF fix
$mail->setReplyTo($from, ($fromname ?: false));
if (!$fromname)
$fromname = "$from ";
$mail->setFrom("atlas@atlascms.se", $fromname);
foreach (explode(",", $to) as $to){
if ($a = parse_mail($to)){
[$toname, $toemail] = $a;
#debug($toname, $toemail);
$mail->addTo($toemail, $toname);
} else {
$mail->addTo($to);
}
}
if (!empty($files) && is_array($files)){
foreach ($files as $fieldname => $fileinfo){
if (is_array($fileinfo)){
$file_source = $fileinfo['tmp_name'];
} else {
if (file_exists(get_path($fileinfo))){
$file_source = get_path($fileinfo);
}
}
$content = file_get_contents($file_source);
$mimetype = mimetype($file_source);
$at = new Zend_Mime_Part($content);
$at->type = $mimetype;
$is_image = is_array($fileinfo) ? strstr($fileinfo['type'], 'image') : is_image($fileinfo);
$filename = is_array($fileinfo) ? $fileinfo['name'] : $file_source;
if (!empty($is_image)){
$at->disposition = Zend_Mime::DISPOSITION_INLINE;
} else {
$at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
}
$at->encoding = Zend_Mime::ENCODING_BASE64;
$at->filename = $filename;
$mail->addAttachment($at);
}
}
if (is_array($headers)){
foreach ($headers as $key => $value){
if ($key == "Reply-To"){
$mail->setReplyTo($value);
} else {
$mail->addHeader($key, $value);
}
}
}
$mail->setSubject($subject);
$mail->setBodyText($text);
if (!empty($html)){
#debug($html);
$mail->setBodyHtml($html);
}
try{
$mail->send();
$data = [
"fromemail" => $from,
"toemail" => $to,
"subject" => $subject,
"origin" => $origin,
#"files" => serialize($files),
"date" => date("Y-m-d H:i:s"),
"data" => ($html ?: $text)
];
save2db("atlas", "feedback", $data);
} catch (Zend_Mail_Transport_Exception $e){
php_error(1, $e);
return false;
}
return true;
}
function numappend($number){
$appends["en"] = ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"];
$appends["se"] = [":e", ":a", ":a", ":e", ":e", ":e", ":e", ":e", ":e", ":e"];
if ($number == 0)
return;
$numbers = preg_split("//", $number, -1, PREG_SPLIT_NO_EMPTY);
$lastnum = $numbers[count($numbers) - 1];
return $number . $appends[$GLOBALS["language"]][$lastnum];
}
function oom($number, $one, $more, $include = false){
if (!$number)
$number = 0;
$label = $number == 1 ? $one : $more;
return $include ? $number . SPACE . $label : $label;
}
function read_settings($file){
$GLOBALS["incfiles"][] = $file;
$sfile = file($file);
foreach ($sfile as $line){
[$key, $value] = explode("\t", trim($line));
$settings[$key] = $value;
}
return $settings;
}
function site_settings($keyword = false, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
$query = [
"select" => "keyword, value",
"from" => "atlas.settings",
"where" => [
"kort" => $kort
]
];
if (!empty($keyword)){
$query["where"]["keyword"] = $keyword;
}
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$return[$r["keyword"]] = $r["value"];
}
return $keyword ? $return[$keyword] : $return;
}
function save_site_settings($keyword, $value = false, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (!empty($value)){
$query = [
"command" => "delete",
"from" => "atlas.settings",
"where" => [
"kort" => $kort,
"keyword" => $keyword
]
];
//print bq($query, 1);
db(bq($query));
$data = $query["where"];
$data["value"] = $value;
save2db("atlas", "settings", $data);
}
}
function mimetype($file){
$info = pathinfo(lc($file));
foreach (file($GLOBALS["mime_file"]) as $line){
if (strstr($line, "\t")){
[$type, $extension] = preg_split("/\t+/", trim($line));
if (!$extension)
continue;
foreach (explode(" ", $extension) as $ex){
if (!empty($info["extension"]) && $ex == $info["extension"])
return $type;
}
}
}
return "application/octet-stream";
}
function is_number($string){
if (is_int($string)) return true;
if (is_float($string)) return true;
if (is_string($string)){
if (preg_match("/[^0-9,\.,\.]/", $string)){
return false;
}
return true;
}
return false;
}
function is_email($string){
return filter_var($string, FILTER_VALIDATE_EMAIL);
}
function is_image($file){
$i = pathinfo($file);
if (!empty($i["extension"])){
return in_array(lc($i["extension"]), ["jpg", "jpeg", "png", "gif", "tif", "tiff", "bmp", "webp", "svg"]);
}
return false;
}
function is_video($file){
$i = pathinfo($file);
if (empty($i["extension"])) return false;
return in_array(lc($i["extension"]), ["mpg", "mpeg", "avi", "wmv", "qt", "mov", "m4v", "3gp", "mp4"]);
}
function fsize($size){
if ($size < 1024)
$thesize = "$size b";
if ($size > 1024)
$thesize = number_format($size / 1024) . " Kb";
if ($size > 1024000)
$thesize = number_format($size / 1024000) . " Mb";
if ($size > 1024000000)
$thesize = number_format($size / 1024000000, 0, ",", " ") . " Gb";
return $thesize;
}
function speed($speed, $text = true){
if (!$speed)
return false;
if ($speed < 1000)
$thespeed = "$speed Kbit/s";
if ($speed >= 1000)
$thespeed = $speed / 1000 . " Mbit/s";
if ($speed >= 1000000)
$thespeed = $speed / 1000000 . " Gbit/s";
return $text ? $thespeed : extract_number($thespeed);
}
function extensionicon($name, $size = 16){
if (is_image($name)){
return $size == "src" ? "extensions/image" : icon("extensions/image", $size);
} else {
$info = pathinfo($name);
if (!empty($info["extension"])){
$info["extension"] = lc($info["extension"]);
} else {
return "extensions/unknown";
}
if ($size == "src"){
return file_exists("$GLOBALS[atlas_dir]/virtuals/bilder/icons/extensions/$info[extension].png") ? "extensions/$info[extension]" : "extensions/unknown";
} else {
return file_exists("$GLOBALS[atlas_dir]/virtuals/bilder/icons/extensions/$info[extension].png") ? icon("extensions/$info[extension]", $size) : icon("extensions/unknown", $size);
}
}
}
/**
* stats
*
* print stats("articles", 2345, "4 hours", 1000)
* Returns: Number of unique hits depending on the interval (i.e. a user only counts again after the interval has been reached).
* Extra: [fake] is a fake integer to be added to the result. Set "onlyreturns" to true to only return and not add.
*/
function stats($key, $origin, $interval = "2 hour", $fake = false){
#return "?";
global $user;
if ($key == "member" and $user["id"] == 98 and $origin == 26812)
return;
$me = $user ? $user["id"] : $_SERVER["REMOTE_ADDR"];
$member = 0;
if (!empty($user))
$member = $user["id"];
$c = db("select count(id) as nr from atlas.stats where keyword = '" . sqlesc($key) . "' and origin = '" . sqlesc($origin) . "' and visitor = '$me' and datetime > date_sub(now(), interval $interval)", 1);
if ($c == 0){
if (!empty($user) && $key == "member" && $user["id"] == $origin){
} elseif (!$GLOBALS["web_robot"]) {
$page = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
db("insert into atlas.stats (keyword, origin, visitor, date, datetime, kort, member, page, referer, agent) values ('" . sqlesc($key) . "', '" . sqlesc($origin) . "', '$me', now(), now(), '$_SERVER[kort]', $member, '" . sqlesc($page) . "', '" . sqlesc(($_SERVER["HTTP_REFERER"] ?? false)) . "', '" . sqlesc($_SERVER["HTTP_USER_AGENT"] ?? false) . "')");
}
}
$ahits = db("select hits from atlas.stats_archive where keyword = '" . sqlesc($key) . "' and origin = '" . sqlesc($origin) . "' and kort = '$_SERVER[kort]'", 1);
$hits = db("select count(id) from atlas.stats where origin = '" . sqlesc($origin) . "' and keyword = '" . sqlesc($key) . "'", 1);
if (!empty($ahits))
$hits += $ahits;
gauge("Calculated stats for $key: $origin");
if (!empty($fake)){
if (has_priv()){
return ($hits + $fake) . " ($hits)";
} else {
return $hits + $fake;
}
} else {
return $hits;
}
}
function viewstats($key, $origin, $fake = false){
if (!is_array($origin))
$origin = [$origin];
global $user;
$query = [
"select" => "sum(hits) as hits, origin",
"from" => "atlas.stats_archive",
"where" => [
"keyword" => $key,
"origin:in" => $origin
],
"group" => "origin"
];
$hits = [];
foreach (db(bq($query)) as $r){
$hits[$r["origin"]] = $r["hits"];
}
$query["from"] = "atlas.stats";
$query["select"] = ["count(id) as hits, origin"];
foreach (db(bq($query)) as $r){
if (empty($hits[$r["origin"]])) $hits[$r["origin"]] = 0;
$hits[$r["origin"]] += $r["hits"];
}
if (count($origin) == 1 && !empty($hits[$origin[0]])){
$hits = $hits[$origin[0]];
if (!empty($fake)){
if (has_priv()){
return ($hits + $fake) . " ($hits)";
} else {
return $hits + $fake;
}
} else {
return $hits;
}
} else {
return array_pop($hits);
}
}
function filewrite($filename, $content, $append = false){
$mode = $append ? "a" : "w";
if (!is_writable(dirname($filename))){
warning("Can't write to file $filename");
return false;
}
if (!$handle = fopen(str_replace(" ", "\\ ", $filename), $mode)){
return "Cannot open file ($filename)";
}
if (fwrite($handle, $content) === false){
return "Cannot write to file ($filename)";
}
fclose($handle);
}
function toggle($id, $state = false, $show = 'block', $link = true, $size = 12){
$func = strstr($id, "(") ? $id : "toggle('" . $id . "')";
$icon = icon("symbols/right", $size);
$icon = str_replace("class=", "id='toggle_" . sevenbit($id, true) . "' class=", $icon); // Set right ID
$curstate = $state ? "open" : "closed";
$icon = str_replace("class='svgicon", "class='svgicon toggle_icon $curstate", $icon); // Set right class
if ($link){
return tag($icon, "span", ["onclick" => $func]);
} else {
return $icon;
}
// $closed = "icon-right";
// $open = "icon-down";
// $curstate = $state ? $open : $closed;
//
// if (!$link){
// return span("", "icomoon $curstate", "toggle_$id");
// }
//
// return "$label ";
}
/**
* Parse RXML
*
* print parserxml("ID: #id * - Page: &in.page;", $r);
* Returns: Same string but with PHP values replaced in them.
* Extra: #keyword * relies on $var being sent along, &array.value; does not
*/
function parserxml($string, $var = false){
if (!is_string($string)) return false;
$string = urldecode($string); // Handle urlencoded strings from self() or query()
# RXML 1.0
$string = preg_replace_callback("/#([A-Za-z0-9_]+)#/s", function ($m) use ($var){
return (empty($var[$m[1]]) ? false : $var[$m[1]]);
}, $string);
# RXML 2.0
if (preg_match_all("/&([a-z_A-Z]+)\./i", $string, $matches, PREG_SET_ORDER)){
foreach ($matches as $match){
global ${$match[1]};
$var = ${$match[1]};
$string = preg_replace_callback("/&" . $match[1] . "\.([a-zA-Z_]+);/is", function ($m) use ($var){
return $var[$m[1]] ?? false;
}, $string);
}
}
return $string;
}
function uc_words($string){
foreach (mb_split("\s+", $string) as $w){
$out[] = ucf(lc($w));
}
if (!$out)
return false;
return join(" ", $out);
}
function ucf($string){
$string = ucfirst($string);
#return mb_convert_case($string, MB_CASE_TITLE, 'UTF-8');
#$string = preg_replace("/^([åäöéüæø])/e", "strtr('$1', 'åäöéüæø', 'ÅÄÖÉÜÆØ')", $string);
$string = mb_ereg_replace_callback("^([åäöéüæø])", function ($m){
return strtr($m[1], 'åäöéüæø', 'ÅÄÖÉÜÆØ');
}, $string);
return $string;
}
function uc($string){
return mb_strtoupper($string, mb_detect_encoding($string));
#$string = strtoupper($string);
#$string = preg_replace("/([åäöéüæø])/e", "strtr('$1', 'åäöéüæø', 'ÅÄÖÉÜÆØ')", $string);
#$string = preg_replace_callback("/([åäöéüæø])/", function($m){ return strtr($m[1], 'åäöéüæø', 'ÅÄÖÉÜÆØ'); }, $string);
#return $string;
}
function lc($string){
$encoding = mb_detect_encoding($string) ?: "UTF8";
return mb_strtolower($string, $encoding);
}
function get_agg($key, $kort = false, $date = false){
$kort = !empty($kort) ? $kort : $_SERVER["kort"];
$query = [
"select" => "value",
"from" => "atlas.aggregate",
"where" => [
"kort" => $kort,
"keyword" => $key
]
];
if (!empty($date)){
$query["where"]["date:>"] = date("Y-m-d H:i:s", strtotime($date));
}
#print bq($query, 1);
return db(bq($query), 1);
}
function calculate_agg($db, $table, $key, $query = false){
foreach (db("select count(id) as nr from " . $db . "." . $table . " where kort = '" . $_SERVER["kort"] . "' " . $query) as $r){
agg($key, $r["nr"]);
}
}
function agg($key, $value, $kort = false){
$kort = $kort ? $kort : $_SERVER["kort"];
if (is_array($value))
$value = serialize($value);
db("delete from atlas.aggregate where kort = '$kort' and keyword = '" . addslashes($key) . "'");
db("insert into atlas.aggregate (kort, keyword, value) values ('$kort', '" . addslashes($key) . "', '" . addslashes($value) . "')");
}
function debug($s, $label = false, $file = false, $line = false){
if ($s === false){
$s = "FALSE";
} elseif ($s === true) {
$s = "TRUE";
}
if (empty($s)) $s = "(NULL)";
if (empty($_SERVER["REQUEST_URI"])){
if (is_array($s) || is_object($s)){
pre($s, $label);
} else {
$time = date("H:m:s");
print $label ? "*** [$time] $label: $s\n" : "*** [$time] $s\n";
}
} else {
if (!group("superduperadmin")) return;
if (is_array($s) || is_object($s)){
pre($s, $label);
} else {
if (empty($file) && empty($line)){
$debug = debug_backtrace();
foreach ($debug as $d){
if (in_array(basename($d["file"]), qw("global.php")) && count($debug) > 1) continue;
$file = $d["file"] ?? false;
$line = $d["line"] ?? false;
break;
}
}
if (empty($label)){
$label = basename($file);
}
print "" . overlib($label, bbe($file), $file . " / " . $line) . ":
" . wordwrap(htmlspecialchars($s), 100) . " ";
}
}
}
function pre($a, $label = false){
global $user;
$out = [];
if (empty($a)) return false;
if (empty($_SERVER["REQUEST_URI"])){
print_r($a);
} elseif (group("superduperadmin")) {
if (is_object($a) || is_array($a)){
$debug = debug_backtrace();
$out[] = "";
#$a = array_map( "htmlspecialchars", $a);
$ret = print_r($a, 1);
$out[] = htmlspecialchars($ret);
$out[] = " ";
#print div(backtrace() . join("\n", $out), "square");
require_once $GLOBALS["atlas_dir"] . "/include/layout.php";
$string = overlib(basename($debug[0]["file"]) . SPACE . $label, bbe($debug[0]["file"]), $debug[0]["file"] . " / " . $debug[0]["line"]);
print div($string . join("\n", $out), "square");
} else {
debug($a, "String");
}
}
}
function num($num, $decimals = 0, $currency = false, $showifempty = true){
$li = localeconv();
if (!$num && !$showifempty)
return false;
#pre($li);
$num = is_numeric($num) ? $num : extract_number($num);
$num = number_format($num, $decimals, $li["decimal_point"], $li["mon_thousands_sep"]);
if (!empty($currency)){
$space = $li["p_sep_by_space"] ? " " : "";
$a = $li["p_sign_posn"] == 3 ? [
$li["currency_symbol"],
$space,
$num
] : [
$num,
" ",
$li["currency_symbol"]
];
$num = join("", $a);
}
return $num;
}
function qw($string, $split = " "){
return explode($split, $string);
}
function extract_number($string, $keepnegative = true){
if (is_array($string)) $string = join(",", $string);
if (is_string($string)) $string = trim($string);
$minus = false;
if (!empty($keepnegative)){
$minus = preg_match("/^[−-]/", $string) ? "-" : false;
}
if (preg_match("/[.,]/", $string)){
return floatval($minus . preg_replace("/[^\d\.]/", "", str_replace(",", ".", $string)));
} else {
return intval($minus . preg_replace("/[^\d]/", "", $string));
}
}
function cache_dir($file, $kort = false){
$kort = $kort ? $kort : $_SERVER["kort"];
if (file_exists($file)){
$time = filemtime($file);
return "/$kort/" . date("Y/m/d/h", $time);
}
return false;
}
function create_dir($dir, $perm = "0755"){
if (is_dir($dir))
return true;
$dirs = preg_split("!/!", $dir, -1, PREG_SPLIT_NO_EMPTY);
foreach ($dirs as $d){
$mydir[] = $d;
$thedir = "/" . join("/", $mydir);
if (!is_dir($thedir) && !file_exists($thedir)){
mkdir($thedir, 0755);
}
}
}
function get_dir($dir, $type = "file", $match = false, $return = "base"){
$output = [];
if (is_dir($dir)){
$thedir = opendir($dir);
while (false !== ($file = readdir($thedir))){
if (in_array($file, [".", "..", ".svn", ".DS_Store", "__MACOSX"]))
continue;
if ($type == "file" && !is_file("$dir/$file"))
continue;
if ($type == "dir" && !is_dir("$dir/$file"))
continue;
if (!empty($match) && !preg_match("/$match/", $file))
continue;
$output[] = $return == "base" ? $file : "$dir/$file";
}
}
//if (is_array($output)) asort($output);
return $output;
}
function get_dir_recursive($dir, $type = "file", $match = false, $return = "base"){
if (is_dir($dir)){
$thedir = opendir($dir);
while (false !== ($file = readdir($thedir))){
if (in_array($file, [".", "..", ".svn", ".DS_Store", "__MACOSX"]))
continue;
if (is_dir("$dir/$file") && $found = get_dir_recursive("$dir/$file", $type, $match, $return)){
foreach ($found as $r){
$output[] = $r;
}
}
if ($type == "file" && !is_file("$dir/$file"))
continue;
if ($type == "dir" && !is_dir("$dir/$file"))
continue;
if (!empty($match) && !preg_match("/$match/", $file))
continue;
$output[] = $return == "complete" ? "$dir/$file" : $file;
}
}
return $output;
}
function nofile_error($file){
if (group("superduperadmin")){
$link = "javascript:dialog('/atlas/ajax/admin/create_template?path=" . urlencode($file) . "')";
$buttons = [
["Create", $link, "buttons/plus"]
];
print dialog("No such file", "No such file found: $file", "magnify", $buttons);
}
}
function get_path($file, $paths = false, $debug = false){
global $in;
if (!$file && !$paths)
return false;
$curdir = getcwd();
$file = preg_replace("!^/media!", $GLOBALS["media_dir"], $file);
$base = str_replace($GLOBALS["sites_dir"], "", ($_SERVER["DOCUMENT_ROOT"] ?? ""));
if (!$paths){
$paths = [
$file,
$curdir . "/" . $file,
$_SERVER["DOCUMENT_ROOT"] . $file,
$_SERVER["DOCUMENT_ROOT"] . "/include/" . $file,
$GLOBALS["sitemedia_dir"] . "/icons/$file.png",
$GLOBALS["sitemedia_dir"] . "/$_SERVER[kort]/icons/$file.png",
$GLOBALS["atlas_dir"] . "/virtuals/bilder/icons/" . $_SERVER["kort"] . "/" . $file . ".png",
$GLOBALS["atlas_dir"] . "/virtuals/bilder/icons/" . $_SERVER["shortname"] . "/" . $file . ".png",
$GLOBALS["atlas_dir"] . "/virtuals/bilder/icons/" . $file . ".png",
$GLOBALS["atlas_dir"] . "/virtuals/bilder/" . $file,
$GLOBALS["atlas_dir"] . "/virtuals/" . $file,
$GLOBALS["media_dir"] . "/" . $file,
$GLOBALS["media_dir"] . "/modules/" . $file,
$GLOBALS["media_dir"] . "/sites/" . $base . "/" . $file
];
if (!empty($GLOBALS["layout"]) && is_string($GLOBALS["layout"])){
$paths[] = $GLOBALS["media_dir"] . "/sites/" . $base . "/images/layout/" . $GLOBALS["layout"] . "/" . $file;
}
if (!empty($in["uselayout"])){
$paths[] = $GLOBALS["media_dir"] . "/sites/" . $base . "/images/layout/" . $in["uselayout"] . "/" . $file;
}
}
foreach ($paths as $p){
$p = preg_replace("!^/images/!", $GLOBALS["media_dir"] . "/sites/" . $base . "/images/", $p);
if (is_file($p) || is_link($p)){
$file = $p;
$file = preg_replace("!/+!", "/", $file);
return $file;
}
if (is_file($p . "/" . $file) || is_link($p . "/" . $file)){
$file = $p . "/" . $file;
$file = preg_replace("!/+!", "/", $file);
return $file;
}
}
if (is_image($file) && $GLOBALS["media_host"] != "localhost"){
# We couldn't find the file locally, but it's an image file and
# we're going to assume it's a module file
# return $GLOBALS["media_dir"] . "/modules/" . $file;
}
return false;
}
function atlas_path($path){
$path = preg_replace("!^/media!", $GLOBALS["media_dir"], $path);
$path = preg_replace("!^/cache!", $GLOBALS["media_dir"] . "/cache", $path);
return $path;
}
/**
* Takes an absolute path on the server and returns a browser-accessible version of that path
*
* @param string $path
* @param bool $site
* @return string
*/
function public_path($path, $site = false){
#if (strstr($path, "http")) return $path;
$path = preg_replace("!^" . $GLOBALS["atlas_dir"] . "/applications/([a-z]+)/modules/!", "/pagemodules/$1/modules/", $path);
$path = preg_replace("!^$GLOBALS[atlas_dir]/virtuals/!i", "/", $path);
$path = preg_replace("!^$GLOBALS[media_dir]!", "/media", $path);
$path = preg_replace("!^$_SERVER[DOCUMENT_ROOT]!", "/", $path);
$cleanroot = rtrim($_SERVER["DOCUMENT_ROOT"], "/");
$path = preg_replace("!^$cleanroot!", "/", $path);
$paths = [
$GLOBALS["atlas_dir"],
$GLOBALS["sites_dir"]
];
foreach ($paths as $d){
$path = preg_replace("!^$d!", "", $path);
}
$path = preg_replace("!^/{1,}!", "/", $path);
#if (is_image($path) && !$site && $GLOBALS["media_host"] != "localhost") $site = $GLOBALS["media_host"];
if ($site === true || $site == 1)
$path = "http://$_SERVER[HTTP_HOST]/$path";
if (is_string($site))
$path = "http://$site/$path";
return $path;
}
function short_path($path){
$trimpath = [
$GLOBALS["media_dir"] . "/",
$GLOBALS["atlas_dir"] . "/virtuals/"
];
foreach ($trimpath as $p){
$path = str_replace($p, "", $path);
}
return $path;
}
function qp_decode($string){
return preg_replace_callback('/=\?(.*)\?([BQ])\?(.*)\?=/U', 'quoted_word_callback', $string);
}
function quoted_word_callback($m){
switch ($m[2]){
case 'Q':
case 'q':
return quoted_printable_decode($m[3]);
case 'B':
case 'b':
return base64_decode($m[3]);
}
}
function fdate($date){
if (!empty($date)){
#debug($GLOBALS["locale"]);
$time = strtotime($date);
if (date("Hi", $time) == "0000"){
return format_time("%x", $time);
} else {
return preg_replace("/:00$/", "", format_time("%x %X", $time));
}
} else {
return false;
}
}
/**
* Returns string of all array items like ['one', 'two', 'three'] => "one, two and three"
*
* @param array $array
* @param string $delimiter
* @param string $last
* @param bool $limit
* @param bool $summarize
* @return string
*/
function itemlist($array, $delimiter = ", ", $last = "and", $limit = false, $summarize = false){
$last = lp($last, "L");
if (!is_array($array)) return false;
$array = array_values($array);
if ($c = count($array)){
if ($c > 2){
//$limit = $limit ?? count($array);
if ($limit === false){
$limit = $c;
}
if ($summarize === true && $limit !== false && $limit < $c){
$items = join($delimiter, array_slice($array, 0, $limit));
$summary = lp("and", "L") . SPACE . count(array_slice($array, $limit, $c - 1)) . SPACE . lp("more:3", "L");
return $items . SPACE . $summary;
}
return join($delimiter, array_slice($array, 0, $limit - 1)) . " $last " . $array[$limit - 1];
} else {
return join(" $last ", $array);
}
} else {
return false;
}
}
/**
* Run this function to declare keys that need to be found in $in for the application
* to continue running, if one or more of the keys are not found, it will stop execution of Atlas
* and display a warning for the user
*
* ins("user,passwd");
*
*
* @param string $i a comma-separated list of keywords
*/
function ins($i, $return = false){
global $in, $user;
#pre($in);
$errors = $returnerrors = [];
foreach (explode(",", $i) as $a){
#$moreinfo = has_priv() ? " \$in[$a] was missing " : "";
if ($a == "id" && !empty($in[$a]) && !is_numeric($in[$a])){
$errors[] = lp($a) . " " . lp("was missing", "L");
$returnerrors[] = $a;
} elseif (empty($in[$a])) {
$errors[] = lp($a) . " " . lp("was missing", "L");
$returnerrors[] = $a;
}
}
if (!empty($return)){
return count($returnerrors) ? $returnerrors : false;
}
if (!empty($errors)){
$moreinfo = has_priv() ? " " . join(" ", $errors) : "";
print alert(lp("error"), lp("some input data was missing for the script to process the request") . $moreinfo, "badges/stop", 1);
}
}
function tidy($data){
$data = preg_replace("!(.*?)>([^\s])!m", "$1>\n$2", $data);
$data = preg_replace("/^\s* 0){
$jump = ($time - $GLOBALS["page_gauge"][count($GLOBALS["page_gauge"]) - 1]["time"]);
}
$memory = memory_get_usage(true);
#error_log($string . ": " . $jump);
#print "$string\n";
$GLOBALS["page_gauge"][] = [
"time" => $time,
"string" => $string,
"jump" => $jump,
"page" => $debug[0]["file"],
"file" => $file,
"memory" => $memory
];
}
/**
* Function to return a parsed string as dimensions
*
* $dimensions = dimensions("340x240");
*
*
* It can also be used to recalculate dimensions:
*
* $dimensions = dimensions("1000:500", 500);
* $dimensions = dimensions("1000:500:500");
* // Both returns ["width" => 500, "height" => 250]
*
*
* @param $string
* @param bool $width
* @return array
*/
function dimensions($string, $width = false){
$canvaswidth = $width ? $width : $GLOBALS["contentwidth"];
if (stristr($string, "x")){
[$width, $height] = explode("x", str_replace(" ", "", $string));
$width = extract_number($width);
$height = extract_number($height);
} elseif (stristr($string, ":")) {
$data = explode(":", $string);
if (empty($data[2]))
$data[2] = $canvaswidth; # set to base article width
$width = $data[2];
$height = round(($width / $data[0]) * $data[1]);
}
return [
$width,
$height
];
}
function support_files($file){
$pi = pathinfo($file);
$path = $pi["dirname"] . "/" . $pi["filename"];
$support_files = [
"_styles.css",
"_styles_beta.css",
"_mobile.css",
".css",
"_jquery.js",
"_javascript.js",
".js"
];
$beta = $GLOBALS["beta"] ?? "no";
foreach ($support_files as $append){
if (stripos($append, "beta") !== false && $beta != "yes") continue;
if (strstr($append, "mobile") && !is_phone()) continue;
$file = $path . $append;
$pi = pathinfo($file);
if (file_exists($file)){
if ($pi["extension"] == "css"){
load_css($file);
} elseif ($pi["extension"] == "js") {
load_js($file);
}
}
}
}
function atlas_autoload($class){
$classpath = str_replace("_", "/", $class);
$i = pathinfo($_SERVER["SCRIPT_FILENAME"]);
$path = $i["dirname"];
$paths = [
"/usr/local/php/$classpath.php",
"$path/classes/$class.php",
"$path/classes/$classpath.php",
$GLOBALS["atlas_dir"] . "/include/classes/$class.php",
$GLOBALS["atlas_dir"] . "/include/classes/$classpath.php",
($_SERVER["DOCUMENT_ROOT"] ?? false) . "/include/classes/$class.php",
($_SERVER["DOCUMENT_ROOT"] ?? false) . "/include/classes/$classpath.php",
"/usr/share/php/$classpath.php"
];
#print "";
#print_r($paths);
if ($file = get_path(false, $paths)){
require_once($file);
support_files($file);
}
}
spl_autoload_register("atlas_autoload");
if (is_file(__DIR__ . '/vendor/autoload.php')){
require_once 'vendor/autoload.php';
}
function encode_email($mail, $text = false){
global $in;
if (!empty($GLOBALS["ajax"]) || (isset($GLOBALS["encode_emails"]) && $GLOBALS["encode_emails"] === false))
return "$mail ";
if (in_array("mail", $GLOBALS["output_formats"]))
return $mail;
$chars = ["<", "|", ">", " ", ")", "(", "!"];
$mchars = preg_split("//", $mail);
$s = "";
foreach ($mchars as $c)
$s .= $chars[rand(0, count($chars) - 1)] . $c . $chars[rand(0, count($chars) - 1)];
$s = str_rot13($s);
if (!empty($in["ajax"])){
return "$text ";
}
if ($GLOBALS["security_level"] == 2){
$t = $text ? $text : lp("email", "L");
return "$t ";
} else {
$mailparts = explode("@", $mail);
return tag("", "span", [
"data-u" => strrev($mailparts[0]),
"data-d" => strrev($mailparts[1]),
"class" => "cloaker"
]);
#return "" . gtext("text=$mail", "size=10", "font=lucidagrande", "alt=" . lp("send mail")) . " ";
}
}
function tag($content, $tag = "p", $attr = false){
if (!empty($tag)){
$attributes = "";
if (!empty($attr)){
$attributes = " " . attributes($attr, false, false);
}
if ($GLOBALS["initversion"] == 3){
if (!in_array($tag, $GLOBALS["atlas_site"]->styles["tags"])){
$GLOBALS["atlas_site"]->styles["tags"][] = $tag;
}
}
$selfclose = qw("area base br col embed hr img input link meta param source track wbr");
if (in_array($tag, $selfclose)){
return "<$tag$attributes>";
} else {
return "<$tag$attributes>$content$tag>";
}
} else {
return $content;
}
}
function styletag($a, $attr = true){
if (!is_array($a) || count((array)$a) == 0) return false;
$out = [];
foreach ($a as $key => $value){
if (!$value) continue;
if (is_array($value)) continue;
if ($key == "background-image" && !strstr($value, "url(")){
$value = "url(" . $value . ")";
}
if ($GLOBALS["initversion"] == 3){
$value .= " !important";
}
$out[] = "$key: $value";
}
if (!count($out)) return false;
return $attr ? "style='" . join("; ", $out) . "'" : join("; ", $out);
}
function attributes($a, $valid = false, $tag = false){
global $site;
$out = [];
if (empty($a) || !is_array($a) || count((array)$a) == 0){
return false;
}
if (empty($a["onclick"]) && !empty($a["href"]) && strstr($a["href"], "javascript:")){
$a["onclick"] = str_replace("javascript:", "", $a["href"]);
$a["href"] = "javascript:;";
}
if (!empty($a["onclick"]) && $GLOBALS["initversion"] == 3){
$safe = join("|", qw("dialog bbe visa svisa pop toggle popupmenu"));
if (preg_match("/^($safe)\(['\"](.*?)['\"]\)/", $a["onclick"], $c)){
$a["data-cmd"] = $c[1];
//$a["data-arg"] = $c[2];
$a["data-args"] = join(";", preg_split("/['\"],\s*['\"]/", $c[2]));
} else {
$hash = "link" . crc32($a["onclick"]);
$a["class"] = trim(join(" ", [($a["class"] ?? false), $hash]));
$GLOBALS["jquery_code"][] = " $('body').on('click', '." . $hash . "', function(){ " . $a["onclick"] . "; return false;})";
}
unset($a["onclick"]);
}
if ($GLOBALS["initversion"] == 3){
if (!empty($a["style"]) && $styletag = styletag($a["style"])){
$hash = "style" . crc32($styletag); // Alla med samma stil får samma hash
if (empty($a["class"])) $a["class"] = "";
$a["class"] = trim(join(" ", [$a["class"], $hash]));
$GLOBALS["css"]["." . $hash] = $a["style"];
}
unset($a["style"]);
if (!empty($a["class"])){
//$GLOBALS["atlas_site"]->styles["classes"] = array_merge((array)$GLOBALS["atlas_site"]->styles["classes"], explode(" ", $a["class"]));
foreach (explode(" ", $a["class"]) as $class){
if (empty($class)) continue;
if (preg_match("/^(link|style)\d+$/", $class)) continue;
if (!in_array($class, $GLOBALS["atlas_site"]->styles["classes"])){
$GLOBALS["atlas_site"]->styles["classes"][] = $class;
}
}
}
if (!empty($a["id"]) && !preg_match("/_\d+$/", $a["id"]) && !preg_match("/(AtlasCore|timeline_|children_)/", $a["id"])) $GLOBALS["atlas_site"]->styles["ids"][] = $a["id"];
}
foreach ($a as $key => $value){
if ($value === false) continue;
if (empty($value)) continue;
if (is_array($valid) && (!in_array($key, $valid) && !strstr($key, "data-"))) continue;
if ($key == "style"){
$out[] = styletag($value, true);
} elseif (!is_array($value)) {
$out[] = empty($value) ? $key : "$key=\"$value\"";
}
}
return $tag ? "<$tag " . join(" ", $out) . ">" : join(" ", (array)$out);
}
function arguments($args, $default = false, $order = false){
if (empty($default) || !is_array($default)) $default = [];
foreach ($args as $i => $arg){
if (is_array($arg)){
foreach ($arg as $key => $value){
if (is_array($value)) continue;
$default[$key] = $value;
}
} elseif (is_string($arg) && strstr($arg, '=')) {
[$tag, $val] = explode('=', $arg, 2);
if (empty($val) || empty($tag)) continue;
$default[$tag] = $val;
} elseif (!empty($order)) {
$tag = array_shift($order);
$default[$tag] = $arg;
}
}
return $default;
}
function edit_arguments($array, $key, $value, $limit = false){
$foundit = 0;
foreach ($array as $item){
if (is_string($item) && preg_match("/^[a-z]+\=/", $item)){
[$mkey, $mvalue] = explode("=", $item, 2);
if ($mkey == $key){
$foundit++;
if (!$value)
continue;
$mvalue = edit_list($mvalue, $value, " ");
}
$out[] = "$mkey=$mvalue";
} else {
$out[] = $item;
}
}
if (!$foundit && $value)
$out[] = "$key=$value";
return $out;
}
function lang2string($lang){
foreach (explode(" ", $GLOBALS["languages"]) as $l){
[$short, $long] = explode(";", trim($l));
if ($lang == $short)
return $long;
if ($lang == $long)
return $short;
}
return false;
}
function save_cache_data($keyword, $data, $kort = false){
if (!$kort) $kort = $_SERVER["kort"] ?? "AAA";
if (is_array($data) || is_object($data))
$data = serialize($data);
$key = sevenbit($keyword, true);
$dir = sprintf("%s/cache/aggregate/%s", $GLOBALS["media_dir"], $kort);
create_dir($dir);
$file = sprintf("%s/%s.txt", $dir, $key);
filewrite($file, $data);
}
function clear_cache_data($keyword, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (!$kort) $kort = "AAA";
$cache_file = sprintf("%s/cache/aggregate/%s/%s.txt", $GLOBALS["media_dir"], $kort, $keyword);
if (file_exists($cache_file)){
unlink($cache_file);
}
}
function get_cache_data($keyword, $time = "30 minutes", $kort = false){
if (!$kort)
$kort = $_SERVER["kort"];
$time = strtotime("-$time");
$key = sevenbit($keyword, true);
$cache_file = sprintf("%s/cache/aggregate/%s/%s.txt", $GLOBALS["media_dir"], $kort, $key);
if (file_exists($cache_file)){
$ftime = filemtime($cache_file);
if ($ftime > $time){
$data = file_get_contents($cache_file);
if (is_serialized($data)){
return unserialize($data);
} else {
return $data;
}
} else {
unlink($cache_file);
}
}
return false;
}
function is_serialized($string){
if (!is_string($string)) return false;
if (preg_match("/^([adObis]:|N;)/", $string)){
return true;
}
return false;
}
function urlpath(){
if (func_num_args() > 0){
foreach (func_get_args() as $p){
$parts[] = rawurlencode($p);
}
return join("/", $parts);
}
}
function getpath($parse = true){
if (!empty($_SERVER["PATH_INFO"])){
$parts = array_values(explode("/", $_SERVER["PATH_INFO"]));
unset($parts[0]);
$return = [];
foreach ($parts as $p){
if (!$p) continue;
if (strstr($p, ":") && $parse){
[$key, $value] = explode(":", $p);
$return[$key] = urldecode($value);
} else {
$return[] = urldecode($p);
}
}
return $return;
} else {
return [];
}
}
function query($inkey = false, $invalue = false, $usein = true){
if ($usein === true){
global $in;
} elseif (is_array($usein)) {
$in = $usein;
}
$returns = [];
if (!is_array($inkey)) $inkey = [$inkey => $invalue];
if (!$usein){
return http_build_query($inkey);
}
$q = array_merge((array)$in, $inkey);
if (!empty($q["kort"]) && $q["kort"] == $_SERVER["kort"])
unset($q["kort"]);
foreach ($q as $key => $value){
if (in_array($key, ["load_module_data", "atlas_token"]))
continue;
if (!$value)
continue;
if (is_array($value)){
$knr = 0;
foreach ($value as $k => $v){
if (!is_array($v)){
#pre($v);
if ($k === $knr) $k = "";
$returns[$key][$k] = $v; //"{$key}[$k]=" . rawurlencode($v);
$knr++;
}
}
} else {
$returns[$key] = $value; // .= "$key=" . rawurlencode($value);
}
}
//debug(http_build_query($returns));
return http_build_query($returns);
}
function browser($key = false, $agent = false){
// FIXA: ny get_browser() i och med ny version av PHP
#$browscap = new \BrowscapPHP\Browscap();
if (empty($agent))
$agent = $_SERVER["HTTP_USER_AGENT"];
if (empty($GLOBALS["browser"]))
$GLOBALS["browser"] = get_browser($agent, true);
#pre($GLOBALS["browser"]);
return $key ? $GLOBALS["browser"][$key] : $GLOBALS["browser"];
}
############################################################################
# Function: Language print
# Syntax: lp(string text, string case, boleen direct)
# Example: print lp("example", "U");
# Databases: atlas.language
# Returns: string translated to sites language, in specified case
# Extra: case: U = Uppercase, F = First uppercaser, L = lowercase, C = Capitalize
############################################################################
function lp($word, $case = 'F', $direct = false){
if (!is_string($word)) return false;
if (strlen($word) == 0 || $word == ' ') return;
$nr = 0;
$out = [];
foreach (explode(";", $word) as $word){
$nr++;
if ($nr > 1) $case = "L";
$word = trim($word);
if (is_numeric($word)){
$out[] = $word;
} elseif ($GLOBALS["language"] == "en") {
$GLOBALS["atlas_translation"][$word] = $word;
$out[] = fix_lang($word, $case);
} else {
$GLOBALS["atlas_usedphrases"][] = $word;
#$GLOBALS["atlas_translation"][$word] = $word;
#$out[] = "[LP:$word:$case]";
$out[] = fix_lang($word, $case);
}
}
return join(" ", $out);
}
function tp($string){
$args = array_slice(func_get_args(), 1);
if (count($args) > 0){
# We need to have some arguments
# and then strip whitespace from them
$args = array_map("trim", $args);
}
if (empty($args)) return false;
if (!$string || $string == "")
return false;
$parts = preg_split("/(\%[^\s]+)/", $string, false, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if (count($parts) > 0){
$parts = array_map("trim", $parts);
$nr = 0;
foreach ($parts as $p){
$nr++;
$case = $nr == 1 ? "F" : "L";
$out[] = preg_match("/^\%/", $p) ? $p : lp($p, $case);
}
array_unshift($args, join(" ", $out));
#pre($args);
if (!empty($args)){
return call_user_func_array("sprintf", $args);
}
#return sprintf(join(" ", $out), $args);
}
return false;
}
function fix_lang($word, $case){
if (function_exists("gettext")){
$translated_word = _($word);
if ($translated_word == $word){
$uppercasefirst = ucf($word);
$translated_word = _($uppercasefirst);
if ($translated_word == $uppercasefirst){
$GLOBALS["atlas_orphanedphrases"][$word] = true;
}
}
$word = $translated_word;
}
$word = preg_replace("/:\d$/", "", $word);
if ($case == "C"){
#debug($word);
$word = ucwords($word);
} elseif ($case == "L") {
$word = lc($word);
} elseif ($case == "F") {
$word = ucf($word);
} elseif ($case == "U") {
$word = strtoupper($word);
}
return "$word";
}
function ceiling($value, $precision = 0){
return ceil($value / $precision) * $precision;
}
function flooring($value, $precision = 0){
return floor($value / $precision) * $precision;
}
function better_range($start, $stop, $step){
if ($stop <= $start) return false;
$return = [$start];
while (1){
$start = ceiling($start, $step);
if ($start > $stop) break;
$return[] = $start;
$start += $step;
}
$return[] = $stop;
return $return;
}
function load_javascript($file){
$paths = [
"$_SERVER[DOCUMENT_ROOT]/include/$file",
"$_SERVER[DOCUMENT_ROOT]/include/$file.js",
"$GLOBALS[atlas_dir]/virtuals/atlas/include/$file.js",
"$GLOBALS[atlas_dir]/virtuals/atlas/include/$file",
"$GLOBALS[atlas_dir]/virtuals/atlas/include/javascript/$file",
"$GLOBALS[atlas_dir]/virtuals/atlas/include/javascript/$file.js"
];
if ($path = get_path($file, $paths)){
//debug(public_path($path));
$GLOBALS["page_load_scripts"][] = $path;
}
}
if (!function_exists('http_build_url')){
define('HTTP_URL_REPLACE', 1); // Replace every part of the first URL when there's one of the second URL
define('HTTP_URL_JOIN_PATH', 2); // Join relative paths
define('HTTP_URL_JOIN_QUERY', 4); // Join query strings
define('HTTP_URL_STRIP_USER', 8); // Strip any user authentication information
define('HTTP_URL_STRIP_PASS', 16); // Strip any password authentication information
define('HTTP_URL_STRIP_AUTH', 32); // Strip any authentication information
define('HTTP_URL_STRIP_PORT', 64); // Strip explicit port numbers
define('HTTP_URL_STRIP_PATH', 128); // Strip complete path
define('HTTP_URL_STRIP_QUERY', 256); // Strip query string
define('HTTP_URL_STRIP_FRAGMENT', 512); // Strip any fragments (#identifier)
define('HTTP_URL_STRIP_ALL', 1024); // Strip anything but scheme and host
function http_build_url($url, $parts = [], $flags = HTTP_URL_REPLACE, &$new_url = false){
$keys = ['user', 'pass', 'port', 'path', 'query', 'fragment'];
if (!empty($flags) & HTTP_URL_STRIP_ALL){
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
$flags |= HTTP_URL_STRIP_PORT;
$flags |= HTTP_URL_STRIP_PATH;
$flags |= HTTP_URL_STRIP_QUERY;
$flags |= HTTP_URL_STRIP_FRAGMENT;
} elseif (!empty($flags) & HTTP_URL_STRIP_AUTH) {
$flags |= HTTP_URL_STRIP_USER;
$flags |= HTTP_URL_STRIP_PASS;
}
$parse_url = parse_url($url);
if (!empty($parts['scheme']))
$parse_url['scheme'] = $parts['scheme'];
if (!empty($parts['host']))
$parse_url['host'] = $parts['host'];
if (!empty($flags) & HTTP_URL_REPLACE){
foreach ($keys as $key){
if (!empty($parts[$key]))
$parse_url[$key] = $parts[$key];
}
} else {
if (!empty($parts['path']) && ($flags & HTTP_URL_JOIN_PATH)){
if (!empty($parse_url['path']))
$parse_url['path'] = rtrim(str_replace(basename($parse_url['path']), '', $parse_url['path']), '/') . '/' . ltrim($parts['path'], '/');
else
$parse_url['path'] = $parts['path'];
}
if (!empty($parts['query']) && ($flags & HTTP_URL_JOIN_QUERY)){
if (!empty($parse_url['query']))
$parse_url['query'] .= '&' . $parts['query'];
else
$parse_url['query'] = $parts['query'];
}
}
foreach ($keys as $key){
if (!empty($flags) & (int)constant('HTTP_URL_STRIP_' . strtoupper($key)))
unset($parse_url[$key]);
}
$new_url = $parse_url;
return ((!empty($parse_url['scheme'])) ? $parse_url['scheme'] . '://' : '')
. ((!empty($parse_url['user'])) ? $parse_url['user'] . ((!empty($parse_url['pass'])) ? ':' . $parse_url['pass'] : '') . '@' : '')
. ((!empty($parse_url['host'])) ? $parse_url['host'] : '')
. ((!empty($parse_url['port'])) ? ':' . $parse_url['port'] : '')
. ((!empty($parse_url['path'])) ? $parse_url['path'] : '')
. ((!empty($parse_url['query'])) ? '?' . $parse_url['query'] : '')
. ((!empty($parse_url['fragment'])) ? '#' . $parse_url['fragment'] : '');
}
}
function _strnatcmp($left, $right){
while ((strlen($left) > 0) && (strlen($right) > 0)){
if (preg_match('/^([^0-9]*)([0-9].*)$/Us', $left, $lMatch)){
$lTest = $lMatch[1];
$left = ($lMatch[2] ?? false);
} else {
$lTest = $left;
$left = '';
}
if (preg_match('/^([^0-9]*)([0-9].*)$/Us', $right, $rMatch)){
$rTest = $rMatch[1];
$right = ($rMatch[2] ?? false);
} else {
$rTest = $right;
$right = '';
}
$test = strcmp($lTest, $rTest);
if ($test != 0){
return $test;
}
if (preg_match('/^([0-9]+)([^0-9].*)?$/Us', $left, $lMatch)){
$lTest = intval($lMatch[1]);
$left = ($lMatch[2] ?? false);
} else {
$lTest = 0;
}
if (preg_match('/^([0-9]+)([^0-9].*)?$/Us', $right, $rMatch)){
$rTest = intval($rMatch[1]);
$right = ($rMatch[2] ?? false);
} else {
$rTest = 0;
}
$test = $lTest - $rTest;
if ($test != 0){
return $test;
}
}
return strcmp($left, $right);
}
function is_mobile_layout(){
if (in_array($GLOBALS["layout"], ["mobile", "tablet"]))
return true;
return false;
}
function is_mobile($reallymobile = false){
if (!empty($reallymobile)){
if (
stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "iphone")
|| stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "ipod")
|| stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "android")
|| stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "ipad")
){
return true;
}
} else {
if (!empty($GLOBALS['output_formats']) && is_array($GLOBALS['output_formats']) || is_mobile(true)){
if (in_array("mobile", (array)$GLOBALS["output_formats"]) || in_array("tablet", (array)$GLOBALS["output_formats"]) || is_mobile(true)){
return true;
}
}
}
return false;
}
function is_phone($agent = false){
if (!empty($agent)){
if (
stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "iphone")
|| stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "ipod")
|| stristr($_SERVER["HTTP_USER_AGENT"] ?? "", "android")
){
return true;
}
}
if (!empty($GLOBALS["output_formats"]) && is_array($GLOBALS["output_formats"]) && in_array("mobile", $GLOBALS["output_formats"])){
return true;
}
return false;
}
function is_tablet(){
if (in_array("tablet", (array)$GLOBALS["output_formats"])){
return true;
}
return false;
}
function api_login(){
global $in, $user;
if (!empty($user))
return true;
if (!empty($in["user"])){
$u = get_member_info($in["user"]);
} elseif (!empty($in["api_user"])) {
$u = get_member_info($in["api_user"]);
} else {
print "AXA Error User not specified, see AXA documentation for usage";
die();
}
if (!empty($u)){
if (!$in["api_key"]){
print "AXA Error API key missing, see AXA documentation for usage";
die();
}
if ($in["api_key"] != $u["md5pass"]){
print "Missing info API key incorrect, see AXA documentation for usage";
die();
}
} else {
print "AXA Error No such user";
die();
}
}
function float($num){
$larr = localeconv();
$search = [
$larr['decimal_point'],
$larr['mon_decimal_point'],
$larr['thousands_sep'],
$larr['mon_thousands_sep'],
$larr['currency_symbol'],
$larr['int_curr_symbol']
];
$replace = ['.', '.', '', '', '', ''];
return str_replace($search, $replace, $num);
#if (!$num) return floatval(0);
#return floatval(str_replace(",", ".", $num));
}
function validate_social_security($string){
if ($GLOBALS["language"] == "se"){
// if (strlen(str_replace('-', '', $string)) < 12){
// return false;
// }
if ($num = preg_replace("/[^\d\.]/", "", str_replace(",", ".", $string))){
$digits = preg_split("//", $num, -1, PREG_SPLIT_NO_EMPTY);
if (count($digits) > 12 || count($digits) < 10){
return false;
} else {
$orig_digits = $digits;
if (count($digits) > 10){
$digits = array_slice($digits, -10);
}
$nr = 0;
for ($a = 0; $a < 9; $a++){
$plus = $nr++ % 2 ? 1 : 2;
$result = $digits[$a] * $plus;
$sumnums[] = $result;
}
$sum = 0;
foreach ($sumnums as $sumnum){
$mydigs = preg_split("//", $sumnum, -1, PREG_SPLIT_NO_EMPTY);
foreach ($mydigs as $mydig){
$sum += $mydig;
}
}
$control = (10 - $sum % 10);
if ($control == 10)
$control = 0;
if ($control == $digits[9]){
if ($orig_digits == 12){
return join("", array_slice($orig_digits, 0, 10)) . "-" . join("", array_slice($orig_digits, 10, 4));
} else {
return join("", array_slice($orig_digits, 0, 8)) . "-" . join("", array_slice($orig_digits, 8, 4));
}
}
}
}
} elseif ($GLOBALS["language"] == "no") {
return $string;
}
// return false;
}
function format_social_security($string, $type = "person", $format = "############"){
if ($string = validate_social_security($string)){
# It's a valid social security string
if ($type == "person"){
# Let's format it correctly!
$digits = preg_split("//", $string, -1, PREG_SPLIT_NO_EMPTY);
if (count($digits) < 12){
$year = format_time("%C");
$pyear = extract_number($digits[0] . $digits[1]);
if ($pyear <= $year){
return extract_number(20 . join("", $digits));
} else {
return extract_number(19 . join("", $digits));
}
} else {
return extract_number($string); # The number was correct to start with
}
} elseif ($type === 'company') {
return extract_number($string); # The number was correct to start with
}
}
return false;
}
function phone_number($nr, $formats = false){
if (empty($GLOBALS["areacodes"])){
if (file_exists("$GLOBALS[data_dir]/Atlas/Areacodes/$GLOBALS[language].txt")){
$GLOBALS["areacodes"] = array_filter(explode("\n", file_get_contents("$GLOBALS[data_dir]/Atlas/Areacodes/$GLOBALS[language].txt")));
}
}
if ($formats === true){
$number = preg_replace("/[^\d\+]/", "", $nr);
if (preg_match("/^00/", $number)){
$number = preg_replace("/^00/", "+", $number);
} elseif (preg_match("/^0[1-9]/", $number)) {
switch ($GLOBALS["language"]){
case "se":
$number = "+46" . preg_replace("/^0/", "", $number);
break;
}
}
return $number;
}
if (!$formats)
$formats = ["### ##", "## ## ##", "### ## ##", "### ### ##"];
if (!empty($GLOBALS["phone_formats"]))
$formats = explode("\n", $GLOBALS["phone_formats"]);
$country = false;
if (!empty($GLOBALS["areacodes"])){
if (preg_match("/^\+(\d{2})/", $nr, $m)){
$country = "+" . $m[1];
if ($m[1] == 46 && $GLOBALS["language"] == "se"){
$country = false;
$nr = preg_replace("/^\+46/", "0", $nr);
} else {
$nr = preg_replace("/^\+\d{2}/", "", $nr);
}
}
$number = preg_replace("/[^\d\+]/", "", $nr);
$cd = join("|", $GLOBALS["areacodes"]);
if (preg_match("/^($cd)(.*)$/", $number, $m)){
$digits = preg_split("//", $m[2], -1, PREG_SPLIT_NO_EMPTY);
$numlen = count($digits);
foreach ($formats as $f){
$charnum = substr_count($f, "#");
if ($charnum == $numlen){
$lnr = 0;
foreach (preg_split("//", $f, -1, PREG_SPLIT_NO_EMPTY) as $c){
if ($c == "#"){
$out[] = $digits[$lnr];
$lnr++;
} else {
$out[] = $c;
}
}
if (!empty($out)){
return $country . $m[1] . "-" . trim(join("", $out));
}
}
}
}
}
return $country . $nr;
}
function self($a = false, $b = false, $usein = true){
global $in;
$self = !empty($_SERVER["PATH_INFO"]) ? str_replace(".php", "", $_SERVER["PHP_SELF"]) : $_SERVER["PHP_SELF"];
if ($usein){
return $self . "?" . query($a, $b);
} else {
if (is_array($a)){
foreach ($a as $k => $v){
if (is_numeric($k)){
$arg[$v] = $in[$v] ?? false;
} else {
$arg[$k] = $v;
}
}
} else {
if (!$b) return $self;
$arg = [$a => $b];
}
return fix_url($self . "?" . http_build_query($arg));
}
}
function selftoggle($key, $on, $off = false, $usein = false){
global $in;
if (!empty($in[$key]) && $in[$key] == $on){
$value = $off;
} else {
$value = $on;
}
return self($key, $value, $usein);
}
function extract_url($string = false){
if ($string === false) $string = $GLOBALS["protocol"] . "://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
$url = parse_url($string);
if (!empty($url["query"])){
$url["querystring"] = $url["query"];
parse_str(html_entity_decode($url["query"]), $url["query"]);
}
if (!empty($url["path"])){
$url["path"] = preg_replace("!/+!", "/", $url["path"]);
}
return $url;
}
function create_url($a, $onlypath = false, $encode = false){
$url = false;
if (!is_array($a))
$url = $a;
if (!empty($a["query"])){
if (is_array($a["query"])){
$a["query"] = array_map(function ($r){
if (!empty($r))
return $r;
}, $a["query"]);
$a["query"] = http_build_query($a["query"]);
} else {
parse_str($a["query"], $query);
$a["query"] = http_build_query($query);
}
}
if (empty($a["host"]) && !$onlypath){
$a["host"] = $_SERVER["HTTP_HOST"];
}
if (empty($a["scheme"]) && !$onlypath){
$a["scheme"] = (!empty($_SERVER['HTTPS'])) ? 'https' : 'http';
}
if (empty($a["path"]) && !empty($a["host"]) && $a["host"] == $_SERVER["HTTP_HOST"]){
$a["path"] = $_SERVER["PHP_SELF"];
}
#if (!empty($encodeamp)) $a["query"] = preg_replace("/&/", "&", $return);
$return = http_build_url($url, $a);
$return = preg_replace("/\?$/", "", $return);
if (!empty($onlypath))
#$return = preg_replace("/^[a-z]{3,5}\:\/\/[a-z,\.,-]+/", "", $return);
$return = preg_replace("/^http.*:\/\/.*?\//", "/", $return);
return $return;
}
function fix_url($string){
#if (strstr($string, "javascript:") || strstr($string, "tel:")) return $string;
#if (preg_match("/^#*[a-z_]+$/", $string)) return $string;
if (preg_match("/^\//", $string) || preg_match("/^http/", $string)){
return create_url(extract_url($string));
}
return $string;
}
function post_url($url, $headers = false){
if (!is_array($url))
$url = extract_url($url);
$host = $url["scheme"] . "://" . $url["host"] . $url["path"];
if (!empty($url["query"])){
foreach ($url["query"] as $key => $value){
$form[] = "-F '$key=$value'";
}
$form = join(" ", $form);
}
$exec = $GLOBALS["curl_path"] . SPACE . $form . " '$host'";
$data = shell_exec($exec);
return $data;
}
function get_url($url, $headers = false, $timeout = 10){
$heads = "";
if (is_array($url))
$url = create_url($url);
if (!empty($headers) && is_array($headers)){
$heads = [];
foreach ($headers as $header => $value){
$heads[] = "-H '$header: $value'";
}
$heads = join(" ", $heads);
}
$exec = $GLOBALS["curl_path"] . " --connect-timeout $timeout -s $heads '$url'";
$GLOBALS["site_warnings"][] = $exec;
#debug($exec);
$data = shell_exec($exec);
return $data;
}
function tinyurl($url){
$md5 = md5($url);
if (!is_dir("$GLOBALS[media_dir]/cache/tinyurl"))
mkdir("$GLOBALS[media_dir]/cache/tinyurl");
$file = "$GLOBALS[media_dir]/cache/tinyurl/$md5.url";
if (!file_exists($file)){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url=' . $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
if ($data == "Error")
return false;
filewrite($file, $data);
return $data;
} else {
touch($file);
return join("", file($file));
}
}
function include_file($file, $globalize = false){
if ($path = get_path($file)){
global $in, $user, $settings;
if (!empty($globalize)){
if (is_array($globalize)){
$oldin = $in;
#unset($in);
foreach ($globalize as $k => $v){
$in[$k] = $v;
}
} else {
foreach (explode(",", $globalize) as $k){
global $$k;
}
}
}
ob_start();
#pre($in);
#global $in;
include($path);
$output = ob_get_clean();
if (!empty($oldin))
$in = $oldin;
return $output;
} else {
warning("Couldn't include file: $file");
return false;
}
}
function encode($string, $format = "UTF-8"){
# ISO-8859-1
if ($format == "ISO 8859-1")
$format = "ISO-8859-1";
if (!in_array($format, mb_list_encodings())){
#error_log("Incorrect format: $format");
php_error(2, "Incorrect format: $format");
return $string;
}
if (!$string)
return false;
if (is_array($string)){
foreach ($string as $key => $value){
$newkey = encode($key, $format);
if (is_array($value)){
$return[$newkey] = encode($value, $format);
} else {
$newvalue = encode($value, $format);
$return[$newkey] = $newvalue;
}
}
return $return;
} else {
$enc = mb_detect_encoding($string, mb_list_encodings(), true);
if ($enc != "UTF-8")
$enc = "ISO-8859-1";
if ($enc == $format)
return $string;
return mb_convert_encoding($string, $format, $enc);
}
}
function parse_address($address){
global $user;
if (strstr($address, "\n")){
$lines = explode("\n", $address);
$address = array_shift($lines);
foreach ($lines as $line){
if (preg_match("/^([\d ]{5,7})\s+(.*?)$/", $line, $m)){
$return["zip"] = extract_number($m[1]);
$return["city"] = $m[2];
}
}
} elseif (strstr($address, ", ")) {
$lines = explode(", ", $address);
$address = array_shift($lines);
foreach ($lines as $line){
if (preg_match("/^([\d ]{5,7})\s+(.*?)$/", $line, $m)){
$return["zip"] = extract_number($m[1]);
$return["city"] = $m[2];
}
}
}
if (preg_match("/^\s*(\d*?[-a-zA-ZåäöÅÄÖéÉü: ]+) ?([0-9-\s]+)? ?([a-zA-ZåäöÅÄÖü]+)?/", $address, $m)){
$return["streetname"] = uc_words(trim($m[1]));
if (!empty($m[2])){
$return["streetnumber"] = trim($m[2]);
}
if (!empty($m[3])){
if (strlen($m[3]) > 3){
$return["city"] = $m[3];
} else {
$return["streetletter"] = strtoupper($m[3]);
}
}
if (empty($return["zip"]) || empty($return["city"])){
if (preg_match("/([\d ]{5,6})\s+([\w]*?)$/", $address, $m)){
$return["zip"] = extract_number($m[1]);
$return["city"] = $m[2];
}
}
return $return;
}
return false;
}
#function fix_address($address){
# if ($parse = parse_address(
#}
function split_name($string){
$nameparts = explode(" ", $string);
if (count($nameparts) == 2){
# Förnamn, efternamn
return [
"firstname" => uc_words($nameparts[0]),
"surname" => uc_words($nameparts[1])
];
} elseif (count($nameparts) == 1) {
# Bara förnamn
return [
"firstname" => uc_words($nameparts[0]),
"surname" => false
];
} else {
for ($i = 0; $i < count($nameparts); $i++){
if (in_array($nameparts[$i], ["von", "de", "af"])){
return [
"firstname" => uc_words(join(" ", array_slice($nameparts, 0, $i))),
"surname" => $nameparts[$i] . SPACE . uc_words(join(" ", array_slice($nameparts, $i + 1, count($nameparts))))
];
}
}
return [
"surname" => uc_words(array_pop($nameparts)),
"firstname" => uc_words(join(" ", $nameparts))
];
}
}
function refresh($time, $url = false){
if (!$url)
$url = $_SERVER["REQUEST_URI"];
$GLOBALS["page_head"] .= " \n";
}
function reload_parent($next = "close"){
$GLOBALS["page_onload"] = "reload_parent('$next')";
}
function median($data){
if (is_countable($data)){
$c_data = count($data);
$middle = $c_data / 2;
if ($c_data == 0){
return false;
}
if ($c_data < 2){
return $data[0];
} elseif (is_int($middle)) {
return (($data[$middle - 1] + $data[$middle]) / 2);
} else {
return $data[floor($middle)];
}
}
}
function punycode($string){
require_once("idn.php");
$idn = new idna_convert();
return $idn->encode($string, true);
}
function detect_language($string){
$request = [
"q" => $string,
"key" => "db16640b8050d6b40869d2dcc3fa120a"
];
$url = "http://ws.detectlanguage.com/0.2/detect";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
#pre($response);
$lang = $GLOBALS["language"];
foreach ($response["data"]["detections"] as $a){
#pre($a);
if ($a["isReliable"] == 1)
$lang = $a["language"];
if ($a["confidence"] > 0.5)
$lang = $a["language"];
}
if (!empty($lang) && $lang == "sv")
$lang = "se";
return $lang;
}
function tip($origin){
if ($tip = db("select * from atlas.tips where origin = '" . sqlesc($origin) . "' limit 1", 1)){
if (!empty($tip["link"]))
$buttons[] = [lp("show more"), $tip["link"], "info"];
if (group("superduperadmin")){
$buttons[] = [
lp("edit"),
"javascript:visa('http://$GLOBALS[atlas_url]/admin/edit/edit.php?popup=yes&module=tips&id=$tip[id]')",
"buttons/edit",
"showtext=no"
];
$buttons[] = [
lp("add tip for") . SPACE . $origin,
"javascript:visa('http://$GLOBALS[atlas_url]/admin/edit/edit.php?popup=yes&module=tips&origin=$origin')",
"buttons/plus",
"showtext=no"
];
}
$buttons[] = [lp("ok"), "javascript:seentip('$tip[id]')", "badges/ok"];
$img = $tip["image"] ? "help/$tip[image]" : "idea";
return dialog($tip["headline"], format($tip["text"]), img($img, 50), $buttons) . spacer();
} elseif (group("superduperadmin")) {
return nbutton(lp("add tip for") . SPACE . $origin, "javascript:visa('http://$GLOBALS[atlas_url]/admin/edit/edit.php?popup=yes&module=tips&origin=$origin')", "buttons/plus", "showtext=no") . "
";
}
}
function load_js($file){
if ($path = get_path($file)){
$file = $path;
}
if (preg_match("!http(.*)://(.*?)/!", $file, $m)){
$GLOBALS["csp"]->add("script-src", "http" . $m[1] . "://" . $m[2]);
}
$GLOBALS["page_load_scripts"][] = $file;
}
function load_css($file){
if (preg_match("!http(.*)://(.*?)/!", $file, $m)){
$GLOBALS["csp"]->add("style-src", "http" . $m[1] . "://" . $m[2]);
}
if (!is_array($GLOBALS["add_stylesheet"])) $GLOBALS["add_stylesheet"] = [$GLOBALS["add_stylesheet"]];
$GLOBALS["add_stylesheet"][] = $file;
}
function searchlog($search, $hits, $module = false){
$data = [
"module" => $module,
"page" => self(),
"visitor" => uid(),
"search" => $search,
"hits" => $hits ?: "0",
"date" => date("Y-m-d H:i:s"),
"kort" => $_SERVER["kort"]
];
save2db("atlas", "searchlog", $data);
}
function ip_info($ip){
$name = md5($ip);
$cachefile = "$GLOBALS[media_dir]/cache/ipinfo/$name.txt";
require_once "urls.php";
$url = "http://ip-api.com/json/$ip";
$cachefile = cache_url($url, "-1 week", $cachefile);
if (file_exists($cachefile)){
$info = mb_unserialize(join("", file($cachefile)));
return $info;
}
gauge("Fetched IP info for $ip");
return false;
}
function set_progress($keyword, $progress, $max, $status = false){
require_once("vote.php");
$procent = procent($progress, $max);
$file = $GLOBALS["data_dir"] . "/Progress/" . $_SERVER["kort"] . "/" . $keyword . ".txt";
create_dir(dirname($file));
filewrite($file, json_encode([
"progress" => $progress,
"max" => $max,
"percentage" => $procent,
"status" => $status
]));
}
function delete_progress($keyword){
$file = $GLOBALS["data_dir"] . "/Progress/" . $_SERVER["kort"] . "/" . $keyword . ".txt";
if (file_exists($file)){
unlink($file);
}
}
function mb_unserialize($string){
if (gettype($string) === 'string'){
if (preg_match("/^([adObis]:|N;)/", $string)){
$string = preg_replace_callback('!s:(\d+):"(.*?)";!sm', function ($m){
return 's:' . strlen($m[2]) . ':"' . $m[2] . '";';
}, $string);
return @unserialize($string);
} else {
return $string;
}
}
return false;
}
if (!function_exists('mb_ucwords')){
function mb_ucwords($str){
return mb_convert_case($str, MB_CASE_TITLE, "UTF-8");
}
}
/**
* @param $new
* @param $old
* @return array
*/
function arrayDiff($new, $old){
$diff = [];
foreach ($old as $key => $val){
if (array_key_exists($key, $new)){
if ($new[$key] !== $val){
$diff[$key] = $new[$key];
}
}
}
foreach ($new as $key => $val){
if (array_key_exists($key, $old)){
if ($old[$key] !== $val){
$diff[$key] = $val;
}
} else {
$diff[$key] = $val;
}
}
return $diff;
}
function download_headers($filename, $type = ""){
$date = date("c");
header('Content-Encoding: UTF-8');
header("Content-Type: " . mimetype($filename) . "; charset=UTF-8");
header("Last-Modified: $date");
header("Content-Disposition: attachment; filename=$filename; creation-date-parm='$date'; modification-date-parm='$date'");
}
function columnize($items, $columns){
$out = [];
$nr = 0;
$percol = ceil(count($items) / $columns);
$lowcol = floor(count($items) / $columns);
$total = count($items);
$inr = 0;
foreach ($items as $item){
$nr++;
if ($lowcol == ($total - $inr))
$nr = 1;
$inr++;
if ($nr > $percol)
$nr = 1;
#if ($col == 0) $col = $columns;
#print "$nr $item[text] ";
#$item["text"] = $nr . "/" . SPACE . $item["text"];
$out[$nr][] = $item;
}
#pre($out);
$return = [];
foreach ($out as $nr => $items){
foreach ($items as $item){
$return[] = $item;
}
}
#foreach ($items as $item){
# $return[] = $item;
#}
return $return;
}
function extract_array($array, $keys){
$out = [];
foreach ($array as $key => $value){
if (in_array($key, $keys))
$out[$key] = $value;
}
return $out;
}
function shuffle_assoc(&$array): bool{
$keys = array_keys($array);
shuffle_array($keys);
$new = [];
foreach ($keys as $key){
$new[$key] = $array[$key];
}
$array = $new;
return true;
}
function random(array $array){
shuffle_assoc($array);
return end($array);
}
function shuffle_array(&$array){
for ($i = count($array) - 1; $i > 0; $i--){
$j = rand(0, $i);
$tmp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $tmp;
}
}
function load_modules(array $a){
$modules = $return = $identifiers = [];
foreach ($a as $name => $keyword){
$identifier = strstr($keyword, ":") ? $keyword : "module:" . $keyword;
if (is_numeric($name)) $name = $keyword;
$modules[$keyword] = $name;
$identifiers[$identifier] = $name;
}
//pre($identifiers);
// Modules settings
$query = [
"select" => "*",
"from" => "atlas.edit_settings",
"where" => [
"identifier:in" => array_keys($identifiers)
]
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$GLOBALS["module_settings"][$r["identifier"]][$r["name"]] = $r["value"];
}
// MOdules
$query = [
"select" => "*",
"from" => "atlas.modules",
"where" => [
"keyword:in" => array_keys($modules)
]
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$key = $modules[$r["keyword"]];
$GLOBALS["module_settings"]["module:" . $r["keyword"]] = array_merge($r, (array)$GLOBALS["module_settings"]["module:" . $r["keyword"]]);
$return[$key] = new admin_module($r);
}
return $return;
}
function is_index($application = null){
return preg_match('!^/index.*?\.php$!', $_SERVER['PHP_SELF']);
}
/**
* The graphics library is automatically loaded
*/
require_once("graphics.php");
/**
* If the user is an administrator, the admin.php lib will
* also be included
*/
require_once("admin.php");
/**
* Uses db.php for DB specific functions
*/
require_once("db.php");
/**
* Always load jQuery
*/
require_once("jquery.php");
require_once("editfunctions.php");
function generate_translation_file(){
$translation = [];
foreach (db('SELECT phrase,translation FROM atlas.language WHERE language = "se"') as $r){
if (substr($r['translation'], -1) == '.' && substr($r['phrase'], -1) !== '.'){
$phrase = trim($r['phrase']) . '.';
} else {
$phrase = trim($r['phrase']);
}
$phrase = str_replace("\'", "'", $phrase);
$r['translation'] = str_replace("\n", '', $r['translation']);
$r['translation'] = str_replace("\r", '', $r['translation']);
$r['translation'] = str_replace("\'", '', $r['translation']);
$fixad_translation = str_replace('"', '\"', $r['translation']);
$translation[$phrase] = $fixad_translation;
}
$str = 'msgid ""
msgstr ""
"Project-Id-Version: Atlas v1.0\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
"Last-Translator: Micael Bolognini \n"
"Language: sv\n"
';
foreach ($translation as $phrase => $translation_phrase){
$str .= "\n";
$str .= 'msgid ' . '"' . $phrase . '"' . "\n";
$str .= 'msgstr ' . '"' . $translation_phrase . '"' . "\n";
}
$dir = $GLOBALS["data_dir"] . '/locale/' . $GLOBALS["locale"] . '/LC_MESSAGES/';
create_dir($dir);
$fp = fopen($dir . 'atlas.po', 'w+');
fwrite($fp, $str);
fclose($fp);
// konvertera .mo
$command = 'msgfmt' . SPACE . $dir . 'atlas.po' . SPACE . '-o' . SPACE . $dir . 'atlas.mo';
if (system($command) === false){
$GLOBALS["site_warnings"][] = 'Could not convert to .mo file';
}
}
function is_dev(){
return preg_match('/\.local/', $_SERVER['HTTP_HOST'] ?? "");
}
function sanitizeInput($input){
$return = [];
if (is_array($input)){
foreach ($input as $key => $value){
if (is_array($value)){
$return[$key] = sanitizeInput($value);
} else {
if ($key == "id" || preg_match("/.id$/", $key)){
$value = extract_number($value);
}
$cleaned = $value;
$cleaned = htmlspecialchars($cleaned, ENT_QUOTES | ENT_HTML401, 'UTF-8');
$return[$key] = $cleaned;
}
}
return $return;
} else {
$cleaned = $input;
return htmlspecialchars($cleaned, ENT_QUOTES | ENT_HTML401, 'UTF-8');
}
}
function addfeed($data): bool{
global $user;
if (empty($data["date"])) $data["date"] = date("Y-m-d H:i:s");
if (empty($data["kort"])) $data["kort"] = $_SERVER["kort"];
if (empty($data["email"])) $data["email"] = $user["email"];
if (empty($data["name"])) $data["name"] = $user["name"];
$required = explode(" ", "email name type headline");
foreach ($required as $r){
if (empty($data[$r])){
debug("Missed '$r'", "Feed insertion error");
return false;
}
}
save2db("member", "feed", $data);
return true;
}
function load_members($a){
if (empty($a)) return;
if (is_string($a)) $a = explode(",", $a);
$emails = $ids = [];
foreach ($a as $member){
if ($member == "") continue;
if (is_numeric($member)){
if (!empty($GLOBALS["loadedmembers"][$member])) continue;
$ids[] = $member;
} elseif (strstr($member, "@")) {
if (!empty($GLOBALS["loadedmembers"][$member])) continue;
$emails[] = $member;
} else {
$names[] = sqlesc($member);
}
}
// if ($_SERVER["kort"] == "LKC"){
// /** @var user $user */
// global $user;
// if (!empty($user) && $data = $user->data("Söker?")){
// $limited = in_array($data, qw("vän partner")) ? true : false;
// } else {
// $limited = false;
// }
// }
if (!empty($ids)){
$query = [
"select" => "m.*",
"from" => "member.member as m",
"where" => [
"m.id:in" => array_unique($ids),
"m.status" => "ok"
]
];
// if (!empty($limited)){
// $query["join"][] = [
// "db" => "member.data as d",
// "on" => [
// "d.member" => "m.id"
// ]
// ];
// $query["where"]["d.keyword"] = "Söker?";
// $query["where"]["d.value:in"] = qw("vän partner");
// }
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$GLOBALS["loadedmembers"][$r["id"]] = $r;
$GLOBALS["loadedmembers"][$r["email"]] =& $GLOBALS["loadedmembers"][$r["id"]];
}
}
if (!empty($emails)){
$query = [
"select" => "*",
"from" => "member.member as m",
"where" => [
"m.kort:in" => $GLOBALS["korts"],
"m.email:in" => array_unique($emails),
"m.status" => "ok"
],
"order" => "field(m.kort, '" . join("','", $GLOBALS["korts"]) . "')"
];
// if (!empty($limited)){
// $query["join"][] = [
// "db" => "member.data as d",
// "on" => [
// "d.member" => "m.id"
// ]
// ];
// $query["where"]["d.keyword"] = "Söker?";
// $query["where"]["d.value:in"] = qw("vän partner");
// }
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$GLOBALS["loadedmembers"][$r["id"]] = $r;
$GLOBALS["loadedmembers"][$r["email"]] =& $GLOBALS["loadedmembers"][$r["id"]];
}
}
if (!empty($names)){
$query = [
"select" => "*",
"from" => "member.member",
"where" => [
"kort:in" => $GLOBALS["korts"],
"name:in" => array_unique($names)
],
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$GLOBALS["loadedmembers"][$r["id"]] = $r;
$GLOBALS["loadedmembers"][$r["email"]] =& $GLOBALS["loadedmembers"][$r["id"]];
}
}
}
function member_publish($size = 16){
$icon = overlib(icon("pen", $size), "#", lp("publish information"));
$icon = str_replace(" asArray();
if (!$kort) $kort = $_SERVER["kort"];
if (!empty($GLOBALS["loadedmembers"][$member])){
return $GLOBALS["loadedmembers"][$member];
} elseif (!empty($load)) {
$query = [
"select" => "m.*",
"from" => "member.member as m",
"where" => [
"status" => "ok"
],
"limit" => 1
];
if (is_numeric($member)){
#$q2 = $kort ? "kort = '$kort' and id = '$member'" : "$GLOBALS[kortquery] and id = '$member'";
//$q2 = "id = '$member'";
$query["where"]["m.id"] = $member;
} elseif (strstr($member, "@")) {
#$q2 = $kort ? "kort = '$kort' and email = '$member'" : "$GLOBALS[kortquery] and email = '$member'";
$query["where"]["m.email"] = $member;
if (!empty($kort)){
$query["where"]["m.kort"] = $kort;
} else {
$query["where"]["m.kort:in"] = $GLOBALS["korts"];
}
} else {
//$q2 = $kort ? "kort = '$kort' and name = '$member'" : "$GLOBALS[kortquery] and name = '$member'";
$query["where"]["m.name"] = $member;
if (!empty($kort)){
$query["where"]["m.kort"] = $kort;
} else {
$query["where"]["m.kort:in"] = $GLOBALS["korts"];
}
}
#error_log($q2);
#debug($q2);
#$data = db("select * from member.member where status = 'ok' and $q2 limit 1", 1);
#print bq($query, 1);
$data = db(bq($query), 1);
if (!empty($data)){
$GLOBALS["loadedmembers"][$data["id"]] = $data;
$GLOBALS["loadedmembers"][$data["email"]] =& $GLOBALS["loadedmembers"][$data["id"]];
return $data;
} else {
return false;
}
}
return false;
}
function name2id($name){
$query = [
"select" => "*",
"from" => "member.member",
"where" => [
"kort:in" => $GLOBALS["korts"],
"status" => "ok",
"or" => [
"name" => $name,
"concat(firstname, ' ', surname)" => $name
]
],
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$GLOBALS["loadedmembers"][$r["id"]] = $r;
$GLOBALS["loadedmembers"][$r["email"]] = $r;
return $r["id"];
}
return false;
}
function email2id($email, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (is_array($email)){
foreach ($email as $e){
if ($m = is_member($e, $kort)){
$ids[] = $m["id"];
}
}
if (!empty($ids)){
return $ids;
}
} elseif ($member = is_member($email, $kort)) {
return $member["id"];
}
return false;
}
function id2email($id){
if ($member = is_member($id)){
return $member["email"];
} else {
return false;
}
}
function get_member_info($member, $kort = false){
if ($m = is_member($member, $kort)){
return $m;
} else {
return false;
}
}
function member_has_image($member){
if ($m = is_member($member)){
return $m["image"] ? $m["image"] : false;
} else {
return false;
}
}
function access($group = "all", $email = "all"){
global $user;
if (!$user) noaccess("restricted");
if ($group != "all"){
$groups = explode(",", $group);
$ok = 0;
$mygroups = explode(",", $user["access"]);
foreach ($groups as $group){
if (in_array($group, $mygroups)){
$ok = 1;
}
}
if ($ok == 0){
noaccess("nogroup");
}
}
}
function has_access($group){
global $user;
if ($group == "") return true;
if (!$user) return false;
if ($group != "all"){
$groups = explode(",", $group);
$ok = false;
$mygroups = explode(",", $user["access"]);
foreach ($groups as $group){
if (in_array($group, $mygroups)){
$ok = true;
}
}
return $ok;
}
return false;
}
function isadmin(){
if (!has_priv()){
redirect("/member/login.php?msg=nogroup&page={$_SERVER['REQUEST_URI']}");
}
}
function forumaccess($r){
global $user;
$access = "unlock";
$useraccess = explode(",", $user["access"]);
if (($r["member"]) && (!$user)){
$access = "lock";
}
if (!empty($r["access"])){
$access = "lock";
foreach (explode(",", $r["access"]) as $a){
if (in_array($a, $useraccess)){
$access = "unlock";
}
}
}
if (!empty($r["closed"])){
if (!$user){
$access = "hidden";
}
if (!empty($r["access"])){
$access = "hidden";
foreach (explode(",", $r["access"]) as $a){
if (in_array($a, $useraccess)){
$access = "unlock";
}
}
}
}
#if ($r["adminthreads"] == 1 && !has_priv("theforum")){
# $access = "lock";
#}
return $access;
}
function favorites(){
global $myfavorites, $user;
if (!empty($user["email"])){
$query = [
"select" => "*",
"from" => "member.favorites",
"where" => [
"kort" => $_SERVER["kort"],
"member" => $user["email"]
],
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$myfavorites[$r["keyword"]][] = $r["origin"];
}
}
}
function send_email_reply($from, $to, $mail, $subject = "respons", $html = false){
global $user;
$smeta = extract_meta($from["metadata"]);
if (!$from){
if (!empty($user)){
$from = $user;
} else {
$from["email"] = "atlas@sandman.net";
$from["firstname"] = "Anonym";
}
}
if ($smeta["hidemail"] == "yes"){
$from["email"] = "atlas@sandman.net";
}
if ($member = get_member_info($to)){
$meta = extract_meta($member["metadata"]);
if ($meta["mailreply"] == "yes"){
# Japp - vi ska maila!
#print "Lets mail goddammit!";
if (!empty($html)) $html = mail_layout($html);
sendmail(member_mail($from), member_mail($member), $_SERVER["name"] . ": $subject", $mail, $html, false, false, "Member reply");
}
}
}
function project_head($arg){
global $in, $user;
if (!is_object($arg)){
$project = new project($arg);
} else {
$project = $arg;
}
if (!is_object($arg)) return false;
$GLOBALS["page_title_alone"] = true;
$GLOBALS["page_title"] = $project["headline"];
$GLOBALS["page_headimage"] = false;
if (!$project->has_access()) noaccess();
$mod = new admin_module("projects");
$img = $project["image"] ? "$GLOBALS[media_dir]/modules/projectimages/$project[image]" : "/virtuals/bilder/icons/project.png";
#$buttons[] = array(lp("show all actions"), "/projects/project.php?id=$in[id]", "buttons/home");
#$buttons[] = array(lp("show all your actions"), "/projects/project.php?id=$in[id]&member=$user[id]", "buttons/inbox");
#$buttons[] = array(lp("show all todos"), "/projects/project.php?id=$in[id]&type=todo", "buttons/ok");
#$buttons[] = array(lp("show all notes"), "/projects/project.php?id=$in[id]&type=note", "buttons/pin");
#$buttons[] = array(lp("show all files"), "/projects/project.php?id=$in[id]&type=file", "buttons/document");
#$buttons[] = array(lp("show all members"), "/projects/users.php?id=$in[id]", "buttons/member");
#$buttons[] = array(lp("help"), "javascript:documentation('','projects')", "buttons/help");
$buttons[] = [
lp("add"),
$project->addlink(["folder" => $in["folder"], "member" => $in["member"]]),
"buttons/plus"
];
if ($project->access(true)){
$buttons[] = [
lp("delete actions that are marked as done"),
"/projects/project.php?" . query("purge_done", "yes"),
"buttons/delete"
];
}
if (has_priv("projects")){
$buttons[] = [lp("edit project room"), $mod->link("edit", ["id" => $project["id"]]), "buttons/edit"];
}
if ($myprojects = my_projects()){
$myprojs = new itemlist();
foreach ($myprojects as $a){
if ($project["id"] == $a["id"]) continue;
$myprojs->addrow(
[
"text" => $a["headline"],
"link" => "/projects/project.php?id=$a[id]"
]
);
}
if ($myprojs->count() > 0){
$buttons[] = [lp("change project room"), "my_projects", "buttons/replace", false, "popupmenu"];
$GLOBALS["page_divs"][] = div($myprojs->printlist(), "hidden", "my_projects");
}
}
# format($project["description"])
return head($project["headline"], $buttons, $img);
}
function my_inherits($id = false){
if (!$id){
global $user;
$id = $user["id"];
}
$query = [
"select" => "member",
"from" => "member.relations",
"where" => [
"child" => $id,
"inherit" => "1"
],
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$parents[] = $r["member"];
}
return !empty($parents) ? $parents : false;
}
/**
* @param bool $id
* @return array|bool
*/
function my_projects(bool $id = false){
if (!$id){
global $user;
$id = $user["id"];
}
if (!$id) return false;
$query = [
"select" => "p.*",
"from" => "atlas.projects as p, projects.members as m",
"where" => [
"p.kort" => $_SERVER["kort"],
"p.id" => "m.project",
"or" => [
"p.admin" => $id,
"m.member:in" => [$id]
]
],
"group" => "p.id"
];
$parent_groups = [];
if ($parents = my_inherits($id)){
# We have parents, add them as members to the query
$query["where"]["or"]["m.member:in"] = array_merge([$id], $parents);
if ($all_parent_groups = get_member_groups($parents)){
# those parents are members of groups, add those to the query
#debug($all_parent_groups);
foreach ($all_parent_groups as $m => $gs){
$parent_groups = array_merge(array_keys($gs), (array)$parent_groups);
}
}
#debug($parents);
#debug($parent_groups);
#$id = array_merge(array($id), $parents);
#pre($id);
}
if ($groups = get_member_groups($id)){
$thegroups = array_keys($groups[$id]);
}
if (!empty($parent_groups)){
if (!empty($thegroups)){
$thegroups = array_unique(array_merge(array_keys($groups[$id]), $parent_groups));
} else {
$thegroups = $parent_groups;
}
}
#pre($thegroups);
if (!empty($thegroups)){
$query["where"]["or"]["m.gid:in"] = $thegroups;
}
#print bq($query, 1);
$out = [];
foreach (db(bq($query)) as $r){
$out[$r["id"]] = $r;
}
# Let's get those that we are admins for as well
foreach (db("select * from atlas.projects where kort = '$_SERVER[kort]' and admin = '$id'") as $r){
$out[$r["id"]] = $r;
}
return $out;
}
function ircusers($channel){
if (file_exists("/atlas/conf/atlasnet/$channel.txt")){
return join("", file("/atlas/conf/atlasnet/$channel.txt"));
}
return 0;
}
function noaccess($tag = "noaccess", $redirect = false){
global $in;
$url = new url(false, false);
$url->path("/member/alert/" . $tag);
if (!empty($in["popup"])) $url->q("popup", "yes");
$current = new url();
$url->q("page", $current->url["path"]);
redirect($url->output());
// //global $padd, $user, $in;
// $padd = "";
// #pre($_SERVER);
// if (strstr($_SERVER["HTTP_REFERER"] ?? false, $_SERVER["HTTP_HOST"])){
// $padd .= "?page=" . urlencode(str_replace("http://$_SERVER[HTTP_HOST]", "", $_SERVER["HTTP_REFERER"]));
// } else {
// $padd = "?page=" . urlencode($_SERVER["REQUEST_URI"]);
// }
// if (!empty($_GET["debug"])){
// $debug = debug_backtrace();
// print "";
// print_r($debug);
// print " ";
// } else {
// #print alert(
// redirect("/member/alert/$tag$padd");
// }
}
function member_badge($member, $buttons = []){
$a = [
"size" => 48,
"iconside" => "right"
];
$a = arguments(func_get_args(), $a);
global $user;
$m = get_member_info($member);
$meta = extract_meta($m["metadata"]);
if (!empty($user["id"]) && !empty($member["id"]) && $member["id"] == $user["id"]){
#$text[] = overlib(icon("badges/edit", 12, "right"), "javascript:dialog('/atlas/ajax/member/update_status.php','what are you doing?',300,100)", lp("update your status"));
#$update = " " . overlib(icon("buttons/edit", 12, "baseline"), "javascript:dialog('/atlas/ajax/member/update_status.php?loadjs=yes')", lp("update your status"));
}
#if (!empty($meta["now"])){
# $text[] = $meta["now"] . $update;
#} else {
require_once("article.php");
$text[] = format(shorttext(["text" => $m["about"]], 200));
#}
if ($user["id"] == $m["id"]){
$buttons[] = [lp("edit"), "/member/edit", "buttons/edit"];
}
if (!empty($buttons)){
foreach ($buttons as $b){
$b[] = "showtext=no";
$b[] = "class=faded";
$buts[] = call_user_func_array("nbutton", $b);
}
#$text[] = div($buts);
}
$text = join("\n", $text);
return puff(
"ruta=no",
"icon=" . member_image($m, "src", true, true),
"headline=" . member_name($m),
"text=$text",
"iconside=$a[iconside]",
"size=$a[size]"
);
}
function member_name($member, $link = 1, $label = 1, $online = 1, $cut = 30, $format = false, $default = false){
if ($GLOBALS["community"] != "yes") $link = 0; // If this isn't a community, we won't link to users profiles ever
if ($member = is_member($member)){
if (!empty($format)){
$nick = parserxml($format, $member);
} else {
#$nick = $member["nick"] ? cut($member['nick'], $cut) : cut($member['name'], $cut);
if (!empty($member["template"]) && !empty($GLOBALS[$member["template"] . "membername"])){
$lt = $GLOBALS[$member["template"] . "membername"];
} else {
$lt = $GLOBALS["membername"];
}
$nick = parserxml($lt, $member);
}
if (trim($nick) == ""){
$nick = $member["name"];
}
if ($member["kort"] != $_SERVER["kort"] && group("superduperadmin") && !empty($GLOBALS["origins"][$member["kort"]])){
$nick .= " (" . $GLOBALS["origins"][$member["kort"]]["name"] . ")";
}
#$member["label"] = parserxml($GLOBALS["memberlabel"], $member);
$thelink = strstr($_SERVER["REQUEST_URI"] ?? "", "popup") ? "javascript:quicklink('/member/info.php?id=$member[id]')" : "/member/info.php?id=$member[id]";
#$name = $link ? "$nick " : "$nick ";
$name = $nick;
$name = $label ? "$name $member[label] " : $name;
$name = $online ? online($member["id"]) . " $name" : $name;
$overlib = $member["firstname"] ? "$member[firstname] $member[surname]" : false;
$name = $link ? overlib($name, $thelink, $overlib) : $name;
return $name;
} else {
#$GLOBALS["memberinfo"][] = $member;
#return "";
return $default;
}
}
function member_image($member, $size = 48, $thumb = false, $link = false, $align = "no"){
global $members;
if ($member = is_member($member)){
if (!empty($member["image"])){
$thumb = $thumb ? "yes" : "";
if ($size == "src"){
#if ($thumb == "yes"){
# return img("memberpics/" . $member["image"], $size, "align=$align", "square=$thumb", "return=src");
#} else {
return "memberpics/" . $member["image"];
#}
}
$img = img("memberpics/" . $member["image"], $size, "align=$align", "square=$thumb", "class=memberimage");
$a = a("/member/info.php?id=$member[id]", $img, [
"title" => member_name($member, 0, 0, 0),
"class" => "tooltip memberimagelink"
]);
return $link ? $a : $img;
} else {
$img = "member/types/member";
if ($member["template"] == "company") $img = "member/types/company";
if ($member["gender"] == "F") $img = "member/types/member_female";
if ($member["gender"] == "M") $img = "member/types/member_male";
if ($size == "src") return $img;
$img = img($img, $size, "align=$align", "class=memberimage", "alt=" . member_name($member, 0, 0, 0));
$a = a("/member/info.php?id=$member[id]", $img, [
"title" => member_name($member, 0, 0, 0),
"class" => "memberimagelink tooltip"
]);
return $link ? $a : $img;
}
} else {
#$GLOBALS["memberinfo"][] = $member;
#return "";
return icon("member", $size);
}
}
function member_head($user){
$meta = extract_meta($user["metadata"]);
if (!$user["template"]) $user["template"] = "member";
#pre($user);
#debug($GLOBALS[$user["template"] . "page"]);
foreach (explode(" ", $GLOBALS[$user["template"] . "page"]) as $p){
$buttons[] = [lp($p), "/u/$user[name]/" . ucfirst($p), "member/$p"];
}
return head($user["nick"], $meta["now"], $buttons, member_image($user, 48, 1, 1));
}
function member_login(){
$a = [
"register" => "yes"
];
$a = arguments(func_get_args(), $a);
global $user, $in;
$out = [];
if (!empty($user)) return false;
if ($GLOBALS["block_member_registration"] != "yes" && $a["register"] == "yes"){
$out[] = [lp("register"), "/member/join.php", "symbols/edit"];
}
#$out[] = [lp("login"), "javascript:show('member_login')", "symbols/lock"];
$page = !empty($in["page"]) ? $in["page"] : ($_SERVER["REQUEST_URI"] ?? false);
$out[] = [lp("login"), "javascript:dialog('/atlas/ajax/login.php?page=" . urlencode($page) . "')", "symbols/lock"];
#$out[] = div(form("editfields=user:INPUT:username passwd:PASSWD:password", "hiddens=save,page,redirect", "action=/member/login.php"), "innehall hidden", "member_login");
return nbuttons($out);
}
function member_path($member){
if (!is_array($member) && !is_object($member)) $member = get_member_info($member);
return $member["path"] ? $member["path"] : $member["id"];
}
function member_mail($member, $username = false){
if (!is_array($member)) $member = get_member_info($member);
if (!is_array($member)) return false;
$name = $username ? $member["name"] : "$member[firstname] $member[surname]";
return "$name <$member[email]>";
}
function member_data($member, $key = false, $scope = false){
$ret = false;
if (!empty($key) && is_numeric($key)) $key = db("select headline from member.quizform where id = $key", 1);
foreach (db("select * from member.data where member = $member") as $r){
if (!empty($key) && $key == $r["keyword"]) return $r["value"];
$ret[$r["keyword"]] = $r["value"];
}
if (!empty($key)) return false;
return $ret;
}
function member_settings($member, $key = false){
foreach (db("select * from member.settings where member = $member") as $r){
if (!empty($key) && $key == $r["keyword"]) return $r["value"];
$ret[$r["keyword"]] = $r["value"];
}
if (!empty($key)) return false;
return $ret;
}
function member_link($m = false){
$parts = [];
if (!$m){
global $user;
$m = $user;
} else {
$m = get_member_info($m);
}
if ($a = func_get_args()){
foreach (array_splice($a, 1) as $p){
$parts[] = $p;
}
}
$base = "";
if (!empty($m["path"])){
$base = $m["path"];
} elseif (!empty($m["id"])) {
$base = $m["id"];
}
return "/u/$base/" . join("/", (array)$parts);
}
function online($id, $size = 8){
if (!is_numeric($id) || empty($id)) return false;
$member = get_member_info($id);
if (empty($member)) return false;
if (empty($GLOBALS["online_members"]) || !is_array($GLOBALS["online_members"])) return false;
$status = in_array($id, $GLOBALS["online_members"]) ? "online" : "offline";
$extra = "";
if ($status == "offline"){
$extra = !empty($member["lastsurfed"]) ? lp("last online at") . ": " . smart_date($member["lastsurfed"], true) : "";
}
return icon("member/$status", $size, "valign:middle", 0, $extra);
#return overlib(icon("member/$status", $size), "/member/info.php?id=$id&show=about", $member["name"] . " " . lp("is", "L") . " $status" . $extra, ",WIDTH,200");
}
function set_member_meta($member, $key, $value){
$member = get_member_info($member);
$meta = extract_meta($member["metadata"]);
if (($meta[$key] ?? false) == $value){
$meta = set_meta($meta, $key, $value);
$meta = create_meta($meta);
db(sprintf("update member.member set metadata = '%s' where id = %s", sqlesc($meta), sqlesc($member["id"])));
}
}
function set_member_access($member, $access, $mode = "toggle"){
if ($member = is_member($member)){
switch ($mode){
case "add" :
$acc = $access;
break;
case "del" :
$acc = "-$access";
break;
case "toggle" :
$acc = "~$access";
break;
}
$access = edit_list($member["access"], $acc);
if ($access != $member["access"]){
db("update member.member set access = '$access' where id = $member[id]");
}
}
}
function create_member(){
global $user;
$a = [
"message" => lp("you have been automatically added as a member on this site by the person below"),
"subject" => lp("I have added you as a member on") . " $_SERVER[name]",
"status" => "pending",
"passwd" => create_pass(8),
"sendmail" => "yes",
"metadata" => "mailreply=yes"
];
if (is_array(func_get_arg(0))){
############################################################################
# The values were sent along as an array
############################################################################
$b = func_get_arg(0);
$a = array_merge($a, $b);
} else {
$a = arguments(func_get_args(), $a);
}
if (!$a["email"]){
############################################################################
# We can't go anywhere without an email address
############################################################################
print alert(lp("no email address"), lp("all members must have a unique email address"), "badges/stop", 1);
}
if ($member = is_member($a["email"], $_SERVER["kort"])){
############################################################################
# This is already a member! We'll return the member instead
############################################################################
return $member;
}
############################################################################
# Preset som values
############################################################################
$a["md5pass"] = md5($a["passwd"]);
$a["date"] = date("Y-m-d H:i");
$a["atlas_who"] = $user["id"];
$a["atlas_date"] = date("Y-m-d H:i");
if (!empty($a["parent"])){
$a["hasparent"] = 1;
}
################################# 2014-02-14 ##
# Metadata?
###############################################
if (!empty($a["metadata"]) && is_array($a["metadata"])) $a["metadata"] = create_meta($a["metadata"]);
################################# 2014-02-24 ##
# username
###############################################
if (!$a["name"]) $a["name"] = $a["firstname"] . SPACE . $a["surname"];
################################# 2014-02-24 ##
# Address
###############################################
if (is_array($a["address"])){
$a["zip"] = $a["address"]["zip"];
$a["city"] = $a["address"]["city"];
$a["address"] = $a["address"]["street"];
}
if ($id = save2db("member", "member", $a)){
$member = new user($id);
if (!empty($a["access"]) && $id){
add_member_to_group($id, $a["access"]);
}
if (!empty($a["parent"])){
if (!empty($id)){
save2db("member", "relations", ["member" => $a["parent"], "child" => $id, "inherit" => 1]);
}
}
############################################################################
# Ok, let's send some email!
############################################################################
if ($a["sendmail"] == "yes"){
$md["your password"] = $a["passwd"] . " (" . lp("you can change your password after loggin in") . ")";
$md["username"] = $a["name"];
$md["email"] = $a["email"];
if ($a["status"] == "pending"){
if (!empty($a["redirect"])) $redirect = "&redirect=" . urlencode($a["redirect"]);
$md["activation"] = "http://$_SERVER[HTTP_HOST]/member/login.php?accept=" . md5($a["email"]) . $redirect;
} else {
$md["login"] = "http://$_SERVER[HTTP_HOST]/member/login";
}
if ($GLOBALS["community"] == "yes"){
$md["your profile"] = "http://$_SERVER[HTTP_HOST]/member/info";
}
$md["edit your information"] = "http://$_SERVER[HTTP_HOST]/member/edit";
$md["added by"] = "$user[firstname] $user[surname]";
$a["message"] .= "\n\n";
foreach ($md as $k => $v){
$a["message"] .= lp($k) . ": $v\n";
}
sendmail($user["email"], $a["email"], $a["subject"], $a["message"], false, false, false, "New member");
}
return $member;
}
#print "$a[message] ";
}
function uid($uu = true){
global $user;
if (!empty($user) && $uu){
return $user["id"];
} elseif (!empty($_SESSION["uid"])) {
return $_SESSION["uid"];
} else {
$uid = md5("$_SERVER[REMOTE_ADDR] " . date("Y-m-d H:i:s"));
$_SESSION["uid"] = $uid;
return $uid;
}
}
function fix_priv($mod){
global $user;
if (has_priv("themembers") && !has_priv($mod)){
db("insert into atlas.priv (kort, module, email) values ('$_SERVER[kort]', '$mod', '$user[email]')");
redirect($_SERVER["REQUEST_URI"]);
}
}
function printname($name, $email = false, $link = 1, $label = 1, $online = 1){
if (!empty($email)){
if ($m = is_member($email)){
return member_name($m, $link, $label, $online);
} else {
return fix_link($email, $name);
}
} else {
return $name;
}
}
function post_comment($in){
global $members, $user;
$sender = $user ? $user : ["name" => $in["name"], "email" => $in["email"]];
#pre($in);
if ($in["kind"] == "article"){
$origin = db("select * from atlas.articles where id = $in[origin]", 1);
if ($in["follows"] != $in["origin"]){
$q = db("select email from atlas.connects where id = %d", $in["follows"]);
[$omail] = $q[0];
$originmember = email2id($omail);
} else {
$q = db("select member, email from atlas.articles where id = %d", $in["origin"]);
[$omem, $omail] = $q[0];
$originmember = $omem ? $omem : email2id($omail);
}
if (!$omail){
$omail = "atlas@eklundh.com";
}
if (!empty($originmember) && $omail){
$writername = $user ? $user["name"] : $in["name"];
$mailtext = "Hejsan {$members[$originmember][name]}!
$writername har skrivit en kommentar på '$origin[headline]':
http://$_SERVER[HTTP_HOST]/texter/read.php?id=$origin[id]&jump=yes
$in[text]";
send_email_reply($sender, $omail, $mailtext, "comment");
}
db("update articles set comments = comments + 1, lastcomment = now() where id = %d", $in["origin"]);
}
if ($in["kind"] == "ads"){
$q = db("select * from annons.items where id = %d", $in["origin"]);
$origin = $q[0];
if ($in["follows"] != $in["origin"]){
$q = db("select email from atlas.connects where id = %d", $in["follows"]);
[$omail] = $q[0];
$originmember = email2id($omail);
} else {
$q = db("select member from annons.items where id = %d", $in["origin"]);
[$originmember] = $q[0];
}
if (!empty($originmember)){
$writername = $user ? $user["name"] : $in["name"];
$mailtext = "Hejsan {$members[$originmember][name]}!
$writername har skrivit en kommentar på '$origin[headline]':
http://$_SERVER[HTTP_HOST]/ads/item.php?id=$origin[id]
$in[text]";
send_email_reply($sender, $members[$originmember]["email"], $mailtext, "comment");
}
}
if (!$in['name']){
$in["name"] = "Anonym";
}
if (!$user){
setcookie("name", $in["name"], time() + 86400, "/", $_SERVER['HTTP_HOST']);
setcookie("email", $in["email"], time() + 86400, "/", $_SERVER['HTTP_HOST']);
setcookie("url", $in["url"], time() + 86400, "/", $_SERVER['HTTP_HOST']);
}
$in["date"] = date("y-m-d H:i:s");
$in["member"] = $user["id"];
$in["originmember"] = $originmember;
$id = save2db("atlas", "comments", $in);
return $id;
}
function show_grade($origin, $kind, $width = 200, $max = 5){
global $user;
$grades = [];
$out = $mygrade = null;
foreach (db("select * from member.grades where origin = '$origin' and kind = '$kind'") as $r){
$grades[] = $r["grade"];
if ($r["member"] == $user["id"]) $mygrade = $r["grade"];
}
$grade = !empty($grades) ? array_sum($grades) / count($grades) : 0;
$iw = round(($width / $max) - 6);
#print $grade;
if (!empty($grade)){
$out = "
" . num($grade, 1) . " / $max (" . count($grades) . " " . oom(count($grades), lp("vote:2", "L"), lp("votes:2", "L")) . ")
";
}
$grade = str_replace(",", ".", $grade);
$out .= "";
foreach (qw("grade nograde halfgrade") as $item){
if (!file_exists("$GLOBALS[media_dir]/atlas/ratings/grades/" . $item . "_$iw.png")){
system($GLOBALS["convert_path"] . " -geometry $iw $GLOBALS[atlas_dir]/virtuals/bilder/icons/badges/star_$item.png $GLOBALS[media_dir]/atlas/ratings/grades/" . $item . "_$iw.png");
}
}
for ($a = 1; $a <= $max; $a++){
$icon = "nograde";
if ($grade >= $a){
$icon = "grade";
} elseif (($grade - ($a - 1)) > 0.3) {
$icon = "halfgrade";
}
$out .= " ";
#$out .= " ";
}
$out .= "
";
$text = $mygrade ? lp("your grade") . ": $mygrade" : lp("click the stars above to set your grade");
$out .= "
$text
";
return div($out, "gradeimage", "grade_" . $origin);
}
function get_grade($origin, $kind, $voters = 5, $decimals = 0){
$avoters = 0;
$mygrade = 0;
$voters = 0;
$grades = [];
global $user;
foreach (db("select * from member.grades where origin = '$origin' and kind = '$kind'") as $r){
$avoters++;
$grades[] = $r["grade"];
if ($r["member"] == $user["id"]) $mygrade = $r["grade"];
}
if ($avoters < $voters) return false;
return $grades ? num(array_sum($grades) / count($grades), 1) : false;
}
function stars($width, $grade, $max = 5){
$out = "";
$iw = round($width / 5);
if (!file_exists("$GLOBALS[media_dir]/atlas/ratings/grades/grade_$iw.png")) system($GLOBALS["convert_path"] . " -geometry $iw $GLOBALS[atlas_dir]/virtuals/bilder/icons/badges/star_grade.png $GLOBALS[media_dir]/atlas/ratings/grades/grade_$iw.png");
if (!file_exists("$GLOBALS[media_dir]/atlas/ratings/grades/nograde_$iw.png")) system($GLOBALS["convert_path"] . " -geometry $iw $GLOBALS[atlas_dir]/virtuals/bilder/icons/badges/star_nograde.png $GLOBALS[media_dir]/atlas/ratings/grades/nograde_$iw.png");
if (!file_exists("$GLOBALS[media_dir]/atlas/ratings/grades/halfgrade_$iw.png")) system($GLOBALS["convert_path"] . " -geometry $iw $GLOBALS[atlas_dir]/virtuals/bilder/icons/badges/star_gradehalf.png $GLOBALS[media_dir]/atlas/ratings/grades/halfgrade_$iw.png");
for ($a = 1; $a <= $max; $a++){
$icon = "nograde";
if ($grade >= $a){
$icon = "grade";
} elseif (($grade - ($a - 1)) > 0.3) {
$icon = "halfgrade";
}
$out .= " ";
}
$out .= "
";
return $out;
}
function find_member($id = false, $link = false, $hiddens = false){
require_once("form.php");
if (!$link) print alert("Error", "Need a link for adding member", "badges/stop", 1);
$display = $id ? "none" : "block";
$GLOBALS["incfiles"][] = "$GLOBALS[atlas_dir]/virtuals/atlas/ajax/findmember.php";
$out = "
";
return $out;
}
function search_members($search){
$a = [
"full" => "no",
"show" => 40,
"start" => 0
];
//pre(array_slice(func_get_args(), 1));
$a = arguments(array_slice(func_get_args(), 1), $a);
$query = [
"select" => ($a["full"] == "yes" ? '*' : "m.id"),
"calculate" => "yes",
"from" => "member.member as m",
"where" => [
"kort" => $_SERVER["kort"],
"status" => "ok"
],
"limit" => $a["start"] . "," . $a["show"]
];
if (is_string($search)){
foreach (explode(" ", "name firstname surname email city") as $k){
$query["where"]["or"]["$k:like"] = "%" . sqlesc($search) . "%";
}
} else {
foreach (explode(" ", "name firstname surname email city born") as $k){
if (!empty($search[$k])){
if (is_array($search[$k])){
$query["where"][$k . ":in"] = $search[$k];
} else {
$query["where"][$k . ":like"] = "%" . $search[$k] . "%";
}
}
}
if (!empty($search["search"])){
foreach (explode(" ", "name firstname surname email city") as $k){
$query["where"]["or"]["$k:like"] = "%" . sqlesc($search["search"]) . "%";
}
}
if (!empty($search["gender"])){
if (!is_array($search["gender"])) $search["gender"] = explode(",", $search["gender"]);
$query["where"]["gender:in"] = $search["gender"];
}
if (!empty($search["age"])){
if (strstr($search["age"], "-")){
[$young, $old] = explode("-", $search["age"]);
$query["where"][] = "(date_format(from_days(to_days(now())-to_days(born)), '%y')+0 >= '$young' and date_format(from_days(to_days(now())-to_days(born)), '%y')+0 <= '$old')";
} else {
$query["where"][] = "DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW())-TO_DAYS(born)), '%Y')+0 = '$search[age]'";
}
}
}
if (count($query["where"]) == 1) return false;
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$ids[] = $r["id"];
}
if (!empty($ids)){
load_members($ids);
return $ids;
} else {
return false;
}
}
function isuser($string){
global $user;
if (!$user) return false;
foreach (explode(",", $string) as $u){
if (is_numeric($u) && $user["id"] == $u) return true;
if (strstr($u, "@") && $user["email"] == $u) return true;
if ($user["name"] == $u) return true;
}
return false;
}
function group_info($kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (empty($GLOBALS["group_info"])){
foreach (db("select * from atlas.groups where kort = '$kort'") as $r){
$GLOBALS["groupnames"][$r["name"]] = $r["id"];
$GLOBALS["group_info"][$r["id"]]["name"] = $r["name"];
}
foreach (db("select * from atlas.group_members where kort = '$kort'") as $r){
if (!empty($GLOBALS["group_info"][$r["gid"]])){
$GLOBALS["group_info"][$r["gid"]]["members"][] = $r["member"];
}
}
}
return $GLOBALS["group_info"] ?? false;
}
function get_group_members($checkgroups, $kort = false, $inherited = false){
$thegroups = explode(",", $checkgroups);
$members = [];
if ($groups = group_info($kort)){
foreach ($groups as $id => $g){
if (in_array($g["name"], $thegroups) || in_array($id, $thegroups)){
$members = array_merge((array)$members, (array)$g["members"]);
if (!empty($inherited) && $g["members"]){
# inherited members
foreach (db("select child from member.relations where member in(" . join(",", $g["members"]) . ") and inherit = 1") as $r){
$members[] = $r["child"];
}
}
}
}
}
return count($members) > 0 ? $members : false;
}
function get_member_groups($id){
if (is_numeric($id)) $id = [$id];
if (is_string($id)) $id = explode(",", $id);
if (!$id) return false;
$groups = [];
foreach (db("select * from atlas.group_members, atlas.groups where groups.kort = '$_SERVER[kort]' and group_members.gid = groups.id and group_members.member in(" . join(",", $id) . ")") as $r){
$groups[$r["member"]][$r["id"]] = $r["name"];
}
return !empty($groups) ? $groups : false;
}
function group2id($name, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (!$GLOBALS["groupnames"]){
foreach (db("select * from atlas.groups where kort = '$kort'") as $r){
$GLOBALS["groupnames"][$r["name"]] = $r["id"];
}
}
return $GLOBALS["groupnames"][$name];
}
function create_group($group){
$data = [
"kort" => $_SERVER["kort"],
"name" => $group
];
$gid = post_exists("atlas", "groups", $data, "kort,name");
if (!$gid){
return save2db("atlas", "groups", $data);
}
return $gid;
}
function add_member_to_group($members, $groups){
if (!is_array($members)) $members = explode(",", $members);
if (!is_array($groups)) $groups = explode(",", $groups);
load_members($members);
if ($groupinfo = group_info()){
foreach ($groupinfo as $id => $r){
$gid[$r["name"]] = $id;
}
} else {
debug("No groups exists");
return false;
}
foreach ($members as $m){
$member = get_member_info($m);
foreach ($groups as $g){
if (!in_array($g, array_keys((array)$gid)) && !in_array($g, array_values((array)$gid))){
$g = create_group($g);
}
$group_id = is_numeric($g) ? $g : $gid[$g];
if (!in_array($member["id"], (array)$groupinfo[$group_id]["members"])){
# Ok, we're not in this group
save2db("atlas", "group_members", [
"kort" => $_SERVER["kort"],
"member" => $member["id"],
"gid" => $group_id
]);
}
}
}
}
function del_member_from_group($members, $groups){
if (!is_array($members)) $members = explode(",", $members);
if (!is_array($groups)) $groups = explode(",", $groups);
load_members($members);
$groupinfo = group_info();
foreach ($groupinfo as $id => $r){
$gid[$r["name"]] = $id;
}
foreach ($members as $m){
$member = get_member_info($m);
foreach ($groups as $g){
if (!in_array($g, array_keys($gid))){
debug("Group $g does not exist");
continue;
}
$group_id = $gid[$g];
if (in_array($member["id"], (array)$groupinfo[$group_id]["members"])){
# Ok, we're not in this group
db("delete from atlas.group_members where member = $member[id] and gid = $group_id");
}
}
}
}
function format_address($r, $onlystreet = false){
if (empty($r["streetname"])) $r["streetname"] = $r["streetName"] ?? false;
if (empty($r["streetnumber"])) $r["streetnumber"] = $r["streetNumber"] ?? false;
if (empty($r["streetletter"])) $r["streetletter"] = $r["streetLittera"] ?? false;
if (!empty($r["street"])){
$a = parse_address($r["street"]);
$r = array_merge($r, $a);
}
if (empty($r["zip"])) $r["zip"] = $r["postalCode"] ?? false;
if (!empty($r["streetname"])){
$r["address"] = join(" ", array_filter([
ucf(lc($r["streetname"])),
$r["streetnumber"],
$r["streetletter"]
]));
if (!empty($onlystreet)) return $r["address"];
}
if (!empty($r["address"]) && $r["zip"] && $r["city"]){
return $onlystreet ? $r["address"] : "$r[address] $r[zip] $r[city]";
} elseif (!empty($r["streetaddress"]) && $r["zip"] && $r["city"]) {
return $onlystreet ? $r["streetaddress"] : "$r[streetaddress] $r[zip] $r[city]";
} else {
return false;
}
}
function user_alerts($size = 32, $since = false){
global $user;
global $umeta;
$message_icon = $umeta["unread_messages"] ? icon_badge("member/msg", $umeta["unread_messages"], $size) : icon("member/msg", $size);
$guestbook_icon = $umeta["new_guestbook_entries"] ? icon_badge("member/guestbook", $umeta["new_guestbook_entries"], $size) : icon("member/guestbook", $size);
# Messages and guestbook
$out[] = overlib($message_icon, "/member/info.php?id=$user[id]&show=messages", "Dina meddelanden");
$out[] = overlib($guestbook_icon, "/member/info.php?id=$user[id]&show=guestbook", "Din gästbok");
return join("", $out);
}
function feed_count(){
global $user;
$feed = new feed();
if (!empty($user)){
$me = new user($user);
$feed->target = $me;
if (!empty($user["last"])){
$feed->since = $user["last"];
#debug($user["last"]);
}
}
$posts = $feed->get_posts();
return $posts->count() ? $posts->count() : "0";
#return $news ? span(fix_link("javascript:visa('/member/feed?popup=yes&show=list','since')", "$news " . oom($news, lp("new item", "L"), lp("new items", "L"))), "feedalert") : span(lp("nothing new"), 'feedalert');
}
function send_message($to, $subject, $message, $from = false){
global $user;
if (!$from) $from = $user["id"];
$member = get_member_info($to);
$meta = extract_meta($member["metadata"]);
$meta["unread_messages"]++;
set_member_meta($member, "unread_messages", $meta["unread_messages"]);
$data = [
"msgfrom" => $from,
"msgto" => $to,
"status" => "unread",
"headline" => $subject,
"text" => $message,
"date" => date("Y-m-d H:i"),
"follows" => "0"
];
#pre($data);
$id = save2db("member", "msg", $data);
$link = "http://$_SERVER[HTTP_HOST]/member/info.php?id=$member[id]&show=messages";
$mailtext = lp("hello") . "!\n $user[name] " . lp("has written a message to you on", "L") . " $_SERVER[name]\n\n" . lp("subject") . ": $subject\n\n" . $link;
send_email_reply($user, $member["email"], $mailtext, "new message");
return $id;
}
function member_buttons($size = 22, $buts = false, $return = "html"){
global $user;
if (!empty($user)){
$memberpicture = "symbols/member";
$palette[] = [
member_name($user, 0, 0, 0, 20, "#username#"),
"/atlas/ajax/member/memberlinks.php",
$memberpicture,
"title=" . lp("show member menu"),
"class=tooltip popupmenu"
];
$meta = extract_meta($user["metadata"]);
if ($GLOBALS["community"] == "yes"){
$msgicon = !empty($meta["unread_messages"]) ? "badge:symbols/mail:badges/stop" : "symbols/mail";
$palette[] = [
lp("messages"),
"/member/info.php?id=$user[id]&show=messages",
$msgicon,
"showtext=no",
"id=msgicon"
];
if ($GLOBALS["disable_member_feed"] == "no"){
$feed = new feed();
$feed->target = $user;
$feed->onlytarget = true;
$feed->since = $user["last"];
$posts = $feed->get_posts();
$news = $posts->count();
$newsicon = $news > 0 ? "badge:symbols/clock:badges/extra" : "symbols/clock";
$palette[] = [
lp("see what's new since last time you visited"),
"/member/feed", //"javascript:popupmenu('/atlas/ajax/member/feed.php',this)",
$newsicon,
"showtext=no",
"id=feedbutton"
];
}
}
} else {
require_once("form.php");
$url = parse_url($_SERVER["HTTP_REFERER"] ?? false);
$in["page"] = $_SERVER["REQUEST_URI"] ?? false;
$in["user"] = $_SESSION["name"] ?? false;
$in["save"] = "1";
/*
if ($GLOBALS["use_facebook"] == "yes"){
require_once("facebook.php");
$facebook = new facebook(array('appId' => $GLOBALS["facebook_id"], 'secret' => $GLOBALS["facebook_secret"]));
#$loginform = div(facebook_login_button());
$loginform = div(nbutton(lp("login with facebook"), "javascript:svisa('" . $facebook->getLoginUrl(array("scope" => "email,user_checkins,user_photos", "display" => "popup")) . "','fblogin',22,500)", "member/import/facebook"));
}
$loginform .= form("editfields=user::username+or+email passwd:PASSWD:password", "original=in", "action=/member/login", "hiddens=save,page", "method=post", "redirect=$redir");
$GLOBALS["page_divs"][] = div($loginform, "hidden", "hiddenloginform");
*/
$palette[] = [lp("login"), "javascript:dialog('/atlas/ajax/member/login.php?loadjs=yes')", "symbols/lock"];
#$palette[] = array(lp("login"), "javascript:dialog('/atlas/ajax/login.php','" . lp("login") . "',400, 300)", "unlock", lp("login"));
if ($GLOBALS["block_member_registration"] != "yes"){
$palette[] = [lp("join"), "/member/join.php", "symbols/edit", lp("register on") . " $_SERVER[name]"];
}
}
if (!empty($buts)){
foreach ($buts as $id => $b){
$palette[] = $b;
}
}
if (!empty($GLOBALS["add_member_buttons"])){
#pre($GLOBALS["add_member_buttons"]);
foreach ($GLOBALS["add_member_buttons"] as $id => $b){
$palette[] = $b;
}
}
#pre($palette);
if ($return == "array") return $palette;
$GLOBALS["dislayed_memberbuttons"] = true;
return nbuttons($palette, "site_memberbuttons");
// foreach ($palette as $a){
// list ($label, $link, $icon, $over, $class) = $a;
// if (!empty($label)) $label = " $label";
// #$buttons[] = div(overlib(img($icon, $size, "alt=$over", "align=no") . $label, $link, $over, $class), "user_button");
// #$buttons[] = nbutton($label, $link, $icon, "class=tooltip $class", "title=$over", "iconsize=16");
// $buttons[] = call_user_func_array("nbutton", $a);
// }
// return div(join("", $buttons), "buttonwrapper");
}
function get_children($member){
$children = false;
foreach (db("select child, inherit, type from member.relations where member = '$member'") as $r){
$children[$r["child"]] = $r;
}
return $children;
}
function user_homepage($return = true){
global $member, $parts, $in;
$host = $_SERVER["IDN_HTTP_HOST"] ?? $_SERVER["HTTP_HOST"];
$urlparts = explode(".", $host);
if (count($urlparts) == 3 && $urlparts[0] != "www" && $GLOBALS["profile_member"] = db("select * from member.member where $GLOBALS[kortquery] and status = 'ok' and path = '$urlparts[0]'", 1)){
$GLOBALS["layout"] = "profile";
$in["layout"] = "profile";
$GLOBALS["mother_url"] = "http://" . $urlparts[1] . "." . $urlparts[2];
$GLOBALS["page_title"] = $GLOBALS["profile_member"]["name"];
if (preg_match("!^/u/(.*?)/!", $_SERVER["REQUEST_URI"], $m)){
if ($m[1] != $urlparts[0] && $m[1] != $GLOBALS["profile_member"]["path"]){
redirect("http://www." . join(".", array_slice($urlparts, 1, 2)) . "$_SERVER[REQUEST_URI]");
} elseif ($m[1] == $GLOBALS["profile_member"]["path"]) {
redirect(str_replace("/u/$m[1]/", "/index/", $_SERVER["REQUEST_URI"]));
}
}
if (!empty($return)){
$member = new user($GLOBALS["profile_member"]);
$parts = explode("/", $_SERVER["PATH_INFO"]);
if (!$parts[1]) $parts[] = "weblog";
unset($parts[0]);
array_unshift($parts, $urlparts[0]);
array_unshift($parts, false);
$homepage = include_file("$GLOBALS[atlas_dir]/virtuals/member/homepage.php", "member,parts");
return $homepage;
}
return true;
}
return false;
}
function weblog_access($r){
global $user;
if (!empty($r["access"])){
if ($r["access"] == "public") unset($r["access"]);
if ($r["access"] == "private") $r["access"] = $r["member"];
if ($r["access"] == "favorites"){
$member = new user($r["member"]);
$favorites = $member->favorites("member");
$favorites[] = $r["member"];
$r["access"] = join(",", $favorites);
}
return group($r["access"]);
} else {
return true;
}
}
function weblog_published($r){
global $user;
if ($r["publish"] == "0000-00-00 00:00:00" || time() < strtotime($r["publish"]) || !$r["publish"]){
if ($user["id"] != $r["member"]) return false;
$label = lp("unpublished");
if (time() < strtotime($r["publish"])) $label = lp("will be published") . SPACE . smart_date($r["publish"], true);
return $label;
}
return true;
}
function my_social_accounts(){
global $user, $in;
################################# 2013-03-03 ##
# Update profile
###############################################
if (!empty($in["updateprofile"])){
$account = new social_account($in["updateprofile"]);
$profile = $account->service->profile($account->token);
$data = [
"id" => $account["id"],
"data" => serialize($profile),
#"debug" => "yes",
"name" => $profile["name"]
];
save2db("social", "accounts", $data, "duplicates=yes");
if (!$data["debug"]){
redirect($user->link("edit", "social"));
}
}
################################# 2013-07-15 ##
# Delete account
###############################################
if (!empty($in["deleteaccount"])){
db("delete from social.accounts where member = $user[id] and id = $in[deleteaccount]");
}
################################# 2013-03-03 ##
# Add account act
###############################################
if (!empty($in["addaccount"])){
$class = "social_service_" . $in["addaccount"];
$service = new $class;
if (!empty($in[$service->url_param])){
$accesstoken = $service->get_access_token();
$profile = $service->profile($accesstoken);
$data = [
"member" => $user["id"],
"name" => $profile["name"],
"data" => serialize($profile),
"service" => $service["id"],
"auth" => serialize($accesstoken),
#"debug" => "yes"
];
if (!$profile) $data["debug"] = "yes";
$id = save2db("social", "accounts", $data);
if (!$data["debug"]){
redirect($user->link("edit", "social"));
}
} else {
$service->authorize();
}
}
################################# 2013-03-03 ##
# My accounts
###############################################
$mytypes = [];
$list = new itemlist(lp("your accounts"), 32);
if (!empty($user)){
$query = [
"select" => "a.*, s.type",
"from" => "social.accounts as a",
"join" => [
[
"db" => "social.services as s",
"on" => [
"s.id" => "a.service"
]
]
],
"where" => [
"a.kort" => $_SERVER["kort"],
"s.kort" => $_SERVER["kort"],
"member" => $user["id"]
]
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
$buttons = [
[lp("delete"), self("deleteaccount", $r["id"]), "buttons/delete"],
[lp("update information"), self("updateprofile", $r["id"]), "buttons/reload"]
];
$mytypes[] = $r["type"];
$list->addrow(
[
"text" => span($r["name"], "mrubrik"),
"subtext" => ucfirst($r["type"]),
"icon" => "member/import/$r[type]",
"buttons" => $buttons,
#"link" => self("id", $r["id"])
]
);
}
$list->error_msg = lp("no accounts added");
} else {
#$list->error_msg = lp("only registered members can add accounts");
}
################################# 2013-03-03 ##
# Add account
###############################################
$addlist = new itemlist(lp("add account"), 40);
$query = [
"select" => "*",
"from" => "social.services",
"where" => [
"kort" => $_SERVER["kort"],
"active" => "yes"
]
];
#print bq($query, 1);
foreach (db(bq($query)) as $r){
if ($r["multiple"] == "no" && in_array($r["type"], $mytypes)) continue;
$buttons = [
[lp("add"), self("addaccount", $r["type"], false), "symbols/link", "showtext=yes"]
];
$addlist->addrow(
[
"text" => ucfirst($r["type"]),
"icon" => "member/import/$r[type]",
"subtext" => format($r["description"]),
"buttons" => $buttons
]
);
}
if ($addlist->count() > 0){
$list .= $addlist;
}
#$list->addbutton(lp("add account"), $links, "buttons/plus");
return $list;
}
function login_link($member, $url, $kort = false){
if (!$kort) $kort = $_SERVER["kort"];
if (is_numeric($member) || (is_string($member) && strstr($member, "@"))) $member = get_member_info($member, $kort);
if (!$member["id"]) return $url;
$url = extract_url($url);
$host = $url["host"] ? "http://" . $url["host"] : false;
unset($url["host"], $url["scheme"]);
return "$host/member/md5login.php?" . query([
"email" => $member["email"],
"passwd" => $member["md5pass"],
"page" => create_url($url, true)
], false, false);
}
function age($date){
require_once("counttime.php");
$age = counttime(date("Y-m-d"), $date, "years");
return $age . SPACE . oom($age, lp("year", "L"), lp("years", "L"));
}
?>